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