script/
script_thread.rs

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