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