constellation_traits/
from_script_message.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//! Messages send from the ScriptThread to the Constellation.
6
7use std::fmt;
8
9use base::Epoch;
10use base::generic_channel::{GenericCallback, GenericReceiver, GenericSender, SendResult};
11use base::id::{
12    BroadcastChannelRouterId, BrowsingContextId, HistoryStateId, MessagePortId,
13    MessagePortRouterId, PipelineId, ServiceWorkerId, ServiceWorkerRegistrationId, WebViewId,
14};
15use canvas_traits::canvas::{CanvasId, CanvasMsg};
16use compositing_traits::CrossProcessCompositorApi;
17use content_security_policy::sandboxing_directive::SandboxingFlagSet;
18use devtools_traits::{DevtoolScriptControlMsg, ScriptToDevtoolsControlMsg, WorkerId};
19use embedder_traits::{
20    AnimationState, FocusSequenceNumber, JSValue, JavaScriptEvaluationError,
21    JavaScriptEvaluationId, MediaSessionEvent, ScriptToEmbedderChan, Theme, ViewportDetails,
22};
23use euclid::default::Size2D as UntypedSize2D;
24use fonts_traits::SystemFontServiceProxySender;
25use http::{HeaderMap, Method};
26use ipc_channel::ipc::IpcSender;
27use malloc_size_of_derive::MallocSizeOf;
28use net_traits::policy_container::PolicyContainer;
29use net_traits::request::{Destination, InsecureRequestsPolicy, Referrer, RequestBody};
30use net_traits::{ReferrerPolicy, ResourceThreads};
31use profile_traits::mem::MemoryReportResult;
32use profile_traits::{mem, time as profile_time};
33use rustc_hash::FxHashMap;
34use serde::{Deserialize, Serialize};
35use servo_url::{ImmutableOrigin, ServoUrl};
36use storage_traits::StorageThreads;
37use storage_traits::webstorage_thread::StorageType;
38use strum_macros::IntoStaticStr;
39#[cfg(feature = "webgpu")]
40use webgpu_traits::{WebGPU, WebGPUAdapterResponse};
41
42use crate::structured_data::{BroadcastChannelMsg, StructuredSerializedData};
43use crate::{
44    LogEntry, MessagePortMsg, PortMessageTask, PortTransferInfo, TraversalDirection, WindowSizeType,
45};
46
47/// A Script to Constellation channel.
48#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
49pub struct ScriptToConstellationChan {
50    /// Sender for communicating with constellation thread.
51    pub sender: GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
52    /// Used to identify the origin `WebView` of the message.
53    pub webview_id: WebViewId,
54    /// Used to identify the origin `Pipeline` of the message.
55    pub pipeline_id: PipelineId,
56}
57
58impl ScriptToConstellationChan {
59    /// Send ScriptMsg and attach the pipeline_id to the message.
60    pub fn send(&self, msg: ScriptToConstellationMessage) -> SendResult {
61        self.sender.send((self.webview_id, self.pipeline_id, msg))
62    }
63}
64
65/// The origin where a given load was initiated.
66/// Useful for origin checks, for example before evaluation a JS URL.
67#[derive(Clone, Debug, Deserialize, Serialize)]
68pub enum LoadOrigin {
69    /// A load originating in the constellation.
70    Constellation,
71    /// A load originating in webdriver.
72    WebDriver,
73    /// A load originating in script.
74    Script(ImmutableOrigin),
75}
76
77/// can be passed to `LoadUrl` to load a page with GET/POST
78/// parameters or headers
79#[derive(Clone, Debug, Deserialize, Serialize)]
80pub struct LoadData {
81    /// The origin where the load started.
82    pub load_origin: LoadOrigin,
83    /// The URL.
84    pub url: ServoUrl,
85    /// The creator pipeline id if this is an about:blank load.
86    pub creator_pipeline_id: Option<PipelineId>,
87    /// The method.
88    #[serde(
89        deserialize_with = "::hyper_serde::deserialize",
90        serialize_with = "::hyper_serde::serialize"
91    )]
92    pub method: Method,
93    /// The headers.
94    #[serde(
95        deserialize_with = "::hyper_serde::deserialize",
96        serialize_with = "::hyper_serde::serialize"
97    )]
98    pub headers: HeaderMap,
99    /// The data that will be used as the body of the request.
100    pub data: Option<RequestBody>,
101    /// The result of evaluating a javascript scheme url.
102    pub js_eval_result: Option<JsEvalResult>,
103    /// The referrer.
104    pub referrer: Referrer,
105    /// The referrer policy.
106    pub referrer_policy: ReferrerPolicy,
107    /// The policy container.
108    pub policy_container: Option<PolicyContainer>,
109
110    /// The source to use instead of a network response for a srcdoc document.
111    pub srcdoc: String,
112    /// The inherited context is Secure, None if not inherited
113    pub inherited_secure_context: Option<bool>,
114    /// The inherited policy for upgrading insecure requests; None if not inherited.
115    pub inherited_insecure_requests_policy: Option<InsecureRequestsPolicy>,
116    /// Whether the page's ancestors have potentially trustworthy origin
117    pub has_trustworthy_ancestor_origin: bool,
118    /// Servo internal: if crash details are present, trigger a crash error page with these details.
119    pub crash: Option<String>,
120    /// Destination, used for CSP checks
121    pub destination: Destination,
122    /// The "creation sandboxing flag set" that this Pipeline should use when it is created.
123    /// See <https://html.spec.whatwg.org/multipage/#determining-the-creation-sandboxing-flags>.
124    pub creation_sandboxing_flag_set: SandboxingFlagSet,
125}
126
127/// The result of evaluating a javascript scheme url.
128#[derive(Clone, Debug, Deserialize, Serialize)]
129pub enum JsEvalResult {
130    /// The js evaluation had a non-string result, 204 status code.
131    /// <https://html.spec.whatwg.org/multipage/#navigate> 12.11
132    NoContent,
133    /// The js evaluation had a string result.
134    Ok(Vec<u8>),
135}
136
137impl LoadData {
138    /// Create a new `LoadData` object.
139    #[allow(clippy::too_many_arguments)]
140    pub fn new(
141        load_origin: LoadOrigin,
142        url: ServoUrl,
143        creator_pipeline_id: Option<PipelineId>,
144        referrer: Referrer,
145        referrer_policy: ReferrerPolicy,
146        inherited_secure_context: Option<bool>,
147        inherited_insecure_requests_policy: Option<InsecureRequestsPolicy>,
148        has_trustworthy_ancestor_origin: bool,
149        creation_sandboxing_flag_set: SandboxingFlagSet,
150    ) -> Self {
151        Self {
152            load_origin,
153            url,
154            creator_pipeline_id,
155            method: Method::GET,
156            headers: HeaderMap::new(),
157            data: None,
158            js_eval_result: None,
159            referrer,
160            referrer_policy,
161            policy_container: None,
162            srcdoc: "".to_string(),
163            inherited_secure_context,
164            crash: None,
165            inherited_insecure_requests_policy,
166            has_trustworthy_ancestor_origin,
167            destination: Destination::Document,
168            creation_sandboxing_flag_set,
169        }
170    }
171
172    /// Create a new [`LoadData`] for a completely new top-level `WebView` that isn't created
173    /// via APIs like `window.open`. This is for `WebView`s completely unrelated to others.
174    pub fn new_for_new_unrelated_webview(url: ServoUrl) -> Self {
175        Self::new(
176            LoadOrigin::Constellation,
177            url,
178            None,
179            Referrer::NoReferrer,
180            ReferrerPolicy::EmptyString,
181            None,
182            None,
183            false,
184            SandboxingFlagSet::empty(),
185        )
186    }
187}
188
189/// <https://html.spec.whatwg.org/multipage/#navigation-supporting-concepts:navigationhistorybehavior>
190#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
191pub enum NavigationHistoryBehavior {
192    /// The default value, which will be converted very early in the navigate algorithm into "push"
193    /// or "replace". Usually it becomes "push", but under certain circumstances it becomes
194    /// "replace" instead.
195    #[default]
196    Auto,
197    /// A regular navigation which adds a new session history entry, and will clear the forward
198    /// session history.
199    Push,
200    /// A navigation that will replace the active session history entry.
201    Replace,
202}
203
204/// Entities required to spawn service workers
205#[derive(Clone, Debug, Deserialize, Serialize)]
206pub struct ScopeThings {
207    /// script resource url
208    pub script_url: ServoUrl,
209    /// network load origin of the resource
210    pub worker_load_origin: WorkerScriptLoadOrigin,
211    /// base resources required to create worker global scopes
212    pub init: WorkerGlobalScopeInit,
213    /// the port to receive devtools message from
214    pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
215    /// service worker id
216    pub worker_id: WorkerId,
217}
218
219/// Message that gets passed to service worker scope on postMessage
220#[derive(Debug, Deserialize, Serialize)]
221pub struct DOMMessage {
222    /// The origin of the message
223    pub origin: ImmutableOrigin,
224    /// The payload of the message
225    pub data: StructuredSerializedData,
226}
227
228/// Channels to allow service worker manager to communicate with constellation and resource thread
229#[derive(Deserialize, Serialize)]
230pub struct SWManagerSenders {
231    /// Sender of messages to the constellation.
232    pub swmanager_sender: GenericSender<SWManagerMsg>,
233    /// [`ResourceThreads`] for initating fetches or using i/o.
234    pub resource_threads: ResourceThreads,
235    /// [`CrossProcessCompositorApi`] for communicating with the compositor.
236    pub compositor_api: CrossProcessCompositorApi,
237    /// The [`SystemFontServiceProxy`] used to communicate with the `SystemFontService`.
238    pub system_font_service_sender: SystemFontServiceProxySender,
239    /// Sender of messages to the manager.
240    pub own_sender: GenericSender<ServiceWorkerMsg>,
241    /// Receiver of messages from the constellation.
242    pub receiver: GenericReceiver<ServiceWorkerMsg>,
243}
244
245/// Messages sent to Service Worker Manager thread
246#[derive(Debug, Deserialize, Serialize)]
247#[allow(clippy::large_enum_variant)]
248pub enum ServiceWorkerMsg {
249    /// Timeout message sent by active service workers
250    Timeout(ServoUrl),
251    /// Message sent by constellation to forward to a running service worker
252    ForwardDOMMessage(DOMMessage, ServoUrl),
253    /// <https://w3c.github.io/ServiceWorker/#schedule-job-algorithm>
254    ScheduleJob(Job),
255    /// Exit the service worker manager
256    Exit,
257}
258
259#[derive(Debug, Deserialize, PartialEq, Serialize)]
260/// <https://w3c.github.io/ServiceWorker/#dfn-job-type>
261pub enum JobType {
262    /// <https://w3c.github.io/ServiceWorker/#register>
263    Register,
264    /// <https://w3c.github.io/ServiceWorker/#unregister-algorithm>
265    Unregister,
266    /// <https://w3c.github.io/ServiceWorker/#update-algorithm>
267    Update,
268}
269
270#[derive(Debug, Deserialize, Serialize)]
271/// The kind of error the job promise should be rejected with.
272pub enum JobError {
273    /// <https://w3c.github.io/ServiceWorker/#reject-job-promise>
274    TypeError,
275    /// <https://w3c.github.io/ServiceWorker/#reject-job-promise>
276    SecurityError,
277}
278
279#[derive(Debug, Deserialize, Serialize)]
280#[allow(clippy::large_enum_variant)]
281/// Messages sent from Job algorithms steps running in the SW manager,
282/// in order to resolve or reject the job promise.
283pub enum JobResult {
284    /// <https://w3c.github.io/ServiceWorker/#reject-job-promise>
285    RejectPromise(JobError),
286    /// <https://w3c.github.io/ServiceWorker/#resolve-job-promise>
287    ResolvePromise(Job, JobResultValue),
288}
289
290#[derive(Debug, Deserialize, Serialize)]
291/// Jobs are resolved with the help of various values.
292pub enum JobResultValue {
293    /// Data representing a serviceworker registration.
294    Registration {
295        /// The Id of the registration.
296        id: ServiceWorkerRegistrationId,
297        /// The installing worker, if any.
298        installing_worker: Option<ServiceWorkerId>,
299        /// The waiting worker, if any.
300        waiting_worker: Option<ServiceWorkerId>,
301        /// The active worker, if any.
302        active_worker: Option<ServiceWorkerId>,
303    },
304}
305
306#[derive(Debug, Deserialize, Serialize)]
307/// <https://w3c.github.io/ServiceWorker/#dfn-job>
308pub struct Job {
309    /// <https://w3c.github.io/ServiceWorker/#dfn-job-type>
310    pub job_type: JobType,
311    /// <https://w3c.github.io/ServiceWorker/#dfn-job-scope-url>
312    pub scope_url: ServoUrl,
313    /// <https://w3c.github.io/ServiceWorker/#dfn-job-script-url>
314    pub script_url: ServoUrl,
315    /// <https://w3c.github.io/ServiceWorker/#dfn-job-client>
316    pub client: GenericCallback<JobResult>,
317    /// <https://w3c.github.io/ServiceWorker/#job-referrer>
318    pub referrer: ServoUrl,
319    /// Various data needed to process job.
320    pub scope_things: Option<ScopeThings>,
321}
322
323impl Job {
324    /// <https://w3c.github.io/ServiceWorker/#create-job-algorithm>
325    pub fn create_job(
326        job_type: JobType,
327        scope_url: ServoUrl,
328        script_url: ServoUrl,
329        client: GenericCallback<JobResult>,
330        referrer: ServoUrl,
331        scope_things: Option<ScopeThings>,
332    ) -> Job {
333        Job {
334            job_type,
335            scope_url,
336            script_url,
337            client,
338            referrer,
339            scope_things,
340        }
341    }
342}
343
344impl PartialEq for Job {
345    /// Equality criteria as described in <https://w3c.github.io/ServiceWorker/#dfn-job-equivalent>
346    fn eq(&self, other: &Self) -> bool {
347        // TODO: match on job type, take worker type and `update_via_cache_mode` into account.
348        let same_job = self.job_type == other.job_type;
349        if same_job {
350            match self.job_type {
351                JobType::Register | JobType::Update => {
352                    self.scope_url == other.scope_url && self.script_url == other.script_url
353                },
354                JobType::Unregister => self.scope_url == other.scope_url,
355            }
356        } else {
357            false
358        }
359    }
360}
361
362/// Messages outgoing from the Service Worker Manager thread to constellation
363#[derive(Debug, Deserialize, Serialize)]
364pub enum SWManagerMsg {
365    /// Placeholder to keep the enum,
366    /// as it will be needed when implementing
367    /// <https://github.com/servo/servo/issues/24660>
368    PostMessageToClient,
369}
370
371/// Used to determine if a script has any pending asynchronous activity.
372#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
373pub enum DocumentState {
374    /// The document has been loaded and is idle.
375    Idle,
376    /// The document is either loading or waiting on an event.
377    Pending,
378}
379
380/// This trait allows creating a `ServiceWorkerManager` without depending on the `script`
381/// crate.
382pub trait ServiceWorkerManagerFactory {
383    /// Create a `ServiceWorkerManager`.
384    fn create(sw_senders: SWManagerSenders, origin: ImmutableOrigin);
385}
386
387/// Specifies the information required to load an auxiliary browsing context.
388#[derive(Debug, Deserialize, Serialize)]
389pub struct AuxiliaryWebViewCreationRequest {
390    /// Load data containing the url to load
391    pub load_data: LoadData,
392    /// The webview that caused this request.
393    pub opener_webview_id: WebViewId,
394    /// The pipeline opener browsing context.
395    pub opener_pipeline_id: PipelineId,
396    /// Sender for the constellation’s response to our request.
397    pub response_sender: IpcSender<Option<AuxiliaryWebViewCreationResponse>>,
398}
399
400/// Constellation’s response to auxiliary browsing context creation requests.
401#[derive(Debug, Deserialize, Serialize)]
402pub struct AuxiliaryWebViewCreationResponse {
403    /// The new webview ID.
404    pub new_webview_id: WebViewId,
405    /// The new pipeline ID.
406    pub new_pipeline_id: PipelineId,
407}
408
409/// Specifies the information required to load an iframe.
410#[derive(Debug, Deserialize, Serialize)]
411pub struct IFrameLoadInfo {
412    /// Pipeline ID of the parent of this iframe
413    pub parent_pipeline_id: PipelineId,
414    /// The ID for this iframe's nested browsing context.
415    pub browsing_context_id: BrowsingContextId,
416    /// The ID for the top-level ancestor browsing context of this iframe's nested browsing context.
417    pub webview_id: WebViewId,
418    /// The new pipeline ID that the iframe has generated.
419    pub new_pipeline_id: PipelineId,
420    ///  Whether this iframe should be considered private
421    pub is_private: bool,
422    ///  Whether this iframe should be considered secure
423    pub inherited_secure_context: Option<bool>,
424    /// Whether this load should replace the current entry (reload). If true, the current
425    /// entry will be replaced instead of a new entry being added.
426    pub history_handling: NavigationHistoryBehavior,
427}
428
429/// Specifies the information required to load a URL in an iframe.
430#[derive(Debug, Deserialize, Serialize)]
431pub struct IFrameLoadInfoWithData {
432    /// The information required to load an iframe.
433    pub info: IFrameLoadInfo,
434    /// Load data containing the url to load
435    pub load_data: LoadData,
436    /// The old pipeline ID for this iframe, if a page was previously loaded.
437    pub old_pipeline_id: Option<PipelineId>,
438    /// The initial viewport size for this iframe.
439    pub viewport_details: ViewportDetails,
440    /// The [`Theme`] to use within this iframe.
441    pub theme: Theme,
442}
443
444/// Resources required by workerglobalscopes
445#[derive(Clone, Debug, Deserialize, Serialize)]
446pub struct WorkerGlobalScopeInit {
447    /// Chan to a resource thread
448    pub resource_threads: ResourceThreads,
449    /// Chan to a storage thread
450    pub storage_threads: StorageThreads,
451    /// Chan to the memory profiler
452    pub mem_profiler_chan: mem::ProfilerChan,
453    /// Chan to the time profiler
454    pub time_profiler_chan: profile_time::ProfilerChan,
455    /// To devtools sender
456    pub to_devtools_sender: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
457    /// From devtools sender
458    pub from_devtools_sender: Option<IpcSender<DevtoolScriptControlMsg>>,
459    /// Messages to send to constellation
460    pub script_to_constellation_chan: ScriptToConstellationChan,
461    /// Messages to send to the Embedder
462    pub script_to_embedder_chan: ScriptToEmbedderChan,
463    /// The worker id
464    pub worker_id: WorkerId,
465    /// The pipeline id
466    pub pipeline_id: PipelineId,
467    /// The origin
468    pub origin: ImmutableOrigin,
469    /// The creation URL
470    pub creation_url: ServoUrl,
471    /// True if secure context
472    pub inherited_secure_context: Option<bool>,
473    /// Unminify Javascript.
474    pub unminify_js: bool,
475}
476
477/// Common entities representing a network load origin
478#[derive(Clone, Debug, Deserialize, Serialize)]
479pub struct WorkerScriptLoadOrigin {
480    /// referrer url
481    pub referrer_url: Option<ServoUrl>,
482    /// the referrer policy which is used
483    pub referrer_policy: ReferrerPolicy,
484    /// the pipeline id of the entity requesting the load
485    pub pipeline_id: PipelineId,
486}
487
488/// An iframe sizing operation.
489#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
490pub struct IFrameSizeMsg {
491    /// The child browsing context for this iframe.
492    pub browsing_context_id: BrowsingContextId,
493    /// The size and scale factor of the iframe.
494    pub size: ViewportDetails,
495    /// The kind of sizing operation.
496    pub type_: WindowSizeType,
497}
498
499/// An enum that describe a type of keyboard scroll.
500#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
501pub enum KeyboardScroll {
502    /// Scroll the container one line up.
503    Up,
504    /// Scroll the container one line down.
505    Down,
506    /// Scroll the container one "line" left.
507    Left,
508    /// Scroll the container one "line" right.
509    Right,
510    /// Scroll the container one page up.
511    PageUp,
512    /// Scroll the container one page down.
513    PageDown,
514    /// Scroll the container to the vertical start.
515    Home,
516    /// Scroll the container to the vertical end.
517    End,
518}
519
520#[derive(Debug, Deserialize, Serialize)]
521pub enum ScreenshotReadinessResponse {
522    /// The Pipeline associated with this response, is ready for a screenshot at the
523    /// provided [`Epoch`].
524    Ready(Epoch),
525    /// The Pipeline associated with this response is no longer active and should be
526    /// ignored for the purposes of the screenshot.
527    NoLongerActive,
528}
529
530/// Messages from the script to the constellation.
531#[derive(Deserialize, IntoStaticStr, Serialize)]
532pub enum ScriptToConstellationMessage {
533    /// Request to complete the transfer of a set of ports to a router.
534    CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>),
535    /// The results of attempting to complete the transfer of a batch of ports.
536    MessagePortTransferResult(
537        /* The router whose transfer of ports succeeded, if any */
538        Option<MessagePortRouterId>,
539        /* The ids of ports transferred successfully */
540        Vec<MessagePortId>,
541        /* The ids, and buffers, of ports whose transfer failed */
542        FxHashMap<MessagePortId, PortTransferInfo>,
543    ),
544    /// A new message-port was created or transferred, with corresponding control-sender.
545    NewMessagePort(MessagePortRouterId, MessagePortId),
546    /// A global has started managing message-ports
547    NewMessagePortRouter(MessagePortRouterId, IpcSender<MessagePortMsg>),
548    /// A global has stopped managing message-ports
549    RemoveMessagePortRouter(MessagePortRouterId),
550    /// A task requires re-routing to an already shipped message-port.
551    RerouteMessagePort(MessagePortId, PortMessageTask),
552    /// A message-port was shipped, let the entangled port know.
553    MessagePortShipped(MessagePortId),
554    /// Entangle two message-ports.
555    EntanglePorts(MessagePortId, MessagePortId),
556    /// Disentangle two message-ports.
557    /// The first is the initiator, the second the other port,
558    /// unless the message is sent to complete a disentanglement,
559    /// in which case the first one is the other port,
560    /// and the second is none.
561    DisentanglePorts(MessagePortId, Option<MessagePortId>),
562    /// A global has started managing broadcast-channels.
563    NewBroadcastChannelRouter(
564        BroadcastChannelRouterId,
565        IpcSender<BroadcastChannelMsg>,
566        ImmutableOrigin,
567    ),
568    /// A global has stopped managing broadcast-channels.
569    RemoveBroadcastChannelRouter(BroadcastChannelRouterId, ImmutableOrigin),
570    /// A global started managing broadcast channels for a given channel-name.
571    NewBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
572    /// A global stopped managing broadcast channels for a given channel-name.
573    RemoveBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
574    /// Broadcast a message to all same-origin broadcast channels,
575    /// excluding the source of the broadcast.
576    ScheduleBroadcast(BroadcastChannelRouterId, BroadcastChannelMsg),
577    /// Broadcast a storage event to every same-origin pipeline.
578    /// The strings are key, old value and new value.
579    BroadcastStorageEvent(
580        StorageType,
581        ServoUrl,
582        Option<String>,
583        Option<String>,
584        Option<String>,
585    ),
586    /// Indicates whether this pipeline is currently running animations.
587    ChangeRunningAnimationsState(AnimationState),
588    /// Requests that a new 2D canvas thread be created. (This is done in the constellation because
589    /// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
590    CreateCanvasPaintThread(
591        UntypedSize2D<u64>,
592        IpcSender<Option<(GenericSender<CanvasMsg>, CanvasId)>>,
593    ),
594    /// Notifies the constellation that this pipeline is requesting focus.
595    ///
596    /// When this message is sent, the sender pipeline has already its local
597    /// focus state updated. The constellation, after receiving this message,
598    /// will broadcast messages to other pipelines that are affected by this
599    /// focus operation.
600    ///
601    /// The first field contains the browsing context ID of the container
602    /// element if one was focused.
603    ///
604    /// The second field is a sequence number that the constellation should use
605    /// when sending a focus-related message to the sender pipeline next time.
606    Focus(Option<BrowsingContextId>, FocusSequenceNumber),
607    /// Requests the constellation to focus the specified browsing context.
608    FocusRemoteDocument(BrowsingContextId),
609    /// Get the top-level browsing context info for a given browsing context.
610    GetTopForBrowsingContext(BrowsingContextId, IpcSender<Option<WebViewId>>),
611    /// Get the browsing context id of the browsing context in which pipeline is
612    /// embedded and the parent pipeline id of that browsing context.
613    GetBrowsingContextInfo(
614        PipelineId,
615        IpcSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
616    ),
617    /// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
618    GetChildBrowsingContextId(
619        BrowsingContextId,
620        usize,
621        IpcSender<Option<BrowsingContextId>>,
622    ),
623    /// All pending loads are complete, and the `load` event for this pipeline
624    /// has been dispatched.
625    LoadComplete,
626    /// A new load has been requested, with an option to replace the current entry once loaded
627    /// instead of adding a new entry.
628    LoadUrl(LoadData, NavigationHistoryBehavior),
629    /// Abort loading after sending a LoadUrl message.
630    AbortLoadUrl,
631    /// Post a message to the currently active window of a given browsing context.
632    PostMessage {
633        /// The target of the posted message.
634        target: BrowsingContextId,
635        /// The source of the posted message.
636        source: PipelineId,
637        /// The expected origin of the target.
638        target_origin: Option<ImmutableOrigin>,
639        /// The source origin of the message.
640        /// <https://html.spec.whatwg.org/multipage/#dom-messageevent-origin>
641        source_origin: ImmutableOrigin,
642        /// The data to be posted.
643        data: StructuredSerializedData,
644    },
645    /// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
646    NavigatedToFragment(ServoUrl, NavigationHistoryBehavior),
647    /// HTMLIFrameElement Forward or Back traversal.
648    TraverseHistory(TraversalDirection),
649    /// Inform the constellation of a pushed history state.
650    PushHistoryState(HistoryStateId, ServoUrl),
651    /// Inform the constellation of a replaced history state.
652    ReplaceHistoryState(HistoryStateId, ServoUrl),
653    /// Gets the length of the joint session history from the constellation.
654    JointSessionHistoryLength(IpcSender<u32>),
655    /// Notification that this iframe should be removed.
656    /// Returns a list of pipelines which were closed.
657    RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
658    /// Successful response to [crate::ConstellationControlMsg::SetThrottled].
659    SetThrottledComplete(bool),
660    /// A load has been requested in an IFrame.
661    ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
662    /// A load of the initial `about:blank` has been completed in an IFrame.
663    ScriptNewIFrame(IFrameLoadInfoWithData),
664    /// Script has opened a new auxiliary browsing context.
665    CreateAuxiliaryWebView(AuxiliaryWebViewCreationRequest),
666    /// Mark a new document as active
667    ActivateDocument,
668    /// Set the document state for a pipeline (used by screenshot / reftests)
669    SetDocumentState(DocumentState),
670    /// Update the pipeline Url, which can change after redirections.
671    SetFinalUrl(ServoUrl),
672    /// A log entry, with the top-level browsing context id and thread name
673    LogEntry(Option<String>, LogEntry),
674    /// Discard the document.
675    DiscardDocument,
676    /// Discard the browsing context.
677    DiscardTopLevelBrowsingContext,
678    /// Notifies the constellation that this pipeline has exited.
679    PipelineExited,
680    /// Send messages from postMessage calls from serviceworker
681    /// to constellation for storing in service worker manager
682    ForwardDOMMessage(DOMMessage, ServoUrl),
683    /// <https://w3c.github.io/ServiceWorker/#schedule-job-algorithm>
684    ScheduleJob(Job),
685    /// Notifies the constellation about media session events
686    /// (i.e. when there is metadata for the active media session, playback state changes...).
687    MediaSessionEvent(PipelineId, MediaSessionEvent),
688    #[cfg(feature = "webgpu")]
689    /// Create a WebGPU Adapter instance
690    RequestAdapter(
691        IpcSender<WebGPUAdapterResponse>,
692        wgpu_core::instance::RequestAdapterOptions,
693        wgpu_core::id::AdapterId,
694    ),
695    #[cfg(feature = "webgpu")]
696    /// Get WebGPU channel
697    GetWebGPUChan(IpcSender<Option<WebGPU>>),
698    /// Notify the constellation of a pipeline's document's title.
699    TitleChanged(PipelineId, String),
700    /// Notify the constellation that the size of some `<iframe>`s has changed.
701    IFrameSizes(Vec<IFrameSizeMsg>),
702    /// Request results from the memory reporter.
703    ReportMemory(IpcSender<MemoryReportResult>),
704    /// Return the result of the evaluated JavaScript with the given [`JavaScriptEvaluationId`].
705    FinishJavaScriptEvaluation(
706        JavaScriptEvaluationId,
707        Result<JSValue, JavaScriptEvaluationError>,
708    ),
709    /// Forward a keyboard scroll operation from an `<iframe>` to a parent pipeline.
710    ForwardKeyboardScroll(PipelineId, KeyboardScroll),
711    /// Notify the Constellation of the screenshot readiness of a given pipeline.
712    RespondToScreenshotReadinessRequest(ScreenshotReadinessResponse),
713}
714
715impl fmt::Debug for ScriptToConstellationMessage {
716    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
717        let variant_string: &'static str = self.into();
718        write!(formatter, "ScriptMsg::{variant_string}")
719    }
720}