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, MallocSizeOf, 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    pub pipeline_id: PipelineId,
236    /// The payload of the message
237    pub data: StructuredSerializedData,
238}
239
240/// Channels to allow service worker manager to communicate with constellation and resource thread
241#[derive(Deserialize, Serialize)]
242pub struct SWManagerSenders {
243    /// [`ResourceThreads`] for initating fetches or using i/o.
244    pub resource_threads: ResourceThreads,
245    /// [`CrossProcessPaintApi`] for communicating with `Paint`.
246    pub paint_api: CrossProcessPaintApi,
247    /// The [`SystemFontServiceProxy`] used to communicate with the `SystemFontService`.
248    pub system_font_service_sender: SystemFontServiceProxySender,
249    /// Sender of messages to the manager.
250    pub own_sender: GenericSender<ServiceWorkerMsg>,
251    /// Receiver of messages from the constellation.
252    pub receiver: GenericReceiver<ServiceWorkerMsg>,
253}
254
255/// Messages sent to Service Worker Manager thread
256#[derive(Debug, Deserialize, Serialize)]
257pub enum ServiceWorkerMsg {
258    /// Timeout message sent by active service workers
259    Timeout(ServoUrl),
260    /// Message sent by constellation to forward to a running service worker
261    ForwardDOMMessage(DOMMessage, ServoUrl),
262    ForwardWorkerMessage {
263        data: StructuredSerializedData,
264        url: ServoUrl,
265        source: ServiceWorkerId,
266        origin: ImmutableOrigin,
267    },
268    /// <https://w3c.github.io/ServiceWorker/#algorithms>
269    HandleAlgorithm(ServiceWorkerAlgorithm),
270    /// Exit the service worker manager
271    Exit,
272}
273
274#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
275/// <https://w3c.github.io/ServiceWorker/#dfn-job-type>
276pub enum JobType {
277    /// <https://w3c.github.io/ServiceWorker/#register>
278    Register,
279    /// <https://w3c.github.io/ServiceWorker/#unregister-algorithm>
280    Unregister,
281    /// <https://w3c.github.io/ServiceWorker/#update-algorithm>
282    Update,
283}
284
285#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
286/// The kind of error the job promise should be rejected with.
287pub enum JobError {
288    /// <https://w3c.github.io/ServiceWorker/#reject-job-promise>
289    TypeError,
290    /// <https://w3c.github.io/ServiceWorker/#reject-job-promise>
291    SecurityError,
292}
293
294#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
295/// Messages sent from Job algorithms steps running in the SW manager,
296/// in order to resolve or reject the job promise.
297pub enum JobResult {
298    /// <https://w3c.github.io/ServiceWorker/#reject-job-promise>
299    RejectPromise(JobError),
300    /// <https://w3c.github.io/ServiceWorker/#resolve-job-promise>
301    ResolvePromise(JobResultValue),
302}
303
304#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
305/// Jobs are resolved with the help of various values.
306pub enum JobResultValue {
307    Register(ServiceWorkerRegistrationInfo),
308    Unregister(bool),
309}
310
311/// <https://w3c.github.io/ServiceWorker/#dfn-service-worker-registration>
312#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
313pub struct ServiceWorkerRegistrationInfo {
314    /// The Id of the registration.
315    pub id: ServiceWorkerRegistrationId,
316    /// <https://w3c.github.io/ServiceWorker/#dfn-installing-worker>
317    pub installing_worker: Option<ServiceWorkerId>,
318    /// <https://w3c.github.io/ServiceWorker/#dfn-waiting-worker>
319    pub waiting_worker: Option<ServiceWorkerId>,
320    /// <https://w3c.github.io/ServiceWorker/#dfn-active-worker>
321    pub active_worker: Option<ServiceWorkerId>,
322    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-storage-key>
323    pub storage_key: ImmutableOrigin,
324    /// <https://w3c.github.io/ServiceWorker/#dfn-scope-url>
325    pub scope_url: ServoUrl,
326    /// <https://w3c.github.io/ServiceWorker/#dfn-job-script-url>
327    pub script_url: ServoUrl,
328}
329
330/// <https://w3c.github.io/ServiceWorker/#algorithms>
331#[derive(Debug, Deserialize, Serialize)]
332pub enum ServiceWorkerAlgorithm {
333    /// <https://w3c.github.io/ServiceWorker/#start-register>
334    StartRegister(Job),
335    /// <https://w3c.github.io/ServiceWorker/#unregister>
336    Unregister(Job),
337    /// <https://w3c.github.io/ServiceWorker/#match-service-worker-registration>
338    MatchServiceWorkerRegistration {
339        storage_key: ImmutableOrigin,
340        client_url: ServoUrl,
341        result_handler: GenericCallback<ServiceWorkerAlgorithmResult>,
342    },
343}
344
345/// <https://w3c.github.io/ServiceWorker/#algorithms>
346#[allow(clippy::large_enum_variant)]
347#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
348pub enum ServiceWorkerAlgorithmResult {
349    /// <https://w3c.github.io/ServiceWorker/#resolve-job-promise-algorithm>
350    /// <https://w3c.github.io/ServiceWorker/#reject-job-promise-algorithm>
351    Job(JobResult),
352
353    /// <https://w3c.github.io/ServiceWorker/#match-service-worker-registration>
354    MatchServiceWorkerRegistration(Option<ServiceWorkerRegistrationInfo>),
355
356    /// <https://w3c.github.io/ServiceWorker/#dom-client-postmessage-message-options>
357    /// Note: this is not algorithm; re-using algo channel for convenience.
358    MessageFromWorker {
359        message: StructuredSerializedData,
360        source: ServiceWorkerId,
361        scope_url: ServoUrl,
362        script_url: ServoUrl,
363        origin: ImmutableOrigin,
364    },
365}
366
367#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
368/// <https://w3c.github.io/ServiceWorker/#dfn-job>
369pub struct Job {
370    /// <https://w3c.github.io/ServiceWorker/#dfn-job-type>
371    pub job_type: JobType,
372    /// <https://w3c.github.io/ServiceWorker/#dfn-job-scope-url>
373    pub scope_url: ServoUrl,
374    /// <https://w3c.github.io/ServiceWorker/#dfn-job-script-url>
375    pub script_url: ServoUrl,
376    /// <https://w3c.github.io/ServiceWorker/#dfn-job-client>
377    pub client: GenericCallback<ServiceWorkerAlgorithmResult>,
378    /// <https://w3c.github.io/ServiceWorker/#job-referrer>
379    pub referrer: ServoUrl,
380    /// Various data needed to process job.
381    pub scope_things: Option<ScopeThings>,
382    /// <https://w3c.github.io/ServiceWorker/#job-storage-key>
383    pub storage_key: ImmutableOrigin,
384}
385
386impl Job {
387    /// <https://w3c.github.io/ServiceWorker/#create-job-algorithm>
388    pub fn create_job(
389        job_type: JobType,
390        scope_url: ServoUrl,
391        script_url: ServoUrl,
392        client: GenericCallback<ServiceWorkerAlgorithmResult>,
393        referrer: ServoUrl,
394        scope_things: Option<ScopeThings>,
395        storage_key: ImmutableOrigin,
396    ) -> Job {
397        Job {
398            job_type,
399            scope_url,
400            script_url,
401            client,
402            referrer,
403            scope_things,
404            storage_key,
405        }
406    }
407}
408
409impl PartialEq for Job {
410    /// Equality criteria as described in <https://w3c.github.io/ServiceWorker/#dfn-job-equivalent>
411    fn eq(&self, other: &Self) -> bool {
412        // TODO: match on job type, take worker type and `update_via_cache_mode` into account.
413        let same_job = self.job_type == other.job_type;
414        if same_job {
415            match self.job_type {
416                JobType::Register | JobType::Update => {
417                    self.scope_url == other.scope_url && self.script_url == other.script_url
418                },
419                JobType::Unregister => self.scope_url == other.scope_url,
420            }
421        } else {
422            false
423        }
424    }
425}
426
427/// Used to determine if a script has any pending asynchronous activity.
428#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
429pub enum DocumentState {
430    /// The document has been loaded and is idle.
431    Idle,
432    /// The document is either loading or waiting on an event.
433    Pending,
434}
435
436/// This trait allows creating a `ServiceWorkerManager` without depending on the `script`
437/// crate.
438pub trait ServiceWorkerManagerFactory {
439    /// Create a `ServiceWorkerManager`.
440    fn create(sw_senders: SWManagerSenders, origin: ImmutableOrigin);
441}
442
443/// Specifies the information required to load an auxiliary browsing context.
444#[derive(Debug, Deserialize, Serialize)]
445pub struct AuxiliaryWebViewCreationRequest {
446    /// Load data containing the url to load
447    pub load_data: LoadData,
448    /// The webview that caused this request.
449    pub opener_webview_id: WebViewId,
450    /// The pipeline opener browsing context.
451    pub opener_pipeline_id: PipelineId,
452    /// Sender for the constellation’s response to our request.
453    pub response_sender: GenericSender<Option<AuxiliaryWebViewCreationResponse>>,
454}
455
456/// Constellation’s response to auxiliary browsing context creation requests.
457#[derive(Debug, Deserialize, Serialize)]
458pub struct AuxiliaryWebViewCreationResponse {
459    /// The new webview ID.
460    pub new_webview_id: WebViewId,
461    /// The new pipeline ID.
462    pub new_pipeline_id: PipelineId,
463    /// The [`UserContentManagerId`] for this new auxiliary browsing context.
464    pub user_content_manager_id: Option<UserContentManagerId>,
465}
466
467/// Specifies the information required to load an iframe.
468#[derive(Debug, Deserialize, Serialize)]
469pub struct IFrameLoadInfo {
470    /// Pipeline ID of the parent of this iframe
471    pub parent_pipeline_id: PipelineId,
472    /// The ID for this iframe's nested browsing context.
473    pub browsing_context_id: BrowsingContextId,
474    /// The ID for the top-level ancestor browsing context of this iframe's nested browsing context.
475    pub webview_id: WebViewId,
476    /// The new pipeline ID that the iframe has generated.
477    pub new_pipeline_id: PipelineId,
478    ///  Whether this iframe should be considered private
479    pub is_private: bool,
480    ///  Whether this iframe should be considered secure
481    pub inherited_secure_context: Option<bool>,
482    /// Whether this load should replace the current entry (reload). If true, the current
483    /// entry will be replaced instead of a new entry being added.
484    pub history_handling: NavigationHistoryBehavior,
485    /// A snapshot of the navigation-related parameters of the target
486    /// of this navigation.
487    pub target_snapshot_params: TargetSnapshotParams,
488}
489
490/// Specifies the information required to load a URL in an iframe.
491#[derive(Debug, Deserialize, Serialize)]
492pub struct IFrameLoadInfoWithData {
493    /// The information required to load an iframe.
494    pub info: IFrameLoadInfo,
495    /// Load data containing the url to load
496    pub load_data: LoadData,
497    /// The old pipeline ID for this iframe, if a page was previously loaded.
498    pub old_pipeline_id: Option<PipelineId>,
499    /// The initial viewport size for this iframe.
500    pub viewport_details: ViewportDetails,
501    /// The [`Theme`] to use within this iframe.
502    pub theme: Theme,
503}
504
505/// Resources required by workerglobalscopes
506#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
507pub struct WorkerGlobalScopeInit {
508    /// Chan to a resource thread
509    pub resource_threads: ResourceThreads,
510    /// Chan to a storage thread
511    pub storage_threads: StorageThreads,
512    /// Chan to the memory profiler
513    pub mem_profiler_chan: mem::ProfilerChan,
514    /// Chan to the time profiler
515    pub time_profiler_chan: profile_time::ProfilerChan,
516    /// To devtools sender
517    pub to_devtools_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
518    /// From devtools sender
519    pub from_devtools_sender: Option<GenericSender<DevtoolScriptControlMsg>>,
520    /// Messages to send to constellation
521    pub script_to_constellation_chan: ScriptToConstellationChan,
522    /// Messages to send to the Embedder
523    pub script_to_embedder_chan: ScriptToEmbedderChan,
524    /// The worker id
525    pub worker_id: WorkerId,
526    /// The pipeline id
527    pub pipeline_id: PipelineId,
528    /// The origin
529    pub origin: ImmutableOrigin,
530    /// True if secure context
531    pub inherited_secure_context: Option<bool>,
532    /// Unminify Javascript.
533    pub unminify_js: bool,
534    /// Handle for communicating messages to the WebGL thread, if available.
535    pub webgl_chan: Option<WebGLChan>,
536}
537
538/// Common entities representing a network load origin
539#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
540pub struct WorkerScriptLoadOrigin {
541    /// referrer url
542    pub referrer_url: Option<ServoUrl>,
543    /// the referrer policy which is used
544    pub referrer_policy: ReferrerPolicy,
545    /// the pipeline id of the entity requesting the load
546    pub pipeline_id: PipelineId,
547}
548
549/// An iframe sizing operation.
550#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
551pub struct IFrameSizeMsg {
552    /// The child browsing context for this iframe.
553    pub browsing_context_id: BrowsingContextId,
554    /// The size and scale factor of the iframe.
555    pub size: ViewportDetails,
556    /// The kind of sizing operation.
557    pub type_: WindowSizeType,
558}
559
560/// An enum that describe a type of keyboard scroll.
561#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
562pub enum KeyboardScroll {
563    /// Scroll the container one line up.
564    Up,
565    /// Scroll the container one line down.
566    Down,
567    /// Scroll the container one "line" left.
568    Left,
569    /// Scroll the container one "line" right.
570    Right,
571    /// Scroll the container one page up.
572    PageUp,
573    /// Scroll the container one page down.
574    PageDown,
575    /// Scroll the container to the vertical start.
576    Home,
577    /// Scroll the container to the vertical end.
578    End,
579}
580
581#[derive(Debug, Deserialize, Serialize)]
582pub enum ScreenshotReadinessResponse {
583    /// The Pipeline associated with this response, is ready for a screenshot at the
584    /// provided [`Epoch`].
585    Ready(Epoch),
586    /// The Pipeline associated with this response is no longer active and should be
587    /// ignored for the purposes of the screenshot.
588    NoLongerActive,
589}
590
591/// Identifies a category of events/notifications that a pipeline can register
592/// interest in with the constellation. When a pipeline has active listeners for
593/// events in a given category, it registers interest so the constellation only
594/// sends notifications to pipelines that care.
595#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
596pub enum ConstellationInterest {
597    /// Interest in `storage` events (fired when another same-origin pipeline modifies storage).
598    StorageEvent,
599}
600
601/// Messages from the script to the constellation.
602#[derive(Deserialize, IntoStaticStr, Serialize)]
603pub enum ScriptToConstellationMessage {
604    ServiceWorkerAlgorithm(ServiceWorkerAlgorithm),
605    /// Request to complete the transfer of a set of ports to a router.
606    CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>),
607    /// The results of attempting to complete the transfer of a batch of ports.
608    MessagePortTransferResult(
609        /* The router whose transfer of ports succeeded, if any */
610        Option<MessagePortRouterId>,
611        /* The ids of ports transferred successfully */
612        Vec<MessagePortId>,
613        /* The ids, and buffers, of ports whose transfer failed */
614        FxHashMap<MessagePortId, PortTransferInfo>,
615    ),
616    /// A new message-port was created or transferred, with corresponding control-sender.
617    NewMessagePort(MessagePortRouterId, MessagePortId),
618    /// A global has started managing message-ports
619    NewMessagePortRouter(MessagePortRouterId, GenericCallback<MessagePortMsg>),
620    /// A global has stopped managing message-ports
621    RemoveMessagePortRouter(MessagePortRouterId),
622    /// A task requires re-routing to an already shipped message-port.
623    RerouteMessagePort(MessagePortId, PortMessageTask),
624    /// A message-port was shipped, let the entangled port know.
625    MessagePortShipped(MessagePortId),
626    /// Entangle two message-ports.
627    EntanglePorts(MessagePortId, MessagePortId),
628    /// Disentangle two message-ports.
629    /// The first is the initiator, the second the other port,
630    /// unless the message is sent to complete a disentanglement,
631    /// in which case the first one is the other port,
632    /// and the second is none.
633    DisentanglePorts(MessagePortId, Option<MessagePortId>),
634    /// A global has started managing broadcast-channels.
635    NewBroadcastChannelRouter(
636        BroadcastChannelRouterId,
637        IpcSender<BroadcastChannelMsg>,
638        ImmutableOrigin,
639    ),
640    /// A global has stopped managing broadcast-channels.
641    RemoveBroadcastChannelRouter(BroadcastChannelRouterId, ImmutableOrigin),
642    /// A global started managing broadcast channels for a given channel-name.
643    NewBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
644    /// A global stopped managing broadcast channels for a given channel-name.
645    RemoveBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
646    /// Broadcast a message to all same-origin broadcast channels,
647    /// excluding the source of the broadcast.
648    ScheduleBroadcast(BroadcastChannelRouterId, BroadcastChannelMsg),
649    /// Register this pipeline's interest in a category of notifications.
650    /// The constellation will only send notifications in this category to
651    /// pipelines that have registered interest.
652    RegisterInterest(ConstellationInterest),
653    /// Unregister this pipeline's interest in a category of notifications.
654    UnregisterInterest(ConstellationInterest),
655    /// Broadcast a storage event to every same-origin pipeline.
656    /// The strings are key, old value and new value.
657    BroadcastStorageEvent(
658        WebStorageType,
659        ServoUrl,
660        Option<String>,
661        Option<String>,
662        Option<String>,
663    ),
664    /// Indicates whether this pipeline is currently running animations.
665    ChangeRunningAnimationsState(AnimationState),
666    /// Requests that a new 2D canvas thread be created. (This is done in the constellation because
667    /// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
668    CreateCanvasPaintThread(
669        UntypedSize2D<u64>,
670        GenericSender<Option<(GenericSender<CanvasMsg>, CanvasId)>>,
671    ),
672    /// Notifies the constellation that this pipeline is requesting focus.
673    ///
674    /// When this message is sent, the sender pipeline has already its local
675    /// focus state updated. The constellation, after receiving this message,
676    /// will broadcast messages to other pipelines that are affected by this
677    /// focus operation.
678    ///
679    /// The first field contains the browsing context ID of the container
680    /// element if one was focused.
681    ///
682    /// The second field is a sequence number that the constellation should use
683    /// when sending a focus-related message to the sender pipeline next time.
684    FocusAncestorBrowsingContextsForFocusingSteps(Option<BrowsingContextId>, FocusSequenceNumber),
685    /// Focus a remote `BrowsingContext` and run the focusing steps. This is used in two situations:
686    /// - When calling the DOM `focus()` API on a remote `Window` as well as from
687    ///   WebDriver. The difference between this and `FocusDocumentAsPartOfFocusingSteps` is that this
688    ///   version actually does run the focusing steps and may result in blur and focus events firing
689    ///   up the frame tree.
690    /// - When doing sequential focus navigation into and out of frames.
691    FocusRemoteBrowsingContext(BrowsingContextId, RemoteFocusOperation),
692    /// Get the top-level browsing context info for a given browsing context.
693    GetTopForBrowsingContext(BrowsingContextId, GenericSender<Option<WebViewId>>),
694    /// Get the browsing context id of the browsing context in which pipeline is
695    /// embedded and the parent pipeline id of that browsing context.
696    GetBrowsingContextInfo(
697        PipelineId,
698        GenericSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
699    ),
700    /// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
701    GetChildBrowsingContextId(
702        BrowsingContextId,
703        usize,
704        GenericSender<Option<BrowsingContextId>>,
705    ),
706    /// Get the origin of the document corresponding to the given pipeline
707    GetDocumentOrigin(PipelineId, GenericSender<Option<String>>),
708    /// All pending loads are complete, and the `load` event for this pipeline
709    /// has been dispatched.
710    LoadComplete,
711    /// A new load has been requested, with an option to replace the current entry once loaded
712    /// instead of adding a new entry.
713    LoadUrl(LoadData, NavigationHistoryBehavior, TargetSnapshotParams),
714    /// Abort loading after sending a LoadUrl message.
715    AbortLoadUrl,
716    /// Post a message to the currently active window of a given browsing context.
717    PostMessage {
718        /// The target of the posted message.
719        target: BrowsingContextId,
720        /// The source of the posted message.
721        source: PipelineId,
722        /// The expected origin of the target.
723        target_origin: Option<ImmutableOrigin>,
724        /// The source origin of the message.
725        /// <https://html.spec.whatwg.org/multipage/#dom-messageevent-origin>
726        source_origin: ImmutableOrigin,
727        /// The data to be posted.
728        data: StructuredSerializedData,
729    },
730    /// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
731    NavigatedToFragment(ServoUrl, NavigationHistoryBehavior),
732    /// HTMLIFrameElement Forward or Back traversal.
733    TraverseHistory(TraversalDirection),
734    /// Inform the constellation of a pushed history state.
735    PushHistoryState(HistoryStateId, ServoUrl),
736    /// Inform the constellation of a replaced history state.
737    ReplaceHistoryState(HistoryStateId, ServoUrl),
738    /// Gets the length of the joint session history from the constellation.
739    JointSessionHistoryLength(GenericSender<u32>),
740    /// Notification that this iframe should be removed.
741    /// Returns a list of pipelines which were closed.
742    RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
743    /// Successful response to [crate::ConstellationControlMsg::SetThrottled].
744    SetThrottledComplete(bool),
745    /// A load has been requested in an IFrame.
746    ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
747    /// A load of the initial `about:blank` has been completed in an IFrame.
748    ScriptNewIFrame(IFrameLoadInfoWithData),
749    /// Script has opened a new auxiliary browsing context.
750    CreateAuxiliaryWebView(AuxiliaryWebViewCreationRequest),
751    /// Mark a new document as active
752    ActivateDocument,
753    /// Set the document state for a pipeline (used by screenshot / reftests)
754    SetDocumentState(DocumentState),
755    /// Update the pipeline Url, which can change after redirections.
756    SetFinalUrl(ServoUrl),
757    /// A log entry, with the top-level browsing context id and thread name
758    LogEntry(Option<ScriptEventLoopId>, Option<String>, LogEntry),
759    /// Discard the document.
760    DiscardDocument,
761    /// Discard the browsing context.
762    DiscardTopLevelBrowsingContext,
763    /// Notifies the constellation that this pipeline has exited.
764    PipelineExited,
765    /// Send messages from postMessage calls from serviceworker
766    /// to constellation for storing in service worker manager
767    ForwardDOMMessage(DOMMessage, ServoUrl),
768    /// Notifies the constellation about media session events
769    /// (i.e. when there is metadata for the active media session, playback state changes...).
770    MediaSessionEvent(PipelineId, MediaSessionEvent),
771    #[cfg(feature = "webgpu")]
772    /// Create a WebGPU Adapter instance
773    RequestAdapter(
774        GenericCallback<WebGPUAdapterResponse>,
775        wgpu_core::instance::RequestAdapterOptions,
776        wgpu_core::id::AdapterId,
777    ),
778    #[cfg(feature = "webgpu")]
779    /// Get WebGPU channel
780    GetWebGPUChan(GenericSender<Option<WebGPU>>),
781    /// Notify the constellation of a pipeline's document's title.
782    TitleChanged(PipelineId, String),
783    /// Notify the constellation that the size of some `<iframe>`s has changed.
784    IFrameSizes(Vec<IFrameSizeMsg>),
785    /// Request results from the memory reporter.
786    ReportMemory(GenericCallback<MemoryReportResult>),
787    /// Return the result of the evaluated JavaScript with the given [`JavaScriptEvaluationId`].
788    FinishJavaScriptEvaluation(
789        JavaScriptEvaluationId,
790        Result<JSValue, JavaScriptEvaluationError>,
791    ),
792    /// Forward a keyboard scroll operation from an `<iframe>` to a parent pipeline.
793    ForwardKeyboardScroll(PipelineId, KeyboardScroll),
794    /// Notify the Constellation of the screenshot readiness of a given pipeline.
795    RespondToScreenshotReadinessRequest(ScreenshotReadinessResponse),
796    /// Request the constellation to force garbage collection in all `ScriptThread`'s.
797    TriggerGarbageCollection,
798    /// Request to acquire a wake lock of the given type. The constellation will track the
799    /// aggregate lock count and notify the provider only when the count transitions from 0 to 1.
800    /// <https://w3c.github.io/screen-wake-lock/#dfn-acquire-wake-lock>
801    AcquireWakeLock(WakeLockType),
802    /// Request to release a wake lock of the given type. The constellation will track the
803    /// aggregate lock count and notify the provider only when the count transitions from N to 0.
804    /// <https://w3c.github.io/screen-wake-lock/#dfn-release-wake-lock>
805    ReleaseWakeLock(WakeLockType),
806}
807
808impl fmt::Debug for ScriptToConstellationMessage {
809    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
810        let variant_string: &'static str = self.into();
811        write!(formatter, "ScriptMsg::{variant_string}")
812    }
813}
814
815/// <https://html.spec.whatwg.org/multipage/#target-snapshot-params>
816#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
817pub struct TargetSnapshotParams {
818    /// <https://html.spec.whatwg.org/multipage/#target-snapshot-params-sandbox>
819    pub sandboxing_flags: SandboxingFlagSet,
820    /// <https://html.spec.whatwg.org/multipage/#target-snapshot-params-iframe-referrer-policy>
821    pub iframe_element_referrer_policy: ReferrerPolicy,
822}
823
824impl Default for TargetSnapshotParams {
825    fn default() -> Self {
826        Self {
827            sandboxing_flags: SandboxingFlagSet::empty(),
828            iframe_element_referrer_policy: ReferrerPolicy::EmptyString,
829        }
830    }
831}
832
833/// <https://html.spec.whatwg.org/multipage/#sequential-focus-direction>
834///
835/// > A sequential focus direction is one of two possible values: "forward", or "backward". They are
836/// > used in the below algorithms to describe the direction in which sequential focus travels at the
837/// > user's request.
838#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
839pub enum SequentialFocusDirection {
840    Forward,
841    Backward,
842}
843
844/// The type of focus operation to do on a remote document.
845#[derive(Deserialize, Serialize)]
846pub enum RemoteFocusOperation {
847    /// Focus the entire viewport of the remote document.
848    Viewport,
849    /// Do sequential focus navigation using the `<iframe>` element with the given
850    /// [`BrowsingContextId`] as the starting point and in the given direction.
851    Sequential(SequentialFocusDirection, Option<BrowsingContextId>),
852}