Skip to main content

script/
script_thread.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! The script thread is the thread that owns the DOM in memory, runs JavaScript, and triggers
6//! layout. It's in charge of processing events for all same-origin pages in a frame
7//! tree, and manages the entire lifetime of pages in the frame tree from initial request to
8//! teardown.
9//!
10//! Page loads follow a two-step process. When a request for a new page load is received, the
11//! network request is initiated and the relevant data pertaining to the new page is stashed.
12//! While the non-blocking request is ongoing, the script thread is free to process further events,
13//! noting when they pertain to ongoing loads (such as resizes/viewport adjustments). When the
14//! initial response is received for an ongoing load, the second phase starts - the frame tree
15//! entry is created, along with the Window and Document objects, and the appropriate parser
16//! takes over the response body. Once parsing is complete, the document lifecycle for loading
17//! a page runs its course and the script thread returns to processing events in the main event
18//! loop.
19
20use std::cell::{Cell, RefCell};
21use std::collections::HashSet;
22use std::default::Default;
23use std::option::Option;
24use std::rc::{Rc, Weak};
25use std::result::Result;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::thread::{self, JoinHandle};
29use std::time::{Duration, Instant, SystemTime};
30
31use background_hang_monitor_api::{
32    BackgroundHangMonitor, BackgroundHangMonitorExitSignal, BackgroundHangMonitorRegister,
33    HangAnnotation, MonitoredComponentId, MonitoredComponentType,
34};
35use chrono::{DateTime, Local};
36use crossbeam_channel::unbounded;
37use data_url::mime::Mime;
38use devtools_traits::{
39    CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState,
40    ScriptToDevtoolsControlMsg, WorkerId,
41};
42use embedder_traits::user_contents::{UserContentManagerId, UserContents, UserScript};
43use embedder_traits::{
44    EmbedderControlId, EmbedderControlResponse, EmbedderMsg, FocusSequenceNumber,
45    InputEventOutcome, JavaScriptEvaluationError, JavaScriptEvaluationId, MediaSessionActionType,
46    Theme, ViewportDetails, WebDriverScriptCommand,
47};
48use encoding_rs::Encoding;
49use fonts::{FontContext, SystemFontServiceProxy};
50use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
51use http::header::REFRESH;
52use hyper_serde::Serde;
53use ipc_channel::router::ROUTER;
54use js::glue::GetWindowProxyClass;
55use js::jsapi::{GCReason, JS_GC, JSContext as UnsafeJSContext};
56use js::jsval::UndefinedValue;
57use js::rust::ParentRuntime;
58use js::rust::wrappers2::{JS_AddInterruptCallback, SetWindowProxyClass};
59use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory};
60use media::WindowGLContext;
61use metrics::MAX_TASK_NS;
62use net_traits::image_cache::{ImageCache, ImageCacheFactory, ImageCacheResponseMessage};
63use net_traits::request::{Referrer, RequestId};
64use net_traits::response::ResponseInit;
65use net_traits::{
66    FetchMetadata, FetchResponseMsg, Metadata, NetworkError, ResourceFetchTiming, ResourceThreads,
67    ResourceTimingType,
68};
69use paint_api::{CrossProcessPaintApi, PinchZoomInfos, PipelineExitSource};
70use percent_encoding::percent_decode;
71use profile_traits::mem::{ProcessReports, ReportsChan, perform_memory_report};
72use profile_traits::time::ProfilerCategory;
73use profile_traits::time_profile;
74use rustc_hash::{FxHashMap, FxHashSet};
75use script_bindings::cell::DomRefCell;
76use script_bindings::script_runtime::JSContext;
77use script_traits::{
78    ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState,
79    NewPipelineInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage,
80    UpdatePipelineIdReason,
81};
82use servo_arc::Arc as ServoArc;
83use servo_base::cross_process_instant::CrossProcessInstant;
84use servo_base::generic_channel::GenericSender;
85use servo_base::id::{
86    BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, ScriptEventLoopId,
87    TEST_WEBVIEW_ID, WebViewId,
88};
89use servo_base::{Epoch, generic_channel};
90use servo_canvas_traits::webgl::WebGLPipeline;
91use servo_config::opts::{self, DiagnosticsLoggingOption};
92use servo_config::{pref, prefs};
93use servo_constellation_traits::{
94    LoadData, LoadOrigin, NavigationHistoryBehavior, RemoteFocusOperation,
95    ScreenshotReadinessResponse, ScriptToConstellationChan, ScriptToConstellationMessage,
96    ScrollStateUpdate, StructuredSerializedData, TargetSnapshotParams, TraversalDirection,
97    WindowSizeType,
98};
99use servo_url::{ImmutableOrigin, MutableOrigin, OriginSnapshot, ServoUrl};
100use storage_traits::StorageThreads;
101use storage_traits::webstorage_thread::WebStorageType;
102use style::context::QuirksMode;
103use style::error_reporting::RustLogReporter;
104use style::media_queries::MediaList;
105use style::shared_lock::SharedRwLock;
106use style::stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet};
107use style::thread_state::{self, ThreadState};
108use stylo_atoms::Atom;
109use timers::{TimerEventRequest, TimerId, TimerScheduler};
110use url::Position;
111#[cfg(feature = "webgpu")]
112use webgpu_traits::{WebGPUDevice, WebGPUMsg};
113
114use crate::devtools::DevtoolsState;
115use crate::document_collection::DocumentCollection;
116use crate::document_loader::DocumentLoader;
117use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
118    DocumentMethods, DocumentReadyState,
119};
120use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
121use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
122use crate::dom::bindings::conversions::{
123    ConversionResult, SafeFromJSValConvertible, StringificationBehavior,
124};
125use crate::dom::bindings::inheritance::Castable;
126use crate::dom::bindings::reflector::DomGlobal;
127use crate::dom::bindings::root::{Dom, DomRoot};
128use crate::dom::bindings::str::DOMString;
129use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation};
130use crate::dom::customelementregistry::{
131    CallbackReaction, CustomElementDefinition, CustomElementReactionStack,
132};
133use crate::dom::document::focus::FocusableArea;
134use crate::dom::document::{
135    Document, DocumentSource, HasBrowsingContext, IsHTMLDocument, RenderingUpdateReason,
136};
137use crate::dom::element::Element;
138use crate::dom::globalscope::GlobalScope;
139use crate::dom::html::htmliframeelement::{HTMLIFrameElement, IframeContext, ProcessingMode};
140use crate::dom::node::{Node, NodeTraits};
141use crate::dom::servoparser::{ParserContext, ServoParser};
142use crate::dom::types::DebuggerGlobalScope;
143#[cfg(feature = "webgpu")]
144use crate::dom::webgpu::identityhub::IdentityHub;
145use crate::dom::window::Window;
146use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
147use crate::dom::worklet::WorkletThreadPool;
148use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
149use crate::fetch::FetchCanceller;
150use crate::messaging::{
151    CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender,
152    ScriptThreadReceivers, ScriptThreadSenders,
153};
154use crate::microtask::{Microtask, MicrotaskQueue};
155use crate::mime::{APPLICATION, CHARSET, MimeExt, TEXT, XML};
156use crate::navigation::{InProgressLoad, NavigationListener};
157use crate::network_listener::{FetchResponseListener, submit_timing};
158use crate::realms::{enter_auto_realm, enter_realm};
159use crate::script_mutation_observers::ScriptMutationObservers;
160use crate::script_runtime::{
161    CanGc, IntroductionType, JSContextHelper, Runtime, ScriptThreadEventCategory,
162    ThreadSafeJSContext,
163};
164use crate::script_window_proxies::ScriptWindowProxies;
165use crate::task_queue::TaskQueue;
166use crate::webdriver_handlers::jsval_to_webdriver;
167use crate::{devtools, webdriver_handlers};
168
169thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
170
171fn with_optional_script_thread<R>(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R {
172    SCRIPT_THREAD_ROOT.with(|root| {
173        f(root
174            .get()
175            .and_then(|script_thread| unsafe { script_thread.as_ref() }))
176    })
177}
178
179pub(crate) fn with_script_thread<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
180    with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
181}
182
183// We borrow the incomplete parser contexts mutably during parsing,
184// which is fine except that parsing can trigger evaluation,
185// which can trigger GC, and so we can end up tracing the script
186// thread during parsing. For this reason, we don't trace the
187// incomplete parser contexts during GC.
188pub(crate) struct IncompleteParserContexts(RefCell<Vec<(PipelineId, ParserContext)>>);
189
190unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
191
192type NodeIdSet = HashSet<String>;
193
194/// A simple guard structure that restore the user interacting state when dropped
195#[derive(Default)]
196pub(crate) struct ScriptUserInteractingGuard {
197    was_interacting: bool,
198    user_interaction_cell: Rc<Cell<bool>>,
199}
200
201impl ScriptUserInteractingGuard {
202    fn new(user_interaction_cell: Rc<Cell<bool>>) -> Self {
203        let was_interacting = user_interaction_cell.get();
204        user_interaction_cell.set(true);
205        Self {
206            was_interacting,
207            user_interaction_cell,
208        }
209    }
210}
211
212impl Drop for ScriptUserInteractingGuard {
213    fn drop(&mut self) {
214        self.user_interaction_cell.set(self.was_interacting)
215    }
216}
217
218/// This is the `ScriptThread`'s version of [`UserContents`] with the difference that user
219/// stylesheets are represented as parsed `DocumentStyleSheet`s instead of simple source strings.
220struct ScriptThreadUserContents {
221    user_scripts: Rc<Vec<UserScript>>,
222    user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
223}
224
225impl ScriptThreadUserContents {
226    fn new(user_contents: UserContents, shared_locks: &SharedRwLocks) -> Self {
227        let user_stylesheets = user_contents
228            .stylesheets
229            .iter()
230            .map(|user_stylesheet| {
231                DocumentStyleSheet(ServoArc::new(Stylesheet::from_str(
232                    user_stylesheet.source(),
233                    user_stylesheet.url().into(),
234                    Origin::User,
235                    ServoArc::new(shared_locks.ua_or_user.wrap(MediaList::empty())),
236                    shared_locks.ua_or_user.clone(),
237                    None,
238                    Some(&RustLogReporter),
239                    QuirksMode::NoQuirks,
240                    AllowImportRules::Yes,
241                )))
242            })
243            .collect();
244        Self {
245            user_scripts: Rc::new(user_contents.scripts),
246            user_stylesheets: Rc::new(user_stylesheets),
247        }
248    }
249}
250
251#[derive(Clone, MallocSizeOf)]
252pub struct SharedRwLocks {
253    pub author: SharedRwLock,
254    pub ua_or_user: SharedRwLock,
255}
256
257impl Default for SharedRwLocks {
258    fn default() -> Self {
259        Self {
260            author: SharedRwLock::new(),
261            ua_or_user: SharedRwLock::new(),
262        }
263    }
264}
265
266#[derive(JSTraceable)]
267// ScriptThread instances are rooted on creation, so this is okay
268#[cfg_attr(crown, expect(crown::unrooted_must_root))]
269pub struct ScriptThread {
270    /// A reference to the currently operating `ScriptThread`. This should always be
271    /// upgradable to an `Rc` as long as the `ScriptThread` is running.
272    #[no_trace]
273    this: Weak<ScriptThread>,
274
275    /// <https://html.spec.whatwg.org/multipage/#last-render-opportunity-time>
276    last_render_opportunity_time: Cell<Option<Instant>>,
277
278    /// The documents for pipelines managed by this thread
279    documents: DomRefCell<DocumentCollection>,
280    /// The window proxies known by this thread
281    window_proxies: Rc<ScriptWindowProxies>,
282    /// A list of data pertaining to loads that have not yet received a network response
283    incomplete_loads: DomRefCell<Vec<InProgressLoad>>,
284    /// A vector containing parser contexts which have not yet been fully processed
285    incomplete_parser_contexts: IncompleteParserContexts,
286    /// An [`ImageCacheFactory`] to use for creating [`ImageCache`]s for all of the
287    /// child `Pipeline`s.
288    #[no_trace]
289    image_cache_factory: Arc<dyn ImageCacheFactory>,
290
291    /// A [`ScriptThreadReceivers`] holding all of the incoming `Receiver`s for messages
292    /// to this [`ScriptThread`].
293    receivers: ScriptThreadReceivers,
294
295    /// A [`ScriptThreadSenders`] that holds all outgoing sending channels necessary to communicate
296    /// to other parts of Servo.
297    senders: ScriptThreadSenders,
298
299    /// A handle to the resource thread. This is an `Arc` to avoid running out of file descriptors if
300    /// there are many iframes.
301    #[no_trace]
302    resource_threads: ResourceThreads,
303
304    #[no_trace]
305    storage_threads: StorageThreads,
306
307    /// A queue of tasks to be executed in this script-thread.
308    task_queue: TaskQueue<MainThreadScriptMsg>,
309
310    /// The dedicated means of communication with the background-hang-monitor for this script-thread.
311    #[no_trace]
312    background_hang_monitor: Box<dyn BackgroundHangMonitor>,
313    /// A flag set to `true` by the BHM on exit, and checked from within the interrupt handler.
314    closing: Arc<AtomicBool>,
315
316    /// A [`TimerScheduler`] used to schedule timers for this [`ScriptThread`]. Timers are handled
317    /// in the [`ScriptThread`] event loop.
318    #[no_trace]
319    timer_scheduler: RefCell<TimerScheduler>,
320
321    /// A proxy to the `SystemFontService` to use for accessing system font lists.
322    #[no_trace]
323    system_font_service: Arc<SystemFontServiceProxy>,
324
325    /// The JavaScript runtime.
326    js_runtime: Rc<Runtime>,
327
328    /// List of pipelines that have been owned and closed by this script thread.
329    #[no_trace]
330    closed_pipelines: DomRefCell<FxHashSet<PipelineId>>,
331
332    /// <https://html.spec.whatwg.org/multipage/#microtask-queue>
333    microtask_queue: Rc<MicrotaskQueue>,
334
335    mutation_observers: Rc<ScriptMutationObservers>,
336
337    /// A handle to the WebGL thread
338    #[no_trace]
339    webgl_chan: Option<WebGLPipeline>,
340
341    /// The WebXR device registry
342    #[no_trace]
343    #[cfg(feature = "webxr")]
344    webxr_registry: Option<webxr_api::Registry>,
345
346    /// The worklet thread pool
347    worklet_thread_pool: DomRefCell<Option<Rc<WorkletThreadPool>>>,
348
349    /// A list of pipelines containing documents that finished loading all their blocking
350    /// resources during a turn of the event loop.
351    docs_with_no_blocking_loads: DomRefCell<FxHashSet<Dom<Document>>>,
352
353    /// <https://html.spec.whatwg.org/multipage/#custom-element-reactions-stack>
354    custom_element_reaction_stack: Rc<CustomElementReactionStack>,
355
356    /// Cross-process access to `Paint`'s API.
357    #[no_trace]
358    paint_api: CrossProcessPaintApi,
359
360    /// Periodically print out on which events script threads spend their processing time.
361    profile_script_events: bool,
362
363    /// Unminify Javascript.
364    unminify_js: bool,
365
366    /// Directory with stored unminified scripts
367    local_script_source: Option<String>,
368
369    /// Unminify Css.
370    unminify_css: bool,
371
372    /// The [`SharedRwLocks`] that are used by all Stylo operations in this ScriptThread.
373    #[no_trace]
374    shared_style_locks: SharedRwLocks,
375
376    /// A map from [`UserContentManagerId`] to its [`UserContents`]. This is initialized
377    /// with a copy of the map in constellation (via the `InitialScriptState`). After that,
378    /// the constellation forwards any mutations to this `ScriptThread` using messages.
379    #[no_trace]
380    user_contents_for_manager_id:
381        RefCell<FxHashMap<UserContentManagerId, ScriptThreadUserContents>>,
382
383    /// Application window's GL Context for Media player
384    #[no_trace]
385    player_context: WindowGLContext,
386
387    /// A map from pipelines to all owned nodes ever created in this script thread
388    #[no_trace]
389    pipeline_to_node_ids: DomRefCell<FxHashMap<PipelineId, NodeIdSet>>,
390
391    /// Code is running as a consequence of a user interaction
392    is_user_interacting: Rc<Cell<bool>>,
393
394    /// Identity manager for WebGPU resources
395    #[no_trace]
396    #[cfg(feature = "webgpu")]
397    gpu_id_hub: Arc<IdentityHub>,
398
399    /// A factory for making new layouts. This allows layout to depend on script.
400    #[no_trace]
401    layout_factory: Arc<dyn LayoutFactory>,
402
403    /// The [`TimerId`] of a ScriptThread-scheduled "update the rendering" call, if any.
404    /// The ScriptThread schedules calls to "update the rendering," but the renderer can
405    /// also do this when animating. Renderer-based calls always take precedence.
406    #[no_trace]
407    scheduled_update_the_rendering: RefCell<Option<TimerId>>,
408
409    /// Whether an animation tick or ScriptThread-triggered rendering update is pending. This might
410    /// either be because the Servo renderer is managing animations and the [`ScriptThread`] has
411    /// received a [`ScriptThreadMessage::TickAllAnimations`] message, because the [`ScriptThread`]
412    /// itself is managing animations the timer fired triggering a [`ScriptThread`]-based
413    /// animation tick, or if there are no animations running and the [`ScriptThread`] has noticed a
414    /// change that requires a rendering update.
415    needs_rendering_update: Arc<AtomicBool>,
416
417    debugger_global: Dom<DebuggerGlobalScope>,
418
419    debugger_paused: Cell<bool>,
420
421    /// A list of URLs that can access privileged internal APIs.
422    #[no_trace]
423    privileged_urls: Vec<ServoUrl>,
424
425    devtools_state: DevtoolsState,
426}
427
428struct BHMExitSignal {
429    closing: Arc<AtomicBool>,
430    js_context: ThreadSafeJSContext,
431}
432
433impl BackgroundHangMonitorExitSignal for BHMExitSignal {
434    fn signal_to_exit(&self) {
435        self.closing.store(true, Ordering::SeqCst);
436        self.js_context.request_interrupt_callback();
437    }
438}
439
440#[expect(unsafe_code)]
441unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool {
442    let res = ScriptThread::can_continue_running();
443    if !res {
444        ScriptThread::prepare_for_shutdown();
445    }
446    res
447}
448
449/// In the event of thread panic, all data on the stack runs its destructor. However, there
450/// are no reachable, owning pointers to the DOM memory, so it never gets freed by default
451/// when the script thread fails. The ScriptMemoryFailsafe uses the destructor bomb pattern
452/// to forcibly tear down the JS realms for pages associated with the failing ScriptThread.
453struct ScriptMemoryFailsafe<'a> {
454    owner: Option<&'a ScriptThread>,
455}
456
457impl<'a> ScriptMemoryFailsafe<'a> {
458    fn neuter(&mut self) {
459        self.owner = None;
460    }
461
462    fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> {
463        ScriptMemoryFailsafe { owner: Some(owner) }
464    }
465}
466
467impl Drop for ScriptMemoryFailsafe<'_> {
468    fn drop(&mut self) {
469        if let Some(owner) = self.owner {
470            for (_, document) in owner.documents.borrow().iter() {
471                document.window().clear_js_runtime_for_script_deallocation();
472            }
473        }
474    }
475}
476
477impl ScriptThreadFactory for ScriptThread {
478    fn create(
479        state: InitialScriptState,
480        layout_factory: Arc<dyn LayoutFactory>,
481        image_cache_factory: Arc<dyn ImageCacheFactory>,
482        background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
483    ) -> JoinHandle<()> {
484        // Setup pipeline-namespace-installing for all threads in this process.
485        // Idempotent in single-process mode.
486        PipelineNamespace::set_installer_sender(state.namespace_request_sender.clone());
487
488        let script_thread_id = state.id;
489        thread::Builder::new()
490            .name(format!("Script#{script_thread_id}"))
491            .stack_size(8 * 1024 * 1024) // 8 MiB stack to be consistent with other browsers.
492            .spawn(move || {
493                profile_traits::debug_event!(
494                    "ScriptThread::spawned",
495                    script_thread_id = script_thread_id.to_string()
496                );
497                thread_state::initialize(ThreadState::SCRIPT);
498                PipelineNamespace::install(state.pipeline_namespace_id);
499                ScriptEventLoopId::install(state.id);
500                let memory_profiler_sender = state.memory_profiler_sender.clone();
501                let reporter_name = format!("script-reporter-{script_thread_id:?}");
502                let (script_thread, mut cx) = ScriptThread::new(
503                    state,
504                    layout_factory,
505                    image_cache_factory,
506                    background_hang_monitor_register,
507                );
508                SCRIPT_THREAD_ROOT.with(|root| {
509                    root.set(Some(Rc::as_ptr(&script_thread)));
510                });
511                let mut failsafe = ScriptMemoryFailsafe::new(&script_thread);
512
513                memory_profiler_sender.run_with_memory_reporting(
514                    || script_thread.start(&mut cx),
515                    reporter_name,
516                    ScriptEventLoopSender::MainThread(script_thread.senders.self_sender.clone()),
517                    CommonScriptMsg::CollectReports,
518                );
519
520                // This must always be the very last operation performed before the thread completes
521                failsafe.neuter();
522            })
523            .expect("Thread spawning failed")
524    }
525}
526
527impl ScriptThread {
528    pub(crate) fn runtime_handle() -> ParentRuntime {
529        with_optional_script_thread(|script_thread| {
530            script_thread.unwrap().js_runtime.prepare_for_new_child()
531        })
532    }
533
534    pub(crate) fn can_continue_running() -> bool {
535        with_script_thread(|script_thread| script_thread.can_continue_running_inner())
536    }
537
538    pub(crate) fn prepare_for_shutdown() {
539        with_script_thread(|script_thread| {
540            script_thread.prepare_for_shutdown_inner();
541        })
542    }
543
544    pub(crate) fn mutation_observers() -> Rc<ScriptMutationObservers> {
545        with_script_thread(|script_thread| script_thread.mutation_observers.clone())
546    }
547
548    pub(crate) fn microtask_queue() -> Rc<MicrotaskQueue> {
549        with_script_thread(|script_thread| script_thread.microtask_queue.clone())
550    }
551
552    pub(crate) fn shared_style_locks(&self) -> &SharedRwLocks {
553        &self.shared_style_locks
554    }
555
556    pub(crate) fn mark_document_with_no_blocked_loads(doc: &Document) {
557        with_script_thread(|script_thread| {
558            script_thread
559                .docs_with_no_blocking_loads
560                .borrow_mut()
561                .insert(Dom::from_ref(doc));
562        })
563    }
564
565    pub(crate) fn page_headers_available(
566        webview_id: WebViewId,
567        pipeline_id: PipelineId,
568        metadata: Option<&Metadata>,
569        origin: MutableOrigin,
570        cx: &mut js::context::JSContext,
571    ) -> Option<DomRoot<ServoParser>> {
572        with_script_thread(|script_thread| {
573            script_thread.handle_page_headers_available(
574                webview_id,
575                pipeline_id,
576                metadata,
577                origin,
578                cx,
579            )
580        })
581    }
582
583    /// Process a single event as if it were the next event
584    /// in the queue for this window event-loop.
585    /// Returns a boolean indicating whether further events should be processed.
586    pub(crate) fn process_event(msg: CommonScriptMsg, cx: &mut js::context::JSContext) -> bool {
587        with_script_thread(|script_thread| {
588            if !script_thread.can_continue_running_inner() {
589                return false;
590            }
591            script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg), cx);
592            true
593        })
594    }
595
596    /// Schedule a [`TimerEventRequest`] on this [`ScriptThread`]'s [`TimerScheduler`].
597    pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> TimerId {
598        self.timer_scheduler.borrow_mut().schedule_timer(request)
599    }
600
601    /// Cancel a the [`TimerEventRequest`] for the given [`TimerId`] on this
602    /// [`ScriptThread`]'s [`TimerScheduler`].
603    pub(crate) fn cancel_timer(&self, timer_id: TimerId) {
604        self.timer_scheduler.borrow_mut().cancel_timer(timer_id)
605    }
606
607    // https://html.spec.whatwg.org/multipage/#await-a-stable-state
608    pub(crate) fn await_stable_state(task: Microtask) {
609        with_script_thread(|script_thread| {
610            script_thread
611                .microtask_queue
612                .enqueue(task, script_thread.get_cx());
613        });
614    }
615
616    /// Check that two origins are "similar enough",
617    /// for now only used to prevent cross-origin JS url evaluation.
618    ///
619    /// <https://github.com/whatwg/html/issues/2591>
620    fn check_load_origin(source: &LoadOrigin, target: &OriginSnapshot) -> bool {
621        match (source, target.immutable()) {
622            (LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => {
623                // Always allow loads initiated by the constellation or webdriver.
624                true
625            },
626            (_, ImmutableOrigin::Opaque(_)) => {
627                // If the target is opaque, allow.
628                // This covers newly created about:blank auxiliaries, and iframe with no src.
629                // TODO: https://github.com/servo/servo/issues/22879
630                true
631            },
632            (LoadOrigin::Script(source_origin), _) => source_origin.same_origin_domain(target),
633        }
634    }
635
636    /// Inform the `ScriptThread` that it should make a call to
637    /// [`ScriptThread::update_the_rendering`] as soon as possible, as the rendering
638    /// update timer has fired or the renderer has asked us for a new rendering update.
639    pub(crate) fn set_needs_rendering_update(&self) {
640        self.needs_rendering_update.store(true, Ordering::Relaxed);
641    }
642
643    /// <https://html.spec.whatwg.org/multipage/#navigate-to-a-javascript:-url>
644    pub(crate) fn can_navigate_to_javascript_url(
645        cx: &mut js::context::JSContext,
646        initiator_global: &GlobalScope,
647        target_global: &GlobalScope,
648        load_data: &mut LoadData,
649        container: Option<&Element>,
650    ) -> bool {
651        // Step 3. If initiatorOrigin is not same origin-domain with targetNavigable's active document's origin, then return.
652        //
653        // Important re security. See https://github.com/servo/servo/issues/23373
654        if !Self::check_load_origin(&load_data.load_origin, &target_global.origin().snapshot()) {
655            return false;
656        }
657
658        // Step 5: If the result of should navigation request of type be blocked by
659        // Content Security Policy? given request and cspNavigationType is "Blocked", then return. [CSP]
660        if initiator_global
661            .get_csp_list()
662            .should_navigation_request_be_blocked(cx, initiator_global, load_data, container)
663        {
664            return false;
665        }
666
667        true
668    }
669
670    /// Attempt to navigate a global to a javascript: URL. Returns true if a new document is created.
671    /// <https://html.spec.whatwg.org/multipage/#navigate-to-a-javascript:-url>
672    pub(crate) fn navigate_to_javascript_url(
673        cx: &mut js::context::JSContext,
674        initiator_global: &GlobalScope,
675        target_global: &GlobalScope,
676        load_data: &mut LoadData,
677        container: Option<&Element>,
678        initial_insertion: Option<bool>,
679    ) -> bool {
680        // 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.
681        if !Self::can_navigate_to_javascript_url(
682            cx,
683            initiator_global,
684            target_global,
685            load_data,
686            container,
687        ) {
688            return false;
689        }
690
691        // Step 7. Let newDocument be the result of evaluating a javascript: URL given targetNavigable,
692        // url, initiatorOrigin, and userInvolvement.
693        let Some(body) = Self::eval_js_url(cx, target_global, &load_data.url) else {
694            // Step 8. If newDocument is null:
695            let window_proxy = target_global.as_window().window_proxy();
696            if let Some(frame_element) = window_proxy
697                .frame_element()
698                .and_then(Castable::downcast::<HTMLIFrameElement>)
699            {
700                // 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.
701                if initial_insertion == Some(true) && frame_element.is_initial_blank_document() {
702                    frame_element.run_iframe_load_event_steps(cx);
703                }
704            }
705            // Step 8.2. Return.
706            return false;
707        };
708
709        // Step 11. of <https://html.spec.whatwg.org/multipage/#evaluate-a-javascript:-url>.
710        // Let response be a new response with
711        // URL         targetNavigable's active document's URL
712        // header list « (`Content-Type`, `text/html;charset=utf-8`) »
713        // body        the UTF-8 encoding of result, as a body
714        load_data.js_eval_result = Some(body);
715        load_data.url = target_global.get_url();
716        load_data
717            .headers
718            .typed_insert(headers::ContentType::from(mime::TEXT_HTML_UTF_8));
719        true
720    }
721
722    pub(crate) fn get_top_level_for_browsing_context(
723        sender_webview_id: WebViewId,
724        sender_pipeline_id: PipelineId,
725        browsing_context_id: BrowsingContextId,
726    ) -> Option<WebViewId> {
727        with_script_thread(|script_thread| {
728            script_thread.ask_constellation_for_top_level_info(
729                sender_webview_id,
730                sender_pipeline_id,
731                browsing_context_id,
732            )
733        })
734    }
735
736    pub(crate) fn find_window(id: PipelineId) -> Option<DomRoot<Window>> {
737        with_script_thread(|script_thread| script_thread.documents.borrow().find_window(id))
738    }
739
740    pub(crate) fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
741        with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
742    }
743
744    /// Creates a guard that sets user_is_interacting to true and returns the
745    /// state of user_is_interacting on drop of the guard.
746    /// Notice that you need to use `let _guard = ...` as `let _ = ...` is not enough
747    #[must_use]
748    pub(crate) fn user_interacting_guard() -> ScriptUserInteractingGuard {
749        with_script_thread(|script_thread| {
750            ScriptUserInteractingGuard::new(script_thread.is_user_interacting.clone())
751        })
752    }
753
754    pub(crate) fn is_user_interacting() -> bool {
755        with_script_thread(|script_thread| script_thread.is_user_interacting.get())
756    }
757
758    pub(crate) fn get_fully_active_document_ids(&self) -> FxHashSet<PipelineId> {
759        self.documents
760            .borrow()
761            .iter()
762            .filter_map(|(id, document)| {
763                if document.is_fully_active() {
764                    Some(id)
765                } else {
766                    None
767                }
768            })
769            .fold(FxHashSet::default(), |mut set, id| {
770                let _ = set.insert(id);
771                set
772            })
773    }
774
775    pub(crate) fn window_proxies() -> Rc<ScriptWindowProxies> {
776        with_script_thread(|script_thread| script_thread.window_proxies.clone())
777    }
778
779    pub(crate) fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
780        with_script_thread(|script_thread| {
781            script_thread.window_proxies.find_window_proxy_by_name(name)
782        })
783    }
784
785    /// The worklet will use the given `ImageCache`.
786    pub(crate) fn worklet_thread_pool(image_cache: Arc<dyn ImageCache>) -> Rc<WorkletThreadPool> {
787        with_optional_script_thread(|script_thread| {
788            let script_thread = script_thread.unwrap();
789            script_thread
790                .worklet_thread_pool
791                .borrow_mut()
792                .get_or_insert_with(|| {
793                    let init = WorkletGlobalScopeInit {
794                        to_script_thread_sender: script_thread.senders.self_sender.clone(),
795                        resource_threads: script_thread.resource_threads.clone(),
796                        storage_threads: script_thread.storage_threads.clone(),
797                        mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(),
798                        time_profiler_chan: script_thread.senders.time_profiler_sender.clone(),
799                        devtools_chan: script_thread.senders.devtools_server_sender.clone(),
800                        to_constellation_sender: script_thread
801                            .senders
802                            .pipeline_to_constellation_sender
803                            .clone(),
804                        to_embedder_sender: script_thread
805                            .senders
806                            .pipeline_to_embedder_sender
807                            .clone(),
808                        image_cache,
809                        #[cfg(feature = "webgpu")]
810                        gpu_id_hub: script_thread.gpu_id_hub.clone(),
811                    };
812                    Rc::new(WorkletThreadPool::spawn(init))
813                })
814                .clone()
815        })
816    }
817
818    fn handle_register_paint_worklet(
819        &self,
820        pipeline_id: PipelineId,
821        name: Atom,
822        properties: Vec<Atom>,
823        painter: Box<dyn Painter>,
824    ) {
825        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
826            warn!("Paint worklet registered after pipeline {pipeline_id} closed.");
827            return;
828        };
829
830        window
831            .layout_mut()
832            .register_paint_worklet_modules(name, properties, painter);
833    }
834
835    pub(crate) fn custom_element_reaction_stack() -> Rc<CustomElementReactionStack> {
836        with_optional_script_thread(|script_thread| {
837            script_thread
838                .as_ref()
839                .unwrap()
840                .custom_element_reaction_stack
841                .clone()
842        })
843    }
844
845    pub(crate) fn enqueue_callback_reaction(
846        element: &Element,
847        reaction: CallbackReaction,
848        definition: Option<Rc<CustomElementDefinition>>,
849    ) {
850        with_script_thread(|script_thread| {
851            script_thread
852                .custom_element_reaction_stack
853                .enqueue_callback_reaction(element, reaction, definition);
854        })
855    }
856
857    pub(crate) fn enqueue_upgrade_reaction(
858        element: &Element,
859        definition: Rc<CustomElementDefinition>,
860    ) {
861        with_script_thread(|script_thread| {
862            script_thread
863                .custom_element_reaction_stack
864                .enqueue_upgrade_reaction(element, definition);
865        })
866    }
867
868    pub(crate) fn invoke_backup_element_queue(cx: &mut js::context::JSContext) {
869        with_script_thread(|script_thread| {
870            script_thread
871                .custom_element_reaction_stack
872                .invoke_backup_element_queue(cx);
873        })
874    }
875
876    pub(crate) fn save_node_id(pipeline: PipelineId, node_id: String) {
877        with_script_thread(|script_thread| {
878            script_thread
879                .pipeline_to_node_ids
880                .borrow_mut()
881                .entry(pipeline)
882                .or_default()
883                .insert(node_id);
884        })
885    }
886
887    pub(crate) fn has_node_id(pipeline: PipelineId, node_id: &str) -> bool {
888        with_script_thread(|script_thread| {
889            script_thread
890                .pipeline_to_node_ids
891                .borrow()
892                .get(&pipeline)
893                .is_some_and(|node_ids| node_ids.contains(node_id))
894        })
895    }
896
897    /// Creates a new script thread.
898    #[servo_tracing::instrument(name = "ScripThread::new", level = "debug", skip_all)]
899    pub(crate) fn new(
900        state: InitialScriptState,
901        layout_factory: Arc<dyn LayoutFactory>,
902        image_cache_factory: Arc<dyn ImageCacheFactory>,
903        background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
904    ) -> (Rc<ScriptThread>, js::context::JSContext) {
905        let (self_sender, self_receiver) = unbounded();
906        let mut runtime =
907            Runtime::new(Some(ScriptEventLoopSender::MainThread(self_sender.clone())));
908
909        // SAFETY: We ensure that only one JSContext exists in this thread.
910        // This is the first one and the only one
911        let mut cx = unsafe { runtime.cx() };
912
913        unsafe {
914            SetWindowProxyClass(&cx, GetWindowProxyClass());
915            JS_AddInterruptCallback(&cx, Some(interrupt_callback));
916        }
917
918        let constellation_receiver = state
919            .constellation_to_script_receiver
920            .route_preserving_errors();
921
922        // Ask the router to proxy IPC messages from the devtools to us.
923        let devtools_server_sender = state.devtools_server_sender;
924        let (ipc_devtools_sender, ipc_devtools_receiver) = generic_channel::channel().unwrap();
925        let devtools_server_receiver = ipc_devtools_receiver.route_preserving_errors();
926
927        let task_queue = TaskQueue::new(self_receiver, self_sender.clone());
928
929        let closing = Arc::new(AtomicBool::new(false));
930        let background_hang_monitor_exit_signal = BHMExitSignal {
931            closing: closing.clone(),
932            js_context: runtime.thread_safe_js_context(),
933        };
934
935        let background_hang_monitor = background_hang_monitor_register.register_component(
936            // TODO: We shouldn't rely on this PipelineId as a ScriptThread can have multiple
937            // Pipelines and any of them might disappear at any time.
938            MonitoredComponentId(state.id, MonitoredComponentType::Script),
939            Duration::from_millis(1000),
940            Duration::from_millis(5000),
941            Box::new(background_hang_monitor_exit_signal),
942        );
943
944        let (image_cache_sender, image_cache_receiver) = unbounded();
945
946        let receivers = ScriptThreadReceivers {
947            constellation_receiver,
948            image_cache_receiver,
949            devtools_server_receiver,
950            // Initialized to `never` until WebGPU is initialized.
951            #[cfg(feature = "webgpu")]
952            webgpu_receiver: RefCell::new(crossbeam_channel::never()),
953        };
954
955        let opts = opts::get();
956        let senders = ScriptThreadSenders {
957            self_sender,
958            #[cfg(feature = "bluetooth")]
959            bluetooth_sender: state.bluetooth_sender,
960            constellation_sender: state.constellation_to_script_sender,
961            pipeline_to_constellation_sender: state.script_to_constellation_sender,
962            pipeline_to_embedder_sender: state.script_to_embedder_sender.clone(),
963            image_cache_sender,
964            time_profiler_sender: state.time_profiler_sender,
965            memory_profiler_sender: state.memory_profiler_sender,
966            devtools_server_sender,
967            devtools_client_to_script_thread_sender: ipc_devtools_sender,
968        };
969
970        let microtask_queue = runtime.microtask_queue.clone();
971        #[cfg(feature = "webgpu")]
972        let gpu_id_hub = Arc::new(IdentityHub::default());
973
974        let debugger_pipeline_id = PipelineId::new();
975        let script_to_constellation_chan = ScriptToConstellationChan {
976            sender: senders.pipeline_to_constellation_sender.clone(),
977            // This channel is not expected to be used, so the `WebViewId` that we set here
978            // does not matter.
979            // TODO: Look at ways of removing the channel entirely for debugger globals.
980            webview_id: TEST_WEBVIEW_ID,
981            pipeline_id: debugger_pipeline_id,
982        };
983        let debugger_global = DebuggerGlobalScope::new(
984            PipelineId::new(),
985            senders.devtools_server_sender.clone(),
986            senders.devtools_client_to_script_thread_sender.clone(),
987            senders.memory_profiler_sender.clone(),
988            senders.time_profiler_sender.clone(),
989            script_to_constellation_chan,
990            senders.pipeline_to_embedder_sender.clone(),
991            state.resource_threads.clone(),
992            state.storage_threads.clone(),
993            #[cfg(feature = "webgpu")]
994            gpu_id_hub.clone(),
995            &mut cx,
996        );
997
998        debugger_global.execute(&mut cx);
999
1000        let shared_style_locks = Default::default();
1001        let user_contents_for_manager_id =
1002            FxHashMap::from_iter(state.user_contents_for_manager_id.into_iter().map(
1003                |(user_content_manager_id, user_contents)| {
1004                    (
1005                        user_content_manager_id,
1006                        ScriptThreadUserContents::new(user_contents, &shared_style_locks),
1007                    )
1008                },
1009            ));
1010
1011        (
1012            Rc::new_cyclic(|weak_script_thread| {
1013                runtime.set_script_thread(weak_script_thread.clone());
1014                Self {
1015                    documents: DomRefCell::new(DocumentCollection::default()),
1016                    last_render_opportunity_time: Default::default(),
1017                    window_proxies: Default::default(),
1018                    incomplete_loads: DomRefCell::new(vec![]),
1019                    incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])),
1020                    senders,
1021                    receivers,
1022                    image_cache_factory,
1023                    resource_threads: state.resource_threads,
1024                    storage_threads: state.storage_threads,
1025                    task_queue,
1026                    background_hang_monitor,
1027                    closing,
1028                    timer_scheduler: Default::default(),
1029                    microtask_queue,
1030                    js_runtime: Rc::new(runtime),
1031                    closed_pipelines: DomRefCell::new(FxHashSet::default()),
1032                    mutation_observers: Default::default(),
1033                    system_font_service: Arc::new(state.system_font_service.to_proxy()),
1034                    webgl_chan: state.webgl_chan,
1035                    #[cfg(feature = "webxr")]
1036                    webxr_registry: state.webxr_registry,
1037                    worklet_thread_pool: Default::default(),
1038                    docs_with_no_blocking_loads: Default::default(),
1039                    custom_element_reaction_stack: Rc::new(CustomElementReactionStack::new()),
1040                    paint_api: state.cross_process_paint_api,
1041                    profile_script_events: opts
1042                        .debug
1043                        .is_enabled(DiagnosticsLoggingOption::ProfileScriptEvents),
1044                    unminify_js: opts.unminify_js,
1045                    local_script_source: opts.local_script_source.clone(),
1046                    unminify_css: opts.unminify_css,
1047                    shared_style_locks,
1048                    user_contents_for_manager_id: RefCell::new(user_contents_for_manager_id),
1049                    player_context: state.player_context,
1050                    pipeline_to_node_ids: Default::default(),
1051                    is_user_interacting: Rc::new(Cell::new(false)),
1052                    #[cfg(feature = "webgpu")]
1053                    gpu_id_hub,
1054                    layout_factory,
1055                    scheduled_update_the_rendering: Default::default(),
1056                    needs_rendering_update: Arc::new(AtomicBool::new(false)),
1057                    debugger_global: debugger_global.as_traced(),
1058                    debugger_paused: Cell::new(false),
1059                    privileged_urls: state.privileged_urls,
1060                    this: weak_script_thread.clone(),
1061                    devtools_state: Default::default(),
1062                }
1063            }),
1064            cx,
1065        )
1066    }
1067
1068    #[expect(unsafe_code)]
1069    pub(crate) fn get_cx(&self) -> JSContext {
1070        unsafe { JSContext::from_ptr(js::rust::Runtime::get().unwrap().as_ptr()) }
1071    }
1072
1073    /// Check if we are closing.
1074    fn can_continue_running_inner(&self) -> bool {
1075        if self.closing.load(Ordering::SeqCst) {
1076            return false;
1077        }
1078        true
1079    }
1080
1081    /// We are closing, ensure no script can run and potentially hang.
1082    fn prepare_for_shutdown_inner(&self) {
1083        let docs = self.documents.borrow();
1084        for (_, document) in docs.iter() {
1085            document
1086                .owner_global()
1087                .task_manager()
1088                .cancel_all_tasks_and_ignore_future_tasks();
1089        }
1090    }
1091
1092    /// Starts the script thread. After calling this method, the script thread will loop receiving
1093    /// messages on its port.
1094    pub(crate) fn start(&self, cx: &mut js::context::JSContext) {
1095        debug!("Starting script thread.");
1096        while self.handle_msgs(cx) {
1097            // Go on...
1098            debug!("Running script thread.");
1099        }
1100        debug!("Stopped script thread.");
1101    }
1102
1103    /// Process input events as part of a "update the rendering task".
1104    fn process_pending_input_events(
1105        &self,
1106        cx: &mut js::context::JSContext,
1107        pipeline_id: PipelineId,
1108    ) {
1109        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
1110            warn!("Processing pending input events for closed pipeline {pipeline_id}.");
1111            return;
1112        };
1113        // Do not handle events if the BC has been, or is being, discarded
1114        if document.window().Closed() {
1115            warn!("Input event sent to a pipeline with a closed window {pipeline_id}.");
1116            return;
1117        }
1118        if !document.event_handler().has_pending_input_events() {
1119            return;
1120        }
1121
1122        let _guard = ScriptUserInteractingGuard::new(self.is_user_interacting.clone());
1123        document.event_handler().handle_pending_input_events(cx);
1124    }
1125
1126    fn cancel_scheduled_update_the_rendering(&self) {
1127        if let Some(timer_id) = self.scheduled_update_the_rendering.borrow_mut().take() {
1128            self.timer_scheduler.borrow_mut().cancel_timer(timer_id);
1129        }
1130    }
1131
1132    fn schedule_update_the_rendering_timer_if_necessary(&self, delay: Duration) {
1133        if self.scheduled_update_the_rendering.borrow().is_some() {
1134            return;
1135        }
1136
1137        debug!("Scheduling ScriptThread animation frame.");
1138        let trigger_script_thread_animation = self.needs_rendering_update.clone();
1139        let timer_id = self.schedule_timer(TimerEventRequest {
1140            callback: Box::new(move || {
1141                trigger_script_thread_animation.store(true, Ordering::Relaxed);
1142            }),
1143            duration: delay,
1144        });
1145
1146        *self.scheduled_update_the_rendering.borrow_mut() = Some(timer_id);
1147    }
1148
1149    /// <https://html.spec.whatwg.org/multipage/#update-the-rendering>
1150    ///
1151    /// Attempt to update the rendering and then do a microtask checkpoint if rendering was
1152    /// actually updated.
1153    ///
1154    /// Returns true if any reflows produced a new display list.
1155    pub(crate) fn update_the_rendering(&self, cx: &mut js::context::JSContext) -> bool {
1156        self.last_render_opportunity_time.set(Some(Instant::now()));
1157        self.cancel_scheduled_update_the_rendering();
1158        self.needs_rendering_update.store(false, Ordering::Relaxed);
1159
1160        if !self.can_continue_running_inner() {
1161            return false;
1162        }
1163
1164        // TODO(#31242): the filtering of docs is extended to not exclude the ones that
1165        // has pending initial observation targets
1166        // https://w3c.github.io/IntersectionObserver/#pending-initial-observation
1167
1168        // > 2. Let docs be all fully active Document objects whose relevant agent's event loop
1169        // > is eventLoop, sorted arbitrarily except that the following conditions must be
1170        // > met:
1171        //
1172        // > Any Document B whose container document is A must be listed after A in the
1173        // > list.
1174        //
1175        // > If there are two documents A and B that both have the same non-null container
1176        // > document C, then the order of A and B in the list must match the
1177        // > shadow-including tree order of their respective navigable containers in C's
1178        // > node tree.
1179        //
1180        // > In the steps below that iterate over docs, each Document must be processed in
1181        // > the order it is found in the list.
1182        let documents_in_order = self.documents.borrow().documents_in_order();
1183
1184        // TODO: The specification reads: "for doc in docs" at each step whereas this runs all
1185        // steps per doc in docs. Currently `<iframe>` resizing depends on a parent being able to
1186        // queue resize events on a child and have those run in the same call to this method, so
1187        // that needs to be sorted out to fix this.
1188        let mut painters_generating_frames = FxHashSet::default();
1189        for pipeline_id in documents_in_order.iter() {
1190            let document = self
1191                .documents
1192                .borrow()
1193                .find_document(*pipeline_id)
1194                .expect("Got pipeline for Document not managed by this ScriptThread.");
1195
1196            if !document.is_fully_active() {
1197                continue;
1198            }
1199
1200            if document.waiting_on_canvas_image_updates() {
1201                continue;
1202            }
1203
1204            // Step 3. Filter non-renderable documents:
1205            // Remove from docs any Document object doc for which any of the following are true:
1206            if
1207            // doc is render-blocked;
1208            document.is_render_blocked()
1209            // doc's visibility state is "hidden";
1210            // TODO: Currently, this would mean that the script thread does nothing, since
1211            // documents aren't currently correctly set to the visible state when navigating
1212
1213            // doc's rendering is suppressed for view transitions; or
1214            // TODO
1215
1216            // doc's node navigable doesn't currently have a rendering opportunity.
1217            //
1218            // This is implicitly the case when we call this method
1219            {
1220                continue;
1221            }
1222
1223            // Clear this as early as possible so that any callbacks that
1224            // trigger new reasons for updating the rendering don't get lost.
1225            document.clear_rendering_update_reasons();
1226
1227            // TODO(#31581): The steps in the "Revealing the document" section need to be implemented
1228            // `process_pending_input_events` handles the focusing steps as well as other events
1229            // from `Paint`.
1230
1231            // TODO: Should this be broken and to match the specification more closely? For instance see
1232            // https://html.spec.whatwg.org/multipage/#flush-autofocus-candidates.
1233            self.process_pending_input_events(cx, *pipeline_id);
1234
1235            // > 8. For each doc of docs, run the resize steps for doc. [CSSOMVIEW]
1236            let resized = document.window().run_the_resize_steps(cx);
1237
1238            // > 9. For each doc of docs, run the scroll steps for doc.
1239            document.run_the_scroll_steps(cx);
1240
1241            // Media queries is only relevant when there are resizing.
1242            if resized {
1243                // 10. For each doc of docs, evaluate media queries and report changes for doc.
1244                document
1245                    .window()
1246                    .evaluate_media_queries_and_report_changes(cx);
1247
1248                // https://html.spec.whatwg.org/multipage/#img-environment-changes
1249                // As per the spec, this can be run at any time.
1250                document.react_to_environment_changes()
1251            }
1252
1253            let mut realm = enter_auto_realm(cx, &*document);
1254            let cx = &mut realm.current_realm();
1255
1256            // > 11. For each doc of docs, update animations and send events for doc, passing
1257            // > in relative high resolution time given frameTimestamp and doc's relevant
1258            // > global object as the timestamp [WEBANIMATIONS]
1259            document.update_animations_and_send_events(cx);
1260
1261            // TODO(#31866): Implement "run the fullscreen steps" from
1262            // https://fullscreen.spec.whatwg.org/multipage/#run-the-fullscreen-steps.
1263
1264            // TODO(#31868): Implement the "context lost steps" from
1265            // https://html.spec.whatwg.org/multipage/#context-lost-steps.
1266
1267            // > 14. For each doc of docs, run the animation frame callbacks for doc, passing
1268            // > in the relative high resolution time given frameTimestamp and doc's
1269            // > relevant global object as the timestamp.
1270            document.run_the_animation_frame_callbacks(cx);
1271
1272            // Run the resize observer steps.
1273            let mut depth = Default::default();
1274            while document.gather_active_resize_observations_at_depth(&depth) {
1275                // Note: this will reflow the doc.
1276                depth = document.broadcast_active_resize_observations(cx);
1277            }
1278
1279            if document.has_skipped_resize_observations() {
1280                document.deliver_resize_loop_error_notification(CanGc::from_cx(cx));
1281                // Ensure that another turn of the event loop occurs to process
1282                // the skipped observations.
1283                document.add_rendering_update_reason(
1284                    RenderingUpdateReason::ResizeObserverStartedObservingTarget,
1285                );
1286            }
1287
1288            // <https://html.spec.whatwg.org/multipage/#focus-fixup-rule>
1289            // > For each doc of docs, if the focused area of doc is not a focusable area, then run the
1290            // > focusing steps for doc's viewport, and set doc's relevant global object's navigation API's
1291            // > focus changed during ongoing navigation to false.
1292            document.focus_handler().perform_focus_fixup_rule(cx);
1293
1294            // TODO: Perform pending transition operations from
1295            // https://drafts.csswg.org/css-view-transitions/#perform-pending-transition-operations.
1296
1297            // > 19. For each doc of docs, run the update intersection observations steps for doc,
1298            // > passing in the relative high resolution time given now and
1299            // > doc's relevant global object as the timestamp. [INTERSECTIONOBSERVER]
1300            // TODO(stevennovaryo): The time attribute should be relative to the time origin of the global object
1301            document.update_intersection_observer_steps(cx, CrossProcessInstant::now());
1302
1303            // TODO: Mark paint timing from https://w3c.github.io/paint-timing.
1304
1305            // > Step 22: For each doc of docs, update the rendering or user interface of
1306            // > doc and its node navigable to reflect the current state.
1307            if document.update_the_rendering(cx).0.needs_frame() {
1308                painters_generating_frames.insert(document.webview_id().into());
1309            }
1310
1311            // TODO: Process top layer removals according to
1312            // https://drafts.csswg.org/css-position-4/#process-top-layer-removals.
1313        }
1314
1315        let should_generate_frame = !painters_generating_frames.is_empty();
1316        if should_generate_frame {
1317            self.paint_api
1318                .generate_frame(painters_generating_frames.into_iter().collect());
1319        }
1320
1321        // Perform a microtask checkpoint as the specifications says that *update the rendering*
1322        // should be run in a task and a microtask checkpoint is always done when running tasks.
1323        self.perform_a_microtask_checkpoint(cx);
1324        should_generate_frame
1325    }
1326
1327    /// Schedule a rendering update ("update the rendering"), if necessary. This
1328    /// can be necessary for a couple reasons. For instance, when the DOM
1329    /// changes a scheduled rendering update becomes necessary if one isn't
1330    /// scheduled already. Another example is if rAFs are running but no display
1331    /// lists are being produced. In that case the [`ScriptThread`] is
1332    /// responsible for scheduling animation ticks.
1333    fn maybe_schedule_rendering_opportunity_after_ipc_message(
1334        &self,
1335        built_any_display_lists: bool,
1336    ) {
1337        let needs_rendering_update = self
1338            .documents
1339            .borrow()
1340            .iter()
1341            .any(|(_, document)| document.needs_rendering_update());
1342        let running_animations = self.documents.borrow().iter().any(|(_, document)| {
1343            document.is_fully_active() &&
1344                !document.window().throttled() &&
1345                (document.animations().running_animation_count() != 0 ||
1346                    document.has_active_request_animation_frame_callbacks())
1347        });
1348
1349        // If we are not running animations and no rendering update is
1350        // necessary, just exit early and schedule the next rendering update
1351        // when it becomes necessary.
1352        if !needs_rendering_update && !running_animations {
1353            return;
1354        }
1355
1356        // If animations are running and a reflow in this event loop iteration
1357        // produced a display list, rely on the renderer to inform us of the
1358        // next animation tick / rendering opportunity.
1359        if running_animations && built_any_display_lists {
1360            return;
1361        }
1362
1363        // There are two possibilities: rendering needs to be updated or we are
1364        // scheduling a new animation tick because animations are running, but
1365        // not changing the DOM. In the later case we can wait a bit longer
1366        // until the next "update the rendering" call as it's more efficient to
1367        // slow down rAFs that don't change the DOM.
1368        //
1369        // TODO: Should either of these delays be reduced to also reduce update latency?
1370        let animation_delay = if running_animations && !needs_rendering_update {
1371            // 30 milliseconds (33 FPS) is used here as the rendering isn't changing
1372            // so it isn't a problem to slow down rAF callback calls. In addition, this allows
1373            // renderer-based ticks to arrive first.
1374            Duration::from_millis(30)
1375        } else {
1376            // 20 milliseconds (50 FPS) is used here in order to allow any renderer-based
1377            // animation ticks to arrive first.
1378            Duration::from_millis(20)
1379        };
1380
1381        let time_since_last_rendering_opportunity = self
1382            .last_render_opportunity_time
1383            .get()
1384            .map(|last_render_opportunity_time| Instant::now() - last_render_opportunity_time)
1385            .unwrap_or(Duration::MAX)
1386            .min(animation_delay);
1387        self.schedule_update_the_rendering_timer_if_necessary(
1388            animation_delay - time_since_last_rendering_opportunity,
1389        );
1390    }
1391
1392    /// Fulfill the possibly-pending pending `document.fonts.ready` promise if
1393    /// all web fonts have loaded.
1394    fn maybe_fulfill_font_ready_promises(&self, cx: &mut js::context::JSContext) {
1395        let mut sent_message = false;
1396        for (_, document) in self.documents.borrow().iter() {
1397            sent_message = document.maybe_fulfill_font_ready_promise(cx) || sent_message;
1398        }
1399
1400        if sent_message {
1401            self.perform_a_microtask_checkpoint(cx);
1402        }
1403    }
1404
1405    /// If any `Pipeline`s are waiting to become ready for the purpose of taking a
1406    /// screenshot, check to see if the `Pipeline` is now ready and send a message to the
1407    /// Constellation, if so.
1408    fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut js::context::JSContext) {
1409        for (_, document) in self.documents.borrow().iter() {
1410            document
1411                .window()
1412                .maybe_resolve_pending_screenshot_readiness_requests(cx);
1413        }
1414    }
1415
1416    /// Handle incoming messages from other tasks and the task queue.
1417    fn handle_msgs(&self, cx: &mut js::context::JSContext) -> bool {
1418        // Proritize rendering tasks and others, and gather all other events as `sequential`.
1419        let mut sequential = vec![];
1420
1421        // Notify the background-hang-monitor we are waiting for an event.
1422        self.background_hang_monitor.notify_wait();
1423
1424        // Receive at least one message so we don't spinloop.
1425        debug!("Waiting for event.");
1426        let fully_active = self.get_fully_active_document_ids();
1427        let mut event = self.receivers.recv(
1428            &self.task_queue,
1429            &self.timer_scheduler.borrow(),
1430            &fully_active,
1431        );
1432
1433        loop {
1434            debug!("Handling event: {event:?}");
1435
1436            // Dispatch any completed timers, so that their tasks can be run below.
1437            self.timer_scheduler
1438                .borrow_mut()
1439                .dispatch_completed_timers();
1440
1441            // https://html.spec.whatwg.org/multipage/#event-loop-processing-model step 7
1442            match event {
1443                // This has to be handled before the ResizeMsg below,
1444                // otherwise the page may not have been added to the
1445                // child list yet, causing the find() to fail.
1446                MixedMessage::FromConstellation(ScriptThreadMessage::SpawnPipeline(
1447                    new_pipeline_info,
1448                )) => {
1449                    self.spawn_pipeline(cx, new_pipeline_info);
1450                },
1451                MixedMessage::FromScript(MainThreadScriptMsg::Inactive) => {
1452                    // An event came-in from a document that is not fully-active, it has been stored by the task-queue.
1453                    // Continue without adding it to "sequential".
1454                },
1455                MixedMessage::FromConstellation(ScriptThreadMessage::ExitFullScreen(id)) => self
1456                    .profile_event(ScriptThreadEventCategory::ExitFullscreen, Some(id), || {
1457                        self.handle_exit_fullscreen(id, cx);
1458                    }),
1459                _ => {
1460                    sequential.push(event);
1461                },
1462            }
1463
1464            // If any of our input sources has an event pending, we'll perform another
1465            // iteration and check for events. If there are no events pending, we'll move
1466            // on and execute the sequential events.
1467            match self.receivers.try_recv(&self.task_queue, &fully_active) {
1468                Some(new_event) => event = new_event,
1469                None => break,
1470            }
1471        }
1472
1473        // Process the gathered events.
1474        debug!("Processing events.");
1475        for msg in sequential {
1476            debug!("Processing event {:?}.", msg);
1477            let category = self.categorize_msg(&msg);
1478            let pipeline_id = msg.pipeline_id();
1479            let _realm = pipeline_id.and_then(|id| {
1480                let global = self.documents.borrow().find_global(id);
1481                global.map(|global| enter_realm(&*global))
1482            });
1483
1484            if self.closing.load(Ordering::SeqCst) {
1485                // If we've received the closed signal from the BHM, only handle exit messages.
1486                match msg {
1487                    MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1488                        self.handle_exit_script_thread_msg(cx);
1489                        return false;
1490                    },
1491                    MixedMessage::FromConstellation(ScriptThreadMessage::ExitPipeline(
1492                        webview_id,
1493                        pipeline_id,
1494                        discard_browsing_context,
1495                    )) => {
1496                        self.handle_exit_pipeline_msg(
1497                            webview_id,
1498                            pipeline_id,
1499                            discard_browsing_context,
1500                            cx,
1501                        );
1502                    },
1503                    _ => {},
1504                }
1505                continue;
1506            }
1507
1508            let exiting = self.profile_event(category, pipeline_id, || {
1509                match msg {
1510                    MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1511                        self.handle_exit_script_thread_msg(cx);
1512                        return true;
1513                    },
1514                    MixedMessage::FromConstellation(inner_msg) => {
1515                        self.handle_msg_from_constellation(inner_msg, cx)
1516                    },
1517                    MixedMessage::FromScript(inner_msg) => {
1518                        self.handle_msg_from_script(inner_msg, cx)
1519                    },
1520                    MixedMessage::FromDevtools(inner_msg) => {
1521                        self.handle_msg_from_devtools(inner_msg, cx)
1522                    },
1523                    MixedMessage::FromImageCache(inner_msg) => {
1524                        self.handle_msg_from_image_cache(inner_msg, cx)
1525                    },
1526                    #[cfg(feature = "webgpu")]
1527                    MixedMessage::FromWebGPUServer(inner_msg) => {
1528                        self.handle_msg_from_webgpu_server(inner_msg, cx)
1529                    },
1530                    MixedMessage::TimerFired => {},
1531                }
1532
1533                false
1534            });
1535
1536            // If an `ExitScriptThread` message was handled above, bail out now.
1537            if exiting {
1538                return false;
1539            }
1540
1541            // https://html.spec.whatwg.org/multipage/#event-loop-processing-model step 6
1542            // TODO(#32003): A microtask checkpoint is only supposed to be performed after running a task.
1543            self.perform_a_microtask_checkpoint(cx);
1544        }
1545
1546        for (_, doc) in self.documents.borrow().iter() {
1547            let window = doc.window();
1548            window
1549                .upcast::<GlobalScope>()
1550                .perform_a_dom_garbage_collection_checkpoint();
1551        }
1552
1553        {
1554            // https://html.spec.whatwg.org/multipage/#the-end step 6
1555            let mut docs = self.docs_with_no_blocking_loads.borrow_mut();
1556            for document in docs.iter() {
1557                let _realm = enter_auto_realm(cx, &**document);
1558                document.maybe_queue_document_completion();
1559            }
1560            docs.clear();
1561        }
1562
1563        let built_any_display_lists =
1564            self.needs_rendering_update.load(Ordering::Relaxed) && self.update_the_rendering(cx);
1565
1566        self.maybe_fulfill_font_ready_promises(cx);
1567        self.maybe_resolve_pending_screenshot_readiness_requests(cx);
1568
1569        // This must happen last to detect if any change above makes a rendering update necessary.
1570        self.maybe_schedule_rendering_opportunity_after_ipc_message(built_any_display_lists);
1571
1572        true
1573    }
1574
1575    fn categorize_msg(&self, msg: &MixedMessage) -> ScriptThreadEventCategory {
1576        match *msg {
1577            MixedMessage::FromConstellation(ref inner_msg) => match *inner_msg {
1578                ScriptThreadMessage::SendInputEvent(..) => ScriptThreadEventCategory::InputEvent,
1579                _ => ScriptThreadEventCategory::ConstellationMsg,
1580            },
1581            MixedMessage::FromDevtools(_) => ScriptThreadEventCategory::DevtoolsMsg,
1582            MixedMessage::FromImageCache(_) => ScriptThreadEventCategory::ImageCacheMsg,
1583            MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
1584                MainThreadScriptMsg::Common(CommonScriptMsg::Task(category, ..)) => category,
1585                MainThreadScriptMsg::RegisterPaintWorklet { .. } => {
1586                    ScriptThreadEventCategory::WorkletEvent
1587                },
1588                _ => ScriptThreadEventCategory::ScriptEvent,
1589            },
1590            #[cfg(feature = "webgpu")]
1591            MixedMessage::FromWebGPUServer(_) => ScriptThreadEventCategory::WebGPUMsg,
1592            MixedMessage::TimerFired => ScriptThreadEventCategory::TimerEvent,
1593        }
1594    }
1595
1596    fn profile_event<F, R>(
1597        &self,
1598        category: ScriptThreadEventCategory,
1599        pipeline_id: Option<PipelineId>,
1600        f: F,
1601    ) -> R
1602    where
1603        F: FnOnce() -> R,
1604    {
1605        self.background_hang_monitor
1606            .notify_activity(HangAnnotation::Script(category.into()));
1607        let start = Instant::now();
1608        let value = if self.profile_script_events {
1609            let profiler_chan = self.senders.time_profiler_sender.clone();
1610            match category {
1611                ScriptThreadEventCategory::SpawnPipeline => {
1612                    time_profile!(
1613                        ProfilerCategory::ScriptSpawnPipeline,
1614                        None,
1615                        profiler_chan,
1616                        f
1617                    )
1618                },
1619                ScriptThreadEventCategory::ConstellationMsg => time_profile!(
1620                    ProfilerCategory::ScriptConstellationMsg,
1621                    None,
1622                    profiler_chan,
1623                    f
1624                ),
1625                ScriptThreadEventCategory::DatabaseAccessEvent => time_profile!(
1626                    ProfilerCategory::ScriptDatabaseAccessEvent,
1627                    None,
1628                    profiler_chan,
1629                    f
1630                ),
1631                ScriptThreadEventCategory::DevtoolsMsg => {
1632                    time_profile!(ProfilerCategory::ScriptDevtoolsMsg, None, profiler_chan, f)
1633                },
1634                ScriptThreadEventCategory::DocumentEvent => time_profile!(
1635                    ProfilerCategory::ScriptDocumentEvent,
1636                    None,
1637                    profiler_chan,
1638                    f
1639                ),
1640                ScriptThreadEventCategory::InputEvent => {
1641                    time_profile!(ProfilerCategory::ScriptInputEvent, None, profiler_chan, f)
1642                },
1643                ScriptThreadEventCategory::FileRead => {
1644                    time_profile!(ProfilerCategory::ScriptFileRead, None, profiler_chan, f)
1645                },
1646                ScriptThreadEventCategory::FontLoading => {
1647                    time_profile!(ProfilerCategory::ScriptFontLoading, None, profiler_chan, f)
1648                },
1649                ScriptThreadEventCategory::FormPlannedNavigation => time_profile!(
1650                    ProfilerCategory::ScriptPlannedNavigation,
1651                    None,
1652                    profiler_chan,
1653                    f
1654                ),
1655                ScriptThreadEventCategory::GeolocationEvent => {
1656                    time_profile!(
1657                        ProfilerCategory::ScriptGeolocationEvent,
1658                        None,
1659                        profiler_chan,
1660                        f
1661                    )
1662                },
1663                ScriptThreadEventCategory::NavigationAndTraversalEvent => {
1664                    time_profile!(
1665                        ProfilerCategory::ScriptNavigationAndTraversalEvent,
1666                        None,
1667                        profiler_chan,
1668                        f
1669                    )
1670                },
1671                ScriptThreadEventCategory::ImageCacheMsg => time_profile!(
1672                    ProfilerCategory::ScriptImageCacheMsg,
1673                    None,
1674                    profiler_chan,
1675                    f
1676                ),
1677                ScriptThreadEventCategory::NetworkEvent => {
1678                    time_profile!(ProfilerCategory::ScriptNetworkEvent, None, profiler_chan, f)
1679                },
1680                ScriptThreadEventCategory::PortMessage => {
1681                    time_profile!(ProfilerCategory::ScriptPortMessage, None, profiler_chan, f)
1682                },
1683                ScriptThreadEventCategory::Resize => {
1684                    time_profile!(ProfilerCategory::ScriptResize, None, profiler_chan, f)
1685                },
1686                ScriptThreadEventCategory::ScriptEvent => {
1687                    time_profile!(ProfilerCategory::ScriptEvent, None, profiler_chan, f)
1688                },
1689                ScriptThreadEventCategory::SetScrollState => time_profile!(
1690                    ProfilerCategory::ScriptSetScrollState,
1691                    None,
1692                    profiler_chan,
1693                    f
1694                ),
1695                ScriptThreadEventCategory::UpdateReplacedElement => time_profile!(
1696                    ProfilerCategory::ScriptUpdateReplacedElement,
1697                    None,
1698                    profiler_chan,
1699                    f
1700                ),
1701                ScriptThreadEventCategory::StylesheetLoad => time_profile!(
1702                    ProfilerCategory::ScriptStylesheetLoad,
1703                    None,
1704                    profiler_chan,
1705                    f
1706                ),
1707                ScriptThreadEventCategory::SetViewport => {
1708                    time_profile!(ProfilerCategory::ScriptSetViewport, None, profiler_chan, f)
1709                },
1710                ScriptThreadEventCategory::TimerEvent => {
1711                    time_profile!(ProfilerCategory::ScriptTimerEvent, None, profiler_chan, f)
1712                },
1713                ScriptThreadEventCategory::WebSocketEvent => time_profile!(
1714                    ProfilerCategory::ScriptWebSocketEvent,
1715                    None,
1716                    profiler_chan,
1717                    f
1718                ),
1719                ScriptThreadEventCategory::WorkerEvent => {
1720                    time_profile!(ProfilerCategory::ScriptWorkerEvent, None, profiler_chan, f)
1721                },
1722                ScriptThreadEventCategory::WorkletEvent => {
1723                    time_profile!(ProfilerCategory::ScriptWorkletEvent, None, profiler_chan, f)
1724                },
1725                ScriptThreadEventCategory::ServiceWorkerEvent => time_profile!(
1726                    ProfilerCategory::ScriptServiceWorkerEvent,
1727                    None,
1728                    profiler_chan,
1729                    f
1730                ),
1731                ScriptThreadEventCategory::EnterFullscreen => time_profile!(
1732                    ProfilerCategory::ScriptEnterFullscreen,
1733                    None,
1734                    profiler_chan,
1735                    f
1736                ),
1737                ScriptThreadEventCategory::ExitFullscreen => time_profile!(
1738                    ProfilerCategory::ScriptExitFullscreen,
1739                    None,
1740                    profiler_chan,
1741                    f
1742                ),
1743                ScriptThreadEventCategory::PerformanceTimelineTask => time_profile!(
1744                    ProfilerCategory::ScriptPerformanceEvent,
1745                    None,
1746                    profiler_chan,
1747                    f
1748                ),
1749                ScriptThreadEventCategory::Rendering => {
1750                    time_profile!(ProfilerCategory::ScriptRendering, None, profiler_chan, f)
1751                },
1752                #[cfg(feature = "webgpu")]
1753                ScriptThreadEventCategory::WebGPUMsg => {
1754                    time_profile!(ProfilerCategory::ScriptWebGPUMsg, None, profiler_chan, f)
1755                },
1756            }
1757        } else {
1758            f()
1759        };
1760        let task_duration = start.elapsed();
1761        for (doc_id, doc) in self.documents.borrow().iter() {
1762            if let Some(pipeline_id) = pipeline_id &&
1763                pipeline_id == doc_id &&
1764                task_duration.as_nanos() > MAX_TASK_NS
1765            {
1766                if opts::get()
1767                    .debug
1768                    .is_enabled(DiagnosticsLoggingOption::ProgressiveWebMetrics)
1769                {
1770                    println!(
1771                        "Task took longer than max allowed ({category:?}) {:?}",
1772                        task_duration.as_nanos()
1773                    );
1774                }
1775                doc.start_tti();
1776            }
1777            doc.record_tti_if_necessary();
1778        }
1779        value
1780    }
1781
1782    fn handle_msg_from_constellation(
1783        &self,
1784        msg: ScriptThreadMessage,
1785        cx: &mut js::context::JSContext,
1786    ) {
1787        match msg {
1788            ScriptThreadMessage::StopDelayingLoadEventsMode(pipeline_id) => {
1789                self.handle_stop_delaying_load_events_mode(pipeline_id)
1790            },
1791            ScriptThreadMessage::NavigateIframe(
1792                parent_pipeline_id,
1793                browsing_context_id,
1794                load_data,
1795                history_handling,
1796                target_snapshot_params,
1797            ) => self.handle_navigate_iframe(
1798                parent_pipeline_id,
1799                browsing_context_id,
1800                load_data,
1801                history_handling,
1802                target_snapshot_params,
1803                cx,
1804            ),
1805            ScriptThreadMessage::UnloadDocument(pipeline_id) => {
1806                self.handle_unload_document(cx, pipeline_id)
1807            },
1808            ScriptThreadMessage::ResizeInactive(id, new_size) => {
1809                self.handle_resize_inactive_msg(id, new_size)
1810            },
1811            ScriptThreadMessage::ThemeChange(_, theme) => {
1812                self.handle_theme_change_msg(theme);
1813            },
1814            ScriptThreadMessage::GetDocumentOrigin(pipeline_id, result_sender) => {
1815                self.handle_get_document_origin(pipeline_id, result_sender);
1816            },
1817            ScriptThreadMessage::GetTitle(pipeline_id) => self.handle_get_title_msg(pipeline_id),
1818            ScriptThreadMessage::SetDocumentActivity(pipeline_id, activity) => {
1819                self.handle_set_document_activity_msg(cx, pipeline_id, activity)
1820            },
1821            ScriptThreadMessage::SetThrottled(webview_id, pipeline_id, throttled) => {
1822                self.handle_set_throttled_msg(webview_id, pipeline_id, throttled)
1823            },
1824            ScriptThreadMessage::SetThrottledInContainingIframe(
1825                _,
1826                parent_pipeline_id,
1827                browsing_context_id,
1828                throttled,
1829            ) => self.handle_set_throttled_in_containing_iframe_msg(
1830                parent_pipeline_id,
1831                browsing_context_id,
1832                throttled,
1833            ),
1834            ScriptThreadMessage::PostMessage {
1835                target: target_pipeline_id,
1836                source_webview,
1837                source_with_ancestry,
1838                target_origin: origin,
1839                source_origin,
1840                data,
1841            } => self.handle_post_message_msg(
1842                cx,
1843                target_pipeline_id,
1844                source_webview,
1845                source_with_ancestry,
1846                origin,
1847                source_origin,
1848                *data,
1849            ),
1850            ScriptThreadMessage::UpdatePipelineId(
1851                parent_pipeline_id,
1852                browsing_context_id,
1853                webview_id,
1854                new_pipeline_id,
1855                reason,
1856            ) => self.handle_update_pipeline_id(
1857                parent_pipeline_id,
1858                browsing_context_id,
1859                webview_id,
1860                new_pipeline_id,
1861                reason,
1862                cx,
1863            ),
1864            ScriptThreadMessage::UpdateHistoryState(pipeline_id, history_state_id, url) => {
1865                self.handle_update_history_state_msg(cx, pipeline_id, history_state_id, url)
1866            },
1867            ScriptThreadMessage::RemoveHistoryStates(pipeline_id, history_states) => {
1868                self.handle_remove_history_states(pipeline_id, history_states)
1869            },
1870            ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(
1871                pipeline_id,
1872                sequence,
1873                iframe_browsing_context_id,
1874            ) => self.handle_focus_document_as_part_of_focusing_steps(
1875                cx,
1876                pipeline_id,
1877                sequence,
1878                iframe_browsing_context_id,
1879            ),
1880            ScriptThreadMessage::UnfocusDocumentAsPartOfFocusingSteps(pipeline_id, sequence) => {
1881                self.handle_unfocus_document_as_part_of_focusing_steps(cx, pipeline_id, sequence);
1882            },
1883            ScriptThreadMessage::FocusDocument(pipeline_id, remote_focus_operation) => {
1884                self.handle_focus_document(cx, pipeline_id, remote_focus_operation);
1885            },
1886            ScriptThreadMessage::WebDriverScriptCommand(pipeline_id, msg) => {
1887                self.handle_webdriver_msg(pipeline_id, msg, cx)
1888            },
1889            ScriptThreadMessage::WebFontLoaded(pipeline_id) => {
1890                self.handle_web_font_loaded(pipeline_id)
1891            },
1892            ScriptThreadMessage::DispatchIFrameLoadEvent {
1893                target: browsing_context_id,
1894                parent: parent_id,
1895                child: child_id,
1896            } => self.handle_iframe_load_event(parent_id, browsing_context_id, child_id, cx),
1897            ScriptThreadMessage::DispatchStorageEvent(
1898                pipeline_id,
1899                storage,
1900                url,
1901                key,
1902                old_value,
1903                new_value,
1904            ) => {
1905                self.handle_storage_event(pipeline_id, storage, url, key, old_value, new_value, cx)
1906            },
1907            ScriptThreadMessage::ReportCSSError(pipeline_id, filename, line, column, msg) => {
1908                self.handle_css_error_reporting(pipeline_id, filename, line, column, msg)
1909            },
1910            ScriptThreadMessage::Reload(pipeline_id) => self.handle_reload(pipeline_id, cx),
1911            ScriptThreadMessage::Resize(id, size, size_type) => {
1912                self.handle_resize_message(id, size, size_type);
1913            },
1914            ScriptThreadMessage::ExitPipeline(
1915                webview_id,
1916                pipeline_id,
1917                discard_browsing_context,
1918            ) => {
1919                self.handle_exit_pipeline_msg(webview_id, pipeline_id, discard_browsing_context, cx)
1920            },
1921            ScriptThreadMessage::PaintMetric(
1922                pipeline_id,
1923                metric_type,
1924                metric_value,
1925                first_reflow,
1926            ) => self.handle_paint_metric(
1927                pipeline_id,
1928                metric_type,
1929                metric_value,
1930                first_reflow,
1931                CanGc::from_cx(cx),
1932            ),
1933            ScriptThreadMessage::MediaSessionAction(pipeline_id, action) => {
1934                self.handle_media_session_action(cx, pipeline_id, action)
1935            },
1936            ScriptThreadMessage::SendInputEvent(webview_id, id, event) => {
1937                self.handle_input_event(webview_id, id, event)
1938            },
1939            #[cfg(feature = "webgpu")]
1940            ScriptThreadMessage::SetWebGPUPort(port) => {
1941                *self.receivers.webgpu_receiver.borrow_mut() = port.route_preserving_errors();
1942            },
1943            ScriptThreadMessage::TickAllAnimations(_webviews) => {
1944                self.set_needs_rendering_update();
1945            },
1946            ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(pipeline_id) => {
1947                if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1948                    document.handle_no_longer_waiting_on_asynchronous_image_updates();
1949                }
1950            },
1951            msg @ ScriptThreadMessage::SpawnPipeline(..) |
1952            msg @ ScriptThreadMessage::ExitFullScreen(..) |
1953            msg @ ScriptThreadMessage::ExitScriptThread => {
1954                panic!("should have handled {:?} already", msg)
1955            },
1956            ScriptThreadMessage::SetScrollStates(pipeline_id, scroll_states) => {
1957                self.handle_set_scroll_states(pipeline_id, scroll_states)
1958            },
1959            ScriptThreadMessage::EvaluateJavaScript(
1960                webview_id,
1961                pipeline_id,
1962                evaluation_id,
1963                script,
1964            ) => {
1965                self.handle_evaluate_javascript(webview_id, pipeline_id, evaluation_id, script, cx);
1966            },
1967            ScriptThreadMessage::SendImageKeysBatch(pipeline_id, image_keys) => {
1968                if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
1969                    window
1970                        .image_cache()
1971                        .fill_key_cache_with_batch_of_keys(image_keys);
1972                } else {
1973                    warn!(
1974                        "Could not find window corresponding to an image cache to send image keys to pipeline {:?}",
1975                        pipeline_id
1976                    );
1977                }
1978            },
1979            ScriptThreadMessage::RefreshCursor(pipeline_id) => {
1980                self.handle_refresh_cursor(pipeline_id);
1981            },
1982            ScriptThreadMessage::PreferencesUpdated(updates) => {
1983                let mut current_preferences = prefs::get().clone();
1984                for (name, value) in updates {
1985                    current_preferences.set_value(&name, value);
1986                }
1987                prefs::set(current_preferences);
1988            },
1989            ScriptThreadMessage::ForwardKeyboardScroll(pipeline_id, scroll) => {
1990                if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1991                    document.event_handler().do_keyboard_scroll(cx, scroll);
1992                }
1993            },
1994            ScriptThreadMessage::RequestScreenshotReadiness(webview_id, pipeline_id) => {
1995                self.handle_request_screenshot_readiness(webview_id, pipeline_id, cx);
1996            },
1997            ScriptThreadMessage::EmbedderControlResponse(id, response) => {
1998                self.handle_embedder_control_response(id, response, cx);
1999            },
2000            ScriptThreadMessage::SetUserContents(user_content_manager_id, user_contents) => {
2001                self.user_contents_for_manager_id.borrow_mut().insert(
2002                    user_content_manager_id,
2003                    ScriptThreadUserContents::new(user_contents, &self.shared_style_locks),
2004                );
2005            },
2006            ScriptThreadMessage::DestroyUserContentManager(user_content_manager_id) => {
2007                self.user_contents_for_manager_id
2008                    .borrow_mut()
2009                    .remove(&user_content_manager_id);
2010            },
2011            ScriptThreadMessage::UpdatePinchZoomInfos(id, pinch_zoom_infos) => {
2012                self.handle_update_pinch_zoom_infos(id, pinch_zoom_infos, CanGc::from_cx(cx));
2013            },
2014            ScriptThreadMessage::SetAccessibilityActive(pipeline_id, active, epoch) => {
2015                self.set_accessibility_active(pipeline_id, active, epoch);
2016            },
2017            ScriptThreadMessage::TriggerGarbageCollection => unsafe {
2018                JS_GC(*GlobalScope::get_cx(), GCReason::API);
2019            },
2020        }
2021    }
2022
2023    fn handle_set_scroll_states(&self, pipeline_id: PipelineId, scroll_states: ScrollStateUpdate) {
2024        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
2025            warn!("Received scroll states for closed pipeline {pipeline_id}");
2026            return;
2027        };
2028
2029        self.profile_event(
2030            ScriptThreadEventCategory::SetScrollState,
2031            Some(pipeline_id),
2032            || {
2033                window
2034                    .layout_mut()
2035                    .set_scroll_offsets_from_renderer(&scroll_states.offsets);
2036            },
2037        );
2038
2039        window
2040            .Document()
2041            .event_handler()
2042            .handle_embedder_scroll_event(scroll_states.scrolled_node);
2043    }
2044
2045    #[cfg(feature = "webgpu")]
2046    fn handle_msg_from_webgpu_server(&self, msg: WebGPUMsg, cx: &mut js::context::JSContext) {
2047        match msg {
2048            WebGPUMsg::FreeAdapter(id) => self.gpu_id_hub.free_adapter_id(id),
2049            WebGPUMsg::FreeDevice {
2050                device_id,
2051                pipeline_id,
2052            } => {
2053                self.gpu_id_hub.free_device_id(device_id);
2054                if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2055                    global.remove_gpu_device(WebGPUDevice(device_id));
2056                } // page can already be destroyed
2057            },
2058            WebGPUMsg::FreeBuffer(id) => self.gpu_id_hub.free_buffer_id(id),
2059            WebGPUMsg::FreePipelineLayout(id) => self.gpu_id_hub.free_pipeline_layout_id(id),
2060            WebGPUMsg::FreeComputePipeline(id) => self.gpu_id_hub.free_compute_pipeline_id(id),
2061            WebGPUMsg::FreeBindGroup(id) => self.gpu_id_hub.free_bind_group_id(id),
2062            WebGPUMsg::FreeBindGroupLayout(id) => self.gpu_id_hub.free_bind_group_layout_id(id),
2063            WebGPUMsg::FreeCommandBuffer(id) => self.gpu_id_hub.free_command_buffer_id(id),
2064            WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.free_sampler_id(id),
2065            WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.free_shader_module_id(id),
2066            WebGPUMsg::FreeRenderBundle(id) => self.gpu_id_hub.free_render_bundle_id(id),
2067            WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.free_render_pipeline_id(id),
2068            WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.free_texture_id(id),
2069            WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.free_texture_view_id(id),
2070            WebGPUMsg::FreeComputePass(id) => self.gpu_id_hub.free_compute_pass_id(id),
2071            WebGPUMsg::FreeRenderPass(id) => self.gpu_id_hub.free_render_pass_id(id),
2072            WebGPUMsg::Exit => {
2073                *self.receivers.webgpu_receiver.borrow_mut() = crossbeam_channel::never()
2074            },
2075            WebGPUMsg::DeviceLost {
2076                pipeline_id,
2077                device,
2078                reason,
2079                msg,
2080            } => {
2081                let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2082                global.gpu_device_lost(device, reason, msg);
2083            },
2084            WebGPUMsg::UncapturedError {
2085                device,
2086                pipeline_id,
2087                error,
2088            } => {
2089                let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2090                let _ac = enter_auto_realm(cx, &*global);
2091                global.handle_uncaptured_gpu_error(device, error);
2092            },
2093            _ => {},
2094        }
2095    }
2096
2097    fn handle_msg_from_script(&self, msg: MainThreadScriptMsg, cx: &mut js::context::JSContext) {
2098        match msg {
2099            MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, task, pipeline_id, _)) => {
2100                let _realm = pipeline_id.and_then(|id| {
2101                    let global = self.documents.borrow().find_global(id);
2102                    global.map(|global| enter_realm(&*global))
2103                });
2104                task.run_box(cx)
2105            },
2106            MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(chan)) => {
2107                self.collect_reports(chan)
2108            },
2109            MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
2110                pipeline_id,
2111                violations,
2112            )) => {
2113                if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2114                    global.report_csp_violations(violations, None, None);
2115                }
2116            },
2117            MainThreadScriptMsg::NavigationResponse {
2118                pipeline_id,
2119                message,
2120            } => {
2121                self.handle_navigation_response(cx, pipeline_id, *message);
2122            },
2123            MainThreadScriptMsg::WorkletLoaded(pipeline_id) => {
2124                self.handle_worklet_loaded(pipeline_id)
2125            },
2126            MainThreadScriptMsg::RegisterPaintWorklet {
2127                pipeline_id,
2128                name,
2129                properties,
2130                painter,
2131            } => self.handle_register_paint_worklet(pipeline_id, name, properties, painter),
2132            MainThreadScriptMsg::Inactive => {},
2133            MainThreadScriptMsg::WakeUp => {},
2134            MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
2135                control_id,
2136                response,
2137            ) => {
2138                self.handle_embedder_control_response(control_id, response, cx);
2139            },
2140        }
2141    }
2142
2143    fn handle_msg_from_devtools(
2144        &self,
2145        msg: DevtoolScriptControlMsg,
2146        cx: &mut js::context::JSContext,
2147    ) {
2148        let documents = self.documents.borrow();
2149        match msg {
2150            DevtoolScriptControlMsg::GetEventListenerInfo(id, node, reply) => {
2151                devtools::handle_get_event_listener_info(&self.devtools_state, id, &node, reply)
2152            },
2153            DevtoolScriptControlMsg::GetRootNode(id, reply) => {
2154                devtools::handle_get_root_node(cx, &self.devtools_state, &documents, id, reply)
2155            },
2156            DevtoolScriptControlMsg::GetDocumentElement(id, reply) => {
2157                devtools::handle_get_document_element(
2158                    cx,
2159                    &self.devtools_state,
2160                    &documents,
2161                    id,
2162                    reply,
2163                )
2164            },
2165            DevtoolScriptControlMsg::GetStyleSheets(id, reply) => {
2166                devtools::handle_get_stylesheets(&documents, id, reply);
2167            },
2168            DevtoolScriptControlMsg::GetStyleSheetText(id, index, reply) => {
2169                devtools::handle_get_stylesheet_text(cx, &documents, id, index, reply);
2170            },
2171            DevtoolScriptControlMsg::GetChildren(id, node_id, reply) => {
2172                devtools::handle_get_children(cx, &self.devtools_state, id, &node_id, reply)
2173            },
2174            DevtoolScriptControlMsg::GetAttributeStyle(id, node_id, reply) => {
2175                devtools::handle_get_attribute_style(cx, &self.devtools_state, id, &node_id, reply)
2176            },
2177            DevtoolScriptControlMsg::GetStylesheetStyle(id, node_id, matched_rule, reply) => {
2178                devtools::handle_get_stylesheet_style(
2179                    cx,
2180                    &self.devtools_state,
2181                    &documents,
2182                    id,
2183                    &node_id,
2184                    matched_rule,
2185                    reply,
2186                )
2187            },
2188            DevtoolScriptControlMsg::GetSelectors(id, node_id, reply) => {
2189                devtools::handle_get_selectors(
2190                    cx,
2191                    &self.devtools_state,
2192                    &documents,
2193                    id,
2194                    &node_id,
2195                    reply,
2196                )
2197            },
2198            DevtoolScriptControlMsg::GetComputedStyle(id, node_id, reply) => {
2199                devtools::handle_get_computed_style(&self.devtools_state, id, &node_id, reply)
2200            },
2201            DevtoolScriptControlMsg::GetLayout(id, node_id, reply) => {
2202                devtools::handle_get_layout(cx, &self.devtools_state, id, &node_id, reply)
2203            },
2204            DevtoolScriptControlMsg::GetXPath(id, node_id, reply) => {
2205                devtools::handle_get_xpath(&self.devtools_state, id, &node_id, reply)
2206            },
2207            DevtoolScriptControlMsg::ModifyAttribute(id, node_id, modifications) => {
2208                devtools::handle_modify_attribute(
2209                    cx,
2210                    &self.devtools_state,
2211                    &documents,
2212                    id,
2213                    &node_id,
2214                    modifications,
2215                )
2216            },
2217            DevtoolScriptControlMsg::ModifyRule(id, node_id, modifications) => {
2218                devtools::handle_modify_rule(
2219                    cx,
2220                    &self.devtools_state,
2221                    &documents,
2222                    id,
2223                    &node_id,
2224                    modifications,
2225                )
2226            },
2227            DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => {
2228                match documents.find_window(id) {
2229                    Some(window) => {
2230                        window.set_devtools_wants_updates(to_send);
2231                    },
2232                    None => warn!("Message sent to closed pipeline {}.", id),
2233                }
2234            },
2235            DevtoolScriptControlMsg::SetTimelineMarkers(id, marker_types, reply) => {
2236                devtools::handle_set_timeline_markers(&documents, id, marker_types, reply)
2237            },
2238            DevtoolScriptControlMsg::DropTimelineMarkers(id, marker_types) => {
2239                devtools::handle_drop_timeline_markers(&documents, id, marker_types)
2240            },
2241            DevtoolScriptControlMsg::RequestAnimationFrame(id, name) => {
2242                devtools::handle_request_animation_frame(&documents, id, name)
2243            },
2244            DevtoolScriptControlMsg::NavigateTo(pipeline_id, url) => {
2245                self.handle_navigate_to(pipeline_id, url)
2246            },
2247            DevtoolScriptControlMsg::GoBack(pipeline_id) => {
2248                self.handle_traverse_history(pipeline_id, TraversalDirection::Back(1))
2249            },
2250            DevtoolScriptControlMsg::GoForward(pipeline_id) => {
2251                self.handle_traverse_history(pipeline_id, TraversalDirection::Forward(1))
2252            },
2253            DevtoolScriptControlMsg::Reload(id) => self.handle_reload(id, cx),
2254            DevtoolScriptControlMsg::GetCssDatabase(reply) => {
2255                devtools::handle_get_css_database(reply)
2256            },
2257            DevtoolScriptControlMsg::SimulateColorScheme(id, theme) => {
2258                match documents.find_window(id) {
2259                    Some(window) => {
2260                        window.set_theme(theme);
2261                    },
2262                    None => warn!("Message sent to closed pipeline {}.", id),
2263                }
2264            },
2265            DevtoolScriptControlMsg::HighlightDomNode(id, node_id) => {
2266                devtools::handle_highlight_dom_node(
2267                    &self.devtools_state,
2268                    &documents,
2269                    id,
2270                    node_id.as_deref(),
2271                )
2272            },
2273            DevtoolScriptControlMsg::Eval(code, id, frame_actor_id, reply) => {
2274                self.debugger_global
2275                    .fire_eval(cx, code.into(), id, None, frame_actor_id, reply);
2276            },
2277            DevtoolScriptControlMsg::GetPossibleBreakpoints(spidermonkey_id, result_sender) => {
2278                self.debugger_global.fire_get_possible_breakpoints(
2279                    cx,
2280                    spidermonkey_id,
2281                    result_sender,
2282                );
2283            },
2284            DevtoolScriptControlMsg::SetBreakpoint(spidermonkey_id, script_id, offset) => {
2285                self.debugger_global
2286                    .fire_set_breakpoint(cx, spidermonkey_id, script_id, offset);
2287            },
2288            DevtoolScriptControlMsg::ClearBreakpoint(spidermonkey_id, script_id, offset) => {
2289                self.debugger_global
2290                    .fire_clear_breakpoint(cx, spidermonkey_id, script_id, offset);
2291            },
2292            DevtoolScriptControlMsg::Interrupt => {
2293                self.debugger_global.fire_interrupt(cx);
2294            },
2295            DevtoolScriptControlMsg::ListFrames(pipeline_id, start, count, result_sender) => {
2296                self.debugger_global
2297                    .fire_list_frames(cx, pipeline_id, start, count, result_sender);
2298            },
2299            DevtoolScriptControlMsg::GetEnvironment(frame_actor_id, result_sender) => {
2300                self.debugger_global
2301                    .fire_get_environment(cx, frame_actor_id, result_sender);
2302            },
2303            DevtoolScriptControlMsg::Resume(resume_limit_type, frame_actor_id) => {
2304                self.debugger_global
2305                    .fire_resume(cx, resume_limit_type, frame_actor_id);
2306                self.debugger_paused.set(false);
2307            },
2308        }
2309    }
2310
2311    /// Enter a nested event loop for debugger pause.
2312    /// TODO: This should also be called when manual pause is triggered.
2313    pub(crate) fn enter_debugger_pause_loop(&self) {
2314        self.debugger_paused.set(true);
2315
2316        #[allow(unsafe_code)]
2317        let mut cx = unsafe { js::context::JSContext::from_ptr(js::rust::Runtime::get().unwrap()) };
2318
2319        while self.debugger_paused.get() {
2320            match self.receivers.devtools_server_receiver.recv() {
2321                Ok(Ok(msg)) => self.handle_msg_from_devtools(msg, &mut cx),
2322                _ => {
2323                    self.debugger_paused.set(false);
2324                    break;
2325                },
2326            }
2327        }
2328    }
2329
2330    fn handle_msg_from_image_cache(
2331        &self,
2332        response: ImageCacheResponseMessage,
2333        cx: &mut js::context::JSContext,
2334    ) {
2335        match response {
2336            ImageCacheResponseMessage::NotifyPendingImageLoadStatus(pending_image_response) => {
2337                let window = self
2338                    .documents
2339                    .borrow()
2340                    .find_window(pending_image_response.pipeline_id);
2341                if let Some(ref window) = window {
2342                    window.pending_image_notification(pending_image_response, cx);
2343                }
2344            },
2345            ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
2346                let window = self.documents.borrow().find_window(response.pipeline_id);
2347                if let Some(ref window) = window {
2348                    window.handle_image_rasterization_complete_notification(response);
2349                }
2350            },
2351        };
2352    }
2353
2354    fn handle_webdriver_msg(
2355        &self,
2356        pipeline_id: PipelineId,
2357        msg: WebDriverScriptCommand,
2358        cx: &mut js::context::JSContext,
2359    ) {
2360        let documents = self.documents.borrow();
2361        match msg {
2362            WebDriverScriptCommand::AddCookie(params, reply) => {
2363                webdriver_handlers::handle_add_cookie(&documents, pipeline_id, params, reply)
2364            },
2365            WebDriverScriptCommand::DeleteCookies(reply) => {
2366                webdriver_handlers::handle_delete_cookies(&documents, pipeline_id, reply)
2367            },
2368            WebDriverScriptCommand::DeleteCookie(name, reply) => {
2369                webdriver_handlers::handle_delete_cookie(&documents, pipeline_id, name, reply)
2370            },
2371            WebDriverScriptCommand::ElementClear(element_id, reply) => {
2372                webdriver_handlers::handle_element_clear(
2373                    cx,
2374                    &documents,
2375                    pipeline_id,
2376                    element_id,
2377                    reply,
2378                )
2379            },
2380            WebDriverScriptCommand::FindElementsCSSSelector(selector, reply) => {
2381                webdriver_handlers::handle_find_elements_css_selector(
2382                    &documents,
2383                    pipeline_id,
2384                    selector,
2385                    reply,
2386                )
2387            },
2388            WebDriverScriptCommand::FindElementsLinkText(selector, partial, reply) => {
2389                webdriver_handlers::handle_find_elements_link_text(
2390                    &documents,
2391                    pipeline_id,
2392                    selector,
2393                    partial,
2394                    reply,
2395                )
2396            },
2397            WebDriverScriptCommand::FindElementsTagName(selector, reply) => {
2398                webdriver_handlers::handle_find_elements_tag_name(
2399                    cx,
2400                    &documents,
2401                    pipeline_id,
2402                    selector,
2403                    reply,
2404                )
2405            },
2406            WebDriverScriptCommand::FindElementsXpathSelector(selector, reply) => {
2407                webdriver_handlers::handle_find_elements_xpath_selector(
2408                    cx,
2409                    &documents,
2410                    pipeline_id,
2411                    selector,
2412                    reply,
2413                )
2414            },
2415            WebDriverScriptCommand::FindElementElementsCSSSelector(selector, element_id, reply) => {
2416                webdriver_handlers::handle_find_element_elements_css_selector(
2417                    &documents,
2418                    pipeline_id,
2419                    element_id,
2420                    selector,
2421                    reply,
2422                )
2423            },
2424            WebDriverScriptCommand::FindElementElementsLinkText(
2425                selector,
2426                element_id,
2427                partial,
2428                reply,
2429            ) => webdriver_handlers::handle_find_element_elements_link_text(
2430                &documents,
2431                pipeline_id,
2432                element_id,
2433                selector,
2434                partial,
2435                reply,
2436            ),
2437            WebDriverScriptCommand::FindElementElementsTagName(selector, element_id, reply) => {
2438                webdriver_handlers::handle_find_element_elements_tag_name(
2439                    cx,
2440                    &documents,
2441                    pipeline_id,
2442                    element_id,
2443                    selector,
2444                    reply,
2445                )
2446            },
2447            WebDriverScriptCommand::FindElementElementsXPathSelector(
2448                selector,
2449                element_id,
2450                reply,
2451            ) => webdriver_handlers::handle_find_element_elements_xpath_selector(
2452                cx,
2453                &documents,
2454                pipeline_id,
2455                element_id,
2456                selector,
2457                reply,
2458            ),
2459            WebDriverScriptCommand::FindShadowElementsCSSSelector(
2460                selector,
2461                shadow_root_id,
2462                reply,
2463            ) => webdriver_handlers::handle_find_shadow_elements_css_selector(
2464                &documents,
2465                pipeline_id,
2466                shadow_root_id,
2467                selector,
2468                reply,
2469            ),
2470            WebDriverScriptCommand::FindShadowElementsLinkText(
2471                selector,
2472                shadow_root_id,
2473                partial,
2474                reply,
2475            ) => webdriver_handlers::handle_find_shadow_elements_link_text(
2476                &documents,
2477                pipeline_id,
2478                shadow_root_id,
2479                selector,
2480                partial,
2481                reply,
2482            ),
2483            WebDriverScriptCommand::FindShadowElementsTagName(selector, shadow_root_id, reply) => {
2484                webdriver_handlers::handle_find_shadow_elements_tag_name(
2485                    &documents,
2486                    pipeline_id,
2487                    shadow_root_id,
2488                    selector,
2489                    reply,
2490                )
2491            },
2492            WebDriverScriptCommand::FindShadowElementsXPathSelector(
2493                selector,
2494                shadow_root_id,
2495                reply,
2496            ) => webdriver_handlers::handle_find_shadow_elements_xpath_selector(
2497                cx,
2498                &documents,
2499                pipeline_id,
2500                shadow_root_id,
2501                selector,
2502                reply,
2503            ),
2504            WebDriverScriptCommand::GetElementShadowRoot(element_id, reply) => {
2505                webdriver_handlers::handle_get_element_shadow_root(
2506                    &documents,
2507                    pipeline_id,
2508                    element_id,
2509                    reply,
2510                )
2511            },
2512            WebDriverScriptCommand::ElementClick(element_id, reply) => {
2513                webdriver_handlers::handle_element_click(
2514                    cx,
2515                    &documents,
2516                    pipeline_id,
2517                    element_id,
2518                    reply,
2519                )
2520            },
2521            WebDriverScriptCommand::GetKnownElement(element_id, reply) => {
2522                webdriver_handlers::handle_get_known_element(
2523                    &documents,
2524                    pipeline_id,
2525                    element_id,
2526                    reply,
2527                )
2528            },
2529            WebDriverScriptCommand::GetKnownWindow(webview_id, reply) => {
2530                webdriver_handlers::handle_get_known_window(
2531                    &documents,
2532                    pipeline_id,
2533                    webview_id,
2534                    reply,
2535                )
2536            },
2537            WebDriverScriptCommand::GetKnownShadowRoot(element_id, reply) => {
2538                webdriver_handlers::handle_get_known_shadow_root(
2539                    &documents,
2540                    pipeline_id,
2541                    element_id,
2542                    reply,
2543                )
2544            },
2545            WebDriverScriptCommand::GetActiveElement(reply) => {
2546                webdriver_handlers::handle_get_active_element(&documents, pipeline_id, reply)
2547            },
2548            WebDriverScriptCommand::GetComputedRole(node_id, reply) => {
2549                webdriver_handlers::handle_get_computed_role(
2550                    &documents,
2551                    pipeline_id,
2552                    node_id,
2553                    reply,
2554                )
2555            },
2556            WebDriverScriptCommand::GetPageSource(reply) => {
2557                webdriver_handlers::handle_get_page_source(cx, &documents, pipeline_id, reply)
2558            },
2559            WebDriverScriptCommand::GetCookies(reply) => {
2560                webdriver_handlers::handle_get_cookies(&documents, pipeline_id, reply)
2561            },
2562            WebDriverScriptCommand::GetCookie(name, reply) => {
2563                webdriver_handlers::handle_get_cookie(&documents, pipeline_id, name, reply)
2564            },
2565            WebDriverScriptCommand::GetElementTagName(node_id, reply) => {
2566                webdriver_handlers::handle_get_name(&documents, pipeline_id, node_id, reply)
2567            },
2568            WebDriverScriptCommand::GetElementAttribute(node_id, name, reply) => {
2569                webdriver_handlers::handle_get_attribute(
2570                    cx,
2571                    &documents,
2572                    pipeline_id,
2573                    node_id,
2574                    name,
2575                    reply,
2576                )
2577            },
2578            WebDriverScriptCommand::GetElementProperty(node_id, name, reply) => {
2579                webdriver_handlers::handle_get_property(
2580                    &documents,
2581                    pipeline_id,
2582                    node_id,
2583                    name,
2584                    reply,
2585                    cx,
2586                )
2587            },
2588            WebDriverScriptCommand::GetElementCSS(node_id, name, reply) => {
2589                webdriver_handlers::handle_get_css(&documents, pipeline_id, node_id, name, reply)
2590            },
2591            WebDriverScriptCommand::GetElementRect(node_id, reply) => {
2592                webdriver_handlers::handle_get_rect(cx, &documents, pipeline_id, node_id, reply)
2593            },
2594            WebDriverScriptCommand::ScrollAndGetBoundingClientRect(node_id, reply) => {
2595                webdriver_handlers::handle_scroll_and_get_bounding_client_rect(
2596                    cx,
2597                    &documents,
2598                    pipeline_id,
2599                    node_id,
2600                    reply,
2601                )
2602            },
2603            WebDriverScriptCommand::GetElementText(node_id, reply) => {
2604                webdriver_handlers::handle_get_text(&documents, pipeline_id, node_id, reply)
2605            },
2606            WebDriverScriptCommand::GetElementInViewCenterPoint(node_id, reply) => {
2607                webdriver_handlers::handle_get_element_in_view_center_point(
2608                    cx,
2609                    &documents,
2610                    pipeline_id,
2611                    node_id,
2612                    reply,
2613                )
2614            },
2615            WebDriverScriptCommand::GetParentFrameId(reply) => {
2616                webdriver_handlers::handle_get_parent_frame_id(&documents, pipeline_id, reply)
2617            },
2618            WebDriverScriptCommand::GetBrowsingContextId(webdriver_frame_id, reply) => {
2619                webdriver_handlers::handle_get_browsing_context_id(
2620                    &documents,
2621                    pipeline_id,
2622                    webdriver_frame_id,
2623                    reply,
2624                )
2625            },
2626            WebDriverScriptCommand::GetUrl(reply) => {
2627                webdriver_handlers::handle_get_url(&documents, pipeline_id, reply)
2628            },
2629            WebDriverScriptCommand::IsEnabled(element_id, reply) => {
2630                webdriver_handlers::handle_is_enabled(&documents, pipeline_id, element_id, reply)
2631            },
2632            WebDriverScriptCommand::IsSelected(element_id, reply) => {
2633                webdriver_handlers::handle_is_selected(&documents, pipeline_id, element_id, reply)
2634            },
2635            WebDriverScriptCommand::GetTitle(reply) => {
2636                webdriver_handlers::handle_get_title(&documents, pipeline_id, reply)
2637            },
2638            WebDriverScriptCommand::WillSendKeys(
2639                element_id,
2640                text,
2641                strict_file_interactability,
2642                reply,
2643            ) => webdriver_handlers::handle_will_send_keys(
2644                cx,
2645                &documents,
2646                pipeline_id,
2647                element_id,
2648                text,
2649                strict_file_interactability,
2650                reply,
2651            ),
2652            WebDriverScriptCommand::AddLoadStatusSender(_, response_sender) => {
2653                webdriver_handlers::handle_add_load_status_sender(
2654                    &documents,
2655                    pipeline_id,
2656                    response_sender,
2657                )
2658            },
2659            WebDriverScriptCommand::RemoveLoadStatusSender(_) => {
2660                webdriver_handlers::handle_remove_load_status_sender(&documents, pipeline_id)
2661            },
2662            // https://github.com/servo/servo/issues/23535
2663            // The Script messages need different treatment since the JS script might mutate
2664            // `self.documents`, which would conflict with the immutable borrow of it that
2665            // occurs for the rest of the messages.
2666            // We manually drop the immutable borrow first, and quickly
2667            // end the borrow of documents to avoid runtime error.
2668            WebDriverScriptCommand::ExecuteScriptWithCallback(script, reply) => {
2669                let window = documents.find_window(pipeline_id);
2670                drop(documents);
2671                webdriver_handlers::handle_execute_async_script(window, script, reply, cx);
2672            },
2673            WebDriverScriptCommand::SetProtocolHandlerAutomationMode(mode) => {
2674                webdriver_handlers::set_protocol_handler_automation_mode(
2675                    &documents,
2676                    pipeline_id,
2677                    mode,
2678                )
2679            },
2680        }
2681    }
2682
2683    /// Batch window resize operations into a single "update the rendering" task,
2684    /// or, if a load is in progress, set the window size directly.
2685    pub(crate) fn handle_resize_message(
2686        &self,
2687        id: PipelineId,
2688        viewport_details: ViewportDetails,
2689        size_type: WindowSizeType,
2690    ) {
2691        self.profile_event(ScriptThreadEventCategory::Resize, Some(id), || {
2692            let window = self.documents.borrow().find_window(id);
2693            if let Some(ref window) = window {
2694                window.add_resize_event(viewport_details, size_type);
2695                return;
2696            }
2697            let mut loads = self.incomplete_loads.borrow_mut();
2698            if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2699                load.viewport_details = viewport_details;
2700            }
2701        })
2702    }
2703
2704    /// Handle changes to the theme, triggering reflow if the theme actually changed.
2705    fn handle_theme_change_msg(&self, theme: Theme) {
2706        for (_, document) in self.documents.borrow().iter() {
2707            document.window().set_theme(theme);
2708        }
2709        let mut loads = self.incomplete_loads.borrow_mut();
2710        for load in loads.iter_mut() {
2711            load.theme = theme;
2712        }
2713    }
2714
2715    fn handle_get_document_origin(
2716        &self,
2717        id: PipelineId,
2718        result_sender: GenericSender<Option<String>>,
2719    ) {
2720        let _ = result_sender.send(
2721            self.documents
2722                .borrow()
2723                .find_document(id)
2724                .map(|document| document.origin().immutable().ascii_serialization()),
2725        );
2726    }
2727
2728    // exit_fullscreen creates a new JS promise object, so we need to have entered a realm
2729    fn handle_exit_fullscreen(&self, id: PipelineId, cx: &mut js::context::JSContext) {
2730        let document = self.documents.borrow().find_document(id);
2731        if let Some(document) = document {
2732            let mut realm = enter_auto_realm(cx, &*document);
2733            document.exit_fullscreen(CanGc::from_cx(&mut realm));
2734        }
2735    }
2736
2737    pub(crate) fn spawn_pipeline(
2738        &self,
2739        cx: &mut js::context::JSContext,
2740        new_pipeline_info: NewPipelineInfo,
2741    ) {
2742        self.profile_event(
2743            ScriptThreadEventCategory::SpawnPipeline,
2744            Some(new_pipeline_info.new_pipeline_id),
2745            || {
2746                self.devtools_state
2747                    .notify_pipeline_created(new_pipeline_info.new_pipeline_id);
2748
2749                // Kick off the fetch for the new resource.
2750                self.pre_page_load(cx, InProgressLoad::new(new_pipeline_info));
2751            },
2752        );
2753    }
2754
2755    fn collect_reports(&self, reports_chan: ReportsChan) {
2756        let documents = self.documents.borrow();
2757        let urls = itertools::join(documents.iter().map(|(_, d)| d.url().to_string()), ", ");
2758
2759        let mut reports = vec![];
2760        perform_memory_report(|ops| {
2761            for (_, document) in documents.iter() {
2762                document
2763                    .window()
2764                    .layout()
2765                    .collect_reports(&mut reports, ops);
2766            }
2767
2768            let prefix = format!("url({urls})");
2769            reports.extend(self.get_cx().get_reports(prefix, ops));
2770        });
2771
2772        reports_chan.send(ProcessReports::new(reports));
2773    }
2774
2775    /// Updates iframe element after a change in visibility
2776    fn handle_set_throttled_in_containing_iframe_msg(
2777        &self,
2778        parent_pipeline_id: PipelineId,
2779        browsing_context_id: BrowsingContextId,
2780        throttled: bool,
2781    ) {
2782        let iframe = self
2783            .documents
2784            .borrow()
2785            .find_iframe(parent_pipeline_id, browsing_context_id);
2786        if let Some(iframe) = iframe {
2787            iframe.set_throttled(throttled);
2788        }
2789    }
2790
2791    fn handle_set_throttled_msg(
2792        &self,
2793        webview_id: WebViewId,
2794        pipeline_id: PipelineId,
2795        throttled: bool,
2796    ) {
2797        // Separate message sent since parent script thread could be different (Iframe of different
2798        // domain)
2799        self.senders
2800            .pipeline_to_constellation_sender
2801            .send((
2802                webview_id,
2803                pipeline_id,
2804                ScriptToConstellationMessage::SetThrottledComplete(throttled),
2805            ))
2806            .unwrap();
2807
2808        let window = self.documents.borrow().find_window(pipeline_id);
2809        match window {
2810            Some(window) => {
2811                window.set_throttled(throttled);
2812                return;
2813            },
2814            None => {
2815                let mut loads = self.incomplete_loads.borrow_mut();
2816                if let Some(ref mut load) = loads
2817                    .iter_mut()
2818                    .find(|load| load.pipeline_id == pipeline_id)
2819                {
2820                    load.throttled = throttled;
2821                    return;
2822                }
2823            },
2824        }
2825
2826        warn!("SetThrottled sent to nonexistent pipeline");
2827    }
2828
2829    /// Handles activity change message
2830    fn handle_set_document_activity_msg(
2831        &self,
2832        cx: &mut js::context::JSContext,
2833        id: PipelineId,
2834        activity: DocumentActivity,
2835    ) {
2836        debug!(
2837            "Setting activity of {} to be {:?} in {:?}.",
2838            id,
2839            activity,
2840            thread::current().name()
2841        );
2842        let document = self.documents.borrow().find_document(id);
2843        if let Some(document) = document {
2844            document.set_activity(cx, activity);
2845            return;
2846        }
2847        let mut loads = self.incomplete_loads.borrow_mut();
2848        if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2849            load.activity = activity;
2850            return;
2851        }
2852        warn!("change of activity sent to nonexistent pipeline");
2853    }
2854
2855    fn handle_focus_document_as_part_of_focusing_steps(
2856        &self,
2857        cx: &mut js::context::JSContext,
2858        pipeline_id: PipelineId,
2859        sequence: FocusSequenceNumber,
2860        browsing_context_id: Option<BrowsingContextId>,
2861    ) {
2862        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2863            warn!("Unknown {pipeline_id:?} for FocusDocumentAsPartOfFocusingSteps message.");
2864            return;
2865        };
2866
2867        let focus_handler = document.focus_handler();
2868        if focus_handler.focus_sequence() > sequence {
2869            debug!(
2870                "Disregarding the FocusDocumentAsPartOfFocusingSteps message because \
2871                the contained sequence number is too old ({sequence:?} < {:?})",
2872                focus_handler.focus_sequence()
2873            );
2874            return;
2875        }
2876
2877        // This is separate from the next few lines in order to drop the borrow
2878        // on `document.iframes()`.
2879        let iframe_element = browsing_context_id.and_then(|browsing_context_id| {
2880            document
2881                .iframes()
2882                .get(browsing_context_id)
2883                .map(|iframe| iframe.element.as_rooted())
2884        });
2885        let focusable_area = iframe_element
2886            .map(|iframe_element| {
2887                let kind = iframe_element.upcast::<Element>().focusable_area_kind();
2888                FocusableArea::IFrameViewport {
2889                    iframe_element,
2890                    kind,
2891                }
2892            })
2893            .unwrap_or(FocusableArea::Viewport);
2894
2895        focus_handler.focus_update_steps(
2896            cx,
2897            focusable_area.focus_chain(),
2898            focus_handler.current_focus_chain(),
2899            &focusable_area,
2900        );
2901    }
2902
2903    fn handle_focus_document(
2904        &self,
2905        cx: &mut js::context::JSContext,
2906        pipeline_id: PipelineId,
2907        remote_focus_operation: RemoteFocusOperation,
2908    ) {
2909        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2910            warn!("Unknown {pipeline_id:?} for FocusDocument message.");
2911            return;
2912        };
2913        match remote_focus_operation {
2914            RemoteFocusOperation::Viewport => document.window().Focus(cx),
2915            RemoteFocusOperation::Sequential(direction, iframe_browsing_context_id) => document
2916                .focus_handler()
2917                .sequential_focus_from_another_document(cx, iframe_browsing_context_id, direction),
2918        }
2919    }
2920
2921    fn handle_unfocus_document_as_part_of_focusing_steps(
2922        &self,
2923        cx: &mut js::context::JSContext,
2924        pipeline_id: PipelineId,
2925        sequence: FocusSequenceNumber,
2926    ) {
2927        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2928            warn!("Unknown {pipeline_id:?} for UnfocusDocumentAsPartOfFocusingSteps");
2929            return;
2930        };
2931
2932        // We ignore unfocus requests for top-level `Document`s as they *always* have focus.
2933        // Note that this does not take into account system focus.
2934        let window = document.window();
2935        if window.is_top_level() {
2936            return;
2937        }
2938
2939        let focus_handler = document.focus_handler();
2940        if focus_handler.focus_sequence() > sequence {
2941            debug!(
2942                "Disregarding the Unfocus message because the contained sequence number is \
2943                too old ({:?} < {:?})",
2944                sequence,
2945                focus_handler.focus_sequence()
2946            );
2947            return;
2948        }
2949
2950        focus_handler.focus_update_steps(
2951            cx,
2952            vec![],
2953            focus_handler.current_focus_chain(),
2954            &FocusableArea::Viewport,
2955        );
2956    }
2957
2958    #[expect(clippy::too_many_arguments)]
2959    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
2960    fn handle_post_message_msg(
2961        &self,
2962        cx: &mut js::context::JSContext,
2963        pipeline_id: PipelineId,
2964        source_webview: WebViewId,
2965        source_with_ancestry: Vec<BrowsingContextId>,
2966        origin: Option<ImmutableOrigin>,
2967        source_origin: ImmutableOrigin,
2968        data: StructuredSerializedData,
2969    ) {
2970        let window = self.documents.borrow().find_window(pipeline_id);
2971        match window {
2972            None => warn!("postMessage after target pipeline {} closed.", pipeline_id),
2973            Some(window) => {
2974                let mut last = None;
2975                for browsing_context_id in source_with_ancestry.into_iter().rev() {
2976                    if let Some(window_proxy) =
2977                        self.window_proxies.find_window_proxy(browsing_context_id)
2978                    {
2979                        last = Some(window_proxy);
2980                        continue;
2981                    }
2982                    let window_proxy = WindowProxy::new_dissimilar_origin(
2983                        cx,
2984                        window.upcast::<GlobalScope>(),
2985                        browsing_context_id,
2986                        source_webview,
2987                        last.as_deref(),
2988                        None,
2989                        CreatorBrowsingContextInfo::from(last.as_deref(), None),
2990                    );
2991                    self.window_proxies
2992                        .insert(browsing_context_id, window_proxy.clone());
2993                    last = Some(window_proxy);
2994                }
2995
2996                // Step 8.3: Let source be the WindowProxy object corresponding to
2997                // incumbentSettings's global object (a Window object).
2998                let source = last.expect("Source with ancestry should contain at least one bc.");
2999
3000                // FIXME(#22512): enqueues a task; unnecessary delay.
3001                window.post_message(origin, source_origin, &source, data)
3002            },
3003        }
3004    }
3005
3006    fn handle_stop_delaying_load_events_mode(&self, pipeline_id: PipelineId) {
3007        let window = self.documents.borrow().find_window(pipeline_id);
3008        if let Some(window) = window {
3009            match window.undiscarded_window_proxy() {
3010                Some(window_proxy) => window_proxy.stop_delaying_load_events_mode(),
3011                None => warn!(
3012                    "Attempted to take {} of 'delaying-load-events-mode' after having been discarded.",
3013                    pipeline_id
3014                ),
3015            };
3016        }
3017    }
3018
3019    fn handle_unload_document(&self, cx: &mut js::context::JSContext, pipeline_id: PipelineId) {
3020        let document = self.documents.borrow().find_document(pipeline_id);
3021        if let Some(document) = document {
3022            document.unload(cx, false);
3023        }
3024    }
3025
3026    fn handle_update_pipeline_id(
3027        &self,
3028        parent_pipeline_id: PipelineId,
3029        browsing_context_id: BrowsingContextId,
3030        webview_id: WebViewId,
3031        new_pipeline_id: PipelineId,
3032        reason: UpdatePipelineIdReason,
3033        cx: &mut js::context::JSContext,
3034    ) {
3035        let frame_element = self
3036            .documents
3037            .borrow()
3038            .find_iframe(parent_pipeline_id, browsing_context_id);
3039        let Some(frame_element) = frame_element else {
3040            return;
3041        };
3042        if !frame_element.update_pipeline_id(new_pipeline_id, reason, cx) {
3043            return;
3044        };
3045
3046        let Some(window) = self.documents.borrow().find_window(new_pipeline_id) else {
3047            return;
3048        };
3049        // Ensure that the state of any local window proxies accurately reflects
3050        // the new pipeline.
3051        let _ = self.window_proxies.local_window_proxy(
3052            cx,
3053            &self.senders,
3054            &self.documents,
3055            &window,
3056            browsing_context_id,
3057            webview_id,
3058            Some(parent_pipeline_id),
3059            // Any local window proxy has already been created, so there
3060            // is no need to pass along existing opener information that
3061            // will be discarded.
3062            None,
3063        );
3064    }
3065
3066    fn handle_update_history_state_msg(
3067        &self,
3068        cx: &mut js::context::JSContext,
3069        pipeline_id: PipelineId,
3070        history_state_id: Option<HistoryStateId>,
3071        url: ServoUrl,
3072    ) {
3073        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3074            return warn!("update history state after pipeline {pipeline_id} closed.",);
3075        };
3076        window.History().activate_state(cx, history_state_id, url);
3077    }
3078
3079    fn handle_remove_history_states(
3080        &self,
3081        pipeline_id: PipelineId,
3082        history_states: Vec<HistoryStateId>,
3083    ) {
3084        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3085            return warn!("update history state after pipeline {pipeline_id} closed.",);
3086        };
3087        window.History().remove_states(history_states);
3088    }
3089
3090    /// Window was resized, but this script was not active, so don't reflow yet
3091    fn handle_resize_inactive_msg(&self, id: PipelineId, new_viewport_details: ViewportDetails) {
3092        let window = self.documents.borrow().find_window(id)
3093            .expect("ScriptThread: received a resize msg for a pipeline not in this script thread. This is a bug.");
3094        window.set_viewport_details(new_viewport_details);
3095    }
3096
3097    /// We have received notification that the response associated with a load has completed.
3098    /// Kick off the document and frame tree creation process using the result.
3099    fn handle_page_headers_available(
3100        &self,
3101        webview_id: WebViewId,
3102        pipeline_id: PipelineId,
3103        metadata: Option<&Metadata>,
3104        origin: MutableOrigin,
3105        cx: &mut js::context::JSContext,
3106    ) -> Option<DomRoot<ServoParser>> {
3107        if self.closed_pipelines.borrow().contains(&pipeline_id) {
3108            // If the pipeline closed, do not process the headers.
3109            return None;
3110        }
3111
3112        let Some(idx) = self
3113            .incomplete_loads
3114            .borrow()
3115            .iter()
3116            .position(|load| load.pipeline_id == pipeline_id)
3117        else {
3118            unreachable!("Pipeline shouldn't have finished loading.");
3119        };
3120
3121        // https://html.spec.whatwg.org/multipage/#process-a-navigate-response
3122        // 2. If response's status is 204 or 205, then abort these steps.
3123        //
3124        // TODO: The specification has been updated and we no longer should abort.
3125        let is_204_205 = match metadata {
3126            Some(metadata) => metadata.status.in_range(204..=205),
3127            _ => false,
3128        };
3129
3130        if is_204_205 {
3131            // If we have an existing window that is being navigated:
3132            if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
3133                let window_proxy = window.window_proxy();
3134                // https://html.spec.whatwg.org/multipage/
3135                // #navigating-across-documents:delaying-load-events-mode-2
3136                if window_proxy.parent().is_some() {
3137                    // The user agent must take this nested browsing context
3138                    // out of the delaying load events mode
3139                    // when this navigation algorithm later matures,
3140                    // or when it terminates (whether due to having run all the steps,
3141                    // or being canceled, or being aborted), whichever happens first.
3142                    window_proxy.stop_delaying_load_events_mode();
3143                }
3144            }
3145            self.senders
3146                .pipeline_to_constellation_sender
3147                .send((
3148                    webview_id,
3149                    pipeline_id,
3150                    ScriptToConstellationMessage::AbortLoadUrl,
3151                ))
3152                .unwrap();
3153            return None;
3154        };
3155
3156        let load = self.incomplete_loads.borrow_mut().remove(idx);
3157        metadata.map(|meta| self.load(meta, load, origin, cx))
3158    }
3159
3160    /// Handles a request for the window title.
3161    fn handle_get_title_msg(&self, pipeline_id: PipelineId) {
3162        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3163            return warn!("Message sent to closed pipeline {pipeline_id}.");
3164        };
3165        document.send_title_to_embedder();
3166    }
3167
3168    /// Handles a request to exit a pipeline and shut down layout.
3169    fn handle_exit_pipeline_msg(
3170        &self,
3171        webview_id: WebViewId,
3172        pipeline_id: PipelineId,
3173        discard_bc: DiscardBrowsingContext,
3174        cx: &mut js::context::JSContext,
3175    ) {
3176        debug!("{pipeline_id}: Starting pipeline exit.");
3177
3178        // Abort the parser, if any,
3179        // to prevent any further incoming networking messages from being handled.
3180        let document = self.documents.borrow_mut().remove(pipeline_id);
3181        if let Some(document) = document {
3182            // We should never have a pipeline that's still an incomplete load, but also has a Document.
3183            debug_assert!(
3184                !self
3185                    .incomplete_loads
3186                    .borrow()
3187                    .iter()
3188                    .any(|load| load.pipeline_id == pipeline_id)
3189            );
3190
3191            if let Some(parser) = document.get_current_parser() {
3192                parser.abort(cx);
3193            }
3194
3195            debug!("{pipeline_id}: Shutting down layout");
3196            document.window().layout_mut().exit_now();
3197
3198            // Clear any active animations and unroot all of the associated DOM objects.
3199            debug!("{pipeline_id}: Clearing animations");
3200            document.animations().clear();
3201
3202            // We discard the browsing context after requesting layout shut down,
3203            // to avoid running layout on detached iframes.
3204            let window = document.window();
3205            if discard_bc == DiscardBrowsingContext::Yes {
3206                window.discard_browsing_context();
3207            }
3208
3209            debug!("{pipeline_id}: Clearing JavaScript runtime");
3210            window.clear_js_runtime();
3211        }
3212
3213        // Prevent any further work for this Pipeline.
3214        self.closed_pipelines.borrow_mut().insert(pipeline_id);
3215
3216        debug!("{pipeline_id}: Sending PipelineExited message to constellation");
3217        self.senders
3218            .pipeline_to_constellation_sender
3219            .send((
3220                webview_id,
3221                pipeline_id,
3222                ScriptToConstellationMessage::PipelineExited,
3223            ))
3224            .ok();
3225
3226        self.paint_api
3227            .pipeline_exited(webview_id, pipeline_id, PipelineExitSource::Script);
3228
3229        self.devtools_state.notify_pipeline_exited(pipeline_id);
3230
3231        debug!("{pipeline_id}: Finished pipeline exit");
3232    }
3233
3234    /// Handles a request to exit the script thread and shut down layout.
3235    fn handle_exit_script_thread_msg(&self, cx: &mut js::context::JSContext) {
3236        debug!("Exiting script thread.");
3237
3238        let mut webview_and_pipeline_ids = Vec::new();
3239        webview_and_pipeline_ids.extend(
3240            self.incomplete_loads
3241                .borrow()
3242                .iter()
3243                .next()
3244                .map(|load| (load.webview_id, load.pipeline_id)),
3245        );
3246        webview_and_pipeline_ids.extend(
3247            self.documents
3248                .borrow()
3249                .iter()
3250                .next()
3251                .map(|(pipeline_id, document)| (document.webview_id(), pipeline_id)),
3252        );
3253
3254        for (webview_id, pipeline_id) in webview_and_pipeline_ids {
3255            self.handle_exit_pipeline_msg(webview_id, pipeline_id, DiscardBrowsingContext::Yes, cx);
3256        }
3257
3258        self.background_hang_monitor.unregister();
3259
3260        // If we're in multiprocess mode, shut-down the IPC router for this process.
3261        if opts::get().multiprocess {
3262            debug!("Exiting IPC router thread in script thread.");
3263            ROUTER.shutdown();
3264        }
3265
3266        debug!("Exited script thread.");
3267    }
3268
3269    /// Handles animation tick requested during testing.
3270    pub(crate) fn handle_tick_all_animations_for_testing(id: PipelineId) {
3271        with_script_thread(|script_thread| {
3272            let Some(document) = script_thread.documents.borrow().find_document(id) else {
3273                warn!("Animation tick for tests for closed pipeline {id}.");
3274                return;
3275            };
3276            document.maybe_mark_animating_nodes_as_dirty();
3277        });
3278    }
3279
3280    /// Handles a Web font being loaded. Does nothing if the page no longer exists.
3281    fn handle_web_font_loaded(&self, pipeline_id: PipelineId) {
3282        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3283            warn!("Web font loaded in closed pipeline {}.", pipeline_id);
3284            return;
3285        };
3286
3287        // TODO: This should only dirty nodes that are waiting for a web font to finish loading!
3288        document.dirty_all_nodes();
3289    }
3290
3291    /// Handles a worklet being loaded by triggering a relayout of the page. Does nothing if the
3292    /// page no longer exists.
3293    fn handle_worklet_loaded(&self, pipeline_id: PipelineId) {
3294        if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
3295            document.add_restyle_reason(RestyleReason::PaintWorkletLoaded);
3296        }
3297    }
3298
3299    /// Notify a window of a storage event
3300    #[allow(clippy::too_many_arguments)]
3301    fn handle_storage_event(
3302        &self,
3303        pipeline_id: PipelineId,
3304        storage_type: WebStorageType,
3305        url: ServoUrl,
3306        key: Option<String>,
3307        old_value: Option<String>,
3308        new_value: Option<String>,
3309        cx: &mut js::context::JSContext,
3310    ) {
3311        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3312            return warn!("Storage event sent to closed pipeline {pipeline_id}.");
3313        };
3314
3315        let storage = match storage_type {
3316            WebStorageType::Local => window.GetLocalStorage(cx),
3317            WebStorageType::Session => window.GetSessionStorage(cx),
3318        };
3319        let Ok(storage) = storage else {
3320            return;
3321        };
3322
3323        storage.queue_storage_event(url, key, old_value, new_value);
3324    }
3325
3326    /// Notify the containing document of a child iframe that has completed loading.
3327    fn handle_iframe_load_event(
3328        &self,
3329        parent_id: PipelineId,
3330        browsing_context_id: BrowsingContextId,
3331        child_id: PipelineId,
3332        cx: &mut js::context::JSContext,
3333    ) {
3334        let iframe = self
3335            .documents
3336            .borrow()
3337            .find_iframe(parent_id, browsing_context_id);
3338        match iframe {
3339            Some(iframe) => iframe.iframe_load_event_steps(child_id, cx),
3340            None => warn!("Message sent to closed pipeline {}.", parent_id),
3341        }
3342    }
3343
3344    fn ask_constellation_for_top_level_info(
3345        &self,
3346        sender_webview_id: WebViewId,
3347        sender_pipeline_id: PipelineId,
3348        browsing_context_id: BrowsingContextId,
3349    ) -> Option<WebViewId> {
3350        let (result_sender, result_receiver) = generic_channel::channel().unwrap();
3351        let msg = ScriptToConstellationMessage::GetTopForBrowsingContext(
3352            browsing_context_id,
3353            result_sender,
3354        );
3355        self.senders
3356            .pipeline_to_constellation_sender
3357            .send((sender_webview_id, sender_pipeline_id, msg))
3358            .expect("Failed to send to constellation.");
3359        result_receiver
3360            .recv()
3361            .expect("Failed to get top-level id from constellation.")
3362    }
3363
3364    /// The entry point to document loading. Defines bindings, sets up the window and document
3365    /// objects, parses HTML and CSS, and kicks off initial layout.
3366    fn load(
3367        &self,
3368        metadata: &Metadata,
3369        incomplete: InProgressLoad,
3370        origin: MutableOrigin,
3371        cx: &mut js::context::JSContext,
3372    ) -> DomRoot<ServoParser> {
3373        let script_to_constellation_chan = ScriptToConstellationChan {
3374            sender: self.senders.pipeline_to_constellation_sender.clone(),
3375            webview_id: incomplete.webview_id,
3376            pipeline_id: incomplete.pipeline_id,
3377        };
3378
3379        let final_url = metadata.final_url.clone();
3380        let _ = script_to_constellation_chan
3381            .send(ScriptToConstellationMessage::SetFinalUrl(final_url.clone()));
3382
3383        debug!(
3384            "ScriptThread: loading {} on pipeline {:?}",
3385            incomplete.load_data.url, incomplete.pipeline_id
3386        );
3387
3388        let font_context = Arc::new(FontContext::new(
3389            self.system_font_service.clone(),
3390            self.paint_api.clone(),
3391            self.resource_threads.clone(),
3392        ));
3393
3394        let image_cache = self.image_cache_factory.create(
3395            incomplete.webview_id,
3396            incomplete.pipeline_id,
3397            &self.paint_api,
3398        );
3399
3400        let (user_contents, user_stylesheets) = incomplete
3401            .user_content_manager_id
3402            .and_then(|user_content_manager_id| {
3403                self.user_contents_for_manager_id
3404                    .borrow()
3405                    .get(&user_content_manager_id)
3406                    .map(|script_thread_user_contents| {
3407                        (
3408                            script_thread_user_contents.user_scripts.clone(),
3409                            script_thread_user_contents.user_stylesheets.clone(),
3410                        )
3411                    })
3412            })
3413            .unwrap_or_default();
3414
3415        let layout_config = LayoutConfig {
3416            id: incomplete.pipeline_id,
3417            webview_id: incomplete.webview_id,
3418            url: final_url.clone(),
3419            is_iframe: incomplete.parent_info.is_some(),
3420            script_chan: self.senders.constellation_sender.clone(),
3421            image_cache: image_cache.clone(),
3422            font_context: font_context.clone(),
3423            time_profiler_chan: self.senders.time_profiler_sender.clone(),
3424            paint_api: self.paint_api.clone(),
3425            viewport_details: incomplete.viewport_details,
3426            user_stylesheets,
3427            theme: incomplete.theme,
3428            embedder_chan: self.senders.pipeline_to_embedder_sender.clone(),
3429        };
3430
3431        // Create the window and document objects.
3432        let window = Window::new(
3433            cx,
3434            incomplete.webview_id,
3435            self.js_runtime.clone(),
3436            self.senders.self_sender.clone(),
3437            self.layout_factory.create(layout_config),
3438            font_context,
3439            self.senders.image_cache_sender.clone(),
3440            image_cache.clone(),
3441            self.resource_threads.clone(),
3442            self.storage_threads.clone(),
3443            #[cfg(feature = "bluetooth")]
3444            self.senders.bluetooth_sender.clone(),
3445            self.senders.memory_profiler_sender.clone(),
3446            self.senders.time_profiler_sender.clone(),
3447            self.senders.devtools_server_sender.clone(),
3448            script_to_constellation_chan,
3449            self.senders.pipeline_to_embedder_sender.clone(),
3450            self.senders.constellation_sender.clone(),
3451            incomplete.pipeline_id,
3452            incomplete.parent_info,
3453            incomplete.viewport_details,
3454            origin.clone(),
3455            final_url.clone(),
3456            // TODO(37417): Set correct top-level URL here. Currently, we only specify the
3457            // url of the current window. However, in case this is an iframe, we should
3458            // pass in the URL from the frame that includes the iframe (which potentially
3459            // is another nested iframe in a frame).
3460            final_url.clone(),
3461            incomplete.navigation_start,
3462            self.webgl_chan.as_ref().map(|chan| chan.channel()),
3463            #[cfg(feature = "webxr")]
3464            self.webxr_registry.clone(),
3465            self.paint_api.clone(),
3466            self.unminify_js,
3467            self.unminify_css,
3468            self.local_script_source.clone(),
3469            user_contents,
3470            self.player_context.clone(),
3471            #[cfg(feature = "webgpu")]
3472            self.gpu_id_hub.clone(),
3473            incomplete.load_data.inherited_secure_context,
3474            incomplete.theme,
3475            self.this.clone(),
3476        );
3477        self.debugger_global
3478            .fire_add_debuggee(cx, window.upcast(), incomplete.pipeline_id, None);
3479
3480        let mut realm = enter_auto_realm(cx, &*window);
3481        let cx = &mut realm;
3482
3483        // Initialize the browsing context for the window.
3484        let window_proxy = self.window_proxies.local_window_proxy(
3485            cx,
3486            &self.senders,
3487            &self.documents,
3488            &window,
3489            incomplete.browsing_context_id,
3490            incomplete.webview_id,
3491            incomplete.parent_info,
3492            incomplete.opener,
3493        );
3494        if window_proxy.parent().is_some() {
3495            // https://html.spec.whatwg.org/multipage/#navigating-across-documents:delaying-load-events-mode-2
3496            // The user agent must take this nested browsing context
3497            // out of the delaying load events mode
3498            // when this navigation algorithm later matures.
3499            window_proxy.stop_delaying_load_events_mode();
3500        }
3501        window.init_window_proxy(&window_proxy);
3502
3503        // https://html.spec.whatwg.org/multipage/#resource-metadata-management
3504        // > The Document's source file's last modification date and time must be derived from
3505        // > relevant features of the networking protocols used, e.g.
3506        // > from the value of the HTTP `Last-Modified` header of the document,
3507        // > or from metadata in the file system for local files.
3508        // > If the last modification date and time are not known,
3509        // > the attribute must return the current date and time in the above format.
3510        let last_modified = metadata.headers.as_ref().and_then(|headers| {
3511            headers.typed_get::<LastModified>().map(|tm| {
3512                let tm: SystemTime = tm.into();
3513                let local_time: DateTime<Local> = tm.into();
3514                local_time.format("%m/%d/%Y %H:%M:%S").to_string()
3515            })
3516        });
3517
3518        let loader = DocumentLoader::new_with_threads(
3519            self.resource_threads.clone(),
3520            Some(final_url.clone()),
3521        );
3522
3523        let content_type: Option<Mime> = metadata
3524            .content_type
3525            .clone()
3526            .map(Serde::into_inner)
3527            .map(Mime::from_ct);
3528        let encoding_hint_from_content_type = content_type
3529            .as_ref()
3530            .and_then(|mime| mime.get_parameter(CHARSET))
3531            .and_then(|charset| Encoding::for_label(charset.as_bytes()));
3532
3533        let is_html_document = match content_type {
3534            Some(ref mime) if mime.type_ == APPLICATION && mime.has_suffix("xml") => {
3535                IsHTMLDocument::NonHTMLDocument
3536            },
3537
3538            Some(ref mime) if mime.matches(TEXT, XML) || mime.matches(APPLICATION, XML) => {
3539                IsHTMLDocument::NonHTMLDocument
3540            },
3541            _ => IsHTMLDocument::HTMLDocument,
3542        };
3543
3544        let referrer = metadata
3545            .referrer
3546            .as_ref()
3547            .map(|referrer| referrer.clone().into_string());
3548
3549        let is_initial_about_blank = final_url.as_str() == "about:blank";
3550
3551        let document = Document::new(
3552            &window,
3553            HasBrowsingContext::Yes,
3554            Some(final_url.clone()),
3555            incomplete.load_data.about_base_url,
3556            origin,
3557            is_html_document,
3558            content_type,
3559            last_modified,
3560            incomplete.activity,
3561            DocumentSource::FromParser,
3562            loader,
3563            referrer,
3564            Some(metadata.status.raw_code()),
3565            incomplete.canceller,
3566            is_initial_about_blank,
3567            true,
3568            incomplete.load_data.inherited_insecure_requests_policy,
3569            incomplete.load_data.has_trustworthy_ancestor_origin,
3570            self.custom_element_reaction_stack.clone(),
3571            incomplete.load_data.creation_sandboxing_flag_set,
3572            CanGc::from_cx(cx),
3573        );
3574
3575        let referrer_policy = metadata
3576            .headers
3577            .as_deref()
3578            .and_then(|h| h.typed_get::<ReferrerPolicyHeader>())
3579            .into();
3580        document.set_referrer_policy(referrer_policy);
3581
3582        let refresh_header = metadata.headers.as_deref().and_then(|h| h.get(REFRESH));
3583        if let Some(refresh_val) = refresh_header {
3584            // There are tests that this header handles Unicode code points
3585            document.shared_declarative_refresh_steps(refresh_val.as_bytes());
3586        }
3587
3588        document.set_ready_state(cx, DocumentReadyState::Loading);
3589
3590        self.documents
3591            .borrow_mut()
3592            .insert(incomplete.pipeline_id, &document);
3593
3594        window.init_document(&document);
3595
3596        // For any similar-origin iframe, ensure that the contentWindow/contentDocument
3597        // APIs resolve to the new window/document as soon as parsing starts.
3598        if let Some(frame) = window_proxy
3599            .frame_element()
3600            .and_then(|e| e.downcast::<HTMLIFrameElement>())
3601        {
3602            let parent_pipeline = frame.global().pipeline_id();
3603            self.handle_update_pipeline_id(
3604                parent_pipeline,
3605                window_proxy.browsing_context_id(),
3606                window_proxy.webview_id(),
3607                incomplete.pipeline_id,
3608                UpdatePipelineIdReason::Navigation,
3609                cx,
3610            );
3611        }
3612
3613        self.senders
3614            .pipeline_to_constellation_sender
3615            .send((
3616                incomplete.webview_id,
3617                incomplete.pipeline_id,
3618                ScriptToConstellationMessage::ActivateDocument,
3619            ))
3620            .unwrap();
3621
3622        // Notify devtools that a new script global exists.
3623        let incomplete_browsing_context_id: BrowsingContextId = incomplete.webview_id.into();
3624        let is_top_level_global = incomplete_browsing_context_id == incomplete.browsing_context_id;
3625        self.notify_devtools(
3626            document.Title(),
3627            final_url.clone(),
3628            is_top_level_global,
3629            (
3630                incomplete.browsing_context_id,
3631                incomplete.pipeline_id,
3632                None,
3633                incomplete.webview_id,
3634            ),
3635        );
3636
3637        document.set_navigation_start(incomplete.navigation_start);
3638
3639        if is_html_document == IsHTMLDocument::NonHTMLDocument {
3640            ServoParser::parse_xml_document(
3641                &document,
3642                None,
3643                final_url,
3644                encoding_hint_from_content_type,
3645                cx,
3646            );
3647        } else {
3648            ServoParser::parse_html_document(
3649                &document,
3650                None,
3651                final_url,
3652                encoding_hint_from_content_type,
3653                incomplete.load_data.container_document_encoding,
3654                cx,
3655            );
3656        }
3657
3658        if incomplete.activity == DocumentActivity::FullyActive {
3659            window.resume(CanGc::from_cx(cx));
3660        } else {
3661            window.suspend(cx);
3662        }
3663
3664        if incomplete.throttled {
3665            window.set_throttled(true);
3666        }
3667
3668        document.get_current_parser().unwrap()
3669    }
3670
3671    fn notify_devtools(
3672        &self,
3673        title: DOMString,
3674        url: ServoUrl,
3675        is_top_level_global: bool,
3676        (browsing_context_id, pipeline_id, worker_id, webview_id): (
3677            BrowsingContextId,
3678            PipelineId,
3679            Option<WorkerId>,
3680            WebViewId,
3681        ),
3682    ) {
3683        if let Some(ref chan) = self.senders.devtools_server_sender {
3684            let page_info = DevtoolsPageInfo {
3685                title: String::from(title),
3686                url,
3687                is_top_level_global,
3688                is_service_worker: false,
3689            };
3690            chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
3691                (browsing_context_id, pipeline_id, worker_id, webview_id),
3692                self.senders.devtools_client_to_script_thread_sender.clone(),
3693                page_info.clone(),
3694            ))
3695            .unwrap();
3696
3697            let state = NavigationState::Stop(pipeline_id, page_info);
3698            let _ = chan.send(ScriptToDevtoolsControlMsg::Navigate(
3699                browsing_context_id,
3700                state,
3701            ));
3702        }
3703    }
3704
3705    /// Queue input events for later dispatching as part of a `update_the_rendering` task.
3706    fn handle_input_event(
3707        &self,
3708        webview_id: WebViewId,
3709        pipeline_id: PipelineId,
3710        event: ConstellationInputEvent,
3711    ) {
3712        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3713            warn!("Input event sent to closed pipeline {pipeline_id}.");
3714            let _ = self
3715                .senders
3716                .pipeline_to_embedder_sender
3717                .send(EmbedderMsg::InputEventsHandled(
3718                    webview_id,
3719                    vec![InputEventOutcome {
3720                        id: event.event.id,
3721                        result: Default::default(),
3722                    }],
3723                ));
3724            return;
3725        };
3726        document.event_handler().note_pending_input_event(event);
3727    }
3728
3729    /// See the docs for [`ScriptThreadMessage::SetAccessibilityActive`].
3730    fn set_accessibility_active(&self, pipeline_id: PipelineId, active: bool, epoch: Epoch) {
3731        if !(pref!(accessibility_enabled)) {
3732            return;
3733        }
3734
3735        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3736            if active {
3737                error!("Trying to set accessibility active on stale document: {pipeline_id}");
3738            }
3739            return;
3740        };
3741
3742        document
3743            .window()
3744            .layout()
3745            .set_accessibility_active(active, epoch);
3746    }
3747
3748    /// Handle a "navigate an iframe" message from the constellation.
3749    fn handle_navigate_iframe(
3750        &self,
3751        parent_pipeline_id: PipelineId,
3752        browsing_context_id: BrowsingContextId,
3753        load_data: LoadData,
3754        history_handling: NavigationHistoryBehavior,
3755        target_snapshot_params: TargetSnapshotParams,
3756        cx: &mut js::context::JSContext,
3757    ) {
3758        let iframe = self
3759            .documents
3760            .borrow()
3761            .find_iframe(parent_pipeline_id, browsing_context_id);
3762        if let Some(iframe) = iframe {
3763            iframe.navigate_or_reload_child_browsing_context(
3764                load_data,
3765                history_handling,
3766                ProcessingMode::NotFirstTime,
3767                target_snapshot_params,
3768                cx,
3769            );
3770        }
3771    }
3772
3773    /// Turn javascript: URL into JS code to eval, according to the steps in
3774    /// <https://html.spec.whatwg.org/multipage/#evaluate-a-javascript:-url>
3775    /// Returns the evaluated body, if available.
3776    fn eval_js_url(
3777        cx: &mut js::context::JSContext,
3778        global_scope: &GlobalScope,
3779        url: &ServoUrl,
3780    ) -> Option<String> {
3781        // Step 1. Let urlString be the result of running the URL serializer on url.
3782        // Step 2. Let encodedScriptSource be the result of removing the leading "javascript:" from urlString.
3783        let encoded = &url[Position::AfterScheme..][1..];
3784
3785        // // Step 3. Let scriptSource be the UTF-8 decoding of the percent-decoding of encodedScriptSource.
3786        let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
3787
3788        // Step 4. Let settings be targetNavigable's active document's relevant settings object.
3789        // Step 5. Let baseURL be settings's API base URL.
3790        // Step 6. Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default script fetch options.
3791        // Note: these steps are handled by `evaluate_js_on_global`.
3792        let mut realm = enter_auto_realm(cx, global_scope);
3793        let cx = &mut realm.current_realm();
3794
3795        rooted!(&in(cx) let mut jsval = UndefinedValue());
3796        // Step 7. Let evaluationStatus be the result of running the classic script script.
3797        let evaluation_status = global_scope.evaluate_js_on_global(
3798            cx,
3799            script_source,
3800            "",
3801            Some(IntroductionType::JAVASCRIPT_URL),
3802            Some(jsval.handle_mut()),
3803        );
3804
3805        // Step 9. If evaluationStatus is a normal completion, and evaluationStatus.[[Value]]
3806        //   is a String, then set result to evaluationStatus.[[Value]].
3807        // Step 10. Otherwise, return null.
3808        if evaluation_status.is_err() || !jsval.get().is_string() {
3809            return None;
3810        }
3811
3812        let strval = DOMString::safe_from_jsval(
3813            cx.into(),
3814            jsval.handle(),
3815            StringificationBehavior::Empty,
3816            CanGc::from_cx(cx),
3817        );
3818        match strval {
3819            Ok(ConversionResult::Success(s)) => {
3820                // Step 11. Let response be a new response with
3821                // the UTF-8 encoding of result, as a body.
3822                Some(String::from(s))
3823            },
3824            _ => unreachable!("Couldn't get a string from a JS string??"),
3825        }
3826    }
3827
3828    /// Instructs the constellation to fetch the document that will be loaded. Stores the InProgressLoad
3829    /// argument until a notification is received that the fetch is complete.
3830    #[servo_tracing::instrument(skip_all)]
3831    fn pre_page_load(&self, cx: &mut js::context::JSContext, mut incomplete: InProgressLoad) {
3832        let url_str = incomplete.load_data.url.as_str();
3833        if url_str == "about:blank" || incomplete.load_data.js_eval_result.is_some() {
3834            self.start_synchronous_page_load(cx, incomplete);
3835            return;
3836        }
3837        if url_str == "about:srcdoc" {
3838            self.page_load_about_srcdoc(cx, incomplete);
3839            return;
3840        }
3841
3842        let context = ParserContext::new(
3843            incomplete.webview_id,
3844            incomplete.pipeline_id,
3845            incomplete.load_data.url.clone(),
3846            incomplete.load_data.creation_sandboxing_flag_set,
3847            incomplete.parent_info,
3848            incomplete.target_snapshot_params,
3849            incomplete.load_data.load_origin.clone(),
3850        );
3851        self.incomplete_parser_contexts
3852            .0
3853            .borrow_mut()
3854            .push((incomplete.pipeline_id, context));
3855
3856        let request_builder = incomplete.request_builder();
3857        incomplete.canceller = FetchCanceller::new(
3858            request_builder.id,
3859            false,
3860            self.resource_threads.core_thread.clone(),
3861        );
3862        NavigationListener::new(request_builder, self.senders.self_sender.clone())
3863            .initiate_fetch(&self.resource_threads.core_thread, None);
3864        self.incomplete_loads.borrow_mut().push(incomplete);
3865    }
3866
3867    fn handle_navigation_response(
3868        &self,
3869        cx: &mut js::context::JSContext,
3870        pipeline_id: PipelineId,
3871        message: FetchResponseMsg,
3872    ) {
3873        if let Some(metadata) = NavigationListener::http_redirect_metadata(&message) {
3874            self.handle_navigation_redirect(pipeline_id, metadata);
3875            return;
3876        };
3877
3878        match message {
3879            FetchResponseMsg::ProcessResponse(request_id, metadata) => {
3880                self.handle_fetch_metadata(cx, pipeline_id, request_id, metadata)
3881            },
3882            FetchResponseMsg::ProcessResponseChunk(request_id, chunk) => {
3883                self.handle_fetch_chunk(cx, pipeline_id, request_id, chunk.0)
3884            },
3885            FetchResponseMsg::ProcessResponseEOF(request_id, eof, timing) => {
3886                self.handle_fetch_eof(cx, pipeline_id, request_id, eof, timing)
3887            },
3888            FetchResponseMsg::ProcessCspViolations(request_id, violations) => {
3889                self.handle_csp_violations(pipeline_id, request_id, violations)
3890            },
3891            FetchResponseMsg::ProcessRequestBody(..) => {},
3892        }
3893    }
3894
3895    fn handle_fetch_metadata(
3896        &self,
3897        cx: &mut js::context::JSContext,
3898        id: PipelineId,
3899        request_id: RequestId,
3900        fetch_metadata: Result<FetchMetadata, NetworkError>,
3901    ) {
3902        match fetch_metadata {
3903            Ok(_) => (),
3904            Err(NetworkError::Crash(..)) => (),
3905            Err(ref e) => {
3906                warn!("Network error: {:?}", e);
3907            },
3908        };
3909
3910        let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3911        let parser = incomplete_parser_contexts
3912            .iter_mut()
3913            .find(|&&mut (pipeline_id, _)| pipeline_id == id);
3914        if let Some(&mut (_, ref mut ctxt)) = parser {
3915            ctxt.process_response(cx, request_id, fetch_metadata);
3916        }
3917    }
3918
3919    fn handle_fetch_chunk(
3920        &self,
3921        cx: &mut js::context::JSContext,
3922        pipeline_id: PipelineId,
3923        request_id: RequestId,
3924        chunk: Vec<u8>,
3925    ) {
3926        let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3927        let parser = incomplete_parser_contexts
3928            .iter_mut()
3929            .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
3930        if let Some(&mut (_, ref mut ctxt)) = parser {
3931            ctxt.process_response_chunk(cx, request_id, chunk);
3932        }
3933    }
3934
3935    #[expect(clippy::redundant_clone, reason = "False positive")]
3936    fn handle_fetch_eof(
3937        &self,
3938        cx: &mut js::context::JSContext,
3939        id: PipelineId,
3940        request_id: RequestId,
3941        eof: Result<(), NetworkError>,
3942        timing: ResourceFetchTiming,
3943    ) {
3944        let idx = self
3945            .incomplete_parser_contexts
3946            .0
3947            .borrow()
3948            .iter()
3949            .position(|&(pipeline_id, _)| pipeline_id == id);
3950
3951        if let Some(idx) = idx {
3952            let (_, context) = self.incomplete_parser_contexts.0.borrow_mut().remove(idx);
3953
3954            // we need to register an iframe entry to the performance timeline if present
3955            if let Some(window_proxy) = context
3956                .get_document()
3957                .and_then(|document| document.browsing_context()) &&
3958                let Some(frame_element) = window_proxy.frame_element()
3959            {
3960                let iframe_ctx = IframeContext::new(
3961                    frame_element
3962                        .downcast::<HTMLIFrameElement>()
3963                        .expect("WindowProxy::frame_element should be an HTMLIFrameElement"),
3964                );
3965
3966                // submit_timing will only accept timing that is of type ResourceTimingType::Resource
3967                let mut resource_timing = timing.clone();
3968                resource_timing.timing_type = ResourceTimingType::Resource;
3969                submit_timing(cx, &iframe_ctx, &eof, &resource_timing);
3970            }
3971
3972            context.process_response_eof(cx, request_id, eof, timing);
3973        }
3974    }
3975
3976    fn handle_csp_violations(
3977        &self,
3978        pipeline_id: PipelineId,
3979        _request_id: RequestId,
3980        violations: Vec<Violation>,
3981    ) {
3982        let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3983        let parser = incomplete_parser_contexts
3984            .iter_mut()
3985            .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
3986        let Some(&mut (_, ref mut ctxt)) = parser else {
3987            return;
3988        };
3989        // We need to report violations for navigations in iframes in the parent page
3990        let pipeline_id = ctxt.parent_info().unwrap_or(pipeline_id);
3991        if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
3992            global.report_csp_violations(violations, None, None);
3993        }
3994    }
3995
3996    fn handle_navigation_redirect(&self, id: PipelineId, metadata: &Metadata) {
3997        // TODO(mrobinson): This tries to accomplish some steps from
3998        // <https://html.spec.whatwg.org/multipage/#process-a-navigate-fetch>, but it's
3999        // very out of sync with the specification.
4000        assert!(metadata.location_url.is_some());
4001
4002        let mut incomplete_loads = self.incomplete_loads.borrow_mut();
4003        let Some(incomplete_load) = incomplete_loads
4004            .iter_mut()
4005            .find(|incomplete_load| incomplete_load.pipeline_id == id)
4006        else {
4007            return;
4008        };
4009
4010        // Update the `url_list` of the incomplete load to track all redirects. This will be reflected
4011        // in the new `RequestBuilder` as well.
4012        incomplete_load.url_list.push(metadata.final_url.clone());
4013
4014        let mut request_builder = incomplete_load.request_builder();
4015        request_builder.referrer = metadata
4016            .referrer
4017            .clone()
4018            .map(Referrer::ReferrerUrl)
4019            .unwrap_or(Referrer::NoReferrer);
4020        request_builder.referrer_policy = metadata.referrer_policy;
4021        request_builder.origin = request_builder
4022            .client
4023            .as_ref()
4024            .expect("Must have a client during redirect")
4025            .origin
4026            .clone();
4027
4028        let headers = metadata
4029            .headers
4030            .as_ref()
4031            .map(|headers| headers.clone().into_inner())
4032            .unwrap_or_default();
4033
4034        let response_init = Some(ResponseInit {
4035            url: metadata.final_url.clone(),
4036            location_url: metadata.location_url.clone(),
4037            headers,
4038            referrer: metadata.referrer.clone(),
4039            status_code: metadata
4040                .status
4041                .try_code()
4042                .map(|code| code.as_u16())
4043                .unwrap_or(200),
4044        });
4045
4046        incomplete_load.canceller = FetchCanceller::new(
4047            request_builder.id,
4048            false,
4049            self.resource_threads.core_thread.clone(),
4050        );
4051        NavigationListener::new(request_builder, self.senders.self_sender.clone())
4052            .initiate_fetch(&self.resource_threads.core_thread, response_init);
4053    }
4054
4055    /// Synchronously fetch a page with fixed content. Stores the `InProgressLoad`
4056    /// argument until a notification is received that the fetch is complete.
4057    fn start_synchronous_page_load(
4058        &self,
4059        cx: &mut js::context::JSContext,
4060        mut incomplete: InProgressLoad,
4061    ) {
4062        let mut context = ParserContext::new(
4063            incomplete.webview_id,
4064            incomplete.pipeline_id,
4065            incomplete.load_data.url.clone(),
4066            incomplete.load_data.creation_sandboxing_flag_set,
4067            incomplete.parent_info,
4068            incomplete.target_snapshot_params,
4069            incomplete.load_data.load_origin.clone(),
4070        );
4071
4072        let mut meta = Metadata::default(incomplete.load_data.url.clone());
4073        meta.set_content_type(Some(&mime::TEXT_HTML));
4074        meta.set_referrer_policy(incomplete.load_data.referrer_policy);
4075
4076        // If this page load is the result of a javascript scheme url, map
4077        // the evaluation result into a response.
4078        let chunk = match incomplete.load_data.js_eval_result {
4079            Some(ref mut content) => std::mem::take(content),
4080            None => String::new(),
4081        };
4082
4083        let policy_container = incomplete.load_data.policy_container.clone();
4084        let about_base_url = incomplete.load_data.about_base_url.clone();
4085        self.incomplete_loads.borrow_mut().push(incomplete);
4086
4087        let dummy_request_id = RequestId::default();
4088        context.process_response(cx, dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
4089        context.set_policy_container(policy_container.as_ref());
4090        context.set_about_base_url(about_base_url);
4091        context.process_response_chunk(cx, dummy_request_id, chunk.into());
4092        context.process_response_eof(
4093            cx,
4094            dummy_request_id,
4095            Ok(()),
4096            ResourceFetchTiming::new(ResourceTimingType::None),
4097        );
4098    }
4099
4100    /// Synchronously parse a srcdoc document from a giving HTML string.
4101    fn page_load_about_srcdoc(
4102        &self,
4103        cx: &mut js::context::JSContext,
4104        mut incomplete: InProgressLoad,
4105    ) {
4106        let url = ServoUrl::parse("about:srcdoc").unwrap();
4107        let mut meta = Metadata::default(url.clone());
4108        meta.set_content_type(Some(&mime::TEXT_HTML));
4109        meta.set_referrer_policy(incomplete.load_data.referrer_policy);
4110
4111        let srcdoc = std::mem::take(&mut incomplete.load_data.srcdoc);
4112        let chunk = srcdoc.into_bytes();
4113
4114        let policy_container = incomplete.load_data.policy_container.clone();
4115        let creation_sandboxing_flag_set = incomplete.load_data.creation_sandboxing_flag_set;
4116
4117        let webview_id = incomplete.webview_id;
4118        let pipeline_id = incomplete.pipeline_id;
4119        let parent_info = incomplete.parent_info;
4120        let about_base_url = incomplete.load_data.about_base_url.clone();
4121        let target_snapshot_params = incomplete.target_snapshot_params;
4122        let load_origin = incomplete.load_data.load_origin.clone();
4123        self.incomplete_loads.borrow_mut().push(incomplete);
4124
4125        let mut context = ParserContext::new(
4126            webview_id,
4127            pipeline_id,
4128            url,
4129            creation_sandboxing_flag_set,
4130            parent_info,
4131            target_snapshot_params,
4132            load_origin,
4133        );
4134        let dummy_request_id = RequestId::default();
4135
4136        context.process_response(cx, dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
4137        context.set_policy_container(policy_container.as_ref());
4138        context.set_about_base_url(about_base_url);
4139        context.process_response_chunk(cx, dummy_request_id, chunk);
4140        context.process_response_eof(
4141            cx,
4142            dummy_request_id,
4143            Ok(()),
4144            ResourceFetchTiming::new(ResourceTimingType::None),
4145        );
4146    }
4147
4148    fn handle_css_error_reporting(
4149        &self,
4150        pipeline_id: PipelineId,
4151        filename: String,
4152        line: u32,
4153        column: u32,
4154        msg: String,
4155    ) {
4156        let Some(ref sender) = self.senders.devtools_server_sender else {
4157            return;
4158        };
4159
4160        if let Some(window) = self.documents.borrow().find_window(pipeline_id) &&
4161            window.live_devtools_updates()
4162        {
4163            let css_error = CSSError {
4164                filename,
4165                line,
4166                column,
4167                msg,
4168            };
4169            let message = ScriptToDevtoolsControlMsg::ReportCSSError(pipeline_id, css_error);
4170            sender.send(message).unwrap();
4171        }
4172    }
4173
4174    fn handle_navigate_to(&self, pipeline_id: PipelineId, url: ServoUrl) {
4175        // The constellation only needs to know the WebView ID for navigation,
4176        // but actors don't keep track of it. Infer WebView ID from pipeline ID instead.
4177        if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
4178            self.senders
4179                .pipeline_to_constellation_sender
4180                .send((
4181                    document.webview_id(),
4182                    pipeline_id,
4183                    ScriptToConstellationMessage::LoadUrl(
4184                        LoadData::new_for_new_unrelated_webview(url),
4185                        NavigationHistoryBehavior::Push,
4186                        TargetSnapshotParams::default(),
4187                    ),
4188                ))
4189                .unwrap();
4190        }
4191    }
4192
4193    fn handle_traverse_history(&self, pipeline_id: PipelineId, direction: TraversalDirection) {
4194        // The constellation only needs to know the WebView ID for navigation,
4195        // but actors don't keep track of it. Infer WebView ID from pipeline ID instead.
4196        if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
4197            self.senders
4198                .pipeline_to_constellation_sender
4199                .send((
4200                    document.webview_id(),
4201                    pipeline_id,
4202                    ScriptToConstellationMessage::TraverseHistory(direction),
4203                ))
4204                .unwrap();
4205        }
4206    }
4207
4208    fn handle_reload(&self, pipeline_id: PipelineId, cx: &mut js::context::JSContext) {
4209        let window = self.documents.borrow().find_window(pipeline_id);
4210        if let Some(window) = window {
4211            window.Location(cx).reload_without_origin_check(cx);
4212        }
4213    }
4214
4215    fn handle_paint_metric(
4216        &self,
4217        pipeline_id: PipelineId,
4218        metric_type: ProgressiveWebMetricType,
4219        metric_value: CrossProcessInstant,
4220        first_reflow: bool,
4221        can_gc: CanGc,
4222    ) {
4223        match self.documents.borrow().find_document(pipeline_id) {
4224            Some(document) => {
4225                document.handle_paint_metric(metric_type, metric_value, first_reflow, can_gc)
4226            },
4227            None => warn!(
4228                "Received paint metric ({metric_type:?}) for unknown document: {pipeline_id:?}"
4229            ),
4230        }
4231    }
4232
4233    fn handle_media_session_action(
4234        &self,
4235        cx: &mut js::context::JSContext,
4236        pipeline_id: PipelineId,
4237        action: MediaSessionActionType,
4238    ) {
4239        if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
4240            let media_session = window.Navigator().MediaSession();
4241            media_session.handle_action(cx, action);
4242        } else {
4243            warn!("No MediaSession for this pipeline ID");
4244        };
4245    }
4246
4247    pub(crate) fn enqueue_microtask(job: Microtask) {
4248        with_script_thread(|script_thread| {
4249            script_thread
4250                .microtask_queue
4251                .enqueue(job, script_thread.get_cx());
4252        });
4253    }
4254
4255    pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut js::context::JSContext) {
4256        // Only perform the checkpoint if we're not shutting down.
4257        if self.can_continue_running_inner() {
4258            let globals = self
4259                .documents
4260                .borrow()
4261                .iter()
4262                .map(|(_id, document)| DomRoot::from_ref(document.window().upcast()))
4263                .collect();
4264
4265            self.microtask_queue.checkpoint(
4266                cx,
4267                |id| self.documents.borrow().find_global(id),
4268                globals,
4269            )
4270        }
4271    }
4272
4273    fn handle_evaluate_javascript(
4274        &self,
4275        webview_id: WebViewId,
4276        pipeline_id: PipelineId,
4277        evaluation_id: JavaScriptEvaluationId,
4278        script: String,
4279        cx: &mut js::context::JSContext,
4280    ) {
4281        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4282            let _ = self.senders.pipeline_to_constellation_sender.send((
4283                webview_id,
4284                pipeline_id,
4285                ScriptToConstellationMessage::FinishJavaScriptEvaluation(
4286                    evaluation_id,
4287                    Err(JavaScriptEvaluationError::WebViewNotReady),
4288                ),
4289            ));
4290            return;
4291        };
4292
4293        let global_scope = window.as_global_scope();
4294        let mut realm = enter_auto_realm(cx, global_scope);
4295        let cx = &mut realm.current_realm();
4296
4297        rooted!(&in(cx) let mut return_value = UndefinedValue());
4298        if let Err(err) = global_scope.evaluate_js_on_global(
4299            cx,
4300            script.into(),
4301            "",
4302            None, // No known `introductionType` for JS code from embedder
4303            Some(return_value.handle_mut()),
4304        ) {
4305            _ = self.senders.pipeline_to_constellation_sender.send((
4306                webview_id,
4307                pipeline_id,
4308                ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, Err(err)),
4309            ));
4310            return;
4311        };
4312
4313        let result = jsval_to_webdriver(cx, global_scope, return_value.handle());
4314        let _ = self.senders.pipeline_to_constellation_sender.send((
4315            webview_id,
4316            pipeline_id,
4317            ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, result),
4318        ));
4319    }
4320
4321    fn handle_refresh_cursor(&self, pipeline_id: PipelineId) {
4322        let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
4323            return;
4324        };
4325        document.event_handler().handle_refresh_cursor();
4326    }
4327
4328    pub(crate) fn is_servo_privileged(url: ServoUrl) -> bool {
4329        with_script_thread(|script_thread| script_thread.privileged_urls.contains(&url))
4330    }
4331
4332    fn handle_request_screenshot_readiness(
4333        &self,
4334        webview_id: WebViewId,
4335        pipeline_id: PipelineId,
4336        cx: &mut js::context::JSContext,
4337    ) {
4338        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4339            let _ = self.senders.pipeline_to_constellation_sender.send((
4340                webview_id,
4341                pipeline_id,
4342                ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
4343                    ScreenshotReadinessResponse::NoLongerActive,
4344                ),
4345            ));
4346            return;
4347        };
4348        window.request_screenshot_readiness(cx);
4349    }
4350
4351    fn handle_embedder_control_response(
4352        &self,
4353        id: EmbedderControlId,
4354        response: EmbedderControlResponse,
4355        cx: &mut js::context::JSContext,
4356    ) {
4357        let Some(document) = self.documents.borrow().find_document(id.pipeline_id) else {
4358            return;
4359        };
4360        document
4361            .embedder_controls()
4362            .handle_embedder_control_response(cx, id, response);
4363    }
4364
4365    pub(crate) fn handle_update_pinch_zoom_infos(
4366        &self,
4367        pipeline_id: PipelineId,
4368        pinch_zoom_infos: PinchZoomInfos,
4369        can_gc: CanGc,
4370    ) {
4371        let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4372            warn!("Visual viewport update for closed pipeline {pipeline_id}.");
4373            return;
4374        };
4375
4376        window.maybe_update_visual_viewport(pinch_zoom_infos, can_gc);
4377    }
4378
4379    pub(crate) fn devtools_want_updates_for_node(pipeline: PipelineId, node: &Node) -> bool {
4380        with_script_thread(|script_thread| {
4381            script_thread
4382                .devtools_state
4383                .wants_updates_for_node(pipeline, node)
4384        })
4385    }
4386}
4387
4388impl Drop for ScriptThread {
4389    fn drop(&mut self) {
4390        SCRIPT_THREAD_ROOT.with(|root| {
4391            root.set(None);
4392        });
4393    }
4394}