Skip to main content

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