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