Skip to main content

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