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