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