script/
script_thread.rs

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