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};
16use encoding_rs::Encoding;
17use euclid::default::Size2D as UntypedSize2D;
18use fonts_traits::SystemFontServiceProxySender;
19use http::{HeaderMap, Method};
20use ipc_channel::ipc::IpcSender;
21use malloc_size_of_derive::MallocSizeOf;
22use net_traits::policy_container::PolicyContainer;
23use net_traits::request::{Destination, InsecureRequestsPolicy, Referrer, RequestBody};
24use net_traits::{ReferrerPolicy, ResourceThreads};
25use paint_api::CrossProcessPaintApi;
26use profile_traits::mem::MemoryReportResult;
27use profile_traits::{mem, time as profile_time};
28use rustc_hash::FxHashMap;
29use serde::{Deserialize, Serialize};
30use servo_base::Epoch;
31use servo_base::generic_channel::{GenericCallback, GenericReceiver, GenericSender, SendResult};
32use servo_base::id::{
33 BroadcastChannelRouterId, BrowsingContextId, HistoryStateId, MessagePortId,
34 MessagePortRouterId, PipelineId, ScriptEventLoopId, ServiceWorkerId,
35 ServiceWorkerRegistrationId, WebViewId,
36};
37use servo_canvas_traits::canvas::{CanvasId, CanvasMsg};
38use servo_canvas_traits::webgl::WebGLChan;
39use servo_url::{ImmutableOrigin, OriginSnapshot, ServoUrl};
40use servo_wakelock::WakeLockType;
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}
332
333impl Job {
334 /// <https://w3c.github.io/ServiceWorker/#create-job-algorithm>
335 pub fn create_job(
336 job_type: JobType,
337 scope_url: ServoUrl,
338 script_url: ServoUrl,
339 client: GenericCallback<JobResult>,
340 referrer: ServoUrl,
341 scope_things: Option<ScopeThings>,
342 ) -> Job {
343 Job {
344 job_type,
345 scope_url,
346 script_url,
347 client,
348 referrer,
349 scope_things,
350 }
351 }
352}
353
354impl PartialEq for Job {
355 /// Equality criteria as described in <https://w3c.github.io/ServiceWorker/#dfn-job-equivalent>
356 fn eq(&self, other: &Self) -> bool {
357 // TODO: match on job type, take worker type and `update_via_cache_mode` into account.
358 let same_job = self.job_type == other.job_type;
359 if same_job {
360 match self.job_type {
361 JobType::Register | JobType::Update => {
362 self.scope_url == other.scope_url && self.script_url == other.script_url
363 },
364 JobType::Unregister => self.scope_url == other.scope_url,
365 }
366 } else {
367 false
368 }
369 }
370}
371
372/// Messages outgoing from the Service Worker Manager thread to constellation
373#[derive(Debug, Deserialize, Serialize)]
374pub enum SWManagerMsg {
375 /// Placeholder to keep the enum,
376 /// as it will be needed when implementing
377 /// <https://github.com/servo/servo/issues/24660>
378 PostMessageToClient,
379}
380
381/// Used to determine if a script has any pending asynchronous activity.
382#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
383pub enum DocumentState {
384 /// The document has been loaded and is idle.
385 Idle,
386 /// The document is either loading or waiting on an event.
387 Pending,
388}
389
390/// This trait allows creating a `ServiceWorkerManager` without depending on the `script`
391/// crate.
392pub trait ServiceWorkerManagerFactory {
393 /// Create a `ServiceWorkerManager`.
394 fn create(sw_senders: SWManagerSenders, origin: ImmutableOrigin);
395}
396
397/// Specifies the information required to load an auxiliary browsing context.
398#[derive(Debug, Deserialize, Serialize)]
399pub struct AuxiliaryWebViewCreationRequest {
400 /// Load data containing the url to load
401 pub load_data: LoadData,
402 /// The webview that caused this request.
403 pub opener_webview_id: WebViewId,
404 /// The pipeline opener browsing context.
405 pub opener_pipeline_id: PipelineId,
406 /// Sender for the constellation’s response to our request.
407 pub response_sender: GenericSender<Option<AuxiliaryWebViewCreationResponse>>,
408}
409
410/// Constellation’s response to auxiliary browsing context creation requests.
411#[derive(Debug, Deserialize, Serialize)]
412pub struct AuxiliaryWebViewCreationResponse {
413 /// The new webview ID.
414 pub new_webview_id: WebViewId,
415 /// The new pipeline ID.
416 pub new_pipeline_id: PipelineId,
417 /// The [`UserContentManagerId`] for this new auxiliary browsing context.
418 pub user_content_manager_id: Option<UserContentManagerId>,
419}
420
421/// Specifies the information required to load an iframe.
422#[derive(Debug, Deserialize, Serialize)]
423pub struct IFrameLoadInfo {
424 /// Pipeline ID of the parent of this iframe
425 pub parent_pipeline_id: PipelineId,
426 /// The ID for this iframe's nested browsing context.
427 pub browsing_context_id: BrowsingContextId,
428 /// The ID for the top-level ancestor browsing context of this iframe's nested browsing context.
429 pub webview_id: WebViewId,
430 /// The new pipeline ID that the iframe has generated.
431 pub new_pipeline_id: PipelineId,
432 /// Whether this iframe should be considered private
433 pub is_private: bool,
434 /// Whether this iframe should be considered secure
435 pub inherited_secure_context: Option<bool>,
436 /// Whether this load should replace the current entry (reload). If true, the current
437 /// entry will be replaced instead of a new entry being added.
438 pub history_handling: NavigationHistoryBehavior,
439 /// A snapshot of the navigation-related parameters of the target
440 /// of this navigation.
441 pub target_snapshot_params: TargetSnapshotParams,
442}
443
444/// Specifies the information required to load a URL in an iframe.
445#[derive(Debug, Deserialize, Serialize)]
446pub struct IFrameLoadInfoWithData {
447 /// The information required to load an iframe.
448 pub info: IFrameLoadInfo,
449 /// Load data containing the url to load
450 pub load_data: LoadData,
451 /// The old pipeline ID for this iframe, if a page was previously loaded.
452 pub old_pipeline_id: Option<PipelineId>,
453 /// The initial viewport size for this iframe.
454 pub viewport_details: ViewportDetails,
455 /// The [`Theme`] to use within this iframe.
456 pub theme: Theme,
457}
458
459/// Resources required by workerglobalscopes
460#[derive(Clone, Debug, Deserialize, Serialize)]
461pub struct WorkerGlobalScopeInit {
462 /// Chan to a resource thread
463 pub resource_threads: ResourceThreads,
464 /// Chan to a storage thread
465 pub storage_threads: StorageThreads,
466 /// Chan to the memory profiler
467 pub mem_profiler_chan: mem::ProfilerChan,
468 /// Chan to the time profiler
469 pub time_profiler_chan: profile_time::ProfilerChan,
470 /// To devtools sender
471 pub to_devtools_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
472 /// From devtools sender
473 pub from_devtools_sender: Option<GenericSender<DevtoolScriptControlMsg>>,
474 /// Messages to send to constellation
475 pub script_to_constellation_chan: ScriptToConstellationChan,
476 /// Messages to send to the Embedder
477 pub script_to_embedder_chan: ScriptToEmbedderChan,
478 /// The worker id
479 pub worker_id: WorkerId,
480 /// The pipeline id
481 pub pipeline_id: PipelineId,
482 /// The origin
483 pub origin: ImmutableOrigin,
484 /// True if secure context
485 pub inherited_secure_context: Option<bool>,
486 /// Unminify Javascript.
487 pub unminify_js: bool,
488 /// Handle for communicating messages to the WebGL thread, if available.
489 pub webgl_chan: Option<WebGLChan>,
490}
491
492/// Common entities representing a network load origin
493#[derive(Clone, Debug, Deserialize, Serialize)]
494pub struct WorkerScriptLoadOrigin {
495 /// referrer url
496 pub referrer_url: Option<ServoUrl>,
497 /// the referrer policy which is used
498 pub referrer_policy: ReferrerPolicy,
499 /// the pipeline id of the entity requesting the load
500 pub pipeline_id: PipelineId,
501}
502
503/// An iframe sizing operation.
504#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
505pub struct IFrameSizeMsg {
506 /// The child browsing context for this iframe.
507 pub browsing_context_id: BrowsingContextId,
508 /// The size and scale factor of the iframe.
509 pub size: ViewportDetails,
510 /// The kind of sizing operation.
511 pub type_: WindowSizeType,
512}
513
514/// An enum that describe a type of keyboard scroll.
515#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
516pub enum KeyboardScroll {
517 /// Scroll the container one line up.
518 Up,
519 /// Scroll the container one line down.
520 Down,
521 /// Scroll the container one "line" left.
522 Left,
523 /// Scroll the container one "line" right.
524 Right,
525 /// Scroll the container one page up.
526 PageUp,
527 /// Scroll the container one page down.
528 PageDown,
529 /// Scroll the container to the vertical start.
530 Home,
531 /// Scroll the container to the vertical end.
532 End,
533}
534
535#[derive(Debug, Deserialize, Serialize)]
536pub enum ScreenshotReadinessResponse {
537 /// The Pipeline associated with this response, is ready for a screenshot at the
538 /// provided [`Epoch`].
539 Ready(Epoch),
540 /// The Pipeline associated with this response is no longer active and should be
541 /// ignored for the purposes of the screenshot.
542 NoLongerActive,
543}
544
545/// Identifies a category of events/notifications that a pipeline can register
546/// interest in with the constellation. When a pipeline has active listeners for
547/// events in a given category, it registers interest so the constellation only
548/// sends notifications to pipelines that care.
549#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
550pub enum ConstellationInterest {
551 /// Interest in `storage` events (fired when another same-origin pipeline modifies storage).
552 StorageEvent,
553}
554
555/// Messages from the script to the constellation.
556#[derive(Deserialize, IntoStaticStr, Serialize)]
557pub enum ScriptToConstellationMessage {
558 /// Request to complete the transfer of a set of ports to a router.
559 CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>),
560 /// The results of attempting to complete the transfer of a batch of ports.
561 MessagePortTransferResult(
562 /* The router whose transfer of ports succeeded, if any */
563 Option<MessagePortRouterId>,
564 /* The ids of ports transferred successfully */
565 Vec<MessagePortId>,
566 /* The ids, and buffers, of ports whose transfer failed */
567 FxHashMap<MessagePortId, PortTransferInfo>,
568 ),
569 /// A new message-port was created or transferred, with corresponding control-sender.
570 NewMessagePort(MessagePortRouterId, MessagePortId),
571 /// A global has started managing message-ports
572 NewMessagePortRouter(MessagePortRouterId, GenericCallback<MessagePortMsg>),
573 /// A global has stopped managing message-ports
574 RemoveMessagePortRouter(MessagePortRouterId),
575 /// A task requires re-routing to an already shipped message-port.
576 RerouteMessagePort(MessagePortId, PortMessageTask),
577 /// A message-port was shipped, let the entangled port know.
578 MessagePortShipped(MessagePortId),
579 /// Entangle two message-ports.
580 EntanglePorts(MessagePortId, MessagePortId),
581 /// Disentangle two message-ports.
582 /// The first is the initiator, the second the other port,
583 /// unless the message is sent to complete a disentanglement,
584 /// in which case the first one is the other port,
585 /// and the second is none.
586 DisentanglePorts(MessagePortId, Option<MessagePortId>),
587 /// A global has started managing broadcast-channels.
588 NewBroadcastChannelRouter(
589 BroadcastChannelRouterId,
590 IpcSender<BroadcastChannelMsg>,
591 ImmutableOrigin,
592 ),
593 /// A global has stopped managing broadcast-channels.
594 RemoveBroadcastChannelRouter(BroadcastChannelRouterId, ImmutableOrigin),
595 /// A global started managing broadcast channels for a given channel-name.
596 NewBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
597 /// A global stopped managing broadcast channels for a given channel-name.
598 RemoveBroadcastChannelNameInRouter(BroadcastChannelRouterId, String, ImmutableOrigin),
599 /// Broadcast a message to all same-origin broadcast channels,
600 /// excluding the source of the broadcast.
601 ScheduleBroadcast(BroadcastChannelRouterId, BroadcastChannelMsg),
602 /// Register this pipeline's interest in a category of notifications.
603 /// The constellation will only send notifications in this category to
604 /// pipelines that have registered interest.
605 RegisterInterest(ConstellationInterest),
606 /// Unregister this pipeline's interest in a category of notifications.
607 UnregisterInterest(ConstellationInterest),
608 /// Broadcast a storage event to every same-origin pipeline.
609 /// The strings are key, old value and new value.
610 BroadcastStorageEvent(
611 WebStorageType,
612 ServoUrl,
613 Option<String>,
614 Option<String>,
615 Option<String>,
616 ),
617 /// Indicates whether this pipeline is currently running animations.
618 ChangeRunningAnimationsState(AnimationState),
619 /// Requests that a new 2D canvas thread be created. (This is done in the constellation because
620 /// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
621 CreateCanvasPaintThread(
622 UntypedSize2D<u64>,
623 GenericSender<Option<(GenericSender<CanvasMsg>, CanvasId)>>,
624 ),
625 /// Notifies the constellation that this pipeline is requesting focus.
626 ///
627 /// When this message is sent, the sender pipeline has already its local
628 /// focus state updated. The constellation, after receiving this message,
629 /// will broadcast messages to other pipelines that are affected by this
630 /// focus operation.
631 ///
632 /// The first field contains the browsing context ID of the container
633 /// element if one was focused.
634 ///
635 /// The second field is a sequence number that the constellation should use
636 /// when sending a focus-related message to the sender pipeline next time.
637 FocusAncestorBrowsingContextsForFocusingSteps(Option<BrowsingContextId>, FocusSequenceNumber),
638 /// Have the Constellation trigger a remote call to `Focus` on the `Window` of the given
639 /// [`BrowsingContextId`].
640 FocusRemoteBrowsingContext(BrowsingContextId),
641 /// Get the top-level browsing context info for a given browsing context.
642 GetTopForBrowsingContext(BrowsingContextId, GenericSender<Option<WebViewId>>),
643 /// Get the browsing context id of the browsing context in which pipeline is
644 /// embedded and the parent pipeline id of that browsing context.
645 GetBrowsingContextInfo(
646 PipelineId,
647 GenericSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
648 ),
649 /// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
650 GetChildBrowsingContextId(
651 BrowsingContextId,
652 usize,
653 GenericSender<Option<BrowsingContextId>>,
654 ),
655 /// Get the origin of the document corresponding to the given pipeline
656 GetDocumentOrigin(PipelineId, GenericSender<Option<String>>),
657 /// All pending loads are complete, and the `load` event for this pipeline
658 /// has been dispatched.
659 LoadComplete,
660 /// A new load has been requested, with an option to replace the current entry once loaded
661 /// instead of adding a new entry.
662 LoadUrl(LoadData, NavigationHistoryBehavior, TargetSnapshotParams),
663 /// Abort loading after sending a LoadUrl message.
664 AbortLoadUrl,
665 /// Post a message to the currently active window of a given browsing context.
666 PostMessage {
667 /// The target of the posted message.
668 target: BrowsingContextId,
669 /// The source of the posted message.
670 source: PipelineId,
671 /// The expected origin of the target.
672 target_origin: Option<ImmutableOrigin>,
673 /// The source origin of the message.
674 /// <https://html.spec.whatwg.org/multipage/#dom-messageevent-origin>
675 source_origin: ImmutableOrigin,
676 /// The data to be posted.
677 data: StructuredSerializedData,
678 },
679 /// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
680 NavigatedToFragment(ServoUrl, NavigationHistoryBehavior),
681 /// HTMLIFrameElement Forward or Back traversal.
682 TraverseHistory(TraversalDirection),
683 /// Inform the constellation of a pushed history state.
684 PushHistoryState(HistoryStateId, ServoUrl),
685 /// Inform the constellation of a replaced history state.
686 ReplaceHistoryState(HistoryStateId, ServoUrl),
687 /// Gets the length of the joint session history from the constellation.
688 JointSessionHistoryLength(GenericSender<u32>),
689 /// Notification that this iframe should be removed.
690 /// Returns a list of pipelines which were closed.
691 RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
692 /// Successful response to [crate::ConstellationControlMsg::SetThrottled].
693 SetThrottledComplete(bool),
694 /// A load has been requested in an IFrame.
695 ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
696 /// A load of the initial `about:blank` has been completed in an IFrame.
697 ScriptNewIFrame(IFrameLoadInfoWithData),
698 /// Script has opened a new auxiliary browsing context.
699 CreateAuxiliaryWebView(AuxiliaryWebViewCreationRequest),
700 /// Mark a new document as active
701 ActivateDocument,
702 /// Set the document state for a pipeline (used by screenshot / reftests)
703 SetDocumentState(DocumentState),
704 /// Update the pipeline Url, which can change after redirections.
705 SetFinalUrl(ServoUrl),
706 /// A log entry, with the top-level browsing context id and thread name
707 LogEntry(Option<ScriptEventLoopId>, Option<String>, LogEntry),
708 /// Discard the document.
709 DiscardDocument,
710 /// Discard the browsing context.
711 DiscardTopLevelBrowsingContext,
712 /// Notifies the constellation that this pipeline has exited.
713 PipelineExited,
714 /// Send messages from postMessage calls from serviceworker
715 /// to constellation for storing in service worker manager
716 ForwardDOMMessage(DOMMessage, ServoUrl),
717 /// <https://w3c.github.io/ServiceWorker/#schedule-job-algorithm>
718 ScheduleJob(Job),
719 /// Notifies the constellation about media session events
720 /// (i.e. when there is metadata for the active media session, playback state changes...).
721 MediaSessionEvent(PipelineId, MediaSessionEvent),
722 #[cfg(feature = "webgpu")]
723 /// Create a WebGPU Adapter instance
724 RequestAdapter(
725 GenericCallback<WebGPUAdapterResponse>,
726 wgpu_core::instance::RequestAdapterOptions,
727 wgpu_core::id::AdapterId,
728 ),
729 #[cfg(feature = "webgpu")]
730 /// Get WebGPU channel
731 GetWebGPUChan(GenericSender<Option<WebGPU>>),
732 /// Notify the constellation of a pipeline's document's title.
733 TitleChanged(PipelineId, String),
734 /// Notify the constellation that the size of some `<iframe>`s has changed.
735 IFrameSizes(Vec<IFrameSizeMsg>),
736 /// Request results from the memory reporter.
737 ReportMemory(GenericCallback<MemoryReportResult>),
738 /// Return the result of the evaluated JavaScript with the given [`JavaScriptEvaluationId`].
739 FinishJavaScriptEvaluation(
740 JavaScriptEvaluationId,
741 Result<JSValue, JavaScriptEvaluationError>,
742 ),
743 /// Forward a keyboard scroll operation from an `<iframe>` to a parent pipeline.
744 ForwardKeyboardScroll(PipelineId, KeyboardScroll),
745 /// Notify the Constellation of the screenshot readiness of a given pipeline.
746 RespondToScreenshotReadinessRequest(ScreenshotReadinessResponse),
747 /// Request the constellation to force garbage collection in all `ScriptThread`'s.
748 TriggerGarbageCollection,
749 /// Request to acquire a wake lock of the given type. The constellation will track the
750 /// aggregate lock count and notify the provider only when the count transitions from 0 to 1.
751 /// <https://w3c.github.io/screen-wake-lock/#dfn-acquire-wake-lock>
752 AcquireWakeLock(WakeLockType),
753 /// Request to release a wake lock of the given type. The constellation will track the
754 /// aggregate lock count and notify the provider only when the count transitions from N to 0.
755 /// <https://w3c.github.io/screen-wake-lock/#dfn-release-wake-lock>
756 ReleaseWakeLock(WakeLockType),
757}
758
759impl fmt::Debug for ScriptToConstellationMessage {
760 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
761 let variant_string: &'static str = self.into();
762 write!(formatter, "ScriptMsg::{variant_string}")
763 }
764}
765
766/// <https://html.spec.whatwg.org/multipage/#target-snapshot-params>
767#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
768pub struct TargetSnapshotParams {
769 /// <https://html.spec.whatwg.org/multipage/#target-snapshot-params-sandbox>
770 pub sandboxing_flags: SandboxingFlagSet,
771 /// <https://html.spec.whatwg.org/multipage/#target-snapshot-params-iframe-referrer-policy>
772 pub iframe_element_referrer_policy: ReferrerPolicy,
773}
774
775impl Default for TargetSnapshotParams {
776 fn default() -> Self {
777 Self {
778 sandboxing_flags: SandboxingFlagSet::empty(),
779 iframe_element_referrer_policy: ReferrerPolicy::EmptyString,
780 }
781 }
782}