script/
script_thread.rs

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