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