Skip to main content

servo_constellation/
constellation.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 `Constellation`, Servo's Grand Central Station
6//!
7//! The constellation tracks all information kept globally by the
8//! browser engine, which includes:
9//!
10//! * The set of all `EventLoop` objects. Each event loop is
11//!   the constellation's view of a script thread. The constellation
12//!   interacts with a script thread by message-passing.
13//!
14//! * The set of all `Pipeline` objects.  Each pipeline gives the
15//!   constellation's view of a `Window`, with its script thread and
16//!   layout.  Pipelines may share script threads.
17//!
18//! * The set of all `BrowsingContext` objects. Each browsing context
19//!   gives the constellation's view of a `WindowProxy`.
20//!   Each browsing context stores an independent
21//!   session history, created by navigation. The session
22//!   history can be traversed, for example by the back and forwards UI,
23//!   so each session history maintains a list of past and future pipelines,
24//!   as well as the current active pipeline.
25//!
26//! There are two kinds of browsing context: top-level ones (for
27//! example tabs in a browser UI), and nested ones (typically caused
28//! by `iframe` elements). Browsing contexts have a hierarchy
29//! (typically caused by `iframe`s containing `iframe`s), giving rise
30//! to a forest whose roots are top-level browsing context.  The logical
31//! relationship between these types is:
32//!
33//! ```text
34//! +------------+                      +------------+                 +---------+
35//! |  Browsing  | ------parent?------> |  Pipeline  | --event_loop--> |  Event  |
36//! |  Context   | ------current------> |            |                 |  Loop   |
37//! |            | ------prev*--------> |            | <---pipeline*-- |         |
38//! |            | ------next*--------> |            |                 +---------+
39//! |            |                      |            |
40//! |            | <-top_level--------- |            |
41//! |            | <-browsing_context-- |            |
42//! +------------+                      +------------+
43//! ```
44//
45//! The constellation also maintains channels to other parts of Servo, including:
46//!
47//! * The script thread.
48//! * The `Paint` subsystem, which runs in the same thread as the `Servo` instance.
49//! * The font cache, image cache, and resource manager, which load
50//!   and cache shared fonts, images, or other resources.
51//! * The service worker manager.
52//! * The devtools and webdriver servers.
53//!
54//! The constellation passes messages between the threads, and updates its state
55//! to track the evolving state of the browsing context tree.
56//!
57//! The constellation acts as a logger, tracking any `warn!` messages from threads,
58//! and converting any `error!` or `panic!` into a crash report.
59//!
60//! Since there is only one constellation, and its responsibilities include crash reporting,
61//! it is very important that it does not panic.
62//!
63//! It's also important that the constellation not deadlock. In particular, we need
64//! to be careful that we don't introduce any cycles in the can-block-on relation.
65//! Blocking is typically introduced by `receiver.recv()`, which blocks waiting for the
66//! sender to send some data. Servo tries to achieve deadlock-freedom by using the following
67//! can-block-on relation:
68//!
69//! * Constellation can block on `Paint`
70//! * Constellation can block on embedder
71//! * Script can block on anything (other than script)
72//! * Blocking is transitive (if T1 can block on T2 and T2 can block on T3 then T1 can block on T3)
73//! * Nothing can block on itself!
74//!
75//! There is a complexity intoduced by IPC channels, since they do not support
76//! non-blocking send. This means that as well as `receiver.recv()` blocking,
77//! `sender.send(data)` can also block when the IPC buffer is full. For this reason it is
78//! very important that all IPC receivers where we depend on non-blocking send
79//! use a router to route IPC messages to an mpsc channel. The reason why that solves
80//! the problem is that under the hood, the router uses a dedicated thread to forward
81//! messages, and:
82//!
83//! * Anything (other than a routing thread) can block on a routing thread
84//!
85//! See <https://github.com/servo/servo/issues/14704>
86
87use std::borrow::ToOwned;
88use std::cell::{Cell, OnceCell, RefCell};
89use std::collections::hash_map::Entry;
90use std::collections::{HashMap, HashSet, VecDeque};
91use std::marker::PhantomData;
92use std::mem::replace;
93use std::rc::{Rc, Weak};
94use std::sync::Arc;
95use std::thread::JoinHandle;
96use std::{process, thread};
97
98use accesskit::{ActionRequest, TreeId};
99use background_hang_monitor_api::{
100    BackgroundHangMonitorControlMsg, BackgroundHangMonitorRegister, HangAlert,
101};
102use content_security_policy::sandboxing_directive::SandboxingFlagSet;
103use crossbeam_channel::{Receiver, Select, Sender, unbounded};
104#[cfg(feature = "devtools")]
105use devtools_traits::{
106    ChromeToDevtoolsControlMsg, DevtoolsControlMsg, DevtoolsPageInfo, NavigationState,
107    ScriptToDevtoolsControlMsg,
108};
109#[cfg(feature = "multiprocess")]
110use embedder_traits::resources::ResourceBytes;
111use embedder_traits::resources::{self, Resource};
112use embedder_traits::user_contents::{UserContentManagerId, UserContents};
113use embedder_traits::{
114    AnimationState, EmbedderControlId, EmbedderControlResponse, EmbedderProxy, FocusSequenceNumber,
115    GenericEmbedderProxy, InputEvent, InputEventAndId, InputEventOutcome, JSValue,
116    JavaScriptEvaluationError, JavaScriptEvaluationId, KeyboardEvent, MediaSessionActionType,
117    MediaSessionEvent, MediaSessionPlaybackState, MouseButtonAction, MouseButtonEvent,
118    NewWebViewDetails, PaintHitTestResult, Theme, ViewportDetails, WakeLockDelegate, WakeLockType,
119    WebDriverCommandMsg, WebDriverLoadStatus, WebDriverLoadStatusMessage, WebDriverScriptCommand,
120};
121use euclid::default::Size2D as UntypedSize2D;
122use fonts::SystemFontServiceProxy;
123use ipc_channel::router::ROUTER;
124use keyboard_types::{Key, KeyState, Modifiers, NamedKey};
125use layout_api::{LayoutFactory, ScriptThreadFactory};
126use log::{debug, error, info, trace, warn};
127use media::WindowGLContext;
128use net::image_cache::ImageCacheFactoryImpl;
129use net_traits::pub_domains::registered_domain_name;
130use net_traits::request::UpgradeInsecureNavigations;
131use net_traits::{self, AsyncRuntime, FetchThread, ResourceThreads};
132use paint_api::{
133    PaintMessage, PaintProxy, PinchZoomInfos, PipelineExitSource, SendableFrameTree,
134    WebRenderExternalImageIdManager,
135};
136use profile_traits::mem::ProfilerMsg;
137use profile_traits::{mem, time};
138use rand::rngs::SmallRng;
139use rand::seq::IndexedRandom;
140use rand::{RngExt, SeedableRng, make_rng};
141use rustc_hash::{FxHashMap, FxHashSet};
142use script_traits::{
143    ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, MouseButtons,
144    NewPipelineInfo, ScriptThreadMessage, UpdatePipelineIdReason,
145};
146use servo_background_hang_monitor::HangMonitorRegister;
147use servo_base::generic_channel;
148use servo_base::generic_channel::{
149    GenericCallback, GenericSend, GenericSender, RoutedReceiver, SendError,
150};
151use servo_base::id::{
152    BrowsingContextId, CONSTELLATION_PIPELINE_NAMESPACE_ID, FIRST_CONTENT_PIPELINE_NAMESPACE_ID,
153    HistoryStateId, MessagePortId, MessagePortRouterId, PainterId, PipelineId, PipelineNamespace,
154    PipelineNamespaceId, PipelineNamespaceRequest, ScriptEventLoopId, ServiceWorkerId, WebViewId,
155    WorkerId,
156};
157use servo_base::threadboost::{BoostAffinity, ThreadPriority};
158#[cfg(feature = "bluetooth")]
159use servo_bluetooth_traits::BluetoothRequest;
160use servo_canvas::canvas_paint_thread::CanvasPaintThread;
161use servo_canvas_traits::ConstellationCanvasMsg;
162use servo_canvas_traits::canvas::{CanvasId, CanvasMsg};
163use servo_config::{opts, pref};
164use servo_constellation_traits::{
165    AuxiliaryWebViewCreationRequest, AuxiliaryWebViewCreationResponse, ConstellationInterest,
166    EmbedderToConstellationMessage, HistoryTraversalSource, IFrameLoadInfo, IFrameLoadInfoWithData,
167    IFrameSizeMsg, LoadData, LogEntry, MessagePortMsg, NavigationHistoryBehavior, PaintMetricEvent,
168    PortMessageTask, PortTransferInfo, RemoteFocusOperation, SWManagerSenders,
169    ScreenshotReadinessResponse, ScriptToConstellationMessage, ScrollStateUpdate,
170    ServiceWorkerAlgorithm, ServiceWorkerManagerFactory, ServiceWorkerManagerMsg, ServiceWorkerMsg,
171    SessionHistoryTraversalRequest, StructuredSerializedData, TargetSnapshotParams,
172    TraversalDirection, UserContentManagerAction, WindowSizeType, WorkerAnimationFrameTick,
173};
174use servo_url::{Host, ImmutableOrigin, ServoUrl};
175use storage_traits::StorageThreads;
176use storage_traits::cache_storage::CacheStorageThreadMessage;
177use storage_traits::client_storage::ClientStorageThreadMessage;
178use storage_traits::indexeddb::{IndexedDBThreadMsg, SyncOperation};
179use storage_traits::webstorage_thread::{WebStorageThreadMsg, WebStorageType};
180#[cfg(feature = "webgpu")]
181use webgpu::canvas_context::WebGpuExternalImageMap;
182#[cfg(feature = "webgpu")]
183use webgpu_traits::{WebGPU, WebGPURequest};
184
185use super::embedder::ConstellationToEmbedderMsg;
186use crate::broadcastchannel::BroadcastChannels;
187use crate::browsingcontext::{
188    AllBrowsingContextsIterator, BrowsingContext, FullyActiveBrowsingContextsIterator,
189    NewBrowsingContextInfo,
190};
191use crate::constellation_webview::{ConstellationWebView, OngoingHistoryTraversalRequest};
192use crate::event_loop::EventLoop;
193use crate::pipeline::Pipeline;
194use crate::serviceworker::ServiceWorkerUnprivilegedContent;
195use crate::session_history::{NeedsToReload, SessionHistoryChange, SessionHistoryDiff};
196
197struct PendingApprovalNavigation {
198    load_data: LoadData,
199    history_behaviour: NavigationHistoryBehavior,
200    target_snapshot_params: TargetSnapshotParams,
201}
202
203type PendingApprovalNavigations = FxHashMap<PipelineId, PendingApprovalNavigation>;
204
205#[derive(Debug)]
206/// The state used by MessagePortInfo to represent the various states the port can be in.
207enum TransferState {
208    /// The port is currently managed by a given global,
209    /// identified by its router id.
210    Managed(MessagePortRouterId),
211    /// The port is currently in-transfer,
212    /// and incoming tasks should be buffered until it becomes managed again.
213    TransferInProgress(VecDeque<PortMessageTask>),
214    /// A global has requested the transfer to be completed,
215    /// it's pending a confirmation of either failure or success to complete the transfer.
216    CompletionInProgress(MessagePortRouterId),
217    /// While a completion of a transfer was in progress, the port was shipped,
218    /// hence the transfer failed to complete.
219    /// We start buffering incoming messages,
220    /// while awaiting the return of the previous buffer from the global
221    /// that failed to complete the transfer.
222    CompletionFailed(VecDeque<PortMessageTask>),
223    /// While a completion failed, another global requested to complete the transfer.
224    /// We are still buffering messages, and awaiting the return of the buffer from the global who failed.
225    CompletionRequested(MessagePortRouterId, VecDeque<PortMessageTask>),
226}
227
228#[derive(Debug)]
229/// Info related to a message-port tracked by the constellation.
230struct MessagePortInfo {
231    /// The current state of the messageport.
232    state: TransferState,
233
234    /// The id of the entangled port, if any.
235    entangled_with: Option<MessagePortId>,
236}
237
238#[cfg(feature = "webgpu")]
239/// WebRender related objects required by WebGPU threads
240struct WebRenderWGPU {
241    /// List of Webrender external images
242    webrender_external_image_id_manager: WebRenderExternalImageIdManager,
243
244    /// WebGPU data that supplied to Webrender for rendering
245    wgpu_image_map: WebGpuExternalImageMap,
246}
247
248/// A browsing context group.
249///
250/// <https://html.spec.whatwg.org/multipage/#browsing-context-group>
251#[derive(Default)]
252pub(crate) struct BrowsingContextGroup {
253    /// The set of all event loops in this BrowsingContextGroup.
254    /// We store the event loops in a map
255    /// indexed by registered domain name (as a `Host`) to event loops.
256    /// It is important that scripts with the same eTLD+1,
257    /// who are part of the same browsing-context group
258    /// share an event loop, since they can use `document.domain`
259    /// to become same-origin, at which point they can share DOM objects.
260    event_loops: HashMap<Host, Weak<EventLoop>>,
261
262    /// The set of all WebGPU channels in this BrowsingContextGroup.
263    #[cfg(feature = "webgpu")]
264    webgpus: HashMap<Host, WebGPU>,
265}
266
267impl Drop for BrowsingContextGroup {
268    fn drop(&mut self) {
269        #[cfg(feature = "webgpu")]
270        for webgpu in self.webgpus.values() {
271            // Request that the WebGPU exit, but do not wait for it to do so. We are explicitly
272            // avoiding a synchronous wait here in the middle of Constellation operation. If
273            // it becomes necessary in the future these receivers could be waited on asynchronously
274            // via polling.
275            if let Some((sender, _)) = generic_channel::oneshot() &&
276                let Err(error) = webgpu.exit(sender)
277            {
278                warn!("Failed to request WebGPU exit: {error}.");
279            }
280        }
281    }
282}
283
284struct WorkerAnimationFrameProvider {
285    webview_id: WebViewId,
286    pipeline_id: PipelineId,
287    sender: GenericSender<WorkerAnimationFrameTick>,
288    tick_pending: bool,
289}
290
291/// Information about service workers that are pending a state update script task,
292/// on which we have to wait at step 21 of <https://w3c.github.io/ServiceWorker/#installation-algorithm>.
293struct ServiceWorkerPendingUpdate {
294    pipelines: HashMap<PipelineId, usize>,
295    origin: ImmutableOrigin,
296}
297
298/// The `Constellation` itself. In the servo browser, there is one
299/// constellation, which maintains all of the browser global data.
300/// In embedded applications, there may be more than one constellation,
301/// which are independent of each other.
302///
303/// The constellation may be in a different process from the pipelines,
304/// and communicates using IPC.
305///
306/// It is parameterized over a `LayoutThreadFactory` and a
307/// `ScriptThreadFactory` (which in practice are implemented by
308/// `LayoutThread` in the `layout` crate, and `ScriptThread` in
309/// the `script` crate). Script and layout communicate using a `Message`
310/// type.
311pub struct Constellation<STF, SWF> {
312    /// An ipc-sender/threaded-receiver pair
313    /// to facilitate installing pipeline namespaces in threads
314    /// via a per-process installer.
315    namespace_receiver: RoutedReceiver<PipelineNamespaceRequest>,
316    pub(crate) namespace_ipc_sender: GenericSender<PipelineNamespaceRequest>,
317
318    /// A [`Vec`] of all [`EventLoop`]s that have been created for this [`Constellation`].
319    /// This will be cleaned up periodically. This stores weak references so that [`EventLoop`]s
320    /// can be stopped when they are no longer used.
321    event_loops: Vec<Weak<EventLoop>>,
322
323    /// An IPC channel for script threads to send messages to the constellation.
324    /// This is the script threads' view of `script_receiver`.
325    pub(crate) script_sender: GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
326
327    /// A channel for the constellation to receive messages from script threads.
328    /// This is the constellation's view of `script_sender`.
329    script_receiver:
330        Receiver<Result<(WebViewId, PipelineId, ScriptToConstellationMessage), SendError>>,
331
332    /// A handle to register components for hang monitoring.
333    /// None when in multiprocess mode.
334    pub(crate) background_monitor_register: Option<Box<dyn BackgroundHangMonitorRegister>>,
335
336    /// In single process mode, a join handle on the BHM worker thread.
337    background_monitor_register_join_handle: Option<JoinHandle<()>>,
338
339    /// When running in single-process mode, this is a channel to the shared BackgroundHangMonitor
340    /// for all [`EventLoop`]s. This will be `None` in multiprocess mode.
341    background_monitor_control_sender: Option<GenericSender<BackgroundHangMonitorControlMsg>>,
342
343    /// A channel for the background hang monitor to send messages
344    /// to the constellation.
345    #[cfg_attr(not(feature = "multiprocess"), expect(unused))]
346    pub(crate) background_hang_monitor_sender: GenericSender<HangAlert>,
347
348    /// A channel for the constellation to receiver messages
349    /// from the background hang monitor.
350    background_hang_monitor_receiver: RoutedReceiver<HangAlert>,
351
352    /// Receiver of messages from the service worker manager.
353    sw_manager_receiver: RoutedReceiver<ServiceWorkerManagerMsg>,
354
355    /// Sender of messages from the service worker manager.
356    /// Necessary for algorithms like <https://w3c.github.io/ServiceWorker/#update-state-algorithm>,
357    /// which broadcast messages to multiple pipelines.
358    sw_manager_sender: GenericSender<ServiceWorkerManagerMsg>,
359
360    /// Service workers waiting for their state update tasks to complete at step 21 of
361    /// <https://w3c.github.io/ServiceWorker/#installation-algorithm>.
362    service_workers_pending_update: HashMap<ServiceWorkerId, ServiceWorkerPendingUpdate>,
363
364    /// A factory for creating layouts. This allows customizing the kind
365    /// of layout created for a [`Constellation`] and prevents a circular crate
366    /// dependency between script and layout.
367    pub(crate) layout_factory: Arc<dyn LayoutFactory>,
368
369    /// A channel for the embedder (renderer and libservo) to send messages to the [`Constellation`].
370    embedder_to_constellation_receiver: Receiver<EmbedderToConstellationMessage>,
371
372    /// A channel through which messages can be sent to the embedder. This is not used by the `Constellation`
373    /// itself but only needed to create an `EventLoop`.
374    /// Messages from the `Constellation` to the embedder are sent using the `constellation_to_embedder_proxy`
375    pub(crate) embedder_proxy: EmbedderProxy,
376
377    /// A channel through which messages can be sent to the embedder.
378    pub(crate) constellation_to_embedder_proxy: GenericEmbedderProxy<ConstellationToEmbedderMsg>,
379
380    /// A channel (the implementation of which is port-specific) for the
381    /// constellation to send messages to `Paint`.
382    pub(crate) paint_proxy: PaintProxy,
383
384    /// Bookkeeping data for all webviews in the constellation.
385    webviews: FxHashMap<WebViewId, ConstellationWebView>,
386
387    /// Channels for the constellation to send messages to the public
388    /// resource-related threads. There are two groups of resource threads: one
389    /// for public browsing, and one for private browsing.
390    pub(crate) public_resource_threads: ResourceThreads,
391
392    /// Channels for the constellation to send messages to the private
393    /// resource-related threads.  There are two groups of resource
394    /// threads: one for public browsing, and one for private
395    /// browsing.
396    pub(crate) private_resource_threads: ResourceThreads,
397
398    /// Channels for the constellation to send messages to the public
399    /// storage-related threads. There are two groups of storage threads: one
400    /// for public browsing, and one for private browsing.
401    pub(crate) public_storage_threads: StorageThreads,
402
403    /// Channels for the constellation to send messages to the private
404    /// storage-related threads.  There are two groups of storage
405    /// threads: one for public browsing, and one for private
406    /// browsing.
407    pub(crate) private_storage_threads: StorageThreads,
408
409    /// A channel for the constellation to send messages to the font
410    /// cache thread.
411    pub(crate) system_font_service: Arc<SystemFontServiceProxy>,
412
413    /// A channel for the constellation to send messages to the
414    /// devtools thread.
415    #[cfg(feature = "devtools")]
416    pub(crate) devtools_sender: Option<Sender<DevtoolsControlMsg>>,
417
418    /// A (potentially) IPC-based channel to the developer tools, if enabled. This allows
419    /// `EventLoop`s to send messages to then. Shared with all `EventLoop`s.
420    #[cfg(feature = "devtools")]
421    pub script_to_devtools_callback: OnceCell<Option<GenericCallback<ScriptToDevtoolsControlMsg>>>,
422
423    /// An IPC channel for the constellation to send messages to the
424    /// bluetooth thread.
425    #[cfg(feature = "bluetooth")]
426    pub(crate) bluetooth_ipc_sender: GenericSender<BluetoothRequest>,
427
428    /// A map of origin to sender to a Service worker manager.
429    sw_managers: HashMap<ImmutableOrigin, GenericSender<ServiceWorkerMsg>>,
430
431    /// A channel for the constellation to send messages to the
432    /// time profiler thread.
433    pub(crate) time_profiler_chan: time::ProfilerChan,
434
435    /// A channel for the constellation to send messages to the
436    /// memory profiler thread.
437    pub(crate) mem_profiler_chan: mem::ProfilerChan,
438
439    /// WebRender related objects required by WebGPU threads
440    #[cfg(feature = "webgpu")]
441    webrender_wgpu: WebRenderWGPU,
442
443    /// A map of message-port Id to info.
444    message_ports: FxHashMap<MessagePortId, MessagePortInfo>,
445
446    /// A map of router-id to ipc-sender, to route messages to ports.
447    message_port_routers: FxHashMap<MessagePortRouterId, GenericCallback<MessagePortMsg>>,
448
449    /// Bookkeeping for BroadcastChannel functionnality.
450    broadcast_channels: BroadcastChannels,
451
452    /// Tracks which pipelines have registered interest in each notification category.
453    pipeline_interests: FxHashMap<ConstellationInterest, FxHashSet<PipelineId>>,
454
455    /// The set of all the pipelines in the browser.  (See the `pipeline` module
456    /// for more details.)
457    pipelines: FxHashMap<PipelineId, Pipeline>,
458
459    worker_animation_frame_providers: FxHashMap<WorkerId, WorkerAnimationFrameProvider>,
460
461    /// The set of all the browsing contexts in the browser.
462    browsing_contexts: FxHashMap<BrowsingContextId, BrowsingContext>,
463
464    /// Pipeline IDs are namespaced in order to avoid name collisions,
465    /// and the namespaces are allocated by the constellation.
466    next_pipeline_namespace_id: Cell<PipelineNamespaceId>,
467
468    /// Senders to notify WebDriver of navigation events, keyed by webview.
469    webdriver_load_status_senders: FxHashMap<WebViewId, GenericSender<WebDriverLoadStatusMessage>>,
470
471    /// The top-level browsing contexts with a navigation in progress, as last reported to
472    /// WebDriver.
473    webdriver_navigating_webviews: FxHashSet<WebViewId>,
474
475    /// Are we shutting down?
476    shutting_down: bool,
477
478    /// Have we seen any warnings? Hopefully always empty!
479    /// The buffer contains `(thread_name, reason)` entries.
480    handled_warnings: VecDeque<(Option<String>, String)>,
481
482    /// The random number generator and probability for closing pipelines.
483    /// This is for testing the hardening of the constellation.
484    random_pipeline_closure: Option<(SmallRng, f32)>,
485
486    /// Phantom data that keeps the Rust type system happy.
487    phantom: PhantomData<(STF, SWF)>,
488
489    /// Entry point to create and get channels to a WebGLThread.
490    #[cfg(feature = "webgl")]
491    pub(crate) webgl_threads: Option<servo_canvas_traits::webgl::WebGLThreads>,
492
493    /// The XR device registry
494    pub(crate) webxr_registry: Option<webxr_api::Registry>,
495
496    /// Lazily initialized channels for canvas paint thread.
497    canvas: OnceCell<(Sender<ConstellationCanvasMsg>, GenericSender<CanvasMsg>)>,
498
499    /// Navigation requests from script awaiting approval from the embedder.
500    pending_approval_navigations: PendingApprovalNavigations,
501
502    /// Bitmask which indicates which combination of mouse buttons are
503    /// currently being pressed.
504    pressed_mouse_buttons: MouseButtons,
505
506    /// The currently activated keyboard modifiers.
507    active_keyboard_modifiers: Modifiers,
508
509    /// If True, exits on thread failure instead of displaying about:failure
510    hard_fail: bool,
511
512    /// Pipeline ID of the active media session.
513    active_media_session: Option<PipelineId>,
514
515    /// Aggregate screen wake lock count across all webviews. The provider is notified
516    /// only when this transitions 0→1 (acquire) or N→0 (release).
517    screen_wake_lock_count: u32,
518
519    /// Provider for OS-level screen wake lock acquisition and release.
520    wake_lock_provider: Box<dyn WakeLockDelegate>,
521
522    /// The image bytes associated with the BrokenImageIcon embedder resource.
523    /// Read during startup and provided to image caches that are created
524    /// on an as-needed basis, rather than retrieving it every time.
525    #[cfg(feature = "multiprocess")]
526    pub(crate) broken_image_icon_data: ResourceBytes,
527
528    /// The process manager.
529    #[cfg(feature = "multiprocess")]
530    pub(crate) process_manager: crate::process_manager::ProcessManager,
531
532    /// The async runtime.
533    async_runtime: Box<dyn AsyncRuntime>,
534
535    /// A vector of [`JoinHandle`]s used to ensure full termination of threaded [`EventLoop`]s
536    /// which are runnning in the same process.
537    event_loop_join_handles: Vec<JoinHandle<()>>,
538
539    /// A list of URLs that can access privileged internal APIs.
540    pub(crate) privileged_urls: Vec<ServoUrl>,
541
542    /// The [`ImageCacheFactory`] to use for all `ScriptThread`s when we are running in
543    /// single-process mode. In multi-process mode, each process will create its own
544    /// [`ImageCacheFactoryImpl`].
545    pub(crate) image_cache_factory: Arc<ImageCacheFactoryImpl>,
546
547    /// A map from `UserContentManagerId` to the `UserContents` for that manager.
548    /// Multiple `WebView`s can share the same `UserContentManager` and any mutations
549    /// to the `UserContents` need to be forwared to all the `ScriptThread`s that host
550    /// the relevant `WebView`.
551    pub(crate) user_contents_for_manager_id: FxHashMap<UserContentManagerId, UserContents>,
552
553    /// Whether Servo is online or not. This is controlled by the embedder.
554    online: bool,
555}
556
557/// State needed to construct a constellation.
558pub struct InitialConstellationState {
559    /// A channel through which messages can be sent to the embedder. This is not used by the `Constellation`
560    /// itself but only needed to create an `EventLoop`.
561    /// Messages from the `Constellation` to the embedder are sent using the `constellation_to_embedder_proxy`
562    pub embedder_proxy: EmbedderProxy,
563
564    /// A channel through which messages can be sent to the embedder.
565    pub constellation_to_embedder_proxy: GenericEmbedderProxy<ConstellationToEmbedderMsg>,
566
567    /// A channel through which messages can be sent to `Paint` in-process.
568    pub paint_proxy: PaintProxy,
569
570    /// A channel to the developer tools, if applicable.
571    #[cfg(feature = "devtools")]
572    pub devtools_sender: Option<Sender<DevtoolsControlMsg>>,
573
574    /// A channel to the bluetooth thread.
575    #[cfg(feature = "bluetooth")]
576    pub bluetooth_thread: GenericSender<BluetoothRequest>,
577
578    /// A proxy to the `SystemFontService` which manages the list of system fonts.
579    pub system_font_service: Arc<SystemFontServiceProxy>,
580
581    /// A channel to the resource thread.
582    pub public_resource_threads: ResourceThreads,
583
584    /// A channel to the resource thread.
585    pub private_resource_threads: ResourceThreads,
586
587    /// A channel to the storage thread.
588    pub public_storage_threads: StorageThreads,
589
590    /// A channel to the storage thread.
591    pub private_storage_threads: StorageThreads,
592
593    /// A channel to the time profiler thread.
594    pub time_profiler_chan: time::ProfilerChan,
595
596    /// A channel to the memory profiler thread.
597    pub mem_profiler_chan: mem::ProfilerChan,
598
599    /// A [`WebRenderExternalImageIdManager`] used to lazily start up the WebGPU threads.
600    pub webrender_external_image_id_manager: WebRenderExternalImageIdManager,
601
602    /// Entry point to create and get channels to a WebGLThread.
603    #[cfg(feature = "webgl")]
604    pub webgl_threads: Option<servo_canvas_traits::webgl::WebGLThreads>,
605
606    /// The XR device registry
607    pub webxr_registry: Option<webxr_api::Registry>,
608
609    #[cfg(feature = "webgpu")]
610    pub wgpu_image_map: WebGpuExternalImageMap,
611
612    /// A list of URLs that can access privileged internal APIs.
613    pub privileged_urls: Vec<ServoUrl>,
614
615    /// The async runtime.
616    pub async_runtime: Box<dyn AsyncRuntime>,
617
618    /// The wake lock provider for acquiring and releasing OS-level screen wake locks.
619    pub wake_lock_provider: Box<dyn WakeLockDelegate>,
620}
621
622/// The number of warnings to include in each crash report.
623const WARNINGS_BUFFER_SIZE: usize = 32;
624
625impl<STF, SWF> Constellation<STF, SWF>
626where
627    STF: ScriptThreadFactory,
628    SWF: ServiceWorkerManagerFactory,
629{
630    /// Create a new constellation thread.
631    #[servo_tracing::instrument(skip(state, layout_factory))]
632    pub fn start(
633        embedder_to_constellation_receiver: Receiver<EmbedderToConstellationMessage>,
634        state: InitialConstellationState,
635        layout_factory: Arc<dyn LayoutFactory>,
636        random_pipeline_closure_probability: Option<f32>,
637        random_pipeline_closure_seed: Option<usize>,
638        hard_fail: bool,
639    ) {
640        thread::Builder::new()
641            .name("Constellation".to_owned())
642            .spawn(move || {
643                servo_base::threadboost::boost_thread(ThreadPriority::Elevated, BoostAffinity::Boost);
644                let (script_ipc_sender, script_ipc_receiver) =
645                    generic_channel::channel().expect("ipc channel failure");
646                let script_receiver = script_ipc_receiver.route_preserving_errors();
647
648                let (namespace_ipc_sender, namespace_ipc_receiver) =
649                    generic_channel::channel().expect("ipc channel failure");
650                let namespace_receiver = namespace_ipc_receiver.route_preserving_errors();
651
652                let (background_hang_monitor_ipc_sender, background_hang_monitor_ipc_receiver) =
653                    generic_channel::channel().expect("ipc channel failure");
654                let background_hang_monitor_receiver =
655                    background_hang_monitor_ipc_receiver.route_preserving_errors();
656
657                let (sw_manager_sender, sw_manager_ipc_receiver) =
658                    generic_channel::channel().expect("ipc channel failure");
659                let sw_manager_receiver = sw_manager_ipc_receiver.route_preserving_errors();
660
661                // If we are in multiprocess mode,
662                // a dedicated per-process hang monitor will be initialized later inside the content process.
663                // See run_content_process in servo/lib.rs
664
665                let (
666                    background_monitor_register,
667                    background_monitor_register_join_handle,
668                    background_monitor_control_sender
669                ) = if opts::get().multiprocess {
670                    (None, None, None)
671                } else {
672                    let (
673                        background_hang_monitor_control_ipc_sender,
674                        background_hang_monitor_control_ipc_receiver,
675                    ) = generic_channel::channel().expect("ipc channel failure");
676                    let (register, join_handle) = HangMonitorRegister::init(
677                        background_hang_monitor_ipc_sender.clone(),
678                        background_hang_monitor_control_ipc_receiver,
679                        opts::get().background_hang_monitor,
680                    );
681                    (
682                        Some(register),
683                        Some(join_handle),
684                        Some(background_hang_monitor_control_ipc_sender),
685                    )
686                };
687
688                PipelineNamespace::install(CONSTELLATION_PIPELINE_NAMESPACE_ID);
689
690                #[cfg(feature = "webgpu")]
691                let webrender_wgpu = WebRenderWGPU {
692                    webrender_external_image_id_manager: state.webrender_external_image_id_manager,
693                    wgpu_image_map: state.wgpu_image_map,
694                };
695
696                let broken_image_icon_data = resources::read_bytes(Resource::BrokenImageIcon);
697
698                let mut constellation: Constellation<STF, SWF> = Constellation {
699                    event_loops: Default::default(),
700                    sw_manager_sender,
701                    sw_manager_receiver,
702                    service_workers_pending_update: Default::default(),
703                    namespace_receiver,
704                    namespace_ipc_sender,
705                    script_sender: script_ipc_sender,
706                    background_hang_monitor_sender: background_hang_monitor_ipc_sender,
707                    background_hang_monitor_receiver,
708                    background_monitor_register,
709                    background_monitor_register_join_handle,
710                    background_monitor_control_sender,
711                    script_receiver,
712                    embedder_to_constellation_receiver,
713                    layout_factory,
714                    embedder_proxy: state.embedder_proxy,
715                    constellation_to_embedder_proxy: state.constellation_to_embedder_proxy,
716                    paint_proxy: state.paint_proxy,
717                    webviews: Default::default(),
718                    #[cfg(feature = "devtools")]
719                    devtools_sender: state.devtools_sender,
720                    #[cfg(feature = "devtools")]
721                    script_to_devtools_callback: Default::default(),
722                    #[cfg(feature = "bluetooth")]
723                    bluetooth_ipc_sender: state.bluetooth_thread,
724                    public_resource_threads: state.public_resource_threads,
725                    private_resource_threads: state.private_resource_threads,
726                    public_storage_threads: state.public_storage_threads,
727                    private_storage_threads: state.private_storage_threads,
728                    system_font_service: state.system_font_service,
729                    sw_managers: Default::default(),
730                    message_ports: Default::default(),
731                    message_port_routers: Default::default(),
732                    broadcast_channels: Default::default(),
733                    pipeline_interests: Default::default(),
734                    pipelines: Default::default(),
735                    worker_animation_frame_providers: Default::default(),
736                    browsing_contexts: Default::default(),
737                    next_pipeline_namespace_id: Cell::new(FIRST_CONTENT_PIPELINE_NAMESPACE_ID),
738                    time_profiler_chan: state.time_profiler_chan,
739                    mem_profiler_chan: state.mem_profiler_chan.clone(),
740                    phantom: PhantomData,
741                    webdriver_load_status_senders: Default::default(),
742                    webdriver_navigating_webviews: Default::default(),
743                    #[cfg(feature = "webgpu")]
744                    webrender_wgpu,
745                    shutting_down: false,
746                    handled_warnings: VecDeque::new(),
747                    random_pipeline_closure: random_pipeline_closure_probability.map(|probability| {
748                        let rng = random_pipeline_closure_seed
749                            .map(|seed| SmallRng::seed_from_u64(seed as u64))
750                            .unwrap_or_else(make_rng);
751                        warn!("Randomly closing pipelines using seed {random_pipeline_closure_seed:?}.");
752                        (rng, probability)
753                    }),
754                    #[cfg(feature = "webgl")]
755                    webgl_threads: state.webgl_threads,
756                    webxr_registry: state.webxr_registry,
757                    canvas: OnceCell::new(),
758                    pending_approval_navigations: Default::default(),
759                    pressed_mouse_buttons: MouseButtons::empty(),
760                    active_keyboard_modifiers: Modifiers::empty(),
761                    hard_fail,
762                    active_media_session: None,
763                    screen_wake_lock_count: 0,
764                    wake_lock_provider: state.wake_lock_provider,
765                    #[cfg(feature = "multiprocess")]
766                    broken_image_icon_data: broken_image_icon_data.clone(),
767                    #[cfg(feature = "multiprocess")]
768                    process_manager: crate::process_manager::ProcessManager::new(state.mem_profiler_chan),
769                    async_runtime: state.async_runtime,
770                    event_loop_join_handles: Default::default(),
771                    privileged_urls: state.privileged_urls,
772                    image_cache_factory: Arc::new(ImageCacheFactoryImpl::new(
773                        broken_image_icon_data,
774                    )),
775                    user_contents_for_manager_id: Default::default(),
776                    // Servo is online by default.
777                    online: true,
778                };
779
780                constellation.run();
781            })
782            .expect("Thread spawning failed");
783    }
784
785    /// Whether or not the embedder has put Servo in online mode or offline mode.
786    pub(crate) fn online(&self) -> bool {
787        self.online
788    }
789
790    fn event_loops(&self) -> Vec<Rc<EventLoop>> {
791        self.event_loops
792            .iter()
793            .filter_map(|weak_event_loop| weak_event_loop.upgrade())
794            .collect()
795    }
796
797    pub(crate) fn add_event_loop(&mut self, event_loop: &Rc<EventLoop>) {
798        self.event_loops.push(Rc::downgrade(event_loop));
799    }
800
801    pub(crate) fn add_event_loop_join_handle(&mut self, join_handle: JoinHandle<()>) {
802        self.event_loop_join_handles.push(join_handle);
803    }
804
805    fn clean_up_finished_script_event_loops(&mut self) {
806        self.event_loop_join_handles
807            .retain(|join_handle| !join_handle.is_finished());
808        self.event_loops
809            .retain(|event_loop| event_loop.upgrade().is_some());
810    }
811
812    /// The main event loop for the constellation.
813    fn run(&mut self) {
814        while !self.shutting_down || !self.pipelines.is_empty() {
815            // Randomly close a pipeline if --random-pipeline-closure-probability is set
816            // This is for testing the hardening of the constellation.
817            self.maybe_close_random_pipeline();
818            self.handle_request();
819            self.finish_completed_session_history_traversal_requests();
820            self.clean_up_finished_script_event_loops();
821        }
822        self.handle_shutdown();
823
824        if !opts::get().multiprocess {
825            style::global_style_data::StyleThreadPool::shutdown();
826        }
827
828        // Shut down the `FetchThread` if it has been started at any time.
829        FetchThread::exit();
830
831        // Note: the last thing the constellation does, is asking the embedder to
832        // shut down. This helps ensure we've shut down all our internal threads before
833        // de-initializing Servo (see the `thread_count` warning on MacOS).
834        debug!("Asking embedding layer to complete shutdown.");
835        self.constellation_to_embedder_proxy
836            .send(ConstellationToEmbedderMsg::ShutdownComplete);
837    }
838
839    /// Helper that sends a message to the event loop of a given pipeline, logging the
840    /// given failure message and returning `false` on failure.
841    fn send_message_to_pipeline(
842        &mut self,
843        pipeline_id: PipelineId,
844        message: ScriptThreadMessage,
845        failure_message: &str,
846    ) -> bool {
847        let result = match self.pipelines.get(&pipeline_id) {
848            Some(pipeline) => pipeline.event_loop.send(message),
849            None => {
850                warn!("{pipeline_id}: {failure_message}");
851                return false;
852            },
853        };
854        if let Err(err) = result {
855            self.handle_send_error(pipeline_id, err);
856        }
857        true
858    }
859
860    /// Generate a new pipeline id namespace.
861    pub(crate) fn next_pipeline_namespace_id(&self) -> PipelineNamespaceId {
862        let pipeline_namespace_id = self.next_pipeline_namespace_id.get();
863        self.next_pipeline_namespace_id
864            .set(PipelineNamespaceId(pipeline_namespace_id.0 + 1));
865        pipeline_namespace_id
866    }
867
868    fn browsing_context_group_for_webview_id(
869        &self,
870        webview_id: &WebViewId,
871    ) -> Option<Rc<RefCell<BrowsingContextGroup>>> {
872        self.webviews
873            .get(webview_id)
874            .map(ConstellationWebView::browsing_context_group)
875    }
876
877    fn get_event_loop(
878        &self,
879        host: &Host,
880        webview_id: &WebViewId,
881    ) -> Result<Weak<EventLoop>, &'static str> {
882        let Some(browsing_context_group) = self.browsing_context_group_for_webview_id(webview_id)
883        else {
884            return Err("Trying to get an event-loop for an unknown WebView");
885        };
886        browsing_context_group
887            .borrow()
888            .event_loops
889            .get(host)
890            .ok_or("Trying to get an event-loop from an unknown browsing context group")
891            .cloned()
892    }
893
894    fn set_event_loop(&mut self, event_loop: &Rc<EventLoop>, host: Host, webview_id: &WebViewId) {
895        let Some(browsing_context_group) = self.browsing_context_group_for_webview_id(webview_id)
896        else {
897            return warn!("Trying to add an event loop to an unknown WebView ({webview_id})");
898        };
899
900        if browsing_context_group
901            .borrow_mut()
902            .event_loops
903            .insert(host.clone(), Rc::downgrade(event_loop))
904            .is_some_and(|old_event_loop| old_event_loop.strong_count() != 0)
905        {
906            warn!("Double-setting an event loop for {host:?} in {webview_id:?}");
907        }
908    }
909
910    fn get_event_loop_for_new_pipeline(
911        &self,
912        load_data: &LoadData,
913        webview_id: WebViewId,
914        parent_pipeline_id: Option<PipelineId>,
915        registered_domain_name: &Option<Host>,
916    ) -> Option<Rc<EventLoop>> {
917        // Never reuse an existing EventLoop when requesting a sandboxed origin.
918        if load_data
919            .creation_sandboxing_flag_set
920            .contains(SandboxingFlagSet::SANDBOXED_ORIGIN_BROWSING_CONTEXT_FLAG)
921        {
922            return None;
923        }
924
925        // If this is an about:blank or about:srcdoc load, it must share the creator's
926        // event loop. This must match the logic in the ScriptThread when determining
927        // the proper origin.
928        if load_data.url.as_str() == "about:blank" || load_data.url.as_str() == "about:srcdoc" {
929            if let Some(parent) =
930                parent_pipeline_id.and_then(|pipeline_id| self.pipelines.get(&pipeline_id))
931            {
932                return Some(parent.event_loop.clone());
933            }
934
935            if let Some(creator) = load_data
936                .creator_pipeline_id
937                .and_then(|pipeline_id| self.pipelines.get(&pipeline_id))
938            {
939                return Some(creator.event_loop.clone());
940            }
941
942            // This might happen if a new Pipeline is requested and in the meantime the parent
943            // Pipeline has shut down. In this case, just make a new ScriptThread.
944            return None;
945        }
946
947        let Some(registered_domain_name) = registered_domain_name else {
948            return None;
949        };
950
951        self.get_event_loop(registered_domain_name, &webview_id)
952            .ok()?
953            .upgrade()
954    }
955
956    fn get_or_create_event_loop_for_new_pipeline(
957        &mut self,
958        webview_id: WebViewId,
959        parent_pipeline_id: Option<PipelineId>,
960        load_data: &LoadData,
961        is_private: bool,
962    ) -> Result<Rc<EventLoop>, SendError> {
963        let registered_domain_name = if load_data
964            .creation_sandboxing_flag_set
965            .contains(SandboxingFlagSet::SANDBOXED_ORIGIN_BROWSING_CONTEXT_FLAG)
966        {
967            None
968        } else {
969            registered_domain_name(&load_data.url)
970        };
971
972        if let Some(event_loop) = self.get_event_loop_for_new_pipeline(
973            load_data,
974            webview_id,
975            parent_pipeline_id,
976            &registered_domain_name,
977        ) {
978            return Ok(event_loop);
979        }
980
981        let event_loop = EventLoop::spawn(self, is_private)?;
982        if let Some(registered_domain_name) = registered_domain_name {
983            self.set_event_loop(&event_loop, registered_domain_name, &webview_id);
984        }
985        Ok(event_loop)
986    }
987
988    /// Helper function for creating a pipeline
989    #[expect(clippy::too_many_arguments)]
990    fn new_pipeline(
991        &mut self,
992        new_pipeline_id: PipelineId,
993        browsing_context_id: BrowsingContextId,
994        webview_id: WebViewId,
995        parent_pipeline_id: Option<PipelineId>,
996        opener: Option<BrowsingContextId>,
997        initial_viewport_details: ViewportDetails,
998        // TODO: we have to provide ownership of the LoadData
999        // here, because it will be send on an ipc channel,
1000        // and ipc channels take onership of their data.
1001        // https://github.com/servo/ipc-channel/issues/138
1002        load_data: LoadData,
1003        is_private: bool,
1004        target_snapshot_params: TargetSnapshotParams,
1005        name: Option<String>,
1006    ) {
1007        if self.shutting_down {
1008            return;
1009        }
1010
1011        debug!("Creating new pipeline ({new_pipeline_id:?}) in {browsing_context_id}");
1012        let (webview_hidden, webview_state) = {
1013            let Some(webview) = self.webviews.get(&webview_id) else {
1014                warn!("Tried to create Pipeline for unknown WebViewId: {webview_id:?}");
1015                return;
1016            };
1017            (webview.hidden(), webview.state())
1018        };
1019
1020        let event_loop = match self.get_or_create_event_loop_for_new_pipeline(
1021            webview_id,
1022            parent_pipeline_id,
1023            &load_data,
1024            is_private,
1025        ) {
1026            Ok(event_loop) => event_loop,
1027            Err(error) => return self.handle_send_error(new_pipeline_id, error),
1028        };
1029
1030        let user_content_manager_id = self
1031            .webviews
1032            .get(&webview_id)
1033            .and_then(|webview| webview.user_content_manager_id);
1034
1035        let new_pipeline_info = NewPipelineInfo {
1036            webview_state,
1037            parent_info: parent_pipeline_id,
1038            new_pipeline_id,
1039            browsing_context_id,
1040            opener,
1041            load_data,
1042            viewport_details: initial_viewport_details,
1043            user_content_manager_id,
1044            target_snapshot_params,
1045            frame_name: name,
1046        };
1047        let pipeline = match Pipeline::spawn(new_pipeline_info, event_loop, self, webview_hidden) {
1048            Ok(pipeline) => pipeline,
1049            Err(error) => return self.handle_send_error(new_pipeline_id, error),
1050        };
1051
1052        assert!(!self.pipelines.contains_key(&new_pipeline_id));
1053        self.pipelines.insert(new_pipeline_id, pipeline);
1054    }
1055
1056    /// Get an iterator for the fully active browsing contexts in a subtree.
1057    fn fully_active_descendant_browsing_contexts_iter(
1058        &self,
1059        browsing_context_id: BrowsingContextId,
1060    ) -> FullyActiveBrowsingContextsIterator<'_> {
1061        FullyActiveBrowsingContextsIterator::new(
1062            browsing_context_id,
1063            &self.browsing_contexts,
1064            &self.pipelines,
1065        )
1066    }
1067
1068    /// Get an iterator for the fully active browsing contexts in a tree.
1069    fn fully_active_browsing_contexts_iter(
1070        &self,
1071        webview_id: WebViewId,
1072    ) -> FullyActiveBrowsingContextsIterator<'_> {
1073        self.fully_active_descendant_browsing_contexts_iter(BrowsingContextId::from(webview_id))
1074    }
1075
1076    /// Get an iterator for the browsing contexts in a subtree.
1077    fn all_descendant_browsing_contexts_iter(
1078        &self,
1079        browsing_context_id: BrowsingContextId,
1080    ) -> AllBrowsingContextsIterator<'_> {
1081        AllBrowsingContextsIterator {
1082            stack: vec![browsing_context_id],
1083            pipelines: &self.pipelines,
1084            browsing_contexts: &self.browsing_contexts,
1085        }
1086    }
1087
1088    /// Enumerate the specified browsing context's ancestor pipelines up to
1089    /// the top-level pipeline.
1090    fn ancestor_pipelines_of_browsing_context_iter(
1091        &self,
1092        browsing_context_id: BrowsingContextId,
1093    ) -> impl Iterator<Item = &Pipeline> + '_ {
1094        let mut state: Option<PipelineId> = self
1095            .browsing_contexts
1096            .get(&browsing_context_id)
1097            .and_then(|browsing_context| browsing_context.parent_pipeline_id);
1098        std::iter::from_fn(move || {
1099            if let Some(pipeline_id) = state {
1100                let pipeline = self.pipelines.get(&pipeline_id)?;
1101                let browsing_context = self.browsing_contexts.get(&pipeline.browsing_context_id)?;
1102                state = browsing_context.parent_pipeline_id;
1103                Some(pipeline)
1104            } else {
1105                None
1106            }
1107        })
1108    }
1109
1110    /// Enumerate the specified browsing context's ancestor-or-self pipelines up
1111    /// to the top-level pipeline.
1112    fn ancestor_or_self_pipelines_of_browsing_context_iter(
1113        &self,
1114        browsing_context_id: BrowsingContextId,
1115    ) -> impl Iterator<Item = &Pipeline> + '_ {
1116        let this_pipeline = self
1117            .browsing_contexts
1118            .get(&browsing_context_id)
1119            .map(|browsing_context| browsing_context.pipeline_id)
1120            .and_then(|pipeline_id| self.pipelines.get(&pipeline_id));
1121        this_pipeline
1122            .into_iter()
1123            .chain(self.ancestor_pipelines_of_browsing_context_iter(browsing_context_id))
1124    }
1125
1126    /// Create a new browsing context and update the internal bookkeeping.
1127    #[expect(clippy::too_many_arguments)]
1128    fn new_browsing_context(
1129        &mut self,
1130        browsing_context_id: BrowsingContextId,
1131        webview_id: WebViewId,
1132        pipeline_id: PipelineId,
1133        parent_pipeline_id: Option<PipelineId>,
1134        viewport_details: ViewportDetails,
1135        is_private: bool,
1136        inherited_secure_context: Option<bool>,
1137        inherited_upgrade_insecure_navigations_set: HashSet<UpgradeInsecureNavigations>,
1138    ) {
1139        debug!("{browsing_context_id}: Creating new browsing context");
1140        let Some(webview) = self.webviews.get_mut(&webview_id) else {
1141            println!("Adding BrowsingContext for unknown WebView: {webview_id:?}");
1142            return;
1143        };
1144
1145        // Override the viewport details if we have a pending change for that browsing context.
1146        let viewport_details = webview
1147            .take_pending_viewport_details(&browsing_context_id)
1148            .unwrap_or(viewport_details);
1149        let browsing_context = BrowsingContext::new(
1150            browsing_context_id,
1151            webview_id,
1152            pipeline_id,
1153            parent_pipeline_id,
1154            viewport_details,
1155            is_private,
1156            inherited_secure_context,
1157            inherited_upgrade_insecure_navigations_set,
1158        );
1159        self.browsing_contexts
1160            .insert(browsing_context_id, browsing_context);
1161
1162        // If this context is a nested container, attach it to parent pipeline.
1163        if let Some(parent_pipeline_id) = parent_pipeline_id &&
1164            let Some(parent) = self.pipelines.get_mut(&parent_pipeline_id)
1165        {
1166            parent.add_child(browsing_context_id);
1167        }
1168    }
1169
1170    /// Handles loading pages, navigation, and granting access to `Paint`.
1171    #[servo_tracing::instrument(skip_all)]
1172    fn handle_request(&mut self) {
1173        #[expect(clippy::large_enum_variant)]
1174        #[derive(Debug)]
1175        enum Request {
1176            ServiceWorkerManager(ServiceWorkerManagerMsg),
1177            PipelineNamespace(PipelineNamespaceRequest),
1178            Script((WebViewId, PipelineId, ScriptToConstellationMessage)),
1179            BackgroundHangMonitor(HangAlert),
1180            Embedder(EmbedderToConstellationMessage),
1181            #[cfg_attr(not(feature = "multiprocess"), expect(unused))]
1182            RemoveProcess(usize),
1183        }
1184        // Get one incoming request.
1185        // This is one of the few places where `Paint` is
1186        // allowed to panic. If one of the receiver.recv() calls
1187        // fails, it is because the matching sender has been
1188        // reclaimed, but this can't happen in normal execution
1189        // because the constellation keeps a pointer to the sender,
1190        // so it should never be reclaimed. A possible scenario in
1191        // which receiver.recv() fails is if some unsafe code
1192        // produces undefined behaviour, resulting in the destructor
1193        // being called. If this happens, there's not much we can do
1194        // other than panic.
1195        let mut sel = Select::new();
1196        sel.recv(&self.sw_manager_receiver);
1197        sel.recv(&self.namespace_receiver);
1198        sel.recv(&self.script_receiver);
1199        sel.recv(&self.background_hang_monitor_receiver);
1200        sel.recv(&self.embedder_to_constellation_receiver);
1201
1202        #[cfg(feature = "multiprocess")]
1203        self.process_manager.register(&mut sel);
1204
1205        let request = {
1206            let oper = {
1207                let _span = profile_traits::trace_span!("handle_request::select").entered();
1208                sel.select()
1209            };
1210            let index = oper.index();
1211
1212            match index {
1213                0 => oper
1214                    .recv(&self.sw_manager_receiver)
1215                    .expect("Unexpected service worker manager channel panic in constellation")
1216                    .map(Request::ServiceWorkerManager),
1217                1 => oper
1218                    .recv(&self.namespace_receiver)
1219                    .expect("Unexpected script channel panic in constellation")
1220                    .map(Request::PipelineNamespace),
1221                2 => oper
1222                    .recv(&self.script_receiver)
1223                    .expect("Unexpected script channel panic in constellation")
1224                    .map(Request::Script),
1225                3 => oper
1226                    .recv(&self.background_hang_monitor_receiver)
1227                    .expect("Unexpected BHM channel panic in constellation")
1228                    .map(Request::BackgroundHangMonitor),
1229                4 => Ok(Request::Embedder(
1230                    oper.recv(&self.embedder_to_constellation_receiver)
1231                        .expect("Unexpected embedder channel panic in constellation"),
1232                )),
1233                _ => {
1234                    // This can only be a error reading on a closed lifeline receiver.
1235                    let process_index = index - 5;
1236                    #[cfg(feature = "multiprocess")]
1237                    let _ = oper.recv(self.process_manager.receiver_at(process_index));
1238                    Ok(Request::RemoveProcess(process_index))
1239                },
1240            }
1241        };
1242
1243        let request = match request {
1244            Ok(request) => request,
1245            Err(err) => return error!("Deserialization failed ({}).", err),
1246        };
1247
1248        match request {
1249            Request::ServiceWorkerManager(message) => {
1250                self.handle_request_from_service_worker_manager(message);
1251            },
1252            Request::PipelineNamespace(message) => {
1253                self.handle_request_for_pipeline_namespace(message)
1254            },
1255            Request::Embedder(message) => self.handle_request_from_embedder(message),
1256            Request::Script(message) => {
1257                self.handle_request_from_script(message);
1258            },
1259            Request::BackgroundHangMonitor(message) => {
1260                self.handle_request_from_background_hang_monitor(message);
1261            },
1262            #[cfg(feature = "multiprocess")]
1263            Request::RemoveProcess(index) => self.process_manager.remove(index),
1264            #[cfg(not(feature = "multiprocess"))]
1265            Request::RemoveProcess(_) => {},
1266        }
1267    }
1268
1269    #[servo_tracing::instrument(skip_all)]
1270    fn handle_request_for_pipeline_namespace(&mut self, request: PipelineNamespaceRequest) {
1271        let PipelineNamespaceRequest(sender) = request;
1272        let _ = sender.send(self.next_pipeline_namespace_id());
1273    }
1274
1275    #[servo_tracing::instrument(skip_all)]
1276    fn handle_request_from_background_hang_monitor(&self, message: HangAlert) {
1277        // TODO: In case of a permanent hang being reported, add a "kill script" workflow,
1278        // via the embedder?
1279        warn!("Component hang alert: {:?}", message);
1280    }
1281
1282    fn handle_request_from_service_worker_manager(&mut self, message: ServiceWorkerManagerMsg) {
1283        match message {
1284            ServiceWorkerManagerMsg::UpdateWorkerState {
1285                worker_id,
1286                state,
1287                origin,
1288            } => {
1289                // Continuation of <https://w3c.github.io/ServiceWorker/#update-state-algorithm>
1290                // Step 4: For each settingsObject of settingsObjects, queue a task on settingsObject’s responsible event loop
1291
1292                // Note: we need to track queued tasks per worker because of the "Wait for all the tasks queued"
1293                // happening at Step 21 of <https://w3c.github.io/ServiceWorker/#installation-algorithm>.
1294                let pending_update = self
1295                    .service_workers_pending_update
1296                    .entry(worker_id)
1297                    .or_insert_with(|| ServiceWorkerPendingUpdate {
1298                        origin: origin.clone(),
1299                        pipelines: Default::default(),
1300                    });
1301                self.pipelines
1302                    .values()
1303                    .filter(|pipeline| pipeline.url.origin() == origin)
1304                    .for_each(|pipeline| {
1305                        if pipeline
1306                            .event_loop
1307                            .send(ScriptThreadMessage::UpdateServiceWorkerState {
1308                                pipeline_id: pipeline.id,
1309                                worker_id,
1310                                state: state.clone(),
1311                            })
1312                            .is_err()
1313                        {
1314                            error!(
1315                                "Failed to send UpdateServiceWorkerState to pipeline {}",
1316                                pipeline.id
1317                            );
1318                        } else {
1319                            let entry = pending_update.pipelines.entry(pipeline.id).or_insert(0);
1320                            *entry = entry.checked_add(1).unwrap_or(*entry);
1321                        }
1322                    });
1323                if pending_update.pipelines.is_empty() {
1324                    if let Some(manager) = self.sw_managers.get(&origin) {
1325                        if manager
1326                            .send(ServiceWorkerMsg::FinishInstall(worker_id))
1327                            .is_err()
1328                        {
1329                            error!("Failed to send FinishInstall for worker {}", worker_id);
1330                        }
1331                    } else {
1332                        warn!("Unable to send FinishInstall for worker {}", worker_id);
1333                    }
1334                }
1335            },
1336        }
1337    }
1338
1339    #[servo_tracing::instrument(skip_all)]
1340    fn handle_request_from_embedder(&mut self, message: EmbedderToConstellationMessage) {
1341        trace_msg_from_embedder!(message, "{message:?}");
1342        match message {
1343            EmbedderToConstellationMessage::Exit => {
1344                self.handle_exit();
1345            },
1346            EmbedderToConstellationMessage::AllowNavigationResponse(pipeline_id, allowed) => {
1347                self.handle_allow_navigation_response(pipeline_id, allowed);
1348            },
1349            // Load a new page from a typed url
1350            // If there is already a pending page (self.pending_changes), it will not be overridden;
1351            // However, if the id is not encompassed by another change, it will be.
1352            EmbedderToConstellationMessage::LoadUrl(webview_id, url_request) => {
1353                let mut load_data = LoadData::new_for_new_unrelated_webview(url_request.url);
1354
1355                if !url_request.headers.is_empty() {
1356                    load_data.headers.extend(url_request.headers);
1357                }
1358
1359                let ctx_id = BrowsingContextId::from(webview_id);
1360                let pipeline_id = match self.browsing_contexts.get(&ctx_id) {
1361                    Some(ctx) => ctx.pipeline_id,
1362                    None => {
1363                        return warn!("{}: LoadUrl for unknown browsing context", webview_id);
1364                    },
1365                };
1366                // Since this is a top-level load, initiated by the embedder, go straight to load_url,
1367                // bypassing schedule_navigation.
1368                self.load_url(
1369                    webview_id,
1370                    pipeline_id,
1371                    load_data,
1372                    NavigationHistoryBehavior::Push,
1373                    TargetSnapshotParams::default(),
1374                );
1375            },
1376            // Create a new top level browsing context. Will use response_chan to return
1377            // the browsing context id.
1378            EmbedderToConstellationMessage::NewWebView(url, new_webview_details) => {
1379                self.handle_new_top_level_browsing_context(url, new_webview_details);
1380            },
1381            // Close a top level browsing context.
1382            EmbedderToConstellationMessage::CloseWebView(webview_id) => {
1383                self.handle_close_top_level_browsing_context(webview_id);
1384            },
1385            EmbedderToConstellationMessage::SetWebViewHasSystemFocus(
1386                webview_id,
1387                has_system_focus,
1388            ) => {
1389                self.handle_set_has_system_focus(webview_id, has_system_focus);
1390            },
1391            // Handle a forward or back request
1392            EmbedderToConstellationMessage::TraverseHistory(request) => {
1393                self.handle_traverse_session_history_msg(request);
1394            },
1395            EmbedderToConstellationMessage::ChangeViewportDetails(
1396                webview_id,
1397                new_viewport_details,
1398                size_type,
1399            ) => {
1400                self.handle_change_viewport_details_msg(
1401                    webview_id,
1402                    new_viewport_details,
1403                    size_type,
1404                );
1405            },
1406            EmbedderToConstellationMessage::ThemeChange(webview_id, theme) => {
1407                self.handle_theme_change(webview_id, theme);
1408            },
1409            EmbedderToConstellationMessage::TickAnimation(webview_ids) => {
1410                self.handle_tick_animation(webview_ids)
1411            },
1412            EmbedderToConstellationMessage::NoLongerWaitingOnAsynchronousImageUpdates(
1413                pipeline_ids,
1414            ) => self.handle_no_longer_waiting_on_asynchronous_image_updates(pipeline_ids),
1415            EmbedderToConstellationMessage::WebDriverCommand(command) => {
1416                self.handle_webdriver_msg(command);
1417            },
1418            EmbedderToConstellationMessage::Reload(webview_id) => {
1419                self.handle_reload_msg(webview_id);
1420            },
1421            EmbedderToConstellationMessage::LogEntry(event_loop_id, thread_name, entry) => {
1422                self.handle_log_entry(event_loop_id, thread_name, entry);
1423            },
1424            EmbedderToConstellationMessage::ForwardInputEvent(webview_id, event, hit_test) => {
1425                self.forward_input_event(webview_id, event, hit_test);
1426            },
1427            EmbedderToConstellationMessage::RefreshCursor(pipeline_id) => {
1428                self.handle_refresh_cursor(pipeline_id)
1429            },
1430            EmbedderToConstellationMessage::ExitFullScreen(webview_id) => {
1431                self.handle_exit_fullscreen_msg(webview_id);
1432            },
1433            EmbedderToConstellationMessage::MediaSessionAction(action) => {
1434                self.handle_media_session_action_msg(action);
1435            },
1436            EmbedderToConstellationMessage::SetWebViewHidden(webview_id, hidden) => {
1437                self.set_webview_hidden(webview_id, hidden);
1438            },
1439            EmbedderToConstellationMessage::SetScrollStates(pipeline_id, scroll_states) => {
1440                self.handle_set_scroll_states(pipeline_id, scroll_states)
1441            },
1442            EmbedderToConstellationMessage::PaintMetric(pipeline_id, paint_metric_event) => {
1443                self.handle_paint_metric(pipeline_id, paint_metric_event);
1444            },
1445            EmbedderToConstellationMessage::EvaluateJavaScript(
1446                webview_id,
1447                evaluation_id,
1448                script,
1449            ) => {
1450                self.handle_evaluate_javascript(webview_id, evaluation_id, script);
1451            },
1452            EmbedderToConstellationMessage::CreateMemoryReport(sender) => {
1453                self.mem_profiler_chan.send(ProfilerMsg::Report(sender));
1454            },
1455            EmbedderToConstellationMessage::SendImageKeysForPipeline(pipeline_id, image_keys) => {
1456                if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
1457                    if pipeline
1458                        .event_loop
1459                        .send(ScriptThreadMessage::SendImageKeysBatch(
1460                            pipeline_id,
1461                            image_keys,
1462                        ))
1463                        .is_err()
1464                    {
1465                        warn!("Could not send image keys to pipeline {:?}", pipeline_id);
1466                    }
1467                } else {
1468                    warn!(
1469                        "Keys were generated for a pipeline ({:?}) that was
1470                            closed before the request could be fulfilled.",
1471                        pipeline_id
1472                    )
1473                }
1474            },
1475            EmbedderToConstellationMessage::PreferencesUpdated(updates) => {
1476                let event_loops = self
1477                    .pipelines
1478                    .values()
1479                    .map(|pipeline| pipeline.event_loop.clone());
1480                for event_loop in event_loops {
1481                    let _ = event_loop.send(ScriptThreadMessage::PreferencesUpdated(
1482                        updates
1483                            .iter()
1484                            .map(|(name, value)| (String::from(*name), value.clone()))
1485                            .collect(),
1486                    ));
1487                }
1488            },
1489            EmbedderToConstellationMessage::RequestScreenshotReadiness(webview_id) => {
1490                if let Some(webview) = self.webviews.get_mut(&webview_id) {
1491                    webview.handle_screenshot_readiness_request(
1492                        &self.browsing_contexts,
1493                        &self.pipelines,
1494                    );
1495                }
1496            },
1497            EmbedderToConstellationMessage::EmbedderControlResponse(id, response) => {
1498                self.handle_embedder_control_response(id, response);
1499            },
1500            EmbedderToConstellationMessage::UserContentManagerAction(
1501                user_content_manager_id,
1502                action,
1503            ) => {
1504                self.handle_user_content_manager_action(user_content_manager_id, action);
1505            },
1506            EmbedderToConstellationMessage::UpdatePinchZoomInfos(pipeline_id, pinch_zoom) => {
1507                self.handle_update_pinch_zoom_infos(pipeline_id, pinch_zoom);
1508            },
1509            EmbedderToConstellationMessage::SetAccessibilityActive(webview_id, active) => {
1510                self.set_accessibility_active(webview_id, active);
1511            },
1512            EmbedderToConstellationMessage::ForwardAccessibilityAction(action_request) => {
1513                self.forward_accessibility_action(action_request);
1514            },
1515            EmbedderToConstellationMessage::ClearSessionHistory(webview_id) => {
1516                self.handle_clear_session_history(webview_id);
1517            },
1518            EmbedderToConstellationMessage::SetNetworkOnlineState(online) => {
1519                self.handle_set_network_online_state(online);
1520            },
1521            EmbedderToConstellationMessage::StoreCacheToDisk(sender) => {
1522                self.public_resource_threads.store_cache_to_disk(sender);
1523            },
1524        }
1525    }
1526
1527    fn mutate_user_contents_for_manager_id_and_notify_script_threads(
1528        &mut self,
1529        user_content_manager_id: UserContentManagerId,
1530        callback: impl FnOnce(&mut UserContents),
1531    ) {
1532        let event_loops = self.event_loops();
1533        let user_contents = self
1534            .user_contents_for_manager_id
1535            .entry(user_content_manager_id)
1536            .or_default();
1537
1538        callback(user_contents);
1539
1540        for event_loop in event_loops {
1541            let _ = event_loop.send(ScriptThreadMessage::SetUserContents(
1542                user_content_manager_id,
1543                user_contents.clone(),
1544            ));
1545        }
1546    }
1547
1548    fn handle_user_content_manager_action(
1549        &mut self,
1550        user_content_manager_id: UserContentManagerId,
1551        action: UserContentManagerAction,
1552    ) {
1553        match action {
1554            UserContentManagerAction::AddUserScript(user_script) => {
1555                self.mutate_user_contents_for_manager_id_and_notify_script_threads(
1556                    user_content_manager_id,
1557                    |user_contents| {
1558                        user_contents.scripts.push(user_script);
1559                    },
1560                );
1561            },
1562            UserContentManagerAction::RemoveUserScript(user_script_id) => {
1563                self.mutate_user_contents_for_manager_id_and_notify_script_threads(
1564                    user_content_manager_id,
1565                    |user_contents| {
1566                        user_contents
1567                            .scripts
1568                            .retain(|user_script| user_script.id() != user_script_id);
1569                    },
1570                );
1571            },
1572            UserContentManagerAction::AddUserStyleSheet(user_stylesheet) => {
1573                self.mutate_user_contents_for_manager_id_and_notify_script_threads(
1574                    user_content_manager_id,
1575                    |user_contents| {
1576                        user_contents.stylesheets.push(user_stylesheet);
1577                    },
1578                );
1579            },
1580            UserContentManagerAction::RemoveUserStyleSheet(user_stylesheet_id) => {
1581                self.mutate_user_contents_for_manager_id_and_notify_script_threads(
1582                    user_content_manager_id,
1583                    |user_contents| {
1584                        user_contents
1585                            .stylesheets
1586                            .retain(|user_stylesheet| user_stylesheet.id() != user_stylesheet_id);
1587                    },
1588                );
1589            },
1590            UserContentManagerAction::DestroyUserContentManager => {
1591                self.user_contents_for_manager_id
1592                    .remove(&user_content_manager_id);
1593
1594                for event_loop in self.event_loops() {
1595                    let _ = event_loop.send(ScriptThreadMessage::DestroyUserContentManager(
1596                        user_content_manager_id,
1597                    ));
1598                }
1599            },
1600        }
1601    }
1602
1603    fn send_message_to_all_background_hang_monitors(
1604        &self,
1605        message: BackgroundHangMonitorControlMsg,
1606    ) {
1607        if let Some(background_monitor_control_sender) = &self.background_monitor_control_sender &&
1608            let Err(error) = background_monitor_control_sender.send(message.clone())
1609        {
1610            error!("Could not send message ({message:?}) to BHM: {error}");
1611        }
1612        for event_loop in self.event_loops() {
1613            event_loop.send_message_to_background_hang_monitor(&message);
1614        }
1615    }
1616
1617    #[servo_tracing::instrument(skip_all)]
1618    fn handle_evaluate_javascript(
1619        &mut self,
1620        webview_id: WebViewId,
1621        evaluation_id: JavaScriptEvaluationId,
1622        script: String,
1623    ) {
1624        let browsing_context_id = BrowsingContextId::from(webview_id);
1625        let Some(pipeline) = self
1626            .browsing_contexts
1627            .get(&browsing_context_id)
1628            .and_then(|browsing_context| self.pipelines.get(&browsing_context.pipeline_id))
1629        else {
1630            self.handle_finish_javascript_evaluation(
1631                evaluation_id,
1632                Err(JavaScriptEvaluationError::InternalError),
1633            );
1634            return;
1635        };
1636
1637        if pipeline
1638            .event_loop
1639            .send(ScriptThreadMessage::EvaluateJavaScript(
1640                webview_id,
1641                pipeline.id,
1642                evaluation_id,
1643                script,
1644            ))
1645            .is_err()
1646        {
1647            self.handle_finish_javascript_evaluation(
1648                evaluation_id,
1649                Err(JavaScriptEvaluationError::InternalError),
1650            );
1651        }
1652    }
1653
1654    #[servo_tracing::instrument(skip_all)]
1655    fn handle_request_from_script(
1656        &mut self,
1657        message: (WebViewId, PipelineId, ScriptToConstellationMessage),
1658    ) {
1659        let (webview_id, source_pipeline_id, content) = message;
1660        trace_script_msg!(content, "{source_pipeline_id}: {content:?}");
1661
1662        match content {
1663            ScriptToConstellationMessage::CompleteMessagePortTransfer(router_id, ports) => {
1664                self.handle_complete_message_port_transfer(router_id, ports);
1665            },
1666            ScriptToConstellationMessage::MessagePortTransferResult(
1667                router_id,
1668                succeeded,
1669                failed,
1670            ) => {
1671                self.handle_message_port_transfer_completed(router_id, succeeded);
1672                self.handle_message_port_transfer_failed(failed);
1673            },
1674            ScriptToConstellationMessage::RerouteMessagePort(port_id, task) => {
1675                self.handle_reroute_messageport(port_id, task);
1676            },
1677            ScriptToConstellationMessage::MessagePortShipped(port_id) => {
1678                self.handle_messageport_shipped(port_id);
1679            },
1680            ScriptToConstellationMessage::NewMessagePortRouter(router_id, callback) => {
1681                self.handle_new_messageport_router(router_id, callback);
1682            },
1683            ScriptToConstellationMessage::RemoveMessagePortRouter(router_id) => {
1684                self.handle_remove_messageport_router(router_id);
1685            },
1686            ScriptToConstellationMessage::NewMessagePort(router_id, port_id) => {
1687                self.handle_new_messageport(router_id, port_id);
1688            },
1689            ScriptToConstellationMessage::EntanglePorts(port1, port2) => {
1690                self.handle_entangle_messageports(port1, port2);
1691            },
1692            ScriptToConstellationMessage::DisentanglePorts(port1, port2) => {
1693                self.handle_disentangle_messageports(port1, port2);
1694            },
1695            ScriptToConstellationMessage::NewBroadcastChannelRouter(
1696                router_id,
1697                response_sender,
1698                origin,
1699            ) => {
1700                if self
1701                    .check_origin_against_pipeline(&source_pipeline_id, &origin)
1702                    .is_err()
1703                {
1704                    return warn!("Attempt to add broadcast router from an unexpected origin.");
1705                }
1706                self.broadcast_channels
1707                    .new_broadcast_channel_router(router_id, response_sender);
1708            },
1709            ScriptToConstellationMessage::NewBroadcastChannelNameInRouter(
1710                router_id,
1711                channel_name,
1712                origin,
1713            ) => {
1714                if self
1715                    .check_origin_against_pipeline(&source_pipeline_id, &origin)
1716                    .is_err()
1717                {
1718                    return warn!("Attempt to add channel name from an unexpected origin.");
1719                }
1720                self.broadcast_channels
1721                    .new_broadcast_channel_name_in_router(router_id, channel_name, origin);
1722            },
1723            ScriptToConstellationMessage::RemoveBroadcastChannelNameInRouter(
1724                router_id,
1725                channel_name,
1726                origin,
1727            ) => {
1728                if self
1729                    .check_origin_against_pipeline(&source_pipeline_id, &origin)
1730                    .is_err()
1731                {
1732                    return warn!("Attempt to remove channel name from an unexpected origin.");
1733                }
1734                self.broadcast_channels
1735                    .remove_broadcast_channel_name_in_router(router_id, channel_name, origin);
1736            },
1737            ScriptToConstellationMessage::RemoveBroadcastChannelRouter(router_id, origin) => {
1738                if self
1739                    .check_origin_against_pipeline(&source_pipeline_id, &origin)
1740                    .is_err()
1741                {
1742                    return warn!("Attempt to remove broadcast router from an unexpected origin.");
1743                }
1744                self.broadcast_channels
1745                    .remove_broadcast_channel_router(router_id);
1746            },
1747            ScriptToConstellationMessage::ScheduleBroadcast(router_id, message) => {
1748                if self
1749                    .check_origin_against_pipeline(&source_pipeline_id, &message.origin)
1750                    .is_err()
1751                {
1752                    return warn!(
1753                        "Attempt to schedule broadcast from an origin not matching the origin of the msg."
1754                    );
1755                }
1756                self.broadcast_channels
1757                    .schedule_broadcast(router_id, message);
1758            },
1759            ScriptToConstellationMessage::PipelineExited => {
1760                self.handle_pipeline_exited(source_pipeline_id, PipelineExitSource::Constellation);
1761            },
1762            ScriptToConstellationMessage::DiscardDocument => {
1763                self.handle_discard_document(webview_id, source_pipeline_id);
1764            },
1765            ScriptToConstellationMessage::DiscardTopLevelBrowsingContext => {
1766                self.handle_close_top_level_browsing_context(webview_id);
1767            },
1768            ScriptToConstellationMessage::ScriptLoadedURLInIFrame(load_info) => {
1769                self.handle_script_loaded_url_in_iframe_msg(load_info);
1770            },
1771            ScriptToConstellationMessage::ScriptNewIFrame(load_info) => {
1772                self.handle_script_new_iframe(load_info);
1773            },
1774            ScriptToConstellationMessage::CreateAuxiliaryWebView(load_info) => {
1775                self.handle_script_new_auxiliary(load_info);
1776            },
1777            ScriptToConstellationMessage::ChangeRunningAnimationsState(animation_state) => {
1778                self.handle_change_running_animations_state(source_pipeline_id, animation_state)
1779            },
1780            ScriptToConstellationMessage::RegisterWorkerAnimationFrameProvider(
1781                worker_id,
1782                sender,
1783            ) => self.handle_register_worker_animation_frame_provider(
1784                webview_id,
1785                source_pipeline_id,
1786                worker_id,
1787                sender,
1788            ),
1789            ScriptToConstellationMessage::UnregisterWorkerAnimationFrameProvider(worker_id) => {
1790                self.handle_unregister_worker_animation_frame_provider(worker_id)
1791            },
1792            ScriptToConstellationMessage::ChangeWorkerAnimationFrameProviderState(
1793                worker_id,
1794                active,
1795            ) => self.handle_change_worker_animation_frame_provider_state(
1796                source_pipeline_id,
1797                worker_id,
1798                active,
1799            ),
1800            // Ask the embedder for permission to load a new page.
1801            ScriptToConstellationMessage::LoadUrl(
1802                load_data,
1803                history_handling,
1804                target_snapshot_params,
1805            ) => {
1806                self.schedule_navigation(
1807                    webview_id,
1808                    source_pipeline_id,
1809                    load_data,
1810                    history_handling,
1811                    target_snapshot_params,
1812                );
1813            },
1814            ScriptToConstellationMessage::AbortLoadUrl => {
1815                self.handle_abort_load_url_msg(webview_id, source_pipeline_id);
1816            },
1817            ScriptToConstellationMessage::LoadFinished { aborted } => {
1818                self.handle_load_finished_message(webview_id, source_pipeline_id, aborted)
1819            },
1820            // Handle navigating to a fragment
1821            ScriptToConstellationMessage::NavigatedToFragment(new_url, replacement_enabled) => {
1822                self.handle_navigated_to_fragment(source_pipeline_id, new_url, replacement_enabled);
1823            },
1824            // Handle a forward or back request
1825            ScriptToConstellationMessage::TraverseHistory(request) => {
1826                self.handle_traverse_session_history_msg(request);
1827            },
1828            // Handle a push history state request.
1829            ScriptToConstellationMessage::PushHistoryState(history_state_id, url) => {
1830                self.handle_push_history_state_msg(source_pipeline_id, history_state_id, url);
1831            },
1832            ScriptToConstellationMessage::ReplaceHistoryState(history_state_id, url) => {
1833                self.handle_replace_history_state_msg(source_pipeline_id, history_state_id, url);
1834            },
1835            // Handle a joint session history length request.
1836            ScriptToConstellationMessage::JointSessionHistoryLength(response_sender) => {
1837                self.handle_joint_session_history_length(webview_id, response_sender);
1838            },
1839            // Notification that the new document is ready to become active
1840            ScriptToConstellationMessage::ActivateDocument => {
1841                self.handle_activate_document_msg(webview_id, source_pipeline_id);
1842            },
1843            // Update pipeline url after redirections
1844            ScriptToConstellationMessage::SetFinalUrl(final_url) => {
1845                // The script may have finished loading after we already started shutting down.
1846                if let Some(ref mut pipeline) = self.pipelines.get_mut(&source_pipeline_id) {
1847                    pipeline.url = final_url;
1848                } else {
1849                    warn!("constellation got set final url message for dead pipeline");
1850                }
1851            },
1852            ScriptToConstellationMessage::PostMessage {
1853                target: browsing_context_id,
1854                source: source_pipeline_id,
1855                target_origin: origin,
1856                source_origin,
1857                data,
1858            } => {
1859                self.handle_post_message_msg(
1860                    browsing_context_id,
1861                    source_pipeline_id,
1862                    origin,
1863                    source_origin,
1864                    data,
1865                );
1866            },
1867            ScriptToConstellationMessage::FocusAncestorBrowsingContextsForFocusingSteps(
1868                focused_child_browsing_context_id,
1869                sequence,
1870            ) => {
1871                self.handle_focus_ancestor_browsing_contexts_for_focusing_steps(
1872                    source_pipeline_id,
1873                    focused_child_browsing_context_id,
1874                    sequence,
1875                );
1876            },
1877            ScriptToConstellationMessage::FocusRemoteBrowsingContext(
1878                focused_browsing_context_id,
1879                remote_focus_operation,
1880            ) => {
1881                self.handle_focus_remote_browsing_context(
1882                    focused_browsing_context_id,
1883                    remote_focus_operation,
1884                );
1885            },
1886            ScriptToConstellationMessage::RemoveIFrame(browsing_context_id, response_sender) => {
1887                let removed_pipeline_ids =
1888                    self.handle_remove_iframe_msg(webview_id, browsing_context_id);
1889                if let Err(e) = response_sender.send(removed_pipeline_ids) {
1890                    warn!("Error replying to remove iframe ({})", e);
1891                }
1892            },
1893            ScriptToConstellationMessage::CreateCanvasPaintThread(size, response_sender) => {
1894                self.handle_create_canvas_paint_thread_msg(size, response_sender)
1895            },
1896            ScriptToConstellationMessage::LogEntry(event_loop_id, thread_name, entry) => {
1897                self.handle_log_entry(event_loop_id, thread_name, entry);
1898            },
1899            ScriptToConstellationMessage::GetBrowsingContextInfo(pipeline_id, response_sender) => {
1900                let result = self
1901                    .pipelines
1902                    .get(&pipeline_id)
1903                    .and_then(|pipeline| self.browsing_contexts.get(&pipeline.browsing_context_id))
1904                    .map(|ctx| (ctx.id, ctx.parent_pipeline_id));
1905                if let Err(e) = response_sender.send(result) {
1906                    warn!(
1907                        "Sending reply to get browsing context info failed ({:?}).",
1908                        e
1909                    );
1910                }
1911            },
1912            ScriptToConstellationMessage::GetTopForBrowsingContext(
1913                browsing_context_id,
1914                response_sender,
1915            ) => {
1916                let result = self
1917                    .browsing_contexts
1918                    .get(&browsing_context_id)
1919                    .map(|bc| bc.webview_id);
1920                if let Err(e) = response_sender.send(result) {
1921                    warn!(
1922                        "Sending reply to get top for browsing context info failed ({:?}).",
1923                        e
1924                    );
1925                }
1926            },
1927            ScriptToConstellationMessage::GetChildBrowsingContextCount(
1928                browsing_context_id,
1929                response_sender,
1930            ) => {
1931                let count = self
1932                    .browsing_contexts
1933                    .get(&browsing_context_id)
1934                    .and_then(|browsing_context| self.pipelines.get(&browsing_context.pipeline_id))
1935                    .map(|pipeline| pipeline.children.len())
1936                    .unwrap_or_default();
1937                if let Err(error) = response_sender.send(count) {
1938                    warn!("Sending reply to get child browsing context count failed ({error:?}).",);
1939                }
1940            },
1941
1942            ScriptToConstellationMessage::GetChildBrowsingContextId(
1943                browsing_context_id,
1944                index,
1945                response_sender,
1946            ) => {
1947                let result = self
1948                    .browsing_contexts
1949                    .get(&browsing_context_id)
1950                    .and_then(|bc| self.pipelines.get(&bc.pipeline_id))
1951                    .and_then(|pipeline| pipeline.children.get(index))
1952                    .copied();
1953                if let Err(error) = response_sender.send(result) {
1954                    warn!("Sending reply to get child browsing context ID failed ({error:?}).",);
1955                }
1956            },
1957            ScriptToConstellationMessage::IsCurrentlyFullyActive(pipeline_id, response_sender) => {
1958                if let Err(error) = response_sender
1959                    .send(self.get_activity(pipeline_id) == DocumentActivity::FullyActive)
1960                {
1961                    warn!("Sending reply to get document activity failed ({error:?}).");
1962                }
1963            },
1964            ScriptToConstellationMessage::GetDocumentOrigin(pipeline_id, response_sender) => {
1965                self.send_message_to_pipeline(
1966                    pipeline_id,
1967                    ScriptThreadMessage::GetDocumentOrigin(pipeline_id, response_sender),
1968                    "Document origin retrieval after closure",
1969                );
1970            },
1971            ScriptToConstellationMessage::GetDocumentOriginDetails(
1972                pipeline_id,
1973                response_sender,
1974            ) => {
1975                self.send_message_to_pipeline(
1976                    pipeline_id,
1977                    ScriptThreadMessage::GetDocumentOriginDetails(pipeline_id, response_sender),
1978                    "Document ancestor origin details retrieval after closure",
1979                );
1980            },
1981            ScriptToConstellationMessage::ServiceWorkerStateUpdateDone(worker_id, pipeline_id) => {
1982                self.handle_service_worker_state_update_done(worker_id, pipeline_id);
1983            },
1984            ScriptToConstellationMessage::ServiceWorkerAlgorithm(algorithm) => {
1985                self.handle_serviceworker_algorithm(source_pipeline_id, algorithm);
1986            },
1987            ScriptToConstellationMessage::ForwardDOMMessage(msg_vec, scope_url) => {
1988                if let Some(mgr) = self.sw_managers.get(&scope_url.origin()) {
1989                    let _ = mgr.send(ServiceWorkerMsg::ForwardDOMMessage(msg_vec, scope_url));
1990                } else {
1991                    warn!("Unable to forward DOMMessage for postMessage call");
1992                }
1993            },
1994            ScriptToConstellationMessage::RegisterInterest(interest) => {
1995                self.pipeline_interests
1996                    .entry(interest)
1997                    .or_default()
1998                    .insert(source_pipeline_id);
1999            },
2000            ScriptToConstellationMessage::UnregisterInterest(interest) => {
2001                if let Some(set) = self.pipeline_interests.get_mut(&interest) {
2002                    set.remove(&source_pipeline_id);
2003                    if set.is_empty() {
2004                        self.pipeline_interests.remove(&interest);
2005                    }
2006                }
2007            },
2008            ScriptToConstellationMessage::BroadcastStorageEvent(
2009                storage,
2010                url,
2011                key,
2012                old_value,
2013                new_value,
2014            ) => {
2015                self.handle_broadcast_storage_event(
2016                    source_pipeline_id,
2017                    storage,
2018                    url,
2019                    key,
2020                    old_value,
2021                    new_value,
2022                );
2023            },
2024            ScriptToConstellationMessage::MediaSessionEvent(pipeline_id, event) => {
2025                // Unlikely at this point, but we may receive events coming from
2026                // different media sessions, so we set the active media session based
2027                // on Playing events.
2028                // The last media session claiming to be in playing state is set to
2029                // the active media session.
2030                // Events coming from inactive media sessions are discarded.
2031                if self.active_media_session.is_some() &&
2032                    let MediaSessionEvent::PlaybackStateChange(ref state) = event &&
2033                    !matches!(
2034                        state,
2035                        MediaSessionPlaybackState::Playing | MediaSessionPlaybackState::Paused
2036                    )
2037                {
2038                    return;
2039                };
2040                self.active_media_session = Some(pipeline_id);
2041                self.constellation_to_embedder_proxy.send(
2042                    ConstellationToEmbedderMsg::MediaSessionEvent(webview_id, event),
2043                );
2044            },
2045            #[cfg(feature = "webgpu")]
2046            ScriptToConstellationMessage::RequestAdapter(response_sender, options, ids) => self
2047                .handle_wgpu_request(
2048                    webview_id,
2049                    source_pipeline_id,
2050                    ScriptToConstellationMessage::RequestAdapter(response_sender, options, ids),
2051                ),
2052            #[cfg(feature = "webgpu")]
2053            ScriptToConstellationMessage::GetWebGPUChan(response_sender) => self
2054                .handle_wgpu_request(
2055                    webview_id,
2056                    source_pipeline_id,
2057                    ScriptToConstellationMessage::GetWebGPUChan(response_sender),
2058                ),
2059            ScriptToConstellationMessage::TitleChanged(pipeline, title) => {
2060                if let Some(pipeline) = self.pipelines.get_mut(&pipeline) {
2061                    pipeline.title = title;
2062                }
2063            },
2064            ScriptToConstellationMessage::IFrameSizes(iframe_sizes) => {
2065                self.handle_iframe_size_msg(webview_id, iframe_sizes)
2066            },
2067            ScriptToConstellationMessage::ReportMemory(sender) => {
2068                // get memory report and send it back.
2069                self.mem_profiler_chan
2070                    .send(mem::ProfilerMsg::Report(sender));
2071            },
2072            ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, result) => {
2073                self.handle_finish_javascript_evaluation(evaluation_id, result)
2074            },
2075            ScriptToConstellationMessage::ForwardKeyboardScroll(pipeline_id, scroll) => {
2076                if let Some(pipeline) = self.pipelines.get(&pipeline_id) &&
2077                    let Err(error) =
2078                        pipeline
2079                            .event_loop
2080                            .send(ScriptThreadMessage::ForwardKeyboardScroll(
2081                                pipeline_id,
2082                                scroll,
2083                            ))
2084                {
2085                    warn!("Could not forward {scroll:?} to {pipeline_id}: {error:?}");
2086                }
2087            },
2088            ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(response) => {
2089                if let Some(webview) = self.webviews.get_mut(&webview_id) {
2090                    webview.handle_screenshot_readiness_response(
2091                        source_pipeline_id,
2092                        response,
2093                        &self.paint_proxy,
2094                    );
2095                }
2096            },
2097            ScriptToConstellationMessage::TriggerGarbageCollection => {
2098                for event_loop in self.event_loops() {
2099                    let _ = event_loop.send(ScriptThreadMessage::TriggerGarbageCollection);
2100                }
2101            },
2102            ScriptToConstellationMessage::AcquireWakeLock(type_) => match type_ {
2103                WakeLockType::Screen => {
2104                    self.screen_wake_lock_count += 1;
2105                    if self.screen_wake_lock_count == 1 &&
2106                        let Err(e) = self.wake_lock_provider.acquire(type_)
2107                    {
2108                        warn!("Failed to acquire screen wake lock: {e}");
2109                    }
2110                },
2111            },
2112            ScriptToConstellationMessage::ReleaseWakeLock(type_) => match type_ {
2113                WakeLockType::Screen => {
2114                    self.screen_wake_lock_count = self.screen_wake_lock_count.saturating_sub(1);
2115                    if self.screen_wake_lock_count == 0 &&
2116                        let Err(e) = self.wake_lock_provider.release(type_)
2117                    {
2118                        warn!("Failed to release screen wake lock: {e}");
2119                    }
2120                },
2121            },
2122            ScriptToConstellationMessage::AddTupleToUpgradeInsecureNavigationsSet(tuple) => {
2123                let browsing_context_id = match self.pipelines.get(&source_pipeline_id) {
2124                    Some(pipeline) => pipeline.browsing_context_id,
2125                    None => {
2126                        warn!(
2127                            "{}: AddTupleToUpgradeInsecureNavigationsSet after closure",
2128                            source_pipeline_id
2129                        );
2130                        return;
2131                    },
2132                };
2133                let upgrade_insecure_navigations_set =
2134                    match self.browsing_contexts.get_mut(&browsing_context_id) {
2135                        Some(ctx) => &mut ctx.upgrade_insecure_navigations_set,
2136                        None => {
2137                            warn!(
2138                                "{}: AddTupleToUpgradeInsecureNavigationsSet in closed {}",
2139                                source_pipeline_id, browsing_context_id,
2140                            );
2141                            return;
2142                        },
2143                    };
2144
2145                upgrade_insecure_navigations_set.insert(tuple);
2146            },
2147        }
2148    }
2149
2150    /// Check the origin of a message against that of the pipeline it came from.
2151    /// Note: this is still limited as a security check,
2152    /// see <https://github.com/servo/servo/issues/11722>
2153    fn check_origin_against_pipeline(
2154        &self,
2155        pipeline_id: &PipelineId,
2156        origin: &ImmutableOrigin,
2157    ) -> Result<(), ()> {
2158        let pipeline_origin = match self.pipelines.get(pipeline_id) {
2159            Some(pipeline) => pipeline.load_data.url.origin(),
2160            None => {
2161                warn!("Received message from closed or unknown pipeline.");
2162                return Err(());
2163            },
2164        };
2165        if &pipeline_origin == origin {
2166            return Ok(());
2167        }
2168        Err(())
2169    }
2170
2171    /// Returns `None` on every failure path, so callers can always reply to script.
2172    #[cfg(feature = "webgpu")]
2173    fn webgpu_chan_for_pipeline(
2174        &self,
2175        webview_id: WebViewId,
2176        source_pipeline_id: PipelineId,
2177    ) -> Option<WebGPU> {
2178        use webgpu::start_webgpu_thread;
2179
2180        let Some(browsing_context_group) = self.browsing_context_group_for_webview_id(&webview_id)
2181        else {
2182            warn!("WebView ({webview_id:?}) not found when handling WebGPU request");
2183            return None;
2184        };
2185        let Some(source_pipeline) = self.pipelines.get(&source_pipeline_id) else {
2186            warn!("{source_pipeline_id}: ScriptMsg from closed pipeline");
2187            return None;
2188        };
2189        let Some(host) = registered_domain_name(&source_pipeline.url) else {
2190            warn!("Invalid host url");
2191            return None;
2192        };
2193
2194        let mut browsing_context_group = browsing_context_group.borrow_mut();
2195        match browsing_context_group.webgpus.entry(host) {
2196            Entry::Vacant(v) => start_webgpu_thread(
2197                self.paint_proxy.cross_process_paint_api.clone(),
2198                self.webrender_wgpu
2199                    .webrender_external_image_id_manager
2200                    .clone(),
2201                self.webrender_wgpu.wgpu_image_map.clone(),
2202            )
2203            .map(|webgpu| {
2204                let msg = ScriptThreadMessage::SetWebGPUPort(webgpu.1);
2205                if let Err(e) = source_pipeline.event_loop.send(msg) {
2206                    warn!(
2207                        "{}: Failed to send SetWebGPUPort to pipeline ({:?})",
2208                        source_pipeline_id, e
2209                    );
2210                }
2211                v.insert(webgpu.0).clone()
2212            }),
2213            Entry::Occupied(o) => Some(o.get().clone()),
2214        }
2215    }
2216
2217    #[servo_tracing::instrument(skip_all)]
2218    #[cfg(feature = "webgpu")]
2219    fn handle_wgpu_request(
2220        &mut self,
2221        webview_id: WebViewId,
2222        source_pipeline_id: PipelineId,
2223        request: ScriptToConstellationMessage,
2224    ) {
2225        let webgpu_chan = self.webgpu_chan_for_pipeline(webview_id, source_pipeline_id);
2226        match request {
2227            ScriptToConstellationMessage::RequestAdapter(response_sender, options, adapter_id) => {
2228                match webgpu_chan {
2229                    None => {
2230                        if let Err(e) = response_sender.send(None) {
2231                            warn!("Failed to send request adapter message: {}", e)
2232                        }
2233                    },
2234                    Some(webgpu_chan) => {
2235                        let adapter_request = WebGPURequest::RequestAdapter {
2236                            sender: response_sender,
2237                            options,
2238                            adapter_id,
2239                        };
2240                        if webgpu_chan.0.send(adapter_request).is_err() {
2241                            warn!("Failed to send request adapter message on WebGPU channel");
2242                        }
2243                    },
2244                }
2245            },
2246            ScriptToConstellationMessage::GetWebGPUChan(response_sender) => {
2247                if response_sender.send(webgpu_chan).is_err() {
2248                    warn!(
2249                        "{}: Failed to send WebGPU channel to pipeline",
2250                        source_pipeline_id
2251                    )
2252                }
2253            },
2254            _ => warn!("Wrong message type in handle_wgpu_request"),
2255        }
2256    }
2257
2258    #[servo_tracing::instrument(skip_all)]
2259    fn handle_message_port_transfer_completed(
2260        &mut self,
2261        router_id: Option<MessagePortRouterId>,
2262        ports: Vec<MessagePortId>,
2263    ) {
2264        let Some(router_id) = router_id else {
2265            if !ports.is_empty() {
2266                warn!(
2267                    "Constellation unable to process port transfer successes, since no router id was received"
2268                );
2269            }
2270            return;
2271        };
2272        for port_id in ports.into_iter() {
2273            let mut entry = match self.message_ports.entry(port_id) {
2274                Entry::Vacant(_) => {
2275                    warn!(
2276                        "Constellation received a port transfer completed msg for unknown messageport {port_id:?}",
2277                    );
2278                    continue;
2279                },
2280                Entry::Occupied(entry) => entry,
2281            };
2282            match entry.get().state {
2283                TransferState::CompletionInProgress(expected_router_id) => {
2284                    // Here, the transfer was normally completed.
2285
2286                    if expected_router_id != router_id {
2287                        return warn!(
2288                            "Transfer completed by an unexpected router: {:?}",
2289                            router_id
2290                        );
2291                    }
2292                    // Update the state to managed.
2293                    let new_info = MessagePortInfo {
2294                        state: TransferState::Managed(router_id),
2295                        entangled_with: entry.get().entangled_with,
2296                    };
2297                    entry.insert(new_info);
2298                },
2299                _ => warn!("Constellation received unexpected port transfer completed message"),
2300            }
2301        }
2302    }
2303
2304    fn handle_message_port_transfer_failed(
2305        &mut self,
2306        ports: FxHashMap<MessagePortId, PortTransferInfo>,
2307    ) {
2308        for (port_id, mut transfer_info) in ports.into_iter() {
2309            let Some(entry) = self.message_ports.remove(&port_id) else {
2310                warn!(
2311                    "Constellation received a port transfer completed msg for unknown messageport {port_id:?}",
2312                );
2313                continue;
2314            };
2315            let new_info = match entry.state {
2316                TransferState::CompletionFailed(mut current_buffer) => {
2317                    // The transfer failed,
2318                    // and now the global has returned us the buffer we previously sent.
2319                    // So the next update is back to a "normal" transfer in progress.
2320
2321                    // Tasks in the previous buffer are older,
2322                    // hence need to be added to the front of the current one.
2323                    while let Some(task) = transfer_info.port_message_queue.pop_back() {
2324                        current_buffer.push_front(task);
2325                    }
2326                    // Update the state to transfer-in-progress.
2327                    MessagePortInfo {
2328                        state: TransferState::TransferInProgress(current_buffer),
2329                        entangled_with: entry.entangled_with,
2330                    }
2331                },
2332                TransferState::CompletionRequested(target_router_id, mut current_buffer) => {
2333                    // Here, before the global who failed the last transfer could return us the buffer,
2334                    // another global already sent us a request to complete a new transfer.
2335                    // So we use the returned buffer to update
2336                    // the current-buffer(of new incoming messages),
2337                    // and we send everything to the global
2338                    // who is waiting for completion of the current transfer.
2339
2340                    // Tasks in the previous buffer are older,
2341                    // hence need to be added to the front of the current one.
2342                    while let Some(task) = transfer_info.port_message_queue.pop_back() {
2343                        current_buffer.push_front(task);
2344                    }
2345                    // Forward the buffered message-queue to complete the current transfer.
2346                    if let Some(ipc_sender) = self.message_port_routers.get(&target_router_id) {
2347                        if ipc_sender
2348                            .send(MessagePortMsg::CompletePendingTransfer(
2349                                port_id,
2350                                PortTransferInfo {
2351                                    port_message_queue: current_buffer,
2352                                    disentangled: entry.entangled_with.is_none(),
2353                                },
2354                            ))
2355                            .is_err()
2356                        {
2357                            warn!("Constellation failed to send complete port transfer response.");
2358                        }
2359                    } else {
2360                        warn!("No message-port sender for {:?}", target_router_id);
2361                    }
2362
2363                    // Update the state to completion-in-progress.
2364                    MessagePortInfo {
2365                        state: TransferState::CompletionInProgress(target_router_id),
2366                        entangled_with: entry.entangled_with,
2367                    }
2368                },
2369                _ => {
2370                    warn!("Unexpected port transfer failed message received");
2371                    continue;
2372                },
2373            };
2374            self.message_ports.insert(port_id, new_info);
2375        }
2376    }
2377
2378    #[servo_tracing::instrument(skip_all)]
2379    fn handle_complete_message_port_transfer(
2380        &mut self,
2381        router_id: MessagePortRouterId,
2382        ports: Vec<MessagePortId>,
2383    ) {
2384        let mut response = FxHashMap::default();
2385        for port_id in ports.into_iter() {
2386            let Some(entry) = self.message_ports.remove(&port_id) else {
2387                warn!(
2388                    "Constellation asked to complete transfer for unknown messageport {port_id:?}",
2389                );
2390                continue;
2391            };
2392            let new_info = match entry.state {
2393                TransferState::TransferInProgress(buffer) => {
2394                    response.insert(
2395                        port_id,
2396                        PortTransferInfo {
2397                            port_message_queue: buffer,
2398                            disentangled: entry.entangled_with.is_none(),
2399                        },
2400                    );
2401
2402                    // If the port was in transfer, and a global is requesting completion,
2403                    // we note the start of the completion.
2404                    MessagePortInfo {
2405                        state: TransferState::CompletionInProgress(router_id),
2406                        entangled_with: entry.entangled_with,
2407                    }
2408                },
2409                TransferState::CompletionFailed(buffer) |
2410                TransferState::CompletionRequested(_, buffer) => {
2411                    // If the completion had already failed,
2412                    // this is a request coming from a global to complete a new transfer,
2413                    // but we're still awaiting the return of the buffer
2414                    // from the first global who failed.
2415                    //
2416                    // So we note the request from the new global,
2417                    // and continue to buffer incoming messages
2418                    // and wait for the buffer used in the previous transfer to be returned.
2419                    //
2420                    // If another global requests completion in the CompletionRequested state,
2421                    // we simply swap the target router-id for the new one,
2422                    // keeping the buffer.
2423                    MessagePortInfo {
2424                        state: TransferState::CompletionRequested(router_id, buffer),
2425                        entangled_with: entry.entangled_with,
2426                    }
2427                },
2428                _ => {
2429                    warn!("Unexpected complete port transfer message received");
2430                    continue;
2431                },
2432            };
2433            self.message_ports.insert(port_id, new_info);
2434        }
2435
2436        if !response.is_empty() {
2437            // Forward the buffered message-queue.
2438            if let Some(ipc_sender) = self.message_port_routers.get(&router_id) {
2439                if ipc_sender
2440                    .send(MessagePortMsg::CompleteTransfer(response))
2441                    .is_err()
2442                {
2443                    warn!("Constellation failed to send complete port transfer response.");
2444                }
2445            } else {
2446                warn!("No message-port sender for {:?}", router_id);
2447            }
2448        }
2449    }
2450
2451    #[servo_tracing::instrument(skip_all)]
2452    fn handle_reroute_messageport(&mut self, port_id: MessagePortId, task: PortMessageTask) {
2453        let Some(info) = self.message_ports.get_mut(&port_id) else {
2454            return warn!(
2455                "Constellation asked to re-route msg to unknown messageport {:?}",
2456                port_id
2457            );
2458        };
2459        match &mut info.state {
2460            TransferState::Managed(router_id) | TransferState::CompletionInProgress(router_id) => {
2461                // In both the managed and completion of a transfer case, we forward the message.
2462                // Note that in both cases, if the port is transferred before the message is handled,
2463                // it will be sent back here and buffered while the transfer is ongoing.
2464                if let Some(ipc_sender) = self.message_port_routers.get(router_id) {
2465                    let _ = ipc_sender.send(MessagePortMsg::NewTask(port_id, task));
2466                } else {
2467                    warn!("No message-port sender for {:?}", router_id);
2468                }
2469            },
2470            TransferState::TransferInProgress(queue) => queue.push_back(task),
2471            TransferState::CompletionFailed(queue) => queue.push_back(task),
2472            TransferState::CompletionRequested(_, queue) => queue.push_back(task),
2473        }
2474    }
2475
2476    #[servo_tracing::instrument(skip_all)]
2477    fn handle_messageport_shipped(&mut self, port_id: MessagePortId) {
2478        if let Some(info) = self.message_ports.get_mut(&port_id) {
2479            match info.state {
2480                TransferState::Managed(_) => {
2481                    // If shipped while managed, note the start of a transfer.
2482                    info.state = TransferState::TransferInProgress(VecDeque::new());
2483                },
2484                TransferState::CompletionInProgress(_) => {
2485                    // If shipped while completion of a transfer was in progress,
2486                    // the completion failed.
2487                    // This will be followed by a MessagePortTransferFailed message,
2488                    // containing the buffer we previously sent.
2489                    info.state = TransferState::CompletionFailed(VecDeque::new());
2490                },
2491                _ => warn!("Unexpected messageport shipped received"),
2492            }
2493        } else {
2494            warn!(
2495                "Constellation asked to mark unknown messageport as shipped {:?}",
2496                port_id
2497            );
2498        }
2499    }
2500
2501    fn handle_new_messageport_router(
2502        &mut self,
2503        router_id: MessagePortRouterId,
2504        message_port_callbacks: GenericCallback<MessagePortMsg>,
2505    ) {
2506        self.message_port_routers
2507            .insert(router_id, message_port_callbacks);
2508    }
2509
2510    fn handle_remove_messageport_router(&mut self, router_id: MessagePortRouterId) {
2511        self.message_port_routers.remove(&router_id);
2512    }
2513
2514    fn handle_new_messageport(&mut self, router_id: MessagePortRouterId, port_id: MessagePortId) {
2515        match self.message_ports.entry(port_id) {
2516            // If it's a new port, we should not know about it.
2517            Entry::Occupied(_) => warn!(
2518                "Constellation asked to start tracking an existing messageport {:?}",
2519                port_id
2520            ),
2521            Entry::Vacant(entry) => {
2522                let info = MessagePortInfo {
2523                    state: TransferState::Managed(router_id),
2524                    entangled_with: None,
2525                };
2526                entry.insert(info);
2527            },
2528        }
2529    }
2530
2531    #[servo_tracing::instrument(skip_all)]
2532    fn handle_entangle_messageports(&mut self, port1: MessagePortId, port2: MessagePortId) {
2533        if let Some(info) = self.message_ports.get_mut(&port1) {
2534            info.entangled_with = Some(port2);
2535        } else {
2536            warn!(
2537                "Constellation asked to entangle unknown messageport: {:?}",
2538                port1
2539            );
2540        }
2541        if let Some(info) = self.message_ports.get_mut(&port2) {
2542            info.entangled_with = Some(port1);
2543        } else {
2544            warn!(
2545                "Constellation asked to entangle unknown messageport: {:?}",
2546                port2
2547            );
2548        }
2549    }
2550
2551    #[servo_tracing::instrument(skip_all)]
2552    /// <https://html.spec.whatwg.org/multipage/#disentangle>
2553    fn handle_disentangle_messageports(
2554        &mut self,
2555        port1: MessagePortId,
2556        port2: Option<MessagePortId>,
2557    ) {
2558        // Disentangle initiatorPort and otherPort,
2559        // so that they are no longer entangled or associated with each other.
2560        // Note: If `port2` is some, then this is the first message
2561        // and `port1` is the initiatorPort, `port2` is the otherPort.
2562        // We can immediately remove the initiator.
2563        let _ = self.message_ports.remove(&port1);
2564
2565        // Note: the none case is when otherPort sent this message
2566        // in response to completing its own local disentanglement.
2567        let Some(port2) = port2 else {
2568            return;
2569        };
2570
2571        // Start disentanglement of the other port.
2572        if let Some(info) = self.message_ports.get_mut(&port2) {
2573            info.entangled_with = None;
2574            match &mut info.state {
2575                TransferState::Managed(router_id) |
2576                TransferState::CompletionInProgress(router_id) => {
2577                    // We try to disentangle the other port now,
2578                    // and if it has been transfered out by the time the message is received,
2579                    // it will be ignored,
2580                    // and disentanglement will be completed as part of the transfer.
2581                    if let Some(ipc_sender) = self.message_port_routers.get(router_id) {
2582                        let _ = ipc_sender.send(MessagePortMsg::CompleteDisentanglement(port2));
2583                    } else {
2584                        warn!("No message-port sender for {:?}", router_id);
2585                    }
2586                },
2587                _ => {
2588                    // Note: the port is in transfer, disentanglement will complete along with it.
2589                },
2590            }
2591        } else {
2592            warn!(
2593                "Constellation asked to disentangle unknown messageport: {:?}",
2594                port2
2595            );
2596        }
2597    }
2598
2599    #[servo_tracing::instrument(skip_all)]
2600    fn handle_service_worker_state_update_done(
2601        &mut self,
2602        worker_id: ServiceWorkerId,
2603        pipeline_id: PipelineId,
2604    ) {
2605        let (is_empty, origin) = {
2606            let Some(pending) = self.service_workers_pending_update.get_mut(&worker_id) else {
2607                return;
2608            };
2609            if let Some(count) = pending.pipelines.get_mut(&pipeline_id) {
2610                *count = count.saturating_sub(1);
2611                if *count == 0 {
2612                    pending.pipelines.remove(&pipeline_id);
2613                }
2614            }
2615            (pending.pipelines.is_empty(), pending.origin.clone())
2616        };
2617
2618        if is_empty {
2619            self.service_workers_pending_update.remove(&worker_id);
2620            let Some(manager) = self.sw_managers.get(&origin) else {
2621                error!("No service worker manager found for origin {:?}", origin);
2622                return;
2623            };
2624            if manager
2625                .send(ServiceWorkerMsg::FinishInstall(worker_id))
2626                .is_err()
2627            {
2628                warn!("Failed to send FinishInstall message to service worker manager");
2629            }
2630        }
2631    }
2632
2633    /// <https://www.w3.org/TR/service-workers/#algorithms>
2634    /// Algorithms invoked from in-parallel steps run on the service worker mananager,
2635    /// per origin and routed by the constellation.
2636    #[servo_tracing::instrument(skip_all)]
2637    fn handle_serviceworker_algorithm(
2638        &mut self,
2639        pipeline_id: PipelineId,
2640        algorithm: ServiceWorkerAlgorithm,
2641    ) {
2642        let origin = match &algorithm {
2643            ServiceWorkerAlgorithm::StartRegister(job) => job.storage_key.clone(),
2644            ServiceWorkerAlgorithm::Unregister(job) => job.storage_key.clone(),
2645            ServiceWorkerAlgorithm::MatchServiceWorkerRegistration { storage_key, .. } => {
2646                storage_key.clone()
2647            },
2648        };
2649
2650        if self
2651            .check_origin_against_pipeline(&pipeline_id, &origin)
2652            .is_err()
2653        {
2654            return warn!(
2655                "Attempt to schedule a serviceworker job from an origin not matching the origin of the job."
2656            );
2657        }
2658
2659        // This match is equivalent to Entry.or_insert_with but allows for early return.
2660        let sw_manager = match self.sw_managers.entry(origin.clone()) {
2661            Entry::Occupied(entry) => entry.into_mut(),
2662            Entry::Vacant(entry) => {
2663                let (own_sender, receiver) =
2664                    generic_channel::channel().expect("Failed to create IPC channel!");
2665
2666                let sw_senders = SWManagerSenders {
2667                    constellation_sender: self.sw_manager_sender.clone(),
2668                    resource_threads: self.public_resource_threads.clone(),
2669                    own_sender: own_sender.clone(),
2670                    receiver,
2671                    paint_api: self.paint_proxy.cross_process_paint_api.clone(),
2672                    system_font_service_sender: self.system_font_service.to_sender(),
2673                };
2674
2675                #[cfg(feature = "multiprocess")]
2676                if opts::get().multiprocess {
2677                    let (sender, receiver) = generic_channel::channel()
2678                        .expect("Failed to create lifeline channel for sw");
2679                    let content =
2680                        ServiceWorkerUnprivilegedContent::new(sw_senders, origin, Some(sender));
2681
2682                    if let Ok(process) = content.spawn_multiprocess() {
2683                        let crossbeam_receiver = receiver.route_preserving_errors();
2684                        self.process_manager.add(crossbeam_receiver, process);
2685                    } else {
2686                        return warn!("Failed to spawn process for SW manager.");
2687                    }
2688                } else {
2689                    let content = ServiceWorkerUnprivilegedContent::new(sw_senders, origin, None);
2690                    content.start::<SWF>();
2691                }
2692                #[cfg(not(feature = "multiprocess"))]
2693                {
2694                    let content = ServiceWorkerUnprivilegedContent::new(sw_senders, origin, None);
2695                    content.start::<SWF>();
2696                }
2697
2698                entry.insert(own_sender)
2699            },
2700        };
2701        if let Err(err) = sw_manager.send(ServiceWorkerMsg::HandleAlgorithm(algorithm)) {
2702            warn!("Failed to send algorithm to SW manager: {:?}", err);
2703        }
2704    }
2705
2706    #[servo_tracing::instrument(skip_all)]
2707    fn handle_broadcast_storage_event(
2708        &self,
2709        pipeline_id: PipelineId,
2710        storage: WebStorageType,
2711        url: ServoUrl,
2712        key: Option<String>,
2713        old_value: Option<String>,
2714        new_value: Option<String>,
2715    ) {
2716        let origin = url.origin();
2717        let Some(source_pipeline) = self.pipelines.get(&pipeline_id) else {
2718            warn!("Received storage event broadcast request from closed pipeline.");
2719            return;
2720        };
2721
2722        if source_pipeline.url.origin() != origin {
2723            return warn!(
2724                "Attempt to broadcast storage event from an origin not matching the source pipeline origin."
2725            );
2726        }
2727
2728        let interested = match self
2729            .pipeline_interests
2730            .get(&ConstellationInterest::StorageEvent)
2731        {
2732            Some(set) => set,
2733            None => return,
2734        }
2735        .iter()
2736        .filter_map(|interested_id| self.pipelines.get(interested_id));
2737
2738        for pipeline in interested {
2739            if pipeline.id == pipeline_id || pipeline.url.origin() != origin {
2740                continue;
2741            }
2742
2743            // https://html.spec.whatwg.org/multipage/#concept-storage-broadcast
2744            // "Step 3. Let remoteStorages be all Storage objects excluding storage whose:
2745            // type is storage's type
2746            // relevant settings object's origin is same origin with storage's relevant settings object's origin
2747            // and, if type is "session", whose relevant settings object's associated Document's
2748            // node navigable's traversable navigable is thisDocument's node navigable's
2749            // traversable navigable."
2750            if storage == WebStorageType::Session &&
2751                pipeline.webview_id != source_pipeline.webview_id
2752            {
2753                continue;
2754            }
2755
2756            let msg = ScriptThreadMessage::DispatchStorageEvent(
2757                pipeline.id,
2758                storage,
2759                url.clone(),
2760                key.clone(),
2761                old_value.clone(),
2762                new_value.clone(),
2763            );
2764            if let Err(err) = pipeline.event_loop.send(msg) {
2765                warn!(
2766                    "{}: Failed to broadcast storage event to pipeline ({:?}).",
2767                    pipeline.id, err
2768                );
2769            }
2770        }
2771    }
2772
2773    #[servo_tracing::instrument(skip_all)]
2774    fn handle_exit(&mut self) {
2775        debug!("Handling exit.");
2776
2777        // TODO: add a timer, which forces shutdown if threads aren't responsive.
2778        if self.shutting_down {
2779            return;
2780        }
2781        self.shutting_down = true;
2782
2783        self.mem_profiler_chan.send(mem::ProfilerMsg::Exit);
2784
2785        // Tell all BHMs to exit, and to ensure their monitored components exit even when currently
2786        // hanging (on JS or sync XHR). This must be done before starting the process of closing all
2787        // pipelines.
2788        self.send_message_to_all_background_hang_monitors(BackgroundHangMonitorControlMsg::Exit);
2789
2790        // Close the top-level browsing contexts
2791        let browsing_context_ids: Vec<_> = self
2792            .browsing_contexts
2793            .values()
2794            .filter(|browsing_context| browsing_context.is_top_level())
2795            .map(|browsing_context| (browsing_context.webview_id, browsing_context.id))
2796            .collect();
2797        for (webview_id, browsing_context_id) in browsing_context_ids {
2798            debug!(
2799                "{}: Removing top-level browsing context",
2800                browsing_context_id
2801            );
2802            self.close_browsing_context(webview_id, browsing_context_id);
2803        }
2804
2805        // Close any pending changes and pipelines
2806        let pending_changes: Vec<_> = self
2807            .webviews
2808            .values_mut()
2809            .flat_map(|webview| webview.pending_changes.drain(..))
2810            .collect();
2811        for pending in pending_changes {
2812            debug!(
2813                "{}: Removing pending browsing context",
2814                pending.browsing_context_id
2815            );
2816            self.close_browsing_context(pending.webview_id, pending.browsing_context_id);
2817            debug!("{}: Removing pending pipeline", pending.new_pipeline_id);
2818            self.close_pipeline(pending.new_pipeline_id, DiscardBrowsingContext::Yes);
2819        }
2820
2821        // In case there are browsing contexts which weren't attached, we close them.
2822        let browsing_context_ids: Vec<_> = self
2823            .browsing_contexts
2824            .iter()
2825            .map(|(browsing_context_id, browsing_context)| {
2826                (*browsing_context_id, browsing_context.webview_id)
2827            })
2828            .collect();
2829
2830        for (browsing_context_id, webview_id) in browsing_context_ids {
2831            debug!(
2832                "{}: Removing detached browsing context",
2833                browsing_context_id
2834            );
2835            self.close_browsing_context(webview_id, browsing_context_id);
2836        }
2837
2838        // In case there are pipelines which weren't attached to the pipeline tree, we close them.
2839        let pipeline_ids: Vec<PipelineId> = self.pipelines.keys().cloned().collect();
2840        for pipeline_id in pipeline_ids {
2841            debug!("{}: Removing detached pipeline", pipeline_id);
2842            self.close_pipeline(pipeline_id, DiscardBrowsingContext::Yes);
2843        }
2844    }
2845
2846    #[servo_tracing::instrument(skip_all)]
2847    fn handle_shutdown(&mut self) {
2848        debug!("Handling shutdown.");
2849
2850        for join_handle in self.event_loop_join_handles.drain(..) {
2851            if join_handle.join().is_err() {
2852                error!("Failed to join on a script-thread.");
2853            }
2854        }
2855
2856        // In single process mode, join on the background hang monitor worker thread.
2857        drop(self.background_monitor_register.take());
2858        if let Some(join_handle) = self.background_monitor_register_join_handle.take() &&
2859            join_handle.join().is_err()
2860        {
2861            error!("Failed to join on the bhm background thread.");
2862        }
2863
2864        // At this point, there are no active pipelines,
2865        // so we can safely block on other threads, without worrying about deadlock.
2866        // Channels to receive signals when threads are done exiting.
2867        let (core_ipc_sender, core_ipc_receiver) =
2868            generic_channel::oneshot().expect("Failed to create IPC channel!");
2869        let (public_client_storage_generic_sender, public_client_storage_generic_receiver) =
2870            generic_channel::channel().expect("Failed to create generic channel!");
2871        let (private_client_storage_generic_sender, private_client_storage_generic_receiver) =
2872            generic_channel::channel().expect("Failed to create generic channel!");
2873        let (private_cache_storage_generic_sender, private_cache_storage_generic_receiver) =
2874            generic_channel::channel().expect("Failed to create generic channel!");
2875        let (public_cache_storage_generic_sender, public_cache_storage_generic_receiver) =
2876            generic_channel::channel().expect("Failed to create generic channel!");
2877        let (public_indexeddb_ipc_sender, public_indexeddb_ipc_receiver) =
2878            generic_channel::channel().expect("Failed to create generic channel!");
2879        let (private_indexeddb_ipc_sender, private_indexeddb_ipc_receiver) =
2880            generic_channel::channel().expect("Failed to create generic channel!");
2881        let (public_web_storage_generic_sender, public_web_storage_generic_receiver) =
2882            generic_channel::channel().expect("Failed to create generic channel!");
2883        let (private_web_storage_generic_sender, private_web_storage_generic_receiver) =
2884            generic_channel::channel().expect("Failed to create generic channel!");
2885
2886        debug!("Exiting core resource threads.");
2887        if let Err(e) = self
2888            .public_resource_threads
2889            .send(net_traits::CoreResourceMsg::Exit(core_ipc_sender))
2890        {
2891            warn!("Exit resource thread failed ({})", e);
2892        }
2893
2894        #[cfg(feature = "devtools")]
2895        if let Some(ref chan) = self.devtools_sender {
2896            debug!("Exiting devtools.");
2897            let msg = DevtoolsControlMsg::FromChrome(ChromeToDevtoolsControlMsg::ServerExitMsg);
2898            if let Err(e) = chan.send(msg) {
2899                warn!("Exit devtools failed ({:?})", e);
2900            }
2901        }
2902
2903        debug!("Exiting public client storage thread.");
2904        if let Err(e) = generic_channel::GenericSend::send(
2905            &self.public_storage_threads,
2906            ClientStorageThreadMessage::Exit(public_client_storage_generic_sender),
2907        ) {
2908            warn!("Exit public client storage thread failed ({})", e);
2909        }
2910        debug!("Exiting private client storage thread.");
2911        if let Err(e) = generic_channel::GenericSend::send(
2912            &self.private_storage_threads,
2913            ClientStorageThreadMessage::Exit(private_client_storage_generic_sender),
2914        ) {
2915            warn!("Exit private client storage thread failed ({})", e);
2916        }
2917
2918        debug!("Exiting public cache storage thread.");
2919        if let Err(e) = generic_channel::GenericSend::send(
2920            &self.public_storage_threads,
2921            CacheStorageThreadMessage::Exit(public_cache_storage_generic_sender),
2922        ) {
2923            warn!("Exit public cache storage thread failed ({})", e);
2924        }
2925        debug!("Exiting private cache storage thread.");
2926        if let Err(e) = generic_channel::GenericSend::send(
2927            &self.private_storage_threads,
2928            CacheStorageThreadMessage::Exit(private_cache_storage_generic_sender),
2929        ) {
2930            warn!("Exit private cache storage thread failed ({})", e);
2931        }
2932
2933        debug!("Exiting public indexeddb resource threads.");
2934        if let Err(e) =
2935            self.public_storage_threads
2936                .send(IndexedDBThreadMsg::Sync(SyncOperation::Exit(
2937                    public_indexeddb_ipc_sender,
2938                )))
2939        {
2940            warn!("Exit public indexeddb thread failed ({})", e);
2941        }
2942
2943        debug!("Exiting private indexeddb resource threads.");
2944        if let Err(e) =
2945            self.private_storage_threads
2946                .send(IndexedDBThreadMsg::Sync(SyncOperation::Exit(
2947                    private_indexeddb_ipc_sender,
2948                )))
2949        {
2950            warn!("Exit private indexeddb thread failed ({})", e);
2951        }
2952
2953        debug!("Exiting public web storage thread.");
2954        if let Err(e) = generic_channel::GenericSend::send(
2955            &self.public_storage_threads,
2956            WebStorageThreadMsg::Exit(public_web_storage_generic_sender),
2957        ) {
2958            warn!("Exit public web storage thread failed ({})", e);
2959        }
2960
2961        debug!("Exiting private web storage thread.");
2962        if let Err(e) = generic_channel::GenericSend::send(
2963            &self.private_storage_threads,
2964            WebStorageThreadMsg::Exit(private_web_storage_generic_sender),
2965        ) {
2966            warn!("Exit private web storage thread failed ({})", e);
2967        }
2968
2969        #[cfg(feature = "bluetooth")]
2970        {
2971            debug!("Exiting bluetooth thread.");
2972            if let Err(e) = self.bluetooth_ipc_sender.send(BluetoothRequest::Exit) {
2973                warn!("Exit bluetooth thread failed ({})", e);
2974            }
2975        }
2976
2977        debug!("Exiting service worker manager thread.");
2978        for (_, mgr) in self.sw_managers.drain() {
2979            if let Err(e) = mgr.send(ServiceWorkerMsg::Exit) {
2980                warn!("Exit service worker manager failed ({})", e);
2981            }
2982        }
2983
2984        let canvas_exit_receiver = if let Some((canvas_sender, _)) = self.canvas.get() {
2985            debug!("Exiting Canvas Paint thread.");
2986            let (canvas_exit_sender, canvas_exit_receiver) = unbounded();
2987            if let Err(e) = canvas_sender.send(ConstellationCanvasMsg::Exit(canvas_exit_sender)) {
2988                warn!("Exit Canvas Paint thread failed ({})", e);
2989            }
2990            Some(canvas_exit_receiver)
2991        } else {
2992            None
2993        };
2994
2995        debug!("Exiting WebGPU threads.");
2996        #[cfg(feature = "webgpu")]
2997        {
2998            let receivers: Vec<_> = self
2999                .webviews
3000                .values()
3001                .flat_map(|webview| {
3002                    // This `take` is necessary as it ensures that WebViews that
3003                    // share a BrowsingContextGroup don't have their WebGPU
3004                    // entries processed more than once.
3005                    std::mem::take(&mut webview.browsing_context_group().borrow_mut().webgpus)
3006                })
3007                .filter_map(|(_, webgpu)| {
3008                    let (sender, receiver) =
3009                        generic_channel::oneshot().expect("Failed to create IPC channel!");
3010                    webgpu.exit(sender).is_ok().then_some(receiver)
3011                })
3012                .collect();
3013
3014            for receiver in receivers {
3015                if let Err(error) = receiver.recv() {
3016                    warn!("Failed to receive exit response from WebGPU: {error:?}.");
3017                }
3018            }
3019        }
3020
3021        debug!("Exiting GLPlayer thread.");
3022        WindowGLContext::get().exit();
3023
3024        // Wait for the canvas thread to exit before shutting down the font service, as
3025        // canvas might still be using the system font service before shutting down.
3026        if let Some(canvas_exit_receiver) = canvas_exit_receiver {
3027            let _ = canvas_exit_receiver.recv();
3028        }
3029
3030        debug!("Exiting the system font service thread.");
3031        self.system_font_service.exit();
3032
3033        // Receive exit signals from threads.
3034        if let Err(e) = core_ipc_receiver.recv() {
3035            warn!("Exit resource thread failed ({:?})", e);
3036        }
3037        if let Err(e) = public_client_storage_generic_receiver.recv() {
3038            warn!("Exit public client storage thread failed ({:?})", e);
3039        }
3040        if let Err(e) = private_client_storage_generic_receiver.recv() {
3041            warn!("Exit private client storage thread failed ({:?})", e);
3042        }
3043        if let Err(e) = private_cache_storage_generic_receiver.recv() {
3044            warn!("Exit private cache storage thread failed ({:?})", e);
3045        }
3046        if let Err(e) = public_cache_storage_generic_receiver.recv() {
3047            warn!("Exit public cache storage thread failed ({:?})", e);
3048        }
3049        if let Err(e) = public_indexeddb_ipc_receiver.recv() {
3050            warn!("Exit public indexeddb thread failed ({:?})", e);
3051        }
3052        if let Err(e) = private_indexeddb_ipc_receiver.recv() {
3053            warn!("Exit private indexeddb thread failed ({:?})", e);
3054        }
3055        if let Err(e) = public_web_storage_generic_receiver.recv() {
3056            warn!("Exit public web storage thread failed ({:?})", e);
3057        }
3058        if let Err(e) = private_web_storage_generic_receiver.recv() {
3059            warn!("Exit private web storage thread failed ({:?})", e);
3060        }
3061
3062        debug!("Shutting-down IPC router thread in constellation.");
3063        ROUTER.shutdown();
3064
3065        debug!("Shutting-down the async runtime in constellation.");
3066        self.async_runtime.shutdown();
3067    }
3068
3069    /// Stops waiting for all pending service worker state updates for the given pipeline.
3070    fn stop_waiting_for_pending_service_worker_state_update(&mut self, pipeline_id: &PipelineId) {
3071        // loop over all service_workers_pending_update and remove the pipeline,
3072        // message the sw manager if no pipelines are left.
3073        self.service_workers_pending_update
3074            .retain(|worker_id, pending| {
3075                pending.pipelines.remove(pipeline_id);
3076                if pending.pipelines.is_empty() {
3077                    // message sw manager
3078                    if let Some(manager) = self.sw_managers.get(&pending.origin) {
3079                        if manager
3080                            .send(ServiceWorkerMsg::FinishInstall(*worker_id))
3081                            .is_err()
3082                        {
3083                            error!("Failed to send FinishInstall for worker {}", worker_id);
3084                        } else {
3085                            warn!("Unable to send FinishInstall for worker {}", worker_id);
3086                        }
3087                    }
3088                    false
3089                } else {
3090                    true
3091                }
3092            });
3093    }
3094
3095    fn handle_pipeline_exited(&mut self, pipeline_id: PipelineId, exit_source: PipelineExitSource) {
3096        debug!("{}: Exited", pipeline_id);
3097        self.remove_worker_animation_frame_providers_for_pipeline(pipeline_id);
3098
3099        let Some(pipeline) = self.pipelines.remove(&pipeline_id) else {
3100            return;
3101        };
3102
3103        self.stop_waiting_for_pending_service_worker_state_update(&pipeline_id);
3104
3105        // Let the embedding layer release resources it is holding on this pipeline's behalf.
3106        self.constellation_to_embedder_proxy
3107            .send(ConstellationToEmbedderMsg::PipelineExited(pipeline_id));
3108
3109        // Clean up any registered interests for this pipeline.
3110        self.pipeline_interests.retain(|_, set| {
3111            set.remove(&pipeline_id);
3112            !set.is_empty()
3113        });
3114
3115        // Now that the Script and Constellation parts of Servo no longer have a reference to
3116        // this pipeline, tell `Paint` that it has shut down. This is delayed until the
3117        // last moment.
3118        self.paint_proxy.send(PaintMessage::PipelineExited(
3119            pipeline.webview_id,
3120            pipeline.id,
3121            exit_source,
3122        ));
3123    }
3124
3125    #[servo_tracing::instrument(skip_all)]
3126    fn handle_send_error(&mut self, pipeline_id: PipelineId, error: SendError) {
3127        error!("Error sending message to {pipeline_id:?}: {error}",);
3128
3129        // Ignore errors from unknown Pipelines.
3130        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
3131            return;
3132        };
3133
3134        // Treat send error the same as receiving a panic message
3135        self.handle_panic_in_webview(
3136            pipeline.webview_id,
3137            &format!("Send failed ({error})"),
3138            &None,
3139        );
3140    }
3141
3142    #[servo_tracing::instrument(skip_all)]
3143    fn handle_panic(
3144        &mut self,
3145        event_loop_id: Option<ScriptEventLoopId>,
3146        reason: String,
3147        backtrace: Option<String>,
3148    ) {
3149        if self.hard_fail {
3150            // It's quite difficult to make Servo exit cleanly if some threads have failed.
3151            // Hard fail exists for test runners so we crash and that's good enough.
3152            error!("Pipeline failed in hard-fail mode.  Crashing!");
3153            process::exit(1);
3154        }
3155
3156        let Some(event_loop_id) = event_loop_id else {
3157            return;
3158        };
3159        debug!("Panic handler for {event_loop_id:?}: {reason:?}",);
3160
3161        let mut webview_ids = HashSet::new();
3162        let mut crashed_pipelines = Vec::new();
3163        for pipeline in self.pipelines.values() {
3164            if pipeline.event_loop.id() == event_loop_id {
3165                crashed_pipelines.push(pipeline.id);
3166                webview_ids.insert(pipeline.webview_id);
3167            }
3168        }
3169
3170        for webview_id in webview_ids {
3171            self.handle_panic_in_webview(webview_id, &reason, &backtrace);
3172        }
3173
3174        for pipeline_id in crashed_pipelines {
3175            self.close_pipeline(pipeline_id, DiscardBrowsingContext::No);
3176            // The pipeline is now unreachable, so we should consider it gone. We should
3177            // not try to send any subsequent messages to this pipeline. all() here ensures
3178            // that `Paint` cleans up the pipeline display immediately without waiting for
3179            // confirmation from the event loop.
3180            self.handle_pipeline_exited(pipeline_id, PipelineExitSource::all());
3181        }
3182    }
3183
3184    fn handle_panic_in_webview(
3185        &mut self,
3186        webview_id: WebViewId,
3187        reason: &String,
3188        backtrace: &Option<String>,
3189    ) {
3190        self.constellation_to_embedder_proxy
3191            .send(ConstellationToEmbedderMsg::Panic(
3192                webview_id,
3193                reason.clone(),
3194                backtrace.clone(),
3195            ));
3196
3197        let browsing_context_id = BrowsingContextId::from(webview_id);
3198        let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) else {
3199            return warn!("failed browsing context is missing");
3200        };
3201        let viewport_details = browsing_context.viewport_details;
3202        let pipeline_id = browsing_context.pipeline_id;
3203
3204        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
3205            return warn!("failed pipeline is missing");
3206        };
3207        let opener = pipeline.opener;
3208
3209        let old_pipeline_id = pipeline_id;
3210        let Some(old_load_data) = self.refresh_load_data(pipeline_id) else {
3211            return warn!("failed pipeline is missing");
3212        };
3213
3214        self.close_browsing_context_children(
3215            webview_id,
3216            browsing_context_id,
3217            DiscardBrowsingContext::No,
3218        );
3219
3220        if old_load_data.crash.is_some() {
3221            return error!("crash page crashed");
3222        }
3223
3224        warn!("creating replacement pipeline for crash page");
3225
3226        let new_pipeline_id = PipelineId::new();
3227        let new_load_data = LoadData {
3228            crash: Some(
3229                backtrace
3230                    .clone()
3231                    .map(|backtrace| format!("{reason}\n{backtrace}"))
3232                    .unwrap_or_else(|| reason.clone()),
3233            ),
3234            creation_sandboxing_flag_set: SandboxingFlagSet::all(),
3235            ..old_load_data.clone()
3236        };
3237
3238        let is_private = false;
3239        self.new_pipeline(
3240            new_pipeline_id,
3241            browsing_context_id,
3242            webview_id,
3243            None,
3244            opener,
3245            viewport_details,
3246            new_load_data,
3247            is_private,
3248            TargetSnapshotParams::default(),
3249            None,
3250        );
3251
3252        let Some(webview) = self.webviews.get_mut(&webview_id) else {
3253            return warn!("Adding pending change to unknown WebView: {webview_id:?}");
3254        };
3255        webview.add_pending_change(SessionHistoryChange {
3256            webview_id,
3257            browsing_context_id,
3258            new_pipeline_id,
3259            // Pipeline already closed by close_browsing_context_children, so we can pass Yes here
3260            // to avoid closing again in handle_activate_document_msg (though it would be harmless)
3261            replace: Some(NeedsToReload::Yes(old_pipeline_id, old_load_data)),
3262            new_browsing_context_info: None,
3263            viewport_details,
3264        });
3265    }
3266
3267    #[servo_tracing::instrument(skip_all)]
3268    fn handle_set_has_system_focus(&mut self, webview_id: WebViewId, has_system_focus: bool) {
3269        let Some(webview) = self.webviews.get_mut(&webview_id) else {
3270            return warn!("Tried to focus a nonexistent WebView: {webview_id:?}");
3271        };
3272        if !webview.set_has_system_focus(has_system_focus) {
3273            return;
3274        }
3275
3276        let state = webview.state();
3277        for event_loop in self.event_loops() {
3278            if let Err(error) =
3279                event_loop.send(ScriptThreadMessage::UpdateWebViewState(state.clone()))
3280            {
3281                warn!(
3282                    "Sending to closed event loop ({:?}): {error}",
3283                    event_loop.id()
3284                );
3285            }
3286        }
3287    }
3288
3289    #[servo_tracing::instrument(skip_all)]
3290    fn handle_log_entry(
3291        &mut self,
3292        event_loop_id: Option<ScriptEventLoopId>,
3293        thread_name: Option<String>,
3294        entry: LogEntry,
3295    ) {
3296        if let LogEntry::Panic(ref reason, ref backtrace) = entry {
3297            self.handle_panic(event_loop_id, reason.clone(), Some(backtrace.clone()));
3298        }
3299
3300        match entry {
3301            LogEntry::Panic(reason, _) | LogEntry::Error(reason) | LogEntry::Warn(reason) => {
3302                // VecDeque::truncate is unstable
3303                if WARNINGS_BUFFER_SIZE <= self.handled_warnings.len() {
3304                    self.handled_warnings.pop_front();
3305                }
3306                self.handled_warnings.push_back((thread_name, reason));
3307            },
3308        }
3309    }
3310
3311    fn update_pressed_mouse_buttons(&mut self, event: &MouseButtonEvent) {
3312        let Ok(buttons) = MouseButtons::try_from(event.button) else {
3313            return;
3314        };
3315        match event.action {
3316            MouseButtonAction::Down => {
3317                self.pressed_mouse_buttons |= buttons;
3318            },
3319            MouseButtonAction::Up => {
3320                self.pressed_mouse_buttons &= !(buttons);
3321            },
3322        }
3323    }
3324
3325    #[expect(deprecated)]
3326    fn update_active_keybord_modifiers(&mut self, event: &KeyboardEvent) {
3327        self.active_keyboard_modifiers = event.event.modifiers;
3328
3329        // `KeyboardEvent::modifiers` contains the pre-existing modifiers before this key was
3330        // either pressed or released, but `active_keyboard_modifiers` should track the subsequent
3331        // state. If this event will update that state, we need to ensure that we are tracking what
3332        // the event changes.
3333        let Key::Named(named_key) = event.event.key else {
3334            return;
3335        };
3336
3337        let modified_modifier = match named_key {
3338            NamedKey::Alt => Modifiers::ALT,
3339            NamedKey::AltGraph => Modifiers::ALT_GRAPH,
3340            NamedKey::CapsLock => Modifiers::CAPS_LOCK,
3341            NamedKey::Control => Modifiers::CONTROL,
3342            NamedKey::Fn => Modifiers::FN,
3343            NamedKey::FnLock => Modifiers::FN_LOCK,
3344            NamedKey::Meta => Modifiers::META,
3345            NamedKey::NumLock => Modifiers::NUM_LOCK,
3346            NamedKey::ScrollLock => Modifiers::SCROLL_LOCK,
3347            NamedKey::Shift => Modifiers::SHIFT,
3348            NamedKey::Symbol => Modifiers::SYMBOL,
3349            NamedKey::SymbolLock => Modifiers::SYMBOL_LOCK,
3350            NamedKey::Hyper => Modifiers::HYPER,
3351            // The web doesn't make a distinction between these keys (there is only
3352            // "meta") so map "super" to "meta".
3353            NamedKey::Super => Modifiers::META,
3354            _ => return,
3355        };
3356        match event.event.state {
3357            KeyState::Down => self.active_keyboard_modifiers.insert(modified_modifier),
3358            KeyState::Up => self.active_keyboard_modifiers.remove(modified_modifier),
3359        }
3360    }
3361
3362    fn set_accessibility_active(&mut self, webview_id: WebViewId, active: bool) {
3363        if !(pref!(accessibility_enabled)) {
3364            return;
3365        }
3366
3367        let Some(webview) = self.webviews.get_mut(&webview_id) else {
3368            return;
3369        };
3370
3371        webview.accessibility_active = active;
3372        let Some(pipeline_id) = webview.active_top_level_pipeline_id else {
3373            return;
3374        };
3375        let epoch = webview.active_top_level_pipeline_epoch;
3376        // Forward the activation to the webview’s active top-level pipeline, if any. For inactive
3377        // pipelines (documents in bfcache), we only need to forward the activation if and when they
3378        // become active (see set_frame_tree_for_webview()).
3379        // There are two sites like this; this is the a11y activation site.
3380        self.send_message_to_pipeline(
3381            pipeline_id,
3382            ScriptThreadMessage::SetAccessibilityActive(pipeline_id, active, epoch),
3383            "Set accessibility active after closure",
3384        );
3385    }
3386
3387    fn forward_accessibility_action(&mut self, action_request: ActionRequest) {
3388        let Some(pipeline_id) = self
3389            .pipelines
3390            .keys()
3391            .copied()
3392            .find(|&pipeline_id| TreeId::from(pipeline_id) == action_request.target_tree)
3393        else {
3394            warn!(
3395                "Could not complete accessibility action {action_request:?}: no matching pipeline."
3396            );
3397            return;
3398        };
3399
3400        self.send_message_to_pipeline(
3401            pipeline_id,
3402            ScriptThreadMessage::ForwardAccessibilityAction(pipeline_id, action_request),
3403            "Action request failed: sending message to pipeline failed.",
3404        );
3405    }
3406
3407    fn handle_clear_session_history(&mut self, webview_id: WebViewId) {
3408        let Some(webview) = self.webviews.get_mut(&webview_id) else {
3409            return;
3410        };
3411        webview.session_history.future.clear();
3412        webview.session_history.past.clear();
3413        self.notify_history_changed(webview_id);
3414    }
3415
3416    fn forward_input_event(
3417        &mut self,
3418        webview_id: WebViewId,
3419        event: InputEventAndId,
3420        hit_test_result: Option<PaintHitTestResult>,
3421    ) {
3422        if let InputEvent::MouseButton(event) = &event.event {
3423            self.update_pressed_mouse_buttons(event);
3424        }
3425
3426        if let InputEvent::Keyboard(event) = &event.event {
3427            self.update_active_keybord_modifiers(event);
3428        }
3429
3430        // The constellation tracks the state of pressed mouse buttons and keyboard
3431        // modifiers and updates the event here to reflect the current state.
3432        let pressed_mouse_buttons = self.pressed_mouse_buttons;
3433        let active_keyboard_modifiers = self.active_keyboard_modifiers;
3434
3435        let event_id = event.id;
3436        let Some(webview) = self.webviews.get_mut(&webview_id) else {
3437            warn!("Got input event for unknown WebViewId: {webview_id:?}");
3438            self.constellation_to_embedder_proxy.send(
3439                ConstellationToEmbedderMsg::InputEventsHandled(
3440                    webview_id,
3441                    vec![InputEventOutcome {
3442                        id: event_id,
3443                        result: Default::default(),
3444                    }],
3445                ),
3446            );
3447            return;
3448        };
3449
3450        let event = ConstellationInputEvent {
3451            hit_test_result,
3452            pressed_mouse_buttons,
3453            active_keyboard_modifiers,
3454            event,
3455        };
3456
3457        if !webview.forward_input_event(event, &self.pipelines, &self.browsing_contexts) {
3458            self.constellation_to_embedder_proxy.send(
3459                ConstellationToEmbedderMsg::InputEventsHandled(
3460                    webview_id,
3461                    vec![InputEventOutcome {
3462                        id: event_id,
3463                        result: Default::default(),
3464                    }],
3465                ),
3466            );
3467        }
3468    }
3469
3470    #[servo_tracing::instrument(skip_all)]
3471    fn handle_new_top_level_browsing_context(
3472        &mut self,
3473        url: ServoUrl,
3474        NewWebViewDetails {
3475            webview_id,
3476            viewport_details,
3477            user_content_manager_id,
3478        }: NewWebViewDetails,
3479    ) {
3480        let pipeline_id = PipelineId::new();
3481        let browsing_context_id = BrowsingContextId::from(webview_id);
3482        let load_data = LoadData::new_for_new_unrelated_webview(url);
3483        let is_private = false;
3484
3485        // Register this new top-level browsing context id as a webview and set
3486        // its focused browsing context to be itself.
3487        let mut new_webview = ConstellationWebView::new(
3488            webview_id,
3489            // https://html.spec.whatwg.org/multipage/#creating-a-new-browsing-context-group
3490            Rc::new(RefCell::new(BrowsingContextGroup::default())),
3491            browsing_context_id,
3492            user_content_manager_id,
3493        );
3494        new_webview.add_pending_change(SessionHistoryChange {
3495            webview_id,
3496            browsing_context_id,
3497            new_pipeline_id: pipeline_id,
3498            replace: None,
3499            new_browsing_context_info: Some(NewBrowsingContextInfo {
3500                parent_pipeline_id: None,
3501                is_private,
3502                inherited_secure_context: None,
3503                upgrade_insecure_navigations_set: HashSet::new(),
3504            }),
3505            viewport_details,
3506        });
3507        self.webviews.insert(webview_id, new_webview);
3508
3509        self.new_pipeline(
3510            pipeline_id,
3511            browsing_context_id,
3512            webview_id,
3513            None,
3514            None,
3515            viewport_details,
3516            load_data,
3517            is_private,
3518            TargetSnapshotParams::default(),
3519            None,
3520        );
3521
3522        self.system_font_service
3523            .prefetch_font_keys_for_painter(PainterId::from(webview_id));
3524    }
3525
3526    #[servo_tracing::instrument(skip_all)]
3527    /// <https://html.spec.whatwg.org/multipage/#destroy-a-top-level-traversable>
3528    fn handle_close_top_level_browsing_context(&mut self, webview_id: WebViewId) {
3529        debug!("{webview_id}: Closing");
3530
3531        self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStop);
3532        self.webdriver_load_status_senders.remove(&webview_id);
3533
3534        // Step 1. Let browsingContext be traversable's active browsing context.
3535        let browsing_context_id = BrowsingContextId::from(webview_id);
3536        // Step 2. For each historyEntry in traversable's session history
3537        // Step 2.1 Let document be historyEntry's document.
3538        // Step 2.2 If document is not null, then destroy a document and its
3539        // descendants given document.
3540
3541        // Step 3. Remove browsingContext.
3542        self.close_browsing_context(webview_id, browsing_context_id);
3543
3544        // Step 4. Remove traversable from the user interface (e.g., close or
3545        // hide its tab in a tabbed browser).
3546        self.constellation_to_embedder_proxy
3547            .send(ConstellationToEmbedderMsg::WebViewClosed(webview_id));
3548
3549        // Step 5. Remove traversable from the user agent's top-level traversable set.
3550        if let Some(mut webview) = self.webviews.remove(&webview_id) {
3551            // Any queued history traversal requests are never going to finish at this point,
3552            // so notify the embedder that they are now finished.
3553            if let Some(ongoing_request) = webview.ongoing_history_traversal_request {
3554                self.notify_embedder_of_completed_session_history_traversal_request(
3555                    &ongoing_request.traversal_request,
3556                );
3557            }
3558            for request in webview.session_history_traversal_request_queue.drain(..) {
3559                self.notify_embedder_of_completed_session_history_traversal_request(&request);
3560            }
3561        }
3562
3563        debug!("{webview_id}: Closed");
3564    }
3565
3566    #[servo_tracing::instrument(skip_all)]
3567    fn handle_iframe_size_msg(&mut self, webview_id: WebViewId, iframe_sizes: Vec<IFrameSizeMsg>) {
3568        for IFrameSizeMsg {
3569            browsing_context_id,
3570            size,
3571            type_,
3572        } in iframe_sizes
3573        {
3574            self.resize_browsing_context(webview_id, size, type_, browsing_context_id);
3575        }
3576    }
3577
3578    #[servo_tracing::instrument(skip_all)]
3579    fn handle_finish_javascript_evaluation(
3580        &mut self,
3581        evaluation_id: JavaScriptEvaluationId,
3582        result: Result<JSValue, JavaScriptEvaluationError>,
3583    ) {
3584        self.constellation_to_embedder_proxy.send(
3585            ConstellationToEmbedderMsg::FinishJavaScriptEvaluation(evaluation_id, result),
3586        );
3587    }
3588
3589    #[servo_tracing::instrument(skip_all)]
3590    fn handle_subframe_load_finished(&mut self, pipeline_id: PipelineId, aborted: bool) {
3591        let browsing_context_id = match self.pipelines.get(&pipeline_id) {
3592            Some(pipeline) => pipeline.browsing_context_id,
3593            None => return warn!("Subframe ({pipeline_id:?}) load finished after closure"),
3594        };
3595        let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
3596            Some(browsing_context) => browsing_context.parent_pipeline_id,
3597            None => {
3598                return warn!(
3599                    "Subframe ({pipeline_id:?}) load finished in closed {browsing_context_id:?}",
3600                );
3601            },
3602        };
3603        let Some(parent_pipeline_id) = parent_pipeline_id else {
3604            return warn!("Subframe ({pipeline_id:?}) has no parent");
3605        };
3606
3607        let msg = ScriptThreadMessage::IFrameLoadFinished {
3608            target: browsing_context_id,
3609            parent: parent_pipeline_id,
3610            child: pipeline_id,
3611            aborted,
3612        };
3613
3614        let result = match self.pipelines.get(&parent_pipeline_id) {
3615            Some(parent) => parent.event_loop.send(msg),
3616            None => {
3617                return warn!(
3618                    "Parent pipeline ({parent_pipeline_id:?}) browsing context loaded after closure",
3619                );
3620            },
3621        };
3622
3623        if let Err(e) = result {
3624            self.handle_send_error(parent_pipeline_id, e);
3625        }
3626    }
3627
3628    /// The script thread associated with pipeline_id has loaded a URL in an
3629    /// iframe via script. This will result in a new pipeline being spawned and
3630    /// a child being added to the parent browsing context. This message is never
3631    /// the result of a page navigation.
3632    #[servo_tracing::instrument(skip_all)]
3633    fn handle_script_loaded_url_in_iframe_msg(&mut self, load_info: IFrameLoadInfoWithData) {
3634        let IFrameLoadInfo {
3635            parent_pipeline_id,
3636            browsing_context_id,
3637            webview_id,
3638            new_pipeline_id,
3639            is_private,
3640            mut history_handling,
3641            target_snapshot_params,
3642            name,
3643            ..
3644        } = load_info.info;
3645
3646        // If no url is specified, reload.
3647        let old_pipeline = load_info
3648            .old_pipeline_id
3649            .and_then(|id| self.pipelines.get(&id));
3650
3651        // Replacement enabled also takes into account whether the document is "completely loaded",
3652        // see https://html.spec.whatwg.org/multipage/#the-iframe-element:completely-loaded
3653        if let Some(old_pipeline) = old_pipeline {
3654            if !old_pipeline.completely_loaded {
3655                history_handling = NavigationHistoryBehavior::Replace;
3656            }
3657            debug!(
3658                "{:?}: Old pipeline is {}completely loaded",
3659                load_info.old_pipeline_id,
3660                if old_pipeline.completely_loaded {
3661                    ""
3662                } else {
3663                    "not "
3664                }
3665            );
3666        }
3667
3668        let is_parent_private = {
3669            let parent_browsing_context_id = match self.pipelines.get(&parent_pipeline_id) {
3670                Some(pipeline) => pipeline.browsing_context_id,
3671                None => {
3672                    return warn!(
3673                        "{parent_pipeline_id}: Script loaded url in iframe \
3674                        {browsing_context_id} in closed parent pipeline",
3675                    );
3676                },
3677            };
3678
3679            let Some(ctx) = self.browsing_contexts.get(&parent_browsing_context_id) else {
3680                return warn!(
3681                    "{parent_browsing_context_id}: Script loaded url in \
3682                     iframe {browsing_context_id} in closed parent browsing context",
3683                );
3684            };
3685            ctx.is_private
3686        };
3687        let is_private = is_private || is_parent_private;
3688
3689        let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) else {
3690            return warn!(
3691                "{browsing_context_id}: Script loaded url in iframe with closed browsing context",
3692            );
3693        };
3694
3695        let replace = if history_handling == NavigationHistoryBehavior::Replace {
3696            Some(NeedsToReload::No(browsing_context.pipeline_id))
3697        } else {
3698            None
3699        };
3700
3701        let browsing_context_size = browsing_context.viewport_details;
3702        debug_assert_eq!(browsing_context_size, load_info.viewport_details);
3703
3704        // Create the new pipeline, attached to the parent and push to pending changes
3705        self.new_pipeline(
3706            new_pipeline_id,
3707            browsing_context_id,
3708            webview_id,
3709            Some(parent_pipeline_id),
3710            None,
3711            browsing_context_size,
3712            load_info.load_data,
3713            is_private,
3714            target_snapshot_params,
3715            name,
3716        );
3717
3718        let Some(webview) = self.webviews.get_mut(&webview_id) else {
3719            warn!("Could not find WebView for script-loaded iframe: ({webview_id:?})");
3720            return;
3721        };
3722
3723        // This is a transitional implementation of
3724        // <https://html.spec.whatwg.org/multipage/#set-the-ongoing-navigation>
3725        // where setting the ongoing navigation should cancel any previously ongoing
3726        // navigation.
3727        let superseded_pending_changes =
3728            webview.remove_pending_changes_for_browsing_context_id(browsing_context_id);
3729        webview.add_pending_change(SessionHistoryChange {
3730            webview_id,
3731            browsing_context_id,
3732            new_pipeline_id,
3733            replace,
3734            // Browsing context for iframe already exists.
3735            new_browsing_context_info: None,
3736            viewport_details: load_info.viewport_details,
3737        });
3738        for change in superseded_pending_changes {
3739            self.close_pipeline(change.new_pipeline_id, DiscardBrowsingContext::No);
3740        }
3741    }
3742
3743    #[servo_tracing::instrument(skip_all)]
3744    fn handle_script_new_iframe(&mut self, load_info: IFrameLoadInfoWithData) {
3745        let IFrameLoadInfo {
3746            parent_pipeline_id,
3747            new_pipeline_id,
3748            browsing_context_id,
3749            webview_id,
3750            is_private,
3751            ..
3752        } = load_info.info;
3753
3754        let (script_sender, parent_browsing_context_id) =
3755            match self.pipelines.get(&parent_pipeline_id) {
3756                Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id),
3757                None => {
3758                    return warn!(
3759                        "{}: Script loaded url in closed iframe pipeline",
3760                        parent_pipeline_id
3761                    );
3762                },
3763            };
3764        let (is_parent_private, is_parent_secure, parent_upgrade_insecure_navigations_set) =
3765            match self.browsing_contexts.get(&parent_browsing_context_id) {
3766                Some(ctx) => (
3767                    ctx.is_private,
3768                    ctx.inherited_secure_context,
3769                    ctx.upgrade_insecure_navigations_set.clone(),
3770                ),
3771                None => {
3772                    return warn!(
3773                        "{}: New iframe {} loaded in closed parent browsing context",
3774                        parent_browsing_context_id, browsing_context_id,
3775                    );
3776                },
3777            };
3778
3779        let webview_hidden = self
3780            .webviews
3781            .get(&webview_id)
3782            .is_none_or(|webview| webview.hidden());
3783        let is_private = is_private || is_parent_private;
3784        let pipeline = Pipeline::new_already_spawned(
3785            new_pipeline_id,
3786            browsing_context_id,
3787            webview_id,
3788            None,
3789            script_sender,
3790            self.paint_proxy.clone(),
3791            webview_hidden,
3792            load_info.load_data,
3793        );
3794
3795        assert!(!self.pipelines.contains_key(&new_pipeline_id));
3796        self.pipelines.insert(new_pipeline_id, pipeline);
3797
3798        if let Some(webview) = self.webviews.get_mut(&webview_id) {
3799            webview.add_pending_change(SessionHistoryChange {
3800                webview_id,
3801                browsing_context_id,
3802                new_pipeline_id,
3803                replace: None,
3804                // Browsing context for iframe doesn't exist yet.
3805                new_browsing_context_info: Some(NewBrowsingContextInfo {
3806                    parent_pipeline_id: Some(parent_pipeline_id),
3807                    is_private,
3808                    inherited_secure_context: is_parent_secure,
3809                    upgrade_insecure_navigations_set: parent_upgrade_insecure_navigations_set,
3810                }),
3811                viewport_details: load_info.viewport_details,
3812            });
3813        } else {
3814            warn!("Could not find WebView for new iframe: ({webview_id:?})");
3815        }
3816    }
3817
3818    #[servo_tracing::instrument(skip_all)]
3819    fn handle_script_new_auxiliary(&mut self, load_info: AuxiliaryWebViewCreationRequest) {
3820        let AuxiliaryWebViewCreationRequest {
3821            load_data,
3822            opener_webview_id,
3823            opener_pipeline_id,
3824            response_sender,
3825        } = load_info;
3826
3827        let Some(browsing_context_group) =
3828            self.browsing_context_group_for_webview_id(&opener_webview_id)
3829        else {
3830            warn!("Opener WebView ({opener_webview_id:?}) not found for new auxiliary WebView");
3831            let _ = response_sender.send(None);
3832            return;
3833        };
3834
3835        let Some((webview_id_sender, webview_id_receiver)) = generic_channel::channel() else {
3836            warn!("Failed to create channel");
3837            let _ = response_sender.send(None);
3838            return;
3839        };
3840        self.constellation_to_embedder_proxy
3841            .send(ConstellationToEmbedderMsg::AllowOpeningWebView(
3842                opener_webview_id,
3843                webview_id_sender,
3844            ));
3845        let NewWebViewDetails {
3846            webview_id: new_webview_id,
3847            viewport_details,
3848            user_content_manager_id,
3849        } = match webview_id_receiver.recv() {
3850            Ok(Some(new_webview_details)) => new_webview_details,
3851            Ok(None) | Err(_) => {
3852                let _ = response_sender.send(None);
3853                return;
3854            },
3855        };
3856        let new_browsing_context_id = BrowsingContextId::from(new_webview_id);
3857
3858        let (script_sender, opener_browsing_context_id) =
3859            match self.pipelines.get(&opener_pipeline_id) {
3860                Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id),
3861                None => {
3862                    return warn!(
3863                        "{}: Auxiliary loaded url in closed iframe pipeline",
3864                        opener_pipeline_id
3865                    );
3866                },
3867            };
3868        let (is_opener_private, is_opener_secure, opener_upgrade_insecure_navigations_set) =
3869            match self.browsing_contexts.get(&opener_browsing_context_id) {
3870                Some(ctx) => (
3871                    ctx.is_private,
3872                    ctx.inherited_secure_context,
3873                    ctx.upgrade_insecure_navigations_set.clone(),
3874                ),
3875                None => {
3876                    return warn!(
3877                        "{}: New auxiliary {} loaded in closed opener browsing context",
3878                        opener_browsing_context_id, new_browsing_context_id,
3879                    );
3880                },
3881            };
3882        let new_pipeline_id = PipelineId::new();
3883        let pipeline = Pipeline::new_already_spawned(
3884            new_pipeline_id,
3885            new_browsing_context_id,
3886            new_webview_id,
3887            Some(opener_browsing_context_id),
3888            script_sender,
3889            self.paint_proxy.clone(),
3890            // New auxiliary WebViews start out as visible. The embedder can still
3891            // hide it with an explicit call to `WebView::hide()` in which case a
3892            // followup message will arrive to the Constellation to hide it.
3893            false, /* hidden */
3894            load_data,
3895        );
3896        let _ = response_sender.send(Some(AuxiliaryWebViewCreationResponse {
3897            new_webview_id,
3898            new_pipeline_id,
3899            user_content_manager_id,
3900        }));
3901
3902        assert!(!self.pipelines.contains_key(&new_pipeline_id));
3903        self.pipelines.insert(new_pipeline_id, pipeline);
3904
3905        let mut new_webview = ConstellationWebView::new(
3906            new_webview_id,
3907            browsing_context_group,
3908            new_browsing_context_id,
3909            user_content_manager_id,
3910        );
3911
3912        // Inherit the opener's theme, which is also what script does. This
3913        // ensures that the two states are in sync.
3914        let opener_theme = self
3915            .webviews
3916            .get(&opener_webview_id)
3917            .map_or(Theme::Light, |webview| webview.theme());
3918        new_webview.set_theme(opener_theme);
3919
3920        new_webview.add_pending_change(SessionHistoryChange {
3921            webview_id: new_webview_id,
3922            browsing_context_id: new_browsing_context_id,
3923            new_pipeline_id,
3924            replace: None,
3925            new_browsing_context_info: Some(NewBrowsingContextInfo {
3926                // Auxiliary browsing contexts are always top-level.
3927                parent_pipeline_id: None,
3928                is_private: is_opener_private,
3929                inherited_secure_context: is_opener_secure,
3930                upgrade_insecure_navigations_set: opener_upgrade_insecure_navigations_set,
3931            }),
3932            viewport_details,
3933        });
3934        self.webviews.insert(new_webview_id, new_webview);
3935    }
3936
3937    #[servo_tracing::instrument(skip_all)]
3938    fn handle_refresh_cursor(&self, pipeline_id: PipelineId) {
3939        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
3940            return;
3941        };
3942
3943        if let Err(error) = pipeline
3944            .event_loop
3945            .send(ScriptThreadMessage::RefreshCursor(pipeline_id))
3946        {
3947            warn!("Could not send RefreshCursor message to pipeline: {error:?}");
3948        }
3949    }
3950
3951    #[servo_tracing::instrument(skip_all)]
3952    fn handle_change_running_animations_state(
3953        &mut self,
3954        pipeline_id: PipelineId,
3955        animation_state: AnimationState,
3956    ) {
3957        match animation_state {
3958            AnimationState::AnimationCallbacksPresent => {
3959                self.handle_change_document_animation_frame_provider_state(pipeline_id, true);
3960            },
3961            AnimationState::AnimationCallbacksAbsent => {
3962                self.handle_change_document_animation_frame_provider_state(pipeline_id, false);
3963            },
3964            AnimationState::AnimationsPresent | AnimationState::NoAnimationsPresent => {
3965                if let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) &&
3966                    pipeline.animation_state != animation_state
3967                {
3968                    pipeline.animation_state = animation_state;
3969                    self.paint_proxy
3970                        .send(PaintMessage::ChangeRunningAnimationsState(
3971                            pipeline.webview_id,
3972                            pipeline_id,
3973                            animation_state,
3974                        ))
3975                }
3976            },
3977        }
3978    }
3979
3980    fn send_animation_frame_callbacks_state_if_changed(&mut self, pipeline_id: PipelineId) {
3981        let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) else {
3982            return;
3983        };
3984
3985        // Paint only tracks per-pipeline callback state.
3986        let callbacks_active =
3987            pipeline.document_callbacks_active || !pipeline.worker_callbacks_active.is_empty();
3988        if pipeline.last_callbacks_active_sent_to_paint == callbacks_active {
3989            return;
3990        }
3991
3992        pipeline.last_callbacks_active_sent_to_paint = callbacks_active;
3993        let animation_state = if callbacks_active {
3994            AnimationState::AnimationCallbacksPresent
3995        } else {
3996            AnimationState::AnimationCallbacksAbsent
3997        };
3998
3999        self.paint_proxy
4000            .send(PaintMessage::ChangeRunningAnimationsState(
4001                pipeline.webview_id,
4002                pipeline_id,
4003                animation_state,
4004            ));
4005    }
4006
4007    fn handle_change_document_animation_frame_provider_state(
4008        &mut self,
4009        pipeline_id: PipelineId,
4010        active: bool,
4011    ) {
4012        let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) else {
4013            return;
4014        };
4015
4016        if pipeline.document_callbacks_active == active {
4017            return;
4018        }
4019
4020        pipeline.document_callbacks_active = active;
4021        self.send_animation_frame_callbacks_state_if_changed(pipeline_id);
4022    }
4023
4024    fn handle_register_worker_animation_frame_provider(
4025        &mut self,
4026        webview_id: WebViewId,
4027        pipeline_id: PipelineId,
4028        worker_id: WorkerId,
4029        sender: GenericSender<WorkerAnimationFrameTick>,
4030    ) {
4031        if !self.pipelines.contains_key(&pipeline_id) {
4032            debug!(
4033                "Ignoring worker animation frame provider for closed pipeline: worker={worker_id:?}, pipeline={pipeline_id:?} ---->",
4034            );
4035            return;
4036        }
4037
4038        debug!(
4039            "Registering worker animation frame provider: worker={worker_id:?}, pipeline={pipeline_id:?}---->",
4040        );
4041        self.worker_animation_frame_providers.insert(
4042            worker_id,
4043            WorkerAnimationFrameProvider {
4044                webview_id,
4045                pipeline_id,
4046                sender,
4047                tick_pending: false,
4048            },
4049        );
4050    }
4051
4052    fn handle_unregister_worker_animation_frame_provider(&mut self, worker_id: WorkerId) {
4053        let Some(provider) = self.worker_animation_frame_providers.remove(&worker_id) else {
4054            return;
4055        };
4056
4057        debug!(
4058            "Unregistering worker animation frame provider: worker={worker_id:?}, pipeline={:?}",
4059            provider.pipeline_id,
4060        );
4061        if let Some(pipeline) = self.pipelines.get_mut(&provider.pipeline_id) {
4062            pipeline.worker_callbacks_active.remove(&worker_id);
4063        }
4064        self.send_animation_frame_callbacks_state_if_changed(provider.pipeline_id);
4065    }
4066
4067    fn remove_worker_animation_frame_providers_for_pipeline(&mut self, pipeline_id: PipelineId) {
4068        let worker_ids = self
4069            .worker_animation_frame_providers
4070            .iter()
4071            .filter_map(|(worker_id, provider)| {
4072                (provider.pipeline_id == pipeline_id).then_some(*worker_id)
4073            })
4074            .collect::<Vec<_>>();
4075
4076        if worker_ids.is_empty() {
4077            return;
4078        }
4079
4080        for worker_id in &worker_ids {
4081            self.worker_animation_frame_providers.remove(worker_id);
4082        }
4083
4084        if let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) {
4085            let mut changed = false;
4086            for worker_id in &worker_ids {
4087                changed |= pipeline.worker_callbacks_active.remove(worker_id);
4088            }
4089            if changed {
4090                self.send_animation_frame_callbacks_state_if_changed(pipeline_id);
4091            }
4092        }
4093    }
4094
4095    fn handle_change_worker_animation_frame_provider_state(
4096        &mut self,
4097        pipeline_id: PipelineId,
4098        worker_id: WorkerId,
4099        active: bool,
4100    ) {
4101        let Some(provider) = self.worker_animation_frame_providers.get_mut(&worker_id) else {
4102            return;
4103        };
4104        let provider_pipeline_id = provider.pipeline_id;
4105        let provider_webview_id = provider.webview_id;
4106        if provider_pipeline_id != pipeline_id {
4107            warn!("Worker animation frame state arrived for an unexpected pipeline --->");
4108            return;
4109        }
4110        let tick_was_pending = std::mem::take(&mut provider.tick_pending);
4111
4112        if !self.pipelines.contains_key(&pipeline_id) {
4113            debug!(
4114                "Removing worker animation frame provider for closed pipeline: worker={worker_id:?}, pipeline={pipeline_id:?}",
4115            );
4116            self.worker_animation_frame_providers.remove(&worker_id);
4117            return;
4118        }
4119
4120        let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) else {
4121            return;
4122        };
4123
4124        let changed = if active {
4125            pipeline.worker_callbacks_active.insert(worker_id)
4126        } else {
4127            pipeline.worker_callbacks_active.remove(&worker_id)
4128        };
4129        debug!(
4130            "Worker animation frame provider state: worker={worker_id:?}, pipeline={pipeline_id:?}, active={active}, changed={changed}",
4131        );
4132        if changed {
4133            self.send_animation_frame_callbacks_state_if_changed(pipeline_id);
4134        } else if active && tick_was_pending {
4135            // Worker only rAF may not produce a display list so request a frame
4136            // for the next refresh-driver tick.
4137            self.paint_proxy
4138                .send(PaintMessage::GenerateFrame(vec![PainterId::from(
4139                    provider_webview_id,
4140                )]));
4141        }
4142    }
4143
4144    fn deliver_rendering_opportunity_to_worker(&mut self, worker_id: WorkerId) {
4145        let mut send_failed = false;
4146        {
4147            let Some(provider) = self.worker_animation_frame_providers.get_mut(&worker_id) else {
4148                return;
4149            };
4150            if provider.tick_pending {
4151                debug!("Skipping pending rendering opportunity: worker={worker_id:?}");
4152                return;
4153            }
4154            if provider.sender.send(WorkerAnimationFrameTick).is_err() {
4155                send_failed = true;
4156            } else {
4157                debug!("Delivered rendering opportunity: worker={worker_id:?}");
4158                provider.tick_pending = true;
4159            }
4160        }
4161
4162        if send_failed {
4163            self.handle_unregister_worker_animation_frame_provider(worker_id);
4164        }
4165    }
4166
4167    /// <https://html.spec.whatwg.org/multipage/#rendering-opportunity>
4168    #[servo_tracing::instrument(skip_all)]
4169    fn handle_tick_animation(&mut self, webview_ids: Vec<WebViewId>) {
4170        let mut animating_event_loops = HashSet::new();
4171        let mut animating_workers = FxHashSet::default();
4172
4173        for webview_id in webview_ids.iter() {
4174            for browsing_context in self.fully_active_browsing_contexts_iter(*webview_id) {
4175                let Some(pipeline) = self.pipelines.get(&browsing_context.pipeline_id) else {
4176                    continue;
4177                };
4178
4179                animating_workers.extend(pipeline.worker_callbacks_active.iter().copied());
4180
4181                // Window rAF still follows the existing script-thread path.
4182                let event_loop = &pipeline.event_loop;
4183                if !animating_event_loops.contains(&event_loop.id()) {
4184                    // No error handling here. It's unclear what to do when this fails as the error isn't associated
4185                    // with a particular pipeline. In addition, the danger of not progressing animations is pretty
4186                    // low, so it's probably safe to ignore this error and handle the crashed ScriptThread on
4187                    // some other message.
4188                    let _ = event_loop
4189                        .send(ScriptThreadMessage::TickAllAnimations(webview_ids.clone()));
4190                    animating_event_loops.insert(event_loop.id());
4191                }
4192            }
4193        }
4194
4195        // Step 6.1.2 runs on the worker event loop; constellation only sends
4196        // tick messages for workers active on this refresh tick.
4197        for worker_id in animating_workers {
4198            let Some(provider) = self.worker_animation_frame_providers.get(&worker_id) else {
4199                error!(
4200                    "No animation frame provider found for active worker: worker={worker_id:?}, webviews={webview_ids:?}",
4201                );
4202                continue;
4203            };
4204            if webview_ids.contains(&provider.webview_id) {
4205                self.deliver_rendering_opportunity_to_worker(worker_id);
4206            } else {
4207                error!(
4208                    "Worker animation frame provider's WebView is not part of the current refresh tick: worker={worker_id:?}, provider_webview={:?}, webviews={webview_ids:?}",
4209                    provider.webview_id,
4210                );
4211            }
4212        }
4213    }
4214
4215    #[servo_tracing::instrument(skip_all)]
4216    fn handle_no_longer_waiting_on_asynchronous_image_updates(
4217        &mut self,
4218        pipeline_ids: Vec<PipelineId>,
4219    ) {
4220        for pipeline_id in pipeline_ids.into_iter() {
4221            if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
4222                let _ = pipeline.event_loop.send(
4223                    ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(pipeline_id),
4224                );
4225            }
4226        }
4227    }
4228
4229    /// Schedule a navigation(via load_url).
4230    /// 1: Ask the embedder for permission.
4231    /// 2: Store the details of the navigation, pending approval from the embedder.
4232    #[servo_tracing::instrument(skip_all)]
4233    fn schedule_navigation(
4234        &mut self,
4235        webview_id: WebViewId,
4236        source_id: PipelineId,
4237        load_data: LoadData,
4238        history_handling: NavigationHistoryBehavior,
4239        target_snapshot_params: TargetSnapshotParams,
4240    ) {
4241        match self.pending_approval_navigations.entry(source_id) {
4242            Entry::Occupied(_) => {
4243                return warn!(
4244                    "{}: Tried to schedule a navigation while one is already pending",
4245                    source_id
4246                );
4247            },
4248            Entry::Vacant(entry) => {
4249                let _ = entry.insert(PendingApprovalNavigation {
4250                    load_data: load_data.clone(),
4251                    history_behaviour: history_handling,
4252                    target_snapshot_params,
4253                });
4254            },
4255        };
4256
4257        if load_data.is_initial_about_blank {
4258            assert_eq!(load_data.url.as_str(), "about:blank");
4259            // The initial about:blank is not a navigation; the embedder only
4260            // cares about a navigation that follows it.
4261            self.handle_allow_navigation_response(source_id, true);
4262        } else {
4263            // Allow the embedder to handle the url itself
4264            self.constellation_to_embedder_proxy.send(
4265                ConstellationToEmbedderMsg::AllowNavigationRequest(
4266                    webview_id,
4267                    source_id,
4268                    load_data.url,
4269                ),
4270            );
4271        }
4272    }
4273
4274    /// Perform a navigation previously requested by script, if approved by the embedder.
4275    /// If there is already a pending page (self.pending_changes), it will not be overridden;
4276    /// However, if the id is not encompassed by another change, it will be.
4277    fn handle_allow_navigation_response(&mut self, pipeline_id: PipelineId, allowed: bool) {
4278        let pending = self.pending_approval_navigations.remove(&pipeline_id);
4279
4280        let webview_id = match self.pipelines.get(&pipeline_id) {
4281            Some(pipeline) => pipeline.webview_id,
4282            None => return warn!("{}: Attempted to navigate after closure", pipeline_id),
4283        };
4284
4285        match pending {
4286            Some(pending) => {
4287                if allowed {
4288                    self.load_url(
4289                        webview_id,
4290                        pipeline_id,
4291                        pending.load_data,
4292                        pending.history_behaviour,
4293                        pending.target_snapshot_params,
4294                    );
4295                } else {
4296                    let pipeline_is_top_level_pipeline = self
4297                        .browsing_contexts
4298                        .get(&BrowsingContextId::from(webview_id))
4299                        .is_some_and(|ctx| ctx.pipeline_id == pipeline_id);
4300                    if pipeline_is_top_level_pipeline && !self.webview_is_navigating(webview_id) {
4301                        self.send_webdriver_load_status(
4302                            webview_id,
4303                            WebDriverLoadStatus::NavigationStop,
4304                        );
4305                    }
4306                    // If the navigation is refused, and this concerns an iframe,
4307                    // we need to take it out of it's "delaying-load-events-mode".
4308                    // https://html.spec.whatwg.org/multipage/#delaying-load-events-mode
4309                    if !pipeline_is_top_level_pipeline {
4310                        self.send_message_to_pipeline(
4311                            pipeline_id,
4312                            ScriptThreadMessage::StopDelayingLoadEventsMode(pipeline_id),
4313                            "Attempted to navigate after closure",
4314                        );
4315                    }
4316                }
4317            },
4318            None => {
4319                warn!(
4320                    "{}: AllowNavigationResponse for unknown request",
4321                    pipeline_id
4322                )
4323            },
4324        }
4325    }
4326
4327    #[servo_tracing::instrument(skip_all)]
4328    fn load_url(
4329        &mut self,
4330        webview_id: WebViewId,
4331        source_id: PipelineId,
4332        mut load_data: LoadData,
4333        history_handling: NavigationHistoryBehavior,
4334        target_snapshot_params: TargetSnapshotParams,
4335    ) -> Option<PipelineId> {
4336        debug!(
4337            "{}: Loading ({}replacing): {}",
4338            source_id,
4339            match history_handling {
4340                NavigationHistoryBehavior::Push => "not ",
4341                NavigationHistoryBehavior::Replace => "",
4342                NavigationHistoryBehavior::Auto => "unsure if ",
4343            },
4344            load_data.url,
4345        );
4346        // If this load targets an iframe, its framing element may exist
4347        // in a separate script thread than the framed document that initiated
4348        // the new load. The framing element must be notified about the
4349        // requested change so it can update its internal state.
4350        //
4351        // If replace is true, the current entry is replaced instead of a new entry being added.
4352        let (browsing_context_id, opener) = match self.pipelines.get(&source_id) {
4353            Some(pipeline) => (pipeline.browsing_context_id, pipeline.opener),
4354            None => {
4355                warn!("{}: Loaded after closure", source_id);
4356                return None;
4357            },
4358        };
4359        let (
4360            viewport_details,
4361            pipeline_id,
4362            parent_pipeline_id,
4363            is_private,
4364            upgrade_insecure_navigations_set,
4365        ) = match self.browsing_contexts.get(&browsing_context_id) {
4366            Some(ctx) => (
4367                ctx.viewport_details,
4368                ctx.pipeline_id,
4369                ctx.parent_pipeline_id,
4370                ctx.is_private,
4371                ctx.upgrade_insecure_navigations_set.clone(),
4372            ),
4373            None => {
4374                // This should technically never happen (since `load_url` is
4375                // only called on existing browsing contexts), but we prefer to
4376                // avoid `expect`s or `unwrap`s in `Constellation` to ward
4377                // against future changes that might break things.
4378                warn!(
4379                    "{}: Loaded url in closed {}",
4380                    source_id, browsing_context_id,
4381                );
4382                return None;
4383            },
4384        };
4385
4386        load_data.inherited_upgrade_insecure_navigations_set = upgrade_insecure_navigations_set;
4387
4388        #[cfg(feature = "devtools")]
4389        if let Some(ref chan) = self.devtools_sender {
4390            let state = NavigationState::Start(load_data.url.clone());
4391            let _ = chan.send(DevtoolsControlMsg::FromScript(
4392                ScriptToDevtoolsControlMsg::Navigate(browsing_context_id, state),
4393            ));
4394        }
4395
4396        match parent_pipeline_id {
4397            Some(parent_pipeline_id) => {
4398                // Find the script thread for the pipeline containing the iframe
4399                // and issue an iframe load through there.
4400                let msg = ScriptThreadMessage::NavigateIframe(
4401                    parent_pipeline_id,
4402                    browsing_context_id,
4403                    load_data,
4404                    history_handling,
4405                    target_snapshot_params,
4406                );
4407                let result = match self.pipelines.get(&parent_pipeline_id) {
4408                    Some(parent_pipeline) => parent_pipeline.event_loop.send(msg),
4409                    None => {
4410                        warn!("{}: Child loaded after closure", parent_pipeline_id);
4411                        return None;
4412                    },
4413                };
4414                if let Err(e) = result {
4415                    self.handle_send_error(parent_pipeline_id, e);
4416                }
4417
4418                None
4419            },
4420            None => {
4421                // Make sure no pending page would be overridden.
4422                if let Some(webview) = self.webviews.get(&webview_id) &&
4423                    webview.pending_changes.iter().any(|pending_change| {
4424                        pending_change.browsing_context_id == browsing_context_id
4425                    })
4426                {
4427                    // id that sent load msg is being changed already; abort
4428                    return None;
4429                }
4430
4431                if self.get_activity(source_id) == DocumentActivity::Inactive {
4432                    // Disregard this load if the navigating pipeline is not actually
4433                    // active. This could be caused by a delayed navigation (eg. from
4434                    // a timer) or a race between multiple navigations (such as an
4435                    // onclick handler on an anchor element).
4436                    return None;
4437                }
4438
4439                // Being here means either there are no pending changes, or none of the pending
4440                // changes would be overridden by changing the subframe associated with source_id.
4441
4442                // Create the new pipeline
4443
4444                let replace = if history_handling == NavigationHistoryBehavior::Replace {
4445                    Some(NeedsToReload::No(pipeline_id))
4446                } else {
4447                    None
4448                };
4449
4450                let new_pipeline_id = PipelineId::new();
4451                // Report the navigation before creating the pipeline.
4452                self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStart);
4453                self.new_pipeline(
4454                    new_pipeline_id,
4455                    browsing_context_id,
4456                    webview_id,
4457                    None,
4458                    opener,
4459                    viewport_details,
4460                    load_data,
4461                    is_private,
4462                    target_snapshot_params,
4463                    None,
4464                );
4465
4466                if let Some(webview) = self.webviews.get_mut(&webview_id) {
4467                    webview.add_pending_change(SessionHistoryChange {
4468                        webview_id,
4469                        browsing_context_id,
4470                        new_pipeline_id,
4471                        replace,
4472                        // `load_url` is always invoked on an existing browsing context.
4473                        new_browsing_context_info: None,
4474                        viewport_details,
4475                    });
4476                } else {
4477                    warn!("Could not find WebView for URL load: ({webview_id:?})");
4478                }
4479
4480                Some(new_pipeline_id)
4481            },
4482        }
4483    }
4484
4485    #[servo_tracing::instrument(skip_all)]
4486    fn handle_abort_load_url_msg(&mut self, webview_id: WebViewId, new_pipeline_id: PipelineId) {
4487        let Some(change) = self
4488            .webviews
4489            .get_mut(&webview_id)
4490            .and_then(|webview| webview.remove_pending_change_for_pipeline(new_pipeline_id))
4491        else {
4492            return;
4493        };
4494
4495        self.close_pipeline(new_pipeline_id, DiscardBrowsingContext::No);
4496
4497        if change.browsing_context_id == BrowsingContextId::from(webview_id) &&
4498            !self.webview_is_navigating(webview_id)
4499        {
4500            self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStop);
4501        }
4502
4503        if let Some(webview) = self.webviews.get_mut(&webview_id) {
4504            webview.send_screenshot_readiness_requests_to_pipelines(
4505                &self.browsing_contexts,
4506                &self.pipelines,
4507            );
4508        };
4509    }
4510
4511    #[servo_tracing::instrument(skip_all)]
4512    fn handle_load_finished_message(
4513        &mut self,
4514        webview_id: WebViewId,
4515        pipeline_id: PipelineId,
4516        aborted: bool,
4517    ) {
4518        debug!("Load finished in {pipeline_id:?} aborted={aborted}");
4519
4520        if let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) {
4521            pipeline.load_finished = true;
4522            if !aborted {
4523                pipeline.completely_loaded = true;
4524            }
4525        }
4526
4527        // We need to make sure the pipeline that has finished loading is the current
4528        // pipeline and that no pending pipeline will replace the current one.
4529        let pipeline_is_top_level_pipeline = self
4530            .browsing_contexts
4531            .get(&BrowsingContextId::from(webview_id))
4532            .is_some_and(|ctx| ctx.pipeline_id == pipeline_id);
4533        if pipeline_is_top_level_pipeline {
4534            if !self.webview_is_navigating(webview_id) {
4535                self.send_webdriver_load_status(
4536                    webview_id,
4537                    if aborted {
4538                        WebDriverLoadStatus::NavigationStop
4539                    } else {
4540                        WebDriverLoadStatus::Complete
4541                    },
4542                );
4543            }
4544        } else {
4545            self.handle_subframe_load_finished(pipeline_id, aborted);
4546        }
4547    }
4548
4549    #[servo_tracing::instrument(skip_all)]
4550    fn handle_navigated_to_fragment(
4551        &mut self,
4552        pipeline_id: PipelineId,
4553        new_url: ServoUrl,
4554        history_handling: NavigationHistoryBehavior,
4555    ) {
4556        let (webview_id, old_url) = match self.pipelines.get_mut(&pipeline_id) {
4557            Some(pipeline) => {
4558                let old_url = replace(&mut pipeline.url, new_url.clone());
4559                (pipeline.webview_id, old_url)
4560            },
4561            None => {
4562                return warn!("{}: Navigated to fragment after closure", pipeline_id);
4563            },
4564        };
4565
4566        let Some(webview) = self.webviews.get_mut(&webview_id) else {
4567            return warn!("Ignoring navigation in non-existent WebView ({webview_id:?}).");
4568        };
4569
4570        match history_handling {
4571            NavigationHistoryBehavior::Replace => {},
4572            _ => {
4573                let diff = SessionHistoryDiff::Hash {
4574                    pipeline_reloader: NeedsToReload::No(pipeline_id),
4575                    new_url,
4576                    old_url,
4577                };
4578
4579                webview.session_history.push_diff(diff);
4580                self.notify_history_changed(webview_id);
4581            },
4582        }
4583    }
4584
4585    /// Step 4 of <https://html.spec.whatwg.org/multipage/#traverse-the-history-by-a-delta>
4586    ///
4587    /// This change appends a session history traversal to the session history traversal queue,
4588    /// which is stored as [`ConstellationWebView::history_traversal_request_queue`].
4589    ///
4590    /// See also: <https://html.spec.whatwg.org/multipage/#tn-session-history-traversal-queue>
4591    #[servo_tracing::instrument(skip_all)]
4592    fn handle_traverse_session_history_msg(
4593        &mut self,
4594        traversal_request: SessionHistoryTraversalRequest,
4595    ) {
4596        let webview_id = traversal_request.webview_id;
4597        let Some(webview) = self.webviews.get_mut(&webview_id) else {
4598            self.notify_embedder_of_completed_session_history_traversal_request(&traversal_request);
4599            return warn!("Ignoring history traversal in non-existent WebView ({webview_id:?}).");
4600        };
4601
4602        webview
4603            .session_history_traversal_request_queue
4604            .push_back(traversal_request);
4605        // Report the traversal as a navigation before applying it: it may have to wait for a
4606        // previous traversal to finish, and nothing else reports its start.
4607        self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStart);
4608        self.apply_queued_session_history_traversal_requests(webview_id);
4609    }
4610
4611    /// Apply the given [`HistoryTraversalRequest`], triggering the session history navigation.
4612    /// Return the same [`HistoryTraversalRequest`] when it completes immediately or is out
4613    /// of range, otherwise return `None` when it is still pending.
4614    fn apply_session_history_traversal_request(
4615        &mut self,
4616        traversal_request: SessionHistoryTraversalRequest,
4617    ) -> Option<SessionHistoryTraversalRequest> {
4618        let mut browsing_context_changes = FxHashMap::<BrowsingContextId, NeedsToReload>::default();
4619        let mut pipeline_changes =
4620            FxHashMap::<PipelineId, (Option<HistoryStateId>, ServoUrl)>::default();
4621        let mut url_to_load = FxHashMap::<PipelineId, ServoUrl>::default();
4622        let webview_id = traversal_request.webview_id;
4623
4624        {
4625            let Some(webview) = self.webviews.get_mut(&webview_id) else {
4626                warn!("Ignoring history traversal in non-existent WebView ({webview_id:?}).");
4627                return Some(traversal_request);
4628            };
4629
4630            match traversal_request.direction {
4631                TraversalDirection::Forward(forward) => {
4632                    let future_length = webview.session_history.future.len();
4633                    if future_length < forward {
4634                        warn!("Cannot traverse that far into the future.");
4635                        return Some(traversal_request);
4636                    }
4637
4638                    for diff in webview
4639                        .session_history
4640                        .future
4641                        .drain(future_length - forward..)
4642                        .rev()
4643                    {
4644                        match diff {
4645                            SessionHistoryDiff::BrowsingContext {
4646                                browsing_context_id,
4647                                ref new_reloader,
4648                                ..
4649                            } => {
4650                                browsing_context_changes
4651                                    .insert(browsing_context_id, new_reloader.clone());
4652                            },
4653                            SessionHistoryDiff::Pipeline {
4654                                ref pipeline_reloader,
4655                                new_history_state_id,
4656                                ref new_url,
4657                                ..
4658                            } => match *pipeline_reloader {
4659                                NeedsToReload::No(pipeline_id) => {
4660                                    pipeline_changes.insert(
4661                                        pipeline_id,
4662                                        (Some(new_history_state_id), new_url.clone()),
4663                                    );
4664                                },
4665                                NeedsToReload::Yes(pipeline_id, ..) => {
4666                                    url_to_load.insert(pipeline_id, new_url.clone());
4667                                },
4668                            },
4669                            SessionHistoryDiff::Hash {
4670                                ref pipeline_reloader,
4671                                ref new_url,
4672                                ..
4673                            } => match *pipeline_reloader {
4674                                NeedsToReload::No(pipeline_id) => {
4675                                    let state = pipeline_changes
4676                                        .get(&pipeline_id)
4677                                        .and_then(|change| change.0);
4678                                    pipeline_changes.insert(pipeline_id, (state, new_url.clone()));
4679                                },
4680                                NeedsToReload::Yes(pipeline_id, ..) => {
4681                                    url_to_load.insert(pipeline_id, new_url.clone());
4682                                },
4683                            },
4684                        }
4685                        webview.session_history.past.push(diff);
4686                    }
4687                },
4688                TraversalDirection::Back(back) => {
4689                    let past_length = webview.session_history.past.len();
4690                    if past_length < back {
4691                        warn!("Cannot traverse that far into the past.");
4692                        return Some(traversal_request);
4693                    }
4694
4695                    for diff in webview
4696                        .session_history
4697                        .past
4698                        .drain(past_length - back..)
4699                        .rev()
4700                    {
4701                        match diff {
4702                            SessionHistoryDiff::BrowsingContext {
4703                                browsing_context_id,
4704                                ref old_reloader,
4705                                ..
4706                            } => {
4707                                browsing_context_changes
4708                                    .insert(browsing_context_id, old_reloader.clone());
4709                            },
4710                            SessionHistoryDiff::Pipeline {
4711                                ref pipeline_reloader,
4712                                old_history_state_id,
4713                                ref old_url,
4714                                ..
4715                            } => match *pipeline_reloader {
4716                                NeedsToReload::No(pipeline_id) => {
4717                                    pipeline_changes.insert(
4718                                        pipeline_id,
4719                                        (old_history_state_id, old_url.clone()),
4720                                    );
4721                                },
4722                                NeedsToReload::Yes(pipeline_id, ..) => {
4723                                    url_to_load.insert(pipeline_id, old_url.clone());
4724                                },
4725                            },
4726                            SessionHistoryDiff::Hash {
4727                                ref pipeline_reloader,
4728                                ref old_url,
4729                                ..
4730                            } => match *pipeline_reloader {
4731                                NeedsToReload::No(pipeline_id) => {
4732                                    let state = pipeline_changes
4733                                        .get(&pipeline_id)
4734                                        .and_then(|change| change.0);
4735                                    pipeline_changes.insert(pipeline_id, (state, old_url.clone()));
4736                                },
4737                                NeedsToReload::Yes(pipeline_id, ..) => {
4738                                    url_to_load.insert(pipeline_id, old_url.clone());
4739                                },
4740                            },
4741                        }
4742                        webview.session_history.future.push(diff);
4743                    }
4744                },
4745            }
4746        }
4747
4748        let pipelines_awaiting_activation: FxHashSet<_> = browsing_context_changes
4749            .drain()
4750            .filter_map(|(browsing_context_id, mut pipeline_reloader)| {
4751                if let NeedsToReload::Yes(pipeline_id, ref mut load_data) = pipeline_reloader &&
4752                    let Some(url) = url_to_load.get(&pipeline_id)
4753                {
4754                    load_data.url = url.clone();
4755                }
4756                self.activate_history_entry_in_browsing_context(
4757                    browsing_context_id,
4758                    pipeline_reloader,
4759                )
4760            })
4761            .collect();
4762
4763        for (pipeline_id, (history_state_id, url)) in pipeline_changes.drain() {
4764            self.update_pipeline_history_state(pipeline_id, history_state_id, url);
4765        }
4766
4767        self.notify_history_changed(webview_id);
4768        self.trim_history(webview_id);
4769        self.set_frame_tree_for_webview(webview_id);
4770
4771        // The traversal finishes immediately when we are traversing within the same document
4772        // or between already live pipelines. Note that the script event loop may still be
4773        // completing these navigations asynchronously.
4774        if pipelines_awaiting_activation.is_empty() {
4775            return Some(traversal_request);
4776        }
4777
4778        let Some(webview) = self.webviews.get_mut(&webview_id) else {
4779            return Some(traversal_request);
4780        };
4781        webview.ongoing_history_traversal_request = Some(OngoingHistoryTraversalRequest {
4782            traversal_request,
4783            pipelines_awaiting_activation,
4784        });
4785        None
4786    }
4787
4788    /// Finish any completed ongoing history traversal request from any active
4789    /// [`ConstellationWebView`] and trigger (and possibly finish) any other queued history
4790    /// traversals on that same `WebView` until there are no remaining completed ongoing history
4791    /// traversal requests.
4792    fn finish_completed_session_history_traversal_requests(&mut self) {
4793        while let Some(traversal_request) = self
4794            .webviews
4795            .values_mut()
4796            .find_map(|webview| webview.maybe_finish_ongoing_session_history_traversal_request())
4797        {
4798            let webview_id = traversal_request.webview_id;
4799            self.notify_embedder_of_completed_session_history_traversal_request(&traversal_request);
4800
4801            // Apply any queued traversal first, so that a traversal started here is still
4802            // considered below.
4803            self.apply_queued_session_history_traversal_requests(webview_id);
4804
4805            // 1. A traversal started above (implies a pipeline is created which has load)
4806            // 2. A document that is still loading
4807            // will clear the outstanding status itself.
4808            // Otherwise do it manually.
4809            if !self.webview_is_navigating(webview_id) {
4810                self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStop);
4811            }
4812        }
4813    }
4814
4815    /// Whether this webview will report the end of a navigation itself.
4816    /// See [`ConstellationWebView::is_navigating`].
4817    fn webview_is_navigating(&self, webview_id: WebViewId) -> bool {
4818        let Some(webview) = self.webviews.get(&webview_id) else {
4819            return false;
4820        };
4821        let top_level_pipeline = self
4822            .browsing_contexts
4823            .get(&BrowsingContextId::from(webview_id))
4824            .and_then(|context| self.pipelines.get(&context.pipeline_id));
4825        webview.is_navigating(top_level_pipeline)
4826    }
4827
4828    /// Notify the embedder that the given [`HistoryTraversalRequest`] is complete, if it was
4829    /// triggered by the embedder.
4830    fn notify_embedder_of_completed_session_history_traversal_request(
4831        &self,
4832        traversal_request: &SessionHistoryTraversalRequest,
4833    ) {
4834        if traversal_request.source == HistoryTraversalSource::Embedder {
4835            self.constellation_to_embedder_proxy.send(
4836                ConstellationToEmbedderMsg::HistoryTraversalComplete(
4837                    traversal_request.webview_id,
4838                    traversal_request.id.clone(),
4839                ),
4840            );
4841        }
4842    }
4843
4844    /// If the [`ConstellationWebView`] with the given [`WebViewId`] does not have any
4845    /// ongoing traversal history request, apply the next queued request, if one exists.
4846    fn apply_next_queued_session_history_traversal_request(
4847        &mut self,
4848        webview_id: WebViewId,
4849    ) -> Option<SessionHistoryTraversalRequest> {
4850        let webview = self.webviews.get_mut(&webview_id)?;
4851        if webview.ongoing_history_traversal_request.is_some() {
4852            return None;
4853        }
4854
4855        let traversal_request = webview
4856            .session_history_traversal_request_queue
4857            .pop_front()?;
4858        self.apply_session_history_traversal_request(traversal_request)
4859    }
4860
4861    /// If the [`ConstellationWebView`] with the given [`WebViewId`] does not have any ongoing
4862    /// traversal history request, apply the next queued request and potentially finish it
4863    /// until there is either an ongoing history request or no more queued requests.
4864    fn apply_queued_session_history_traversal_requests(&mut self, webview_id: WebViewId) {
4865        let mut completed_any = false;
4866        while let Some(traversal_request) =
4867            self.apply_next_queued_session_history_traversal_request(webview_id)
4868        {
4869            completed_any = true;
4870            self.notify_embedder_of_completed_session_history_traversal_request(&traversal_request);
4871        }
4872
4873        // Everything completed here finished without loading.
4874        // A traversal or document still in flight reports its own.
4875        if completed_any && !self.webview_is_navigating(webview_id) {
4876            self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStop);
4877        }
4878    }
4879
4880    /// <https://html.spec.whatwg.org/multipage/#activate-history-entry>
4881    ///
4882    /// Activate the history entry indicated by the given [`NeedsToReload`]. Returns the
4883    /// [`PipelineId`] of the pipeline if the constellation is waiting for it to reload
4884    /// and `None` otherwise.
4885    #[servo_tracing::instrument(skip_all)]
4886    fn activate_history_entry_in_browsing_context(
4887        &mut self,
4888        browsing_context_id: BrowsingContextId,
4889        new_reloader: NeedsToReload,
4890    ) -> Option<PipelineId> {
4891        let new_pipeline_id = match new_reloader {
4892            NeedsToReload::No(pipeline_id) => pipeline_id,
4893            NeedsToReload::Yes(pipeline_id, mut load_data) => {
4894                debug!(
4895                    "{}: Reloading document {}",
4896                    browsing_context_id, pipeline_id,
4897                );
4898
4899                // <https://html.spec.whatwg.org/multipage/#process-a-navigate-fetch>
4900                // Step 7. If entry's document state's reload pending is true, then set request's reload-navigation flag.
4901                // Step 8. Otherwise, if entry's document state's ever populated is true, then set request's history-navigation flag.
4902                load_data.history_navigation = true;
4903                load_data.reload_navigation = false;
4904
4905                let (webview_id, old_pipeline_id, parent_pipeline_id, viewport_details, is_private) =
4906                    match self.browsing_contexts.get(&browsing_context_id) {
4907                        Some(ctx) => (
4908                            ctx.webview_id,
4909                            ctx.pipeline_id,
4910                            ctx.parent_pipeline_id,
4911                            ctx.viewport_details,
4912                            ctx.is_private,
4913                        ),
4914                        None => {
4915                            warn!("No browsing context to traverse!");
4916                            return None;
4917                        },
4918                    };
4919                let opener = match self.pipelines.get(&old_pipeline_id) {
4920                    Some(pipeline) => pipeline.opener,
4921                    None => None,
4922                };
4923                let new_pipeline_id = PipelineId::new();
4924                if parent_pipeline_id.is_none() {
4925                    // Report the navigation before creating the pipeline.
4926                    self.send_webdriver_load_status(
4927                        webview_id,
4928                        WebDriverLoadStatus::NavigationStart,
4929                    );
4930                }
4931                self.new_pipeline(
4932                    new_pipeline_id,
4933                    browsing_context_id,
4934                    webview_id,
4935                    parent_pipeline_id,
4936                    opener,
4937                    viewport_details,
4938                    load_data.clone(),
4939                    is_private,
4940                    // TODO(jdm): We need to store the original target snapshot params
4941                    // with the pipeline when it's created, so we can support reloading
4942                    // a discarded document properly.
4943                    TargetSnapshotParams::default(),
4944                    None,
4945                );
4946
4947                let webview = self
4948                    .webviews
4949                    .get_mut(&webview_id)
4950                    .expect("WebView for history traversal should always exist at this point");
4951                webview.add_pending_change(SessionHistoryChange {
4952                    webview_id,
4953                    browsing_context_id,
4954                    new_pipeline_id,
4955                    replace: Some(NeedsToReload::Yes(pipeline_id, load_data)),
4956                    // Browsing context must exist at this point.
4957                    new_browsing_context_info: None,
4958                    viewport_details,
4959                });
4960                return Some(new_pipeline_id);
4961            },
4962        };
4963
4964        let (old_pipeline_id, parent_pipeline_id, webview_id) =
4965            match self.browsing_contexts.get_mut(&browsing_context_id) {
4966                Some(browsing_context) => {
4967                    let old_pipeline_id = browsing_context.pipeline_id;
4968                    browsing_context.update_current_entry(new_pipeline_id);
4969                    (
4970                        old_pipeline_id,
4971                        browsing_context.parent_pipeline_id,
4972                        browsing_context.webview_id,
4973                    )
4974                },
4975                None => {
4976                    warn!("{browsing_context_id}: Closed during traversal");
4977                    return None;
4978                },
4979            };
4980
4981        self.unload_document(old_pipeline_id);
4982
4983        if let Some(new_pipeline) = self.pipelines.get_mut(&new_pipeline_id) {
4984            #[cfg(feature = "devtools")]
4985            if let Some(ref chan) = self.devtools_sender {
4986                let state = NavigationState::Start(new_pipeline.url.clone());
4987                let _ = chan.send(DevtoolsControlMsg::FromScript(
4988                    ScriptToDevtoolsControlMsg::Navigate(browsing_context_id, state),
4989                ));
4990                let page_info = DevtoolsPageInfo {
4991                    title: new_pipeline.title.clone(),
4992                    url: new_pipeline.url.clone(),
4993                    is_top_level_global: webview_id == browsing_context_id,
4994                    is_service_worker: false,
4995                };
4996                let state = NavigationState::Stop(new_pipeline.id, page_info);
4997                let _ = chan.send(DevtoolsControlMsg::FromScript(
4998                    ScriptToDevtoolsControlMsg::Navigate(browsing_context_id, state),
4999                ));
5000            }
5001
5002            new_pipeline.set_has_active_document(true);
5003
5004            // When navigating away from a Pipeline it is throttled, so if the WebView
5005            // is not hidden we must now unthrottle it.
5006            let webview_hidden = self
5007                .webviews
5008                .get(&webview_id)
5009                .is_none_or(|webview| webview.hidden());
5010            new_pipeline.send_throttle_messages(webview_hidden);
5011
5012            self.notify_focus_state(new_pipeline_id);
5013        }
5014
5015        self.update_activity(old_pipeline_id);
5016        self.update_activity(new_pipeline_id);
5017
5018        if let Some(parent_pipeline_id) = parent_pipeline_id {
5019            let msg = ScriptThreadMessage::UpdatePipelineId(
5020                parent_pipeline_id,
5021                browsing_context_id,
5022                webview_id,
5023                new_pipeline_id,
5024                UpdatePipelineIdReason::Traversal,
5025            );
5026            self.send_message_to_pipeline(parent_pipeline_id, msg, "Child traversed after closure");
5027        }
5028
5029        None
5030    }
5031
5032    #[servo_tracing::instrument(skip_all)]
5033    fn update_pipeline_history_state(
5034        &mut self,
5035        pipeline_id: PipelineId,
5036        history_state_id: Option<HistoryStateId>,
5037        url: ServoUrl,
5038    ) {
5039        if let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) {
5040            pipeline.history_state_id = history_state_id;
5041            pipeline.url = url.clone();
5042        }
5043        let msg = ScriptThreadMessage::UpdateHistoryState(pipeline_id, history_state_id, url);
5044        self.send_message_to_pipeline(pipeline_id, msg, "History state updated after closure");
5045    }
5046
5047    #[servo_tracing::instrument(skip_all)]
5048    fn handle_joint_session_history_length(
5049        &self,
5050        webview_id: WebViewId,
5051        response_sender: GenericSender<u32>,
5052    ) {
5053        let length = self
5054            .webviews
5055            .get(&webview_id)
5056            .map(|webview| webview.session_history.history_length())
5057            .unwrap_or(1);
5058        let _ = response_sender.send(length as u32);
5059    }
5060
5061    #[servo_tracing::instrument(skip_all)]
5062    fn handle_push_history_state_msg(
5063        &mut self,
5064        pipeline_id: PipelineId,
5065        history_state_id: HistoryStateId,
5066        url: ServoUrl,
5067    ) {
5068        let (webview_id, old_state_id, old_url) = match self.pipelines.get_mut(&pipeline_id) {
5069            Some(pipeline) => {
5070                let old_history_state_id = pipeline.history_state_id;
5071                let old_url = replace(&mut pipeline.url, url.clone());
5072                pipeline.history_state_id = Some(history_state_id);
5073                (pipeline.webview_id, old_history_state_id, old_url)
5074            },
5075            None => {
5076                return warn!(
5077                    "{}: Push history state {} for closed pipeline",
5078                    pipeline_id, history_state_id,
5079                );
5080            },
5081        };
5082
5083        let Some(webview) = self.webviews.get_mut(&webview_id) else {
5084            return warn!("Ignoring history change in non-existent WebView ({webview_id:?}).");
5085        };
5086
5087        let diff = SessionHistoryDiff::Pipeline {
5088            pipeline_reloader: NeedsToReload::No(pipeline_id),
5089            new_history_state_id: history_state_id,
5090            new_url: url,
5091            old_history_state_id: old_state_id,
5092            old_url,
5093        };
5094        webview.session_history.push_diff(diff);
5095        self.notify_history_changed(webview_id);
5096    }
5097
5098    #[servo_tracing::instrument(skip_all)]
5099    fn handle_replace_history_state_msg(
5100        &mut self,
5101        pipeline_id: PipelineId,
5102        history_state_id: HistoryStateId,
5103        url: ServoUrl,
5104    ) {
5105        let webview_id = match self.pipelines.get_mut(&pipeline_id) {
5106            Some(pipeline) => {
5107                pipeline.history_state_id = Some(history_state_id);
5108                pipeline.url = url.clone();
5109                pipeline.webview_id
5110            },
5111            None => {
5112                return warn!(
5113                    "{}: Replace history state {} for closed pipeline",
5114                    history_state_id, pipeline_id
5115                );
5116            },
5117        };
5118
5119        let Some(webview) = self.webviews.get_mut(&webview_id) else {
5120            return warn!("Ignoring history change in non-existent WebView ({webview_id:?}).");
5121        };
5122
5123        webview
5124            .session_history
5125            .replace_history_state(pipeline_id, history_state_id, url);
5126        self.notify_history_changed(webview_id);
5127    }
5128
5129    #[servo_tracing::instrument(skip_all)]
5130    fn handle_reload_msg(&mut self, webview_id: WebViewId) {
5131        let browsing_context_id = BrowsingContextId::from(webview_id);
5132        let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
5133            Some(browsing_context) => browsing_context.pipeline_id,
5134            None => {
5135                return warn!("{}: Got reload event after closure", browsing_context_id);
5136            },
5137        };
5138
5139        self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStart);
5140        if !self.send_message_to_pipeline(
5141            pipeline_id,
5142            ScriptThreadMessage::Reload(pipeline_id),
5143            "Got reload event after closure",
5144        ) {
5145            self.send_webdriver_load_status(webview_id, WebDriverLoadStatus::NavigationStop);
5146        }
5147    }
5148
5149    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
5150    #[servo_tracing::instrument(skip_all)]
5151    fn handle_post_message_msg(
5152        &mut self,
5153        browsing_context_id: BrowsingContextId,
5154        source_pipeline: PipelineId,
5155        origin: Option<ImmutableOrigin>,
5156        source_origin: ImmutableOrigin,
5157        data: StructuredSerializedData,
5158    ) {
5159        let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
5160            None => {
5161                return warn!(
5162                    "{}: PostMessage to closed browsing context",
5163                    browsing_context_id
5164                );
5165            },
5166            Some(browsing_context) => browsing_context.pipeline_id,
5167        };
5168        let source_webview = match self.pipelines.get(&source_pipeline) {
5169            Some(pipeline) => pipeline.webview_id,
5170            None => return warn!("{}: PostMessage from closed pipeline", source_pipeline),
5171        };
5172
5173        let browsing_context_for_pipeline = |pipeline_id| {
5174            self.pipelines
5175                .get(&pipeline_id)
5176                .and_then(|pipeline| self.browsing_contexts.get(&pipeline.browsing_context_id))
5177        };
5178        let mut maybe_browsing_context = browsing_context_for_pipeline(source_pipeline);
5179        if maybe_browsing_context.is_none() {
5180            return warn!("{source_pipeline}: PostMessage from pipeline with closed parent");
5181        }
5182
5183        // Step 8.3: Let source be the WindowProxy object corresponding to
5184        // incumbentSettings's global object (a Window object).
5185        // Note: done here to prevent a round-trip to the constellation later,
5186        // and to prevent panic as part of that round-trip
5187        // in the case that the source would already have been closed.
5188        let mut source_with_ancestry = vec![];
5189        while let Some(browsing_context) = maybe_browsing_context {
5190            source_with_ancestry.push(browsing_context.id);
5191            maybe_browsing_context = browsing_context
5192                .parent_pipeline_id
5193                .and_then(browsing_context_for_pipeline);
5194        }
5195        let msg = ScriptThreadMessage::PostMessage {
5196            target: pipeline_id,
5197            source_webview,
5198            source_with_ancestry,
5199            target_origin: origin,
5200            source_origin,
5201            data: Box::new(data),
5202        };
5203        self.send_message_to_pipeline(pipeline_id, msg, "PostMessage to closed pipeline");
5204    }
5205
5206    #[servo_tracing::instrument(skip_all)]
5207    fn handle_focus_ancestor_browsing_contexts_for_focusing_steps(
5208        &mut self,
5209        pipeline_id: PipelineId,
5210        focused_child_browsing_context_id: Option<BrowsingContextId>,
5211        sequence: FocusSequenceNumber,
5212    ) {
5213        let browsing_context_id = match self.pipelines.get_mut(&pipeline_id) {
5214            Some(pipeline) => {
5215                pipeline.focus_sequence = sequence;
5216                pipeline.browsing_context_id
5217            },
5218            None => return warn!("{}: Focus parent after closure", pipeline_id),
5219        };
5220
5221        // Ignore if the pipeline isn't fully active.
5222        if self.get_activity(pipeline_id) != DocumentActivity::FullyActive {
5223            debug!(
5224                "Ignoring the focus request because pipeline {} is not \
5225                fully active",
5226                pipeline_id
5227            );
5228            return;
5229        }
5230
5231        // If a container with a non-null nested browsing context is focused,
5232        // the nested browsing context's active document becomes the focused
5233        // area of the top-level browsing context instead.
5234        let focused_browsing_context_id =
5235            focused_child_browsing_context_id.unwrap_or(browsing_context_id);
5236
5237        // Send focus messages to the affected pipelines, except
5238        // `pipeline_id`, which has already its local focus state
5239        // updated.
5240        self.focus_browsing_context(Some(pipeline_id), focused_browsing_context_id);
5241    }
5242
5243    fn handle_focus_remote_browsing_context(
5244        &mut self,
5245        target: BrowsingContextId,
5246        operation: RemoteFocusOperation,
5247    ) {
5248        let Some(browsing_context) = self.browsing_contexts.get(&target) else {
5249            return warn!("{target:?} not found for focus message");
5250        };
5251        let pipeline_id = browsing_context.pipeline_id;
5252        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
5253            return warn!("{pipeline_id:?} not found for focus message");
5254        };
5255        if let Err(error) = pipeline
5256            .event_loop
5257            .send(ScriptThreadMessage::FocusDocument(pipeline_id, operation))
5258        {
5259            self.handle_send_error(pipeline_id, error);
5260        }
5261    }
5262
5263    /// Perform [the focusing steps][1] for the active document of
5264    /// `focused_browsing_context_id`.
5265    ///
5266    /// If `initiator_pipeline_id` is specified, this method avoids sending
5267    /// a message to `initiator_pipeline_id`, assuming its local focus state has
5268    /// already been updated. This is necessary for performing the focusing
5269    /// steps for an object that is not the document itself but something that
5270    /// belongs to the document.
5271    ///
5272    /// [1]: https://html.spec.whatwg.org/multipage/#focusing-steps
5273    #[servo_tracing::instrument(skip_all)]
5274    fn focus_browsing_context(
5275        &mut self,
5276        initiator_pipeline_id: Option<PipelineId>,
5277        focused_browsing_context_id: BrowsingContextId,
5278    ) {
5279        let webview_id = match self.browsing_contexts.get(&focused_browsing_context_id) {
5280            Some(browsing_context) => browsing_context.webview_id,
5281            None => return warn!("Browsing context {} not found", focused_browsing_context_id),
5282        };
5283
5284        // Update the webview’s focused browsing context.
5285        let old_focused_browsing_context_id = match self.webviews.get_mut(&webview_id) {
5286            Some(browser) => replace(
5287                &mut browser.focused_browsing_context_id,
5288                focused_browsing_context_id,
5289            ),
5290            None => {
5291                return warn!(
5292                    "{}: Browsing context for focus msg does not exist",
5293                    webview_id
5294                );
5295            },
5296        };
5297
5298        // The following part is similar to [the focus update steps][1] except
5299        // that only `Document`s in the given focus chains are considered. It's
5300        // ultimately up to the script threads to fire focus events at the
5301        // affected objects.
5302        //
5303        // [1]: https://html.spec.whatwg.org/multipage/#focus-update-steps
5304        let mut old_focus_chain_pipelines: Vec<&Pipeline> = self
5305            .ancestor_or_self_pipelines_of_browsing_context_iter(old_focused_browsing_context_id)
5306            .collect();
5307        let mut new_focus_chain_pipelines: Vec<&Pipeline> = self
5308            .ancestor_or_self_pipelines_of_browsing_context_iter(focused_browsing_context_id)
5309            .collect();
5310
5311        debug!(
5312            "old_focus_chain_pipelines = {:?}",
5313            old_focus_chain_pipelines
5314                .iter()
5315                .map(|p| p.id.to_string())
5316                .collect::<Vec<_>>()
5317        );
5318        debug!(
5319            "new_focus_chain_pipelines = {:?}",
5320            new_focus_chain_pipelines
5321                .iter()
5322                .map(|p| p.id.to_string())
5323                .collect::<Vec<_>>()
5324        );
5325
5326        // At least the last entries should match. Otherwise something is wrong,
5327        // and we don't want to proceed and crash the top-level pipeline by
5328        // sending an impossible `Unfocus` message to it.
5329        match (
5330            &old_focus_chain_pipelines[..],
5331            &new_focus_chain_pipelines[..],
5332        ) {
5333            ([.., p1], [.., p2]) if p1.id == p2.id => {},
5334            _ => {
5335                warn!("Aborting the focus operation - focus chain sanity check failed");
5336                return;
5337            },
5338        }
5339
5340        // > If the last entry in `old chain` and the last entry in `new chain`
5341        // > are the same, pop the last entry from `old chain` and the last
5342        // > entry from `new chain` and redo this step.
5343        let mut first_common_pipeline_in_chain = None;
5344        while let ([.., p1], [.., p2]) = (
5345            &old_focus_chain_pipelines[..],
5346            &new_focus_chain_pipelines[..],
5347        ) {
5348            if p1.id != p2.id {
5349                break;
5350            }
5351            old_focus_chain_pipelines.pop();
5352            first_common_pipeline_in_chain = new_focus_chain_pipelines.pop();
5353        }
5354
5355        let mut send_errors = Vec::new();
5356
5357        // > For each entry `entry` in `old chain`, in order, run these
5358        // > substeps: [...]
5359        for &pipeline in old_focus_chain_pipelines.iter() {
5360            if Some(pipeline.id) != initiator_pipeline_id {
5361                let msg = ScriptThreadMessage::UnfocusDocumentAsPartOfFocusingSteps(
5362                    pipeline.id,
5363                    pipeline.focus_sequence,
5364                );
5365                trace!("Sending {:?} to {}", msg, pipeline.id);
5366                if let Err(e) = pipeline.event_loop.send(msg) {
5367                    send_errors.push((pipeline.id, e));
5368                }
5369            } else {
5370                trace!(
5371                    "Not notifying {} - it's the initiator of this focus operation",
5372                    pipeline.id
5373                );
5374            }
5375        }
5376
5377        // > For each entry entry in `new chain`, in reverse order, run these
5378        // > substeps: [...]
5379        let mut child_browsing_context_id = None;
5380        for &pipeline in new_focus_chain_pipelines.iter().rev() {
5381            // Don't send a message to the browsing context that initiated this
5382            // focus operation. It already knows that it has gotten focus.
5383            if Some(pipeline.id) != initiator_pipeline_id &&
5384                let Err(error) = pipeline.event_loop.send(
5385                    ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(
5386                        pipeline.id,
5387                        pipeline.focus_sequence,
5388                        child_browsing_context_id,
5389                    ),
5390                )
5391            {
5392                send_errors.push((pipeline.id, error));
5393            }
5394            child_browsing_context_id = Some(pipeline.browsing_context_id);
5395        }
5396
5397        if let Some(pipeline) = first_common_pipeline_in_chain &&
5398            Some(pipeline.id) != initiator_pipeline_id &&
5399            let Err(error) = pipeline.event_loop.send(
5400                ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(
5401                    pipeline.id,
5402                    pipeline.focus_sequence,
5403                    child_browsing_context_id,
5404                ),
5405            )
5406        {
5407            send_errors.push((pipeline.id, error));
5408        }
5409
5410        for (pipeline_id, error) in send_errors {
5411            self.handle_send_error(pipeline_id, error);
5412        }
5413    }
5414
5415    #[servo_tracing::instrument(skip_all)]
5416    fn handle_remove_iframe_msg(
5417        &mut self,
5418        webview_id: WebViewId,
5419        browsing_context_id: BrowsingContextId,
5420    ) -> Vec<PipelineId> {
5421        let result = self
5422            .all_descendant_browsing_contexts_iter(browsing_context_id)
5423            .flat_map(|browsing_context| browsing_context.pipelines.iter().cloned())
5424            .collect();
5425        self.close_browsing_context(webview_id, browsing_context_id);
5426        result
5427    }
5428
5429    #[servo_tracing::instrument(skip_all)]
5430    fn handle_create_canvas_paint_thread_msg(
5431        &mut self,
5432        size: UntypedSize2D<u64>,
5433        response_sender: GenericSender<Option<(GenericSender<CanvasMsg>, CanvasId)>>,
5434    ) {
5435        let (canvas_data_sender, canvas_data_receiver) = unbounded();
5436        let (canvas_sender, canvas_ipc_sender) = self
5437            .canvas
5438            .get_or_init(|| self.create_canvas_paint_thread());
5439
5440        let response = if let Err(e) = canvas_sender.send(ConstellationCanvasMsg::Create {
5441            sender: canvas_data_sender,
5442            size,
5443        }) {
5444            warn!("Create canvas paint thread failed ({})", e);
5445            None
5446        } else {
5447            match canvas_data_receiver.recv() {
5448                Ok(Some(canvas_id)) => Some((canvas_ipc_sender.clone(), canvas_id)),
5449                Ok(None) => None,
5450                Err(e) => {
5451                    warn!("Create canvas paint thread id response failed ({})", e);
5452                    None
5453                },
5454            }
5455        };
5456        if let Err(e) = response_sender.send(response) {
5457            warn!("Create canvas paint thread response failed ({})", e);
5458        }
5459    }
5460
5461    /// Report a navigation status to the WebDriver server for `webview_id`, if registered.
5462    fn send_webdriver_load_status(&mut self, webview_id: WebViewId, status: WebDriverLoadStatus) {
5463        match status {
5464            WebDriverLoadStatus::NavigationStart => {
5465                self.webdriver_navigating_webviews.insert(webview_id);
5466            },
5467            _ => {
5468                self.webdriver_navigating_webviews.remove(&webview_id);
5469            },
5470        }
5471
5472        let Some(sender) = self.webdriver_load_status_senders.get(&webview_id) else {
5473            return;
5474        };
5475        let _ = sender.send(WebDriverLoadStatusMessage { webview_id, status });
5476    }
5477
5478    /// Dispatch a script command to the current pipeline of the browsing context.
5479    fn dispatch_webdriver_script_command(
5480        &mut self,
5481        browsing_context_id: BrowsingContextId,
5482        cmd: WebDriverScriptCommand,
5483    ) {
5484        let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) else {
5485            return warn!("{}: Browsing context is not ready", browsing_context_id);
5486        };
5487        let pipeline_id = browsing_context.pipeline_id;
5488        let control_msg = ScriptThreadMessage::WebDriverScriptCommand(pipeline_id, cmd);
5489        self.send_message_to_pipeline(pipeline_id, control_msg, "ScriptCommand after closure");
5490    }
5491
5492    #[servo_tracing::instrument(skip_all)]
5493    fn handle_webdriver_msg(&mut self, msg: WebDriverCommandMsg) {
5494        // Find the script channel for the given parent pipeline,
5495        // and pass the event to that script thread.
5496        match msg {
5497            WebDriverCommandMsg::IsBrowsingContextOpen(browsing_context_id, response_sender) => {
5498                let is_open = self.browsing_contexts.contains_key(&browsing_context_id);
5499                let _ = response_sender.send(is_open);
5500            },
5501            WebDriverCommandMsg::FocusBrowsingContext(browsing_context_id) => {
5502                self.handle_focus_remote_browsing_context(
5503                    browsing_context_id,
5504                    RemoteFocusOperation::Viewport,
5505                );
5506            },
5507            WebDriverCommandMsg::AddLoadStatusSender(webview_id, sender) => {
5508                self.webdriver_load_status_senders
5509                    .insert(webview_id, sender);
5510            },
5511            WebDriverCommandMsg::RemoveLoadStatusSender(webview_id) => {
5512                self.webdriver_load_status_senders.remove(&webview_id);
5513            },
5514            WebDriverCommandMsg::IsNavigationInProgress(webview_id, response_sender) => {
5515                let in_progress = self.webdriver_navigating_webviews.contains(&webview_id);
5516                let _ = response_sender.send(in_progress);
5517            },
5518            // TODO: This should use the ScriptThreadMessage::EvaluateJavaScript command
5519            WebDriverCommandMsg::ScriptCommand(browsing_context_id, cmd) => {
5520                self.dispatch_webdriver_script_command(browsing_context_id, cmd);
5521            },
5522            WebDriverCommandMsg::CloseWebView(..) |
5523            WebDriverCommandMsg::NewWindow(..) |
5524            WebDriverCommandMsg::SelectWebViewForInteraction(..) |
5525            WebDriverCommandMsg::IsWebViewOpen(..) |
5526            WebDriverCommandMsg::GetWindowRect(..) |
5527            WebDriverCommandMsg::GetViewportSize(..) |
5528            WebDriverCommandMsg::SetWindowRect(..) |
5529            WebDriverCommandMsg::MaximizeWebView(..) |
5530            WebDriverCommandMsg::LoadUrl(..) |
5531            WebDriverCommandMsg::Refresh(..) |
5532            WebDriverCommandMsg::InputEvent(..) |
5533            WebDriverCommandMsg::TakeScreenshot(..) => {
5534                unreachable!("This command should be send directly to the embedder.");
5535            },
5536            _ => {
5537                warn!("Unhandled WebDriver command: {:?}", msg);
5538            },
5539        }
5540    }
5541
5542    #[servo_tracing::instrument(skip_all)]
5543    fn set_webview_hidden(&mut self, webview_id: WebViewId, hidden: bool) {
5544        if self
5545            .webviews
5546            .get_mut(&webview_id)
5547            .is_none_or(|webview| !webview.set_hidden(hidden))
5548        {
5549            return;
5550        }
5551
5552        for pipeline in self.pipelines.values() {
5553            if pipeline.webview_id == webview_id {
5554                pipeline.send_throttle_messages(hidden);
5555            }
5556        }
5557    }
5558
5559    #[servo_tracing::instrument(skip_all)]
5560    fn notify_history_changed(&self, webview_id: WebViewId) {
5561        // Send a flat projection of the history to embedder.
5562        // The final vector is a concatenation of the URLs of the past
5563        // entries, the current entry and the future entries.
5564        // URLs of inner frames are ignored and replaced with the URL
5565        // of the parent.
5566
5567        let session_history = match self.webviews.get(&webview_id) {
5568            Some(webview) => &webview.session_history,
5569            None => {
5570                return warn!(
5571                    "{}: Session history does not exist for browsing context",
5572                    webview_id
5573                );
5574            },
5575        };
5576
5577        let browsing_context_id = BrowsingContextId::from(webview_id);
5578        let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) else {
5579            return warn!("notify_history_changed error after top-level browsing context closed.");
5580        };
5581
5582        let current_url = match self.pipelines.get(&browsing_context.pipeline_id) {
5583            Some(pipeline) => pipeline.url.clone(),
5584            None => {
5585                return warn!("{}: Refresh after closure", browsing_context.pipeline_id);
5586            },
5587        };
5588
5589        // If URL was ignored, use the URL of the previous SessionHistoryEntry, which
5590        // is the URL of the parent browsing context.
5591        let resolve_url_future =
5592            |previous_url: &mut ServoUrl, diff: &SessionHistoryDiff| match *diff {
5593                SessionHistoryDiff::BrowsingContext {
5594                    browsing_context_id,
5595                    ref new_reloader,
5596                    ..
5597                } => {
5598                    if browsing_context_id == webview_id {
5599                        let url = match *new_reloader {
5600                            NeedsToReload::No(pipeline_id) => {
5601                                match self.pipelines.get(&pipeline_id) {
5602                                    Some(pipeline) => pipeline.url.clone(),
5603                                    None => previous_url.clone(),
5604                                }
5605                            },
5606                            NeedsToReload::Yes(_, ref load_data) => load_data.url.clone(),
5607                        };
5608                        *previous_url = url.clone();
5609                        Some(url)
5610                    } else {
5611                        Some(previous_url.clone())
5612                    }
5613                },
5614                SessionHistoryDiff::Hash { ref new_url, .. } => {
5615                    *previous_url = new_url.clone();
5616                    Some(new_url.clone())
5617                },
5618                _ => Some(previous_url.clone()),
5619            };
5620
5621        let resolve_url_past = |previous_url: &mut ServoUrl, diff: &SessionHistoryDiff| match *diff
5622        {
5623            SessionHistoryDiff::BrowsingContext {
5624                browsing_context_id,
5625                ref old_reloader,
5626                ..
5627            } => {
5628                if browsing_context_id == webview_id {
5629                    let url = match *old_reloader {
5630                        NeedsToReload::No(pipeline_id) => match self.pipelines.get(&pipeline_id) {
5631                            Some(pipeline) => pipeline.url.clone(),
5632                            None => previous_url.clone(),
5633                        },
5634                        NeedsToReload::Yes(_, ref load_data) => load_data.url.clone(),
5635                    };
5636                    *previous_url = url.clone();
5637                    Some(url)
5638                } else {
5639                    Some(previous_url.clone())
5640                }
5641            },
5642            SessionHistoryDiff::Hash { ref old_url, .. } => {
5643                *previous_url = old_url.clone();
5644                Some(old_url.clone())
5645            },
5646            _ => Some(previous_url.clone()),
5647        };
5648
5649        let mut entries: Vec<ServoUrl> = session_history
5650            .past
5651            .iter()
5652            .rev()
5653            .scan(current_url.clone(), &resolve_url_past)
5654            .collect();
5655
5656        entries.reverse();
5657
5658        let current_index = entries.len();
5659
5660        entries.push(current_url.clone());
5661
5662        entries.extend(
5663            session_history
5664                .future
5665                .iter()
5666                .rev()
5667                .scan(current_url, &resolve_url_future),
5668        );
5669        self.constellation_to_embedder_proxy
5670            .send(ConstellationToEmbedderMsg::HistoryChanged(
5671                webview_id,
5672                entries,
5673                current_index,
5674            ));
5675    }
5676
5677    #[servo_tracing::instrument(skip_all)]
5678    fn change_session_history(&mut self, change: SessionHistoryChange) {
5679        debug!(
5680            "{}: Setting to {}",
5681            change.browsing_context_id, change.new_pipeline_id
5682        );
5683
5684        // If the currently focused browsing context is a child of the browsing
5685        // context in which the page is being loaded, then update the focused
5686        // browsing context to be the one where the page is being loaded.
5687        if self.focused_browsing_context_is_descendant_of(&change) &&
5688            let Some(webview) = self.webviews.get_mut(&change.webview_id)
5689        {
5690            webview.focused_browsing_context_id = change.browsing_context_id;
5691        }
5692
5693        let (old_pipeline_id, webview_id) =
5694            match self.browsing_contexts.get_mut(&change.browsing_context_id) {
5695                Some(browsing_context) => {
5696                    debug!("Adding pipeline to existing browsing context.");
5697                    let old_pipeline_id = browsing_context.pipeline_id;
5698                    browsing_context.pipelines.insert(change.new_pipeline_id);
5699                    browsing_context.update_current_entry(change.new_pipeline_id);
5700                    (Some(old_pipeline_id), Some(browsing_context.webview_id))
5701                },
5702                None => {
5703                    debug!("Adding pipeline to new browsing context.");
5704                    (None, None)
5705                },
5706            };
5707
5708        if let Some(old_pipeline_id) = old_pipeline_id {
5709            self.unload_document(old_pipeline_id);
5710        }
5711
5712        let Some(webview) = self.webviews.get_mut(&change.webview_id) else {
5713            return warn!("Ignoring history change in non-existent WebView ({webview_id:?}).");
5714        };
5715
5716        match old_pipeline_id {
5717            None => {
5718                let Some(new_context_info) = change.new_browsing_context_info else {
5719                    return warn!(
5720                        "{}: No NewBrowsingContextInfo for browsing context",
5721                        change.browsing_context_id,
5722                    );
5723                };
5724                self.new_browsing_context(
5725                    change.browsing_context_id,
5726                    change.webview_id,
5727                    change.new_pipeline_id,
5728                    new_context_info.parent_pipeline_id,
5729                    change.viewport_details,
5730                    new_context_info.is_private,
5731                    new_context_info.inherited_secure_context,
5732                    new_context_info.upgrade_insecure_navigations_set,
5733                );
5734                self.update_activity(change.new_pipeline_id);
5735            },
5736            Some(old_pipeline_id) => {
5737                // Deactivate the old pipeline, and activate the new one.
5738                let (pipelines_to_close, states_to_close) = if let Some(replace_reloader) =
5739                    change.replace
5740                {
5741                    webview.session_history.replace_reloader(
5742                        replace_reloader.clone(),
5743                        NeedsToReload::No(change.new_pipeline_id),
5744                    );
5745
5746                    match replace_reloader {
5747                        NeedsToReload::No(pipeline_id) => (Some(vec![pipeline_id]), None),
5748                        NeedsToReload::Yes(..) => (None, None),
5749                    }
5750                } else {
5751                    let diff = SessionHistoryDiff::BrowsingContext {
5752                        browsing_context_id: change.browsing_context_id,
5753                        new_reloader: NeedsToReload::No(change.new_pipeline_id),
5754                        old_reloader: NeedsToReload::No(old_pipeline_id),
5755                    };
5756
5757                    let mut pipelines_to_close = vec![];
5758                    let mut states_to_close = FxHashMap::default();
5759
5760                    let diffs_to_close = webview.session_history.push_diff(diff);
5761                    for diff in diffs_to_close {
5762                        match diff {
5763                            SessionHistoryDiff::BrowsingContext { new_reloader, .. } => {
5764                                if let Some(pipeline_id) = new_reloader.alive_pipeline_id() {
5765                                    pipelines_to_close.push(pipeline_id);
5766                                }
5767                            },
5768                            SessionHistoryDiff::Pipeline {
5769                                pipeline_reloader,
5770                                new_history_state_id,
5771                                ..
5772                            } => {
5773                                if let Some(pipeline_id) = pipeline_reloader.alive_pipeline_id() {
5774                                    let states =
5775                                        states_to_close.entry(pipeline_id).or_insert(Vec::new());
5776                                    states.push(new_history_state_id);
5777                                }
5778                            },
5779                            _ => {},
5780                        }
5781                    }
5782
5783                    (Some(pipelines_to_close), Some(states_to_close))
5784                };
5785
5786                self.update_activity(old_pipeline_id);
5787                self.update_activity(change.new_pipeline_id);
5788
5789                if let Some(states_to_close) = states_to_close {
5790                    for (pipeline_id, states) in states_to_close {
5791                        let msg = ScriptThreadMessage::RemoveHistoryStates(pipeline_id, states);
5792                        if !self.send_message_to_pipeline(
5793                            pipeline_id,
5794                            msg,
5795                            "Removed history states after closure",
5796                        ) {
5797                            return;
5798                        }
5799                    }
5800                }
5801
5802                if let Some(pipelines_to_close) = pipelines_to_close {
5803                    for pipeline_id in pipelines_to_close {
5804                        self.close_pipeline(pipeline_id, DiscardBrowsingContext::No);
5805                    }
5806                }
5807            },
5808        }
5809
5810        if let Some(webview_id) = webview_id {
5811            self.trim_history(webview_id);
5812        }
5813
5814        self.notify_focus_state(change.new_pipeline_id);
5815
5816        self.notify_history_changed(change.webview_id);
5817        self.set_frame_tree_for_webview(change.webview_id);
5818    }
5819
5820    /// Update the focus state of the specified pipeline that recently became
5821    /// active (thus doesn't have a focused container element) and may have
5822    /// out-dated information.
5823    fn notify_focus_state(&mut self, pipeline_id: PipelineId) {
5824        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
5825            return warn!("Pipeline {pipeline_id} is closed");
5826        };
5827
5828        let is_focused = match self.webviews.get(&pipeline.webview_id) {
5829            Some(webview) => webview.focused_browsing_context_id == pipeline.browsing_context_id,
5830            None => {
5831                return warn!(
5832                    "Pipeline {pipeline_id}'s top-level browsing context {} is closed",
5833                    pipeline.webview_id
5834                );
5835            },
5836        };
5837
5838        // If the browsing context is focused, focus the document
5839        let msg = if is_focused {
5840            ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(
5841                pipeline_id,
5842                pipeline.focus_sequence,
5843                None,
5844            )
5845        } else {
5846            ScriptThreadMessage::UnfocusDocumentAsPartOfFocusingSteps(
5847                pipeline_id,
5848                pipeline.focus_sequence,
5849            )
5850        };
5851        if let Err(e) = pipeline.event_loop.send(msg) {
5852            self.handle_send_error(pipeline_id, e);
5853        }
5854    }
5855
5856    #[servo_tracing::instrument(skip_all)]
5857    fn focused_browsing_context_is_descendant_of(&self, change: &SessionHistoryChange) -> bool {
5858        let focused_browsing_context_id = self
5859            .webviews
5860            .get(&change.webview_id)
5861            .map(|webview| webview.focused_browsing_context_id);
5862        focused_browsing_context_id.is_some_and(|focused_browsing_context_id| {
5863            focused_browsing_context_id == change.browsing_context_id ||
5864                self.fully_active_descendant_browsing_contexts_iter(change.browsing_context_id)
5865                    .any(|nested_ctx| nested_ctx.id == focused_browsing_context_id)
5866        })
5867    }
5868
5869    #[servo_tracing::instrument(skip_all)]
5870    fn trim_history(&mut self, webview_id: WebViewId) {
5871        let pipelines_to_evict = {
5872            let Some(webview) = self.webviews.get_mut(&webview_id) else {
5873                return warn!("Not trimming history for non-existent WebView ({webview_id:}");
5874            };
5875            let history_length = pref!(session_history_max_length) as usize;
5876
5877            // The past is stored with older entries at the front.
5878            // We reverse the iter so that newer entries are at the front and then
5879            // skip _n_ entries and evict the remaining entries.
5880            let past_trim = webview
5881                .session_history
5882                .past
5883                .iter()
5884                .rev()
5885                .map(|diff| diff.alive_old_pipeline())
5886                .skip(history_length)
5887                .flatten();
5888
5889            // The future is stored with oldest entries front, so we must
5890            // reverse the iterator like we do for the `past`.
5891            let future_trim = webview
5892                .session_history
5893                .future
5894                .iter()
5895                .rev()
5896                .map(|diff| diff.alive_new_pipeline())
5897                .skip(history_length)
5898                .flatten();
5899
5900            past_trim.chain(future_trim).collect::<Vec<_>>()
5901        };
5902
5903        let mut dead_pipelines = vec![];
5904        for evicted_id in pipelines_to_evict {
5905            let Some(load_data) = self.refresh_load_data(evicted_id) else {
5906                continue;
5907            };
5908
5909            dead_pipelines.push((evicted_id, NeedsToReload::Yes(evicted_id, load_data)));
5910            self.close_pipeline(evicted_id, DiscardBrowsingContext::No);
5911        }
5912
5913        if let Some(webview) = self.webviews.get_mut(&webview_id) {
5914            for (alive_id, dead) in dead_pipelines {
5915                webview
5916                    .session_history
5917                    .replace_reloader(NeedsToReload::No(alive_id), dead);
5918            }
5919        };
5920    }
5921
5922    #[servo_tracing::instrument(skip_all)]
5923    fn handle_activate_document_msg(&mut self, webview_id: WebViewId, pipeline_id: PipelineId) {
5924        debug!("{}: Document ready to activate", pipeline_id);
5925
5926        // Find the pending change whose new pipeline id is pipeline_id. If it is found, remove
5927        // it from the pending changes, and make it the active document of its frame.
5928        let Some(change) = self
5929            .webviews
5930            .get_mut(&webview_id)
5931            .and_then(|webview| webview.remove_pending_change_for_pipeline(pipeline_id))
5932        else {
5933            return;
5934        };
5935
5936        // Notify the parent (if there is one).
5937        let parent_pipeline_id = match change.new_browsing_context_info {
5938            // This will be a new browsing context.
5939            Some(ref info) => info.parent_pipeline_id,
5940            // This is an existing browsing context.
5941            None => match self.browsing_contexts.get(&change.browsing_context_id) {
5942                Some(ctx) => ctx.parent_pipeline_id,
5943                None => {
5944                    return warn!(
5945                        "{}: Activated document after closure of {}",
5946                        change.new_pipeline_id, change.browsing_context_id,
5947                    );
5948                },
5949            },
5950        };
5951        if let Some(parent_pipeline_id) = parent_pipeline_id &&
5952            let Some(parent_pipeline) = self.pipelines.get(&parent_pipeline_id)
5953        {
5954            let msg = ScriptThreadMessage::UpdatePipelineId(
5955                parent_pipeline_id,
5956                change.browsing_context_id,
5957                webview_id,
5958                pipeline_id,
5959                UpdatePipelineIdReason::Navigation,
5960            );
5961            let _ = parent_pipeline.event_loop.send(msg);
5962        }
5963
5964        self.change_session_history(change);
5965
5966        if let Some(webview) = self.webviews.get_mut(&webview_id) {
5967            webview.send_screenshot_readiness_requests_to_pipelines(
5968                &self.browsing_contexts,
5969                &self.pipelines,
5970            );
5971        }
5972    }
5973
5974    /// Called when the window is resized.
5975    #[servo_tracing::instrument(skip_all)]
5976    fn handle_change_viewport_details_msg(
5977        &mut self,
5978        webview_id: WebViewId,
5979        new_viewport_details: ViewportDetails,
5980        size_type: WindowSizeType,
5981    ) {
5982        debug!(
5983            "handle_change_viewport_details_msg: {:?}",
5984            new_viewport_details
5985        );
5986
5987        let browsing_context_id = BrowsingContextId::from(webview_id);
5988        self.resize_browsing_context(
5989            webview_id,
5990            new_viewport_details,
5991            size_type,
5992            browsing_context_id,
5993        );
5994    }
5995
5996    /// Called when the window exits from fullscreen mode
5997    #[servo_tracing::instrument(skip_all)]
5998    fn handle_exit_fullscreen_msg(&mut self, webview_id: WebViewId) {
5999        let browsing_context_id = BrowsingContextId::from(webview_id);
6000        self.switch_fullscreen_mode(browsing_context_id);
6001    }
6002
6003    /// Get the current activity of a pipeline.
6004    #[servo_tracing::instrument(skip_all)]
6005    fn get_activity(&self, pipeline_id: PipelineId) -> DocumentActivity {
6006        let mut ancestor_id = pipeline_id;
6007        loop {
6008            if let Some(ancestor) = self.pipelines.get(&ancestor_id) &&
6009                let Some(browsing_context) =
6010                    self.browsing_contexts.get(&ancestor.browsing_context_id) &&
6011                browsing_context.pipeline_id == ancestor_id
6012            {
6013                if let Some(parent_pipeline_id) = browsing_context.parent_pipeline_id {
6014                    ancestor_id = parent_pipeline_id;
6015                    continue;
6016                } else {
6017                    return DocumentActivity::FullyActive;
6018                }
6019            }
6020            if pipeline_id == ancestor_id {
6021                return DocumentActivity::Inactive;
6022            } else {
6023                return DocumentActivity::Active;
6024            }
6025        }
6026    }
6027
6028    /// Set the current activity of a pipeline.
6029    #[servo_tracing::instrument(skip_all)]
6030    fn set_activity(&self, pipeline_id: PipelineId, activity: DocumentActivity) {
6031        debug!("{}: Setting activity to {:?}", pipeline_id, activity);
6032        if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
6033            pipeline.set_activity(activity);
6034            let child_activity = if activity == DocumentActivity::Inactive {
6035                DocumentActivity::Active
6036            } else {
6037                activity
6038            };
6039            for child_id in &pipeline.children {
6040                if let Some(child) = self.browsing_contexts.get(child_id) {
6041                    self.set_activity(child.pipeline_id, child_activity);
6042                }
6043            }
6044        }
6045    }
6046
6047    /// Update the current activity of a pipeline.
6048    #[servo_tracing::instrument(skip_all)]
6049    fn update_activity(&self, pipeline_id: PipelineId) {
6050        self.set_activity(pipeline_id, self.get_activity(pipeline_id));
6051    }
6052
6053    /// Handle updating the size of a browsing context.
6054    /// This notifies every pipeline in the context of the new size.
6055    #[servo_tracing::instrument(skip_all)]
6056    fn resize_browsing_context(
6057        &mut self,
6058        webview_id: WebViewId,
6059        new_viewport_details: ViewportDetails,
6060        size_type: WindowSizeType,
6061        browsing_context_id: BrowsingContextId,
6062    ) {
6063        let Some(webview) = self.webviews.get_mut(&webview_id) else {
6064            warn!("Resizing browsing context for unkown WebView: {webview_id:?}");
6065            return;
6066        };
6067
6068        if let Some(browsing_context) = self.browsing_contexts.get_mut(&browsing_context_id) {
6069            browsing_context.viewport_details = new_viewport_details;
6070            // Send Resize (or ResizeInactive) messages to each pipeline in the frame tree.
6071            let pipeline_id = browsing_context.pipeline_id;
6072            let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6073                return warn!("{}: Resized after closing", pipeline_id);
6074            };
6075            let _ = pipeline.event_loop.send(ScriptThreadMessage::Resize(
6076                pipeline.id,
6077                new_viewport_details,
6078                size_type,
6079            ));
6080            let pipeline_ids = browsing_context
6081                .pipelines
6082                .iter()
6083                .filter(|pipeline_id| **pipeline_id != pipeline.id);
6084            for id in pipeline_ids {
6085                if let Some(pipeline) = self.pipelines.get(id) {
6086                    let _ = pipeline
6087                        .event_loop
6088                        .send(ScriptThreadMessage::ResizeInactive(
6089                            pipeline.id,
6090                            new_viewport_details,
6091                        ));
6092                }
6093            }
6094        } else {
6095            webview.add_viewport_details(browsing_context_id, new_viewport_details);
6096        }
6097
6098        // Send resize message to any pending pipelines that aren't loaded yet.
6099        for change in &webview.pending_changes {
6100            let pipeline_id = change.new_pipeline_id;
6101            let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6102                warn!("Pending pipeline is closed: {pipeline_id}");
6103                continue;
6104            };
6105            if pipeline.browsing_context_id == browsing_context_id {
6106                let _ = pipeline.event_loop.send(ScriptThreadMessage::Resize(
6107                    pipeline.id,
6108                    new_viewport_details,
6109                    size_type,
6110                ));
6111            }
6112        }
6113    }
6114
6115    /// Handle theme change events from the embedder and forward them to all appropriate `ScriptThread`s.
6116    #[servo_tracing::instrument(skip_all)]
6117    fn handle_theme_change(&mut self, webview_id: WebViewId, theme: Theme) {
6118        let Some(webview) = self.webviews.get_mut(&webview_id) else {
6119            warn!("Received theme change request for unknown WebViewId: {webview_id:?}");
6120            return;
6121        };
6122        if !webview.set_theme(theme) {
6123            return;
6124        }
6125        let state = webview.state();
6126        for event_loop in self.event_loops() {
6127            if let Err(error) =
6128                event_loop.send(ScriptThreadMessage::UpdateWebViewState(state.clone()))
6129            {
6130                warn!(
6131                    "Sending to closed event loop ({:?}): {error}",
6132                    event_loop.id()
6133                );
6134            }
6135        }
6136    }
6137
6138    // Handle switching from fullscreen mode
6139    #[servo_tracing::instrument(skip_all)]
6140    fn switch_fullscreen_mode(&mut self, browsing_context_id: BrowsingContextId) {
6141        if let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) {
6142            let pipeline_id = browsing_context.pipeline_id;
6143            let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6144                return warn!("{pipeline_id}: Switched from fullscreen mode after closing",);
6145            };
6146            let _ = pipeline
6147                .event_loop
6148                .send(ScriptThreadMessage::ExitFullScreen(pipeline.id));
6149        }
6150    }
6151
6152    // Close and return the browsing context with the given id (and its children), if it exists.
6153    #[servo_tracing::instrument(skip_all)]
6154    fn close_browsing_context(
6155        &mut self,
6156        webview_id: WebViewId,
6157        browsing_context_id: BrowsingContextId,
6158    ) -> Option<BrowsingContext> {
6159        debug!("{}: Closing", browsing_context_id);
6160
6161        self.close_browsing_context_children(
6162            webview_id,
6163            browsing_context_id,
6164            DiscardBrowsingContext::Yes,
6165        );
6166
6167        let Some(webview) = self.webviews.get_mut(&webview_id) else {
6168            warn!("Closing BrowsingContext in unknown WebView: {webview_id:?}");
6169            return self.browsing_contexts.remove(&browsing_context_id);
6170        };
6171
6172        webview.close_browsing_context(browsing_context_id);
6173
6174        let Some(browsing_context) = self.browsing_contexts.remove(&browsing_context_id) else {
6175            warn!("fn close_browsing_context: {browsing_context_id}: Closing twice");
6176            return None;
6177        };
6178
6179        if let Some(parent_pipeline_id) = browsing_context.parent_pipeline_id {
6180            match self.pipelines.get_mut(&parent_pipeline_id) {
6181                None => {
6182                    warn!("{parent_pipeline_id}: Child closed after parent");
6183                },
6184                Some(parent_pipeline) => {
6185                    parent_pipeline.remove_child(browsing_context_id);
6186
6187                    // If `browsing_context_id` has focus, focus the parent browsing context
6188                    if webview.focused_browsing_context_id == browsing_context_id {
6189                        trace!(
6190                            "About-to-be-closed browsing context {} is currently focused, so \
6191                                focusing its parent {}",
6192                            browsing_context_id, parent_pipeline.browsing_context_id
6193                        );
6194                        webview.focused_browsing_context_id = parent_pipeline.browsing_context_id;
6195                    }
6196                },
6197            };
6198        }
6199
6200        debug!("{}: Closed", browsing_context_id);
6201        Some(browsing_context)
6202    }
6203
6204    // Close the children of a browsing context
6205    #[servo_tracing::instrument(skip_all)]
6206    fn close_browsing_context_children(
6207        &mut self,
6208        webview_id: WebViewId,
6209        browsing_context_id: BrowsingContextId,
6210        dbc: DiscardBrowsingContext,
6211    ) {
6212        debug!("{}: Closing browsing context children", browsing_context_id);
6213
6214        // Store information about the pipelines to be closed. Then close the
6215        // pipelines, before removing ourself from the browsing_contexts hash map. This
6216        // ordering is vital - so that if close_pipeline() ends up closing
6217        // any child browsing contexts, they can be removed from the parent browsing context correctly.
6218        let mut pipelines_to_close: Vec<_> = {
6219            let Some(webview) = self.webviews.get(&webview_id) else {
6220                return warn!(
6221                    "Couldnot find WebView for closing browsing context id: {webview_id:?}"
6222                );
6223            };
6224            webview
6225                .pending_changes
6226                .iter()
6227                .filter(|change| change.browsing_context_id == browsing_context_id)
6228                .map(|change| change.new_pipeline_id)
6229                .collect()
6230        };
6231
6232        if let Some(browsing_context) = self.browsing_contexts.get(&browsing_context_id) {
6233            pipelines_to_close.extend(&browsing_context.pipelines)
6234        }
6235
6236        for pipeline_id in pipelines_to_close {
6237            self.close_pipeline(pipeline_id, dbc);
6238        }
6239
6240        debug!("{}: Closed browsing context children", browsing_context_id);
6241    }
6242
6243    /// Returns the [LoadData] associated with the given pipeline if it exists,
6244    /// containing the most recent URL associated with the given pipeline.
6245    fn refresh_load_data(&self, pipeline_id: PipelineId) -> Option<LoadData> {
6246        self.pipelines.get(&pipeline_id).map(|pipeline| {
6247            let mut load_data = pipeline.load_data.clone();
6248            load_data.url = pipeline.url.clone();
6249            load_data
6250        })
6251    }
6252
6253    // Discard the pipeline for a given document, udpdate the joint session history.
6254    #[servo_tracing::instrument(skip_all)]
6255    fn handle_discard_document(&mut self, webview_id: WebViewId, pipeline_id: PipelineId) {
6256        let Some(load_data) = self.refresh_load_data(pipeline_id) else {
6257            return warn!("{}: Discarding closed pipeline", pipeline_id);
6258        };
6259        match self.webviews.get_mut(&webview_id) {
6260            Some(webview) => {
6261                webview.session_history.replace_reloader(
6262                    NeedsToReload::No(pipeline_id),
6263                    NeedsToReload::Yes(pipeline_id, load_data),
6264                );
6265            },
6266            None => {
6267                return warn!("{pipeline_id}: Discarding after closure of {webview_id}",);
6268            },
6269        };
6270        self.close_pipeline(pipeline_id, DiscardBrowsingContext::No);
6271    }
6272
6273    /// Send a message to script requesting the document associated with this pipeline runs the 'unload' algorithm.
6274    #[servo_tracing::instrument(skip_all)]
6275    fn unload_document(&mut self, pipeline_id: PipelineId) {
6276        if let Some(pipeline) = self.pipelines.get_mut(&pipeline_id) {
6277            pipeline.set_has_active_document(false);
6278            let _ = pipeline
6279                .event_loop
6280                .send(ScriptThreadMessage::UnloadDocument(pipeline_id));
6281        }
6282    }
6283
6284    // Close all pipelines at and beneath a given browsing context
6285    #[servo_tracing::instrument(skip_all)]
6286    fn close_pipeline(&mut self, pipeline_id: PipelineId, dbc: DiscardBrowsingContext) {
6287        debug!("{}: Closing", pipeline_id);
6288
6289        // Sever connection to browsing context
6290        let Some((webview_id, browsing_context_id)) = self
6291            .pipelines
6292            .get(&pipeline_id)
6293            .map(|pipeline| (pipeline.webview_id, pipeline.browsing_context_id))
6294        else {
6295            return warn!("Tried closing unknown pipeline: {pipeline_id:?}");
6296        };
6297
6298        if let Some(browsing_context) = self.browsing_contexts.get_mut(&browsing_context_id) {
6299            browsing_context.pipelines.remove(&pipeline_id);
6300        }
6301
6302        // Store information about the browsing contexts to be closed. Then close the
6303        // browsing contexts, before removing ourself from the pipelines hash map. This
6304        // ordering is vital - so that if close_browsing_context() ends up closing
6305        // any child pipelines, they can be removed from the parent pipeline correctly.
6306        let browsing_contexts_to_close = {
6307            let mut browsing_contexts_to_close = vec![];
6308
6309            if let Some(pipeline) = self.pipelines.get(&pipeline_id) {
6310                browsing_contexts_to_close.extend_from_slice(&pipeline.children);
6311            }
6312
6313            browsing_contexts_to_close
6314        };
6315
6316        // Remove any child browsing contexts
6317        for child_browsing_context in &browsing_contexts_to_close {
6318            self.close_browsing_context(webview_id, *child_browsing_context);
6319        }
6320
6321        // Note, we don't remove the pipeline now, we wait for the message to come back from
6322        // the pipeline.
6323        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6324            return warn!("fn close_pipeline: {pipeline_id}: Closing twice");
6325        };
6326
6327        // Inform script and paint that this pipeline has exited.
6328        if !pipeline.send_exit_message_to_script(dbc) {
6329            // The pipeline is now unreachable, so we should consider it gone. We should
6330            // not try to send any subsequent messages to this pipeline. all() here ensures
6331            // that `Paint` cleans up the pipeline display immediately without waiting for
6332            // confirmation from the event loop.
6333            self.handle_pipeline_exited(pipeline_id, PipelineExitSource::all());
6334        }
6335
6336        // Remove this pipeline from pending changes if it hasn't loaded yet.
6337        if let Some(webview) = self.webviews.get_mut(&webview_id) {
6338            webview.remove_pending_change_for_pipeline(pipeline_id);
6339            webview.send_screenshot_readiness_requests_to_pipelines(
6340                &self.browsing_contexts,
6341                &self.pipelines,
6342            );
6343            webview.handle_screenshot_readiness_response(
6344                pipeline_id,
6345                ScreenshotReadinessResponse::NoLongerActive,
6346                &self.paint_proxy,
6347            );
6348        }
6349
6350        debug!("{}: Closed", pipeline_id);
6351    }
6352
6353    // Randomly close a pipeline -if --random-pipeline-closure-probability is set
6354    fn maybe_close_random_pipeline(&mut self) {
6355        match self.random_pipeline_closure {
6356            Some((ref mut rng, probability)) => {
6357                if probability <= rng.random::<f32>() {
6358                    return;
6359                }
6360            },
6361            _ => return,
6362        };
6363        // In order to get repeatability, we sort the pipeline ids.
6364        let mut pipeline_ids: Vec<&PipelineId> = self.pipelines.keys().collect();
6365        pipeline_ids.sort_unstable();
6366        if let Some((ref mut rng, probability)) = self.random_pipeline_closure &&
6367            let Some(pipeline_id) = pipeline_ids.choose(rng) &&
6368            let Some(pipeline) = self.pipelines.get(pipeline_id)
6369        {
6370            if self
6371                .webviews
6372                .values()
6373                .any(|webview| webview.pipeline_is_pending(pipeline.id)) &&
6374                probability <= rng.random::<f32>()
6375            {
6376                // We tend not to close pending pipelines, as that almost always
6377                // results in pipelines being closed early in their lifecycle,
6378                // and not stressing the constellation as much.
6379                // https://github.com/servo/servo/issues/18852
6380                info!("{}: Not closing pending pipeline", pipeline_id);
6381            } else {
6382                // Note that we deliberately do not do any of the tidying up
6383                // associated with closing a pipeline. The constellation should cope!
6384                warn!("{}: Randomly closing pipeline", pipeline_id);
6385                pipeline.send_exit_message_to_script(DiscardBrowsingContext::No);
6386            }
6387        }
6388    }
6389
6390    /// Convert a browsing context to a tree of active pipeline ids, for sending to `Paint`.
6391    #[servo_tracing::instrument(skip_all)]
6392    fn browsing_context_to_sendable(
6393        &self,
6394        browsing_context_id: BrowsingContextId,
6395    ) -> Option<SendableFrameTree> {
6396        self.browsing_contexts
6397            .get(&browsing_context_id)
6398            .and_then(|browsing_context| {
6399                self.pipelines
6400                    .get(&browsing_context.pipeline_id)
6401                    .map(|pipeline| {
6402                        let mut frame_tree = SendableFrameTree {
6403                            pipeline: pipeline.to_sendable(),
6404                            children: vec![],
6405                        };
6406
6407                        for child_browsing_context_id in &pipeline.children {
6408                            if let Some(child) =
6409                                self.browsing_context_to_sendable(*child_browsing_context_id)
6410                            {
6411                                frame_tree.children.push(child);
6412                            }
6413                        }
6414
6415                        frame_tree
6416                    })
6417            })
6418    }
6419
6420    /// Send the frame tree for the given webview to `Paint`.
6421    #[servo_tracing::instrument(skip_all)]
6422    fn set_frame_tree_for_webview(&mut self, webview_id: WebViewId) {
6423        // Note that this function can panic, due to ipc-channel creation failure.
6424        // avoiding this panic would require a mechanism for dealing
6425        // with low-resource scenarios.
6426        let browsing_context_id = BrowsingContextId::from(webview_id);
6427        let Some(frame_tree) = self.browsing_context_to_sendable(browsing_context_id) else {
6428            return;
6429        };
6430
6431        let new_pipeline_id = frame_tree.pipeline.id;
6432
6433        debug!("{}: Sending frame tree", browsing_context_id);
6434        self.paint_proxy
6435            .send(PaintMessage::SetFrameTreeForWebView(webview_id, frame_tree));
6436
6437        let Some(webview) = self.webviews.get_mut(&webview_id) else {
6438            return;
6439        };
6440        if webview.active_top_level_pipeline_id == Some(new_pipeline_id) {
6441            return;
6442        }
6443
6444        let old_pipeline_id = webview.active_top_level_pipeline_id;
6445        let old_epoch = webview.active_top_level_pipeline_epoch;
6446        let new_epoch = old_epoch.next();
6447
6448        let accessibility_active = webview.accessibility_active;
6449
6450        webview.active_top_level_pipeline_id = Some(new_pipeline_id);
6451        webview.active_top_level_pipeline_epoch = new_epoch;
6452
6453        // Deactivate accessibility in the now-inactive top-level document in the WebView.
6454        // This ensures that the document stops sending tree updates, since they will be
6455        // discarded in libservo anyway, and also ensures that when accessibility is
6456        // reactivated, the document sends the whole accessibility tree from scratch.
6457        if let Some(old_pipeline_id) = old_pipeline_id {
6458            self.send_message_to_pipeline(
6459                old_pipeline_id,
6460                ScriptThreadMessage::SetAccessibilityActive(old_pipeline_id, false, old_epoch),
6461                "Set accessibility active after closure",
6462            );
6463        }
6464
6465        // Forward activation to layout for the active top-level document in the WebView.
6466        // There are two sites like this; this is the navigation (or bfcache traversal) site.
6467        self.send_message_to_pipeline(
6468            new_pipeline_id,
6469            ScriptThreadMessage::SetAccessibilityActive(
6470                new_pipeline_id,
6471                accessibility_active,
6472                new_epoch,
6473            ),
6474            "Set accessibility active after closure",
6475        );
6476    }
6477
6478    #[servo_tracing::instrument(skip_all)]
6479    fn handle_media_session_action_msg(&mut self, action: MediaSessionActionType) {
6480        if let Some(media_session_pipeline_id) = self.active_media_session {
6481            self.send_message_to_pipeline(
6482                media_session_pipeline_id,
6483                ScriptThreadMessage::MediaSessionAction(media_session_pipeline_id, action),
6484                "Got media session action request after closure",
6485            );
6486        } else {
6487            error!("Got a media session action but no active media session is registered");
6488        }
6489    }
6490
6491    #[servo_tracing::instrument(skip_all)]
6492    fn handle_set_scroll_states(&self, pipeline_id: PipelineId, scroll_states: ScrollStateUpdate) {
6493        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6494            warn!("Discarding scroll offset update for unknown pipeline");
6495            return;
6496        };
6497        if let Err(error) = pipeline
6498            .event_loop
6499            .send(ScriptThreadMessage::SetScrollStates(
6500                pipeline_id,
6501                scroll_states,
6502            ))
6503        {
6504            warn!("Could not send scroll offsets to pipeline: {pipeline_id:?}: {error:?}");
6505        }
6506    }
6507
6508    #[servo_tracing::instrument(skip_all)]
6509    fn handle_paint_metric(&mut self, pipeline_id: PipelineId, event: PaintMetricEvent) {
6510        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6511            warn!("Discarding paint metric event for unknown pipeline");
6512            return;
6513        };
6514        if let Err(error) = pipeline
6515            .event_loop
6516            .send(ScriptThreadMessage::PaintMetric(pipeline_id, event))
6517        {
6518            warn!("Could not send paint metric event to pipeline: {pipeline_id:?}: {error:?}");
6519        }
6520    }
6521
6522    fn create_canvas_paint_thread(
6523        &self,
6524    ) -> (Sender<ConstellationCanvasMsg>, GenericSender<CanvasMsg>) {
6525        CanvasPaintThread::start(
6526            self.paint_proxy.cross_process_paint_api.clone(),
6527            self.mem_profiler_chan.clone(),
6528        )
6529    }
6530
6531    fn handle_embedder_control_response(
6532        &self,
6533        id: EmbedderControlId,
6534        response: EmbedderControlResponse,
6535    ) {
6536        let pipeline_id = id.pipeline_id;
6537        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6538            warn!("Not sending embedder control response for unknown pipeline {pipeline_id:?}");
6539            return;
6540        };
6541
6542        if let Err(error) = pipeline
6543            .event_loop
6544            .send(ScriptThreadMessage::EmbedderControlResponse(id, response))
6545        {
6546            warn!(
6547                "Could not send embedder control response to pipeline {pipeline_id:?}: {error:?}"
6548            );
6549        }
6550    }
6551
6552    fn handle_update_pinch_zoom_infos(
6553        &self,
6554        pipeline_id: PipelineId,
6555        pinch_zoom_infos: PinchZoomInfos,
6556    ) {
6557        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
6558            warn!("Discarding pinch zoom update for unknown pipeline");
6559            return;
6560        };
6561        if let Err(error) = pipeline
6562            .event_loop
6563            .send(ScriptThreadMessage::UpdatePinchZoomInfos(
6564                pipeline_id,
6565                pinch_zoom_infos,
6566            ))
6567        {
6568            warn!("Could not send pinch zoom update to pipeline: {pipeline_id:?}: {error:?}");
6569        }
6570    }
6571
6572    #[cfg(feature = "devtools")]
6573    pub(crate) fn script_to_devtools_callback(
6574        &self,
6575    ) -> Option<GenericCallback<ScriptToDevtoolsControlMsg>> {
6576        self.script_to_devtools_callback
6577            .get_or_init(|| {
6578                self.devtools_sender.as_ref().and_then(|devtools_sender| {
6579                    let devtools_sender = devtools_sender.clone();
6580                    let callback = GenericCallback::new(move |message| match message {
6581                        Err(error) => {
6582                            error!("Cast to ScriptToDevtoolsControlMsg failed ({error}).")
6583                        },
6584                        Ok(message) => {
6585                            if let Err(error) =
6586                                devtools_sender.send(DevtoolsControlMsg::FromScript(message))
6587                            {
6588                                warn!("Sending to devtools failed ({error:?})")
6589                            }
6590                        },
6591                    });
6592                    match callback {
6593                        Ok(callback) => Some(callback),
6594                        Err(error) => {
6595                            error!("Could not create Devtools communication channel: {error}");
6596                            None
6597                        },
6598                    }
6599                })
6600            })
6601            .clone()
6602    }
6603
6604    fn handle_set_network_online_state(&mut self, online: bool) {
6605        let previously_online = std::mem::replace(&mut self.online, online);
6606        if previously_online == online {
6607            return;
6608        }
6609
6610        for event_loop in self.event_loops() {
6611            if let Err(error) = event_loop.send(ScriptThreadMessage::SetNetworkOnlineState(online))
6612            {
6613                error!("Could not send network online state to event loop: {error}");
6614            }
6615        }
6616
6617        for service_worker_manager in self.sw_managers.values() {
6618            if let Err(error) =
6619                service_worker_manager.send(ServiceWorkerMsg::SetNetworkOnlineState(online))
6620            {
6621                error!("Could not send network online state to service worker: {error}");
6622            }
6623        }
6624    }
6625}