servo_constellation_traits/lib.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//! The interface to the `Constellation`, which prevents other crates from depending directly on
6//! the `constellation` crate itself. In addition to all messages to the `Constellation`, this
7//! crate is responsible for defining types that cross the process boundary from the
8//! embedding/rendering layer all the way to script, thus it should have very minimal dependencies
9//! on other parts of Servo.
10
11mod from_script_message;
12mod structured_data;
13
14use std::collections::VecDeque;
15use std::fmt;
16
17use embedder_traits::user_contents::{
18 UserContentManagerId, UserScript, UserScriptId, UserStyleSheet, UserStyleSheetId,
19};
20use embedder_traits::{
21 EmbedderControlId, EmbedderControlResponse, InputEventAndId, JavaScriptEvaluationId,
22 MediaSessionActionType, NewWebViewDetails, PaintHitTestResult, Theme, TraversalId, UrlRequest,
23 ViewportDetails, WebDriverCommandMsg,
24};
25pub use from_script_message::*;
26use malloc_size_of_derive::MallocSizeOf;
27use paint_api::PinchZoomInfos;
28use profile_traits::mem::MemoryReportResult;
29use rustc_hash::FxHashMap;
30use serde::{Deserialize, Serialize};
31use servo_base::cross_process_instant::CrossProcessInstant;
32use servo_base::generic_channel::GenericCallback;
33use servo_base::id::{LCPCandidateID, MessagePortId, PipelineId, ScriptEventLoopId, WebViewId};
34use servo_config::prefs::PrefValue;
35use servo_url::{ImmutableOrigin, ServoUrl};
36pub use structured_data::*;
37use strum::IntoStaticStr;
38use webrender_api::units::LayoutVector2D;
39use webrender_api::{ExternalScrollId, ImageKey};
40
41/// Messages to the Constellation from the embedding layer, whether from `ServoRenderer` or
42/// from `libservo` itself.
43#[derive(IntoStaticStr)]
44pub enum EmbedderToConstellationMessage {
45 /// Exit the constellation.
46 Exit,
47 /// Whether to allow script to navigate.
48 AllowNavigationResponse(PipelineId, bool),
49 /// Request to load a page, with optionally additional data in [`URLRequest`].
50 LoadUrl(WebViewId, UrlRequest),
51 /// Request to traverse the joint session history of the provided browsing context.
52 TraverseHistory(SessionHistoryTraversalRequest),
53 /// Inform the Constellation that a `WebView`'s [`ViewportDetails`] have changed.
54 ChangeViewportDetails(WebViewId, ViewportDetails, WindowSizeType),
55 /// Inform the constellation of a theme change.
56 ThemeChange(WebViewId, Theme),
57 /// Requests that the constellation instruct script/layout to try to layout again and tick
58 /// animations.
59 TickAnimation(Vec<WebViewId>),
60 /// Notify the `ScriptThread` that the Servo renderer is no longer waiting on
61 /// asynchronous image uploads for the given `Pipeline`. These are mainly used
62 /// by canvas to perform uploads while the display list is being built.
63 NoLongerWaitingOnAsynchronousImageUpdates(Vec<PipelineId>),
64 /// Dispatch a webdriver command
65 WebDriverCommand(WebDriverCommandMsg),
66 /// Reload a top-level browsing context.
67 Reload(WebViewId),
68 /// A log entry, with the top-level browsing context id and thread name
69 LogEntry(Option<ScriptEventLoopId>, Option<String>, LogEntry),
70 /// Create a new top level browsing context.
71 NewWebView(ServoUrl, NewWebViewDetails),
72 /// Close a top level browsing context.
73 CloseWebView(WebViewId),
74 /// Make a webview focused. [EmbedderMsg::WebViewFocused] will be sent with
75 /// the result of this operation.
76 FocusWebView(WebViewId),
77 /// Make none of the webviews focused.
78 BlurWebView,
79 /// Forward an input event to an appropriate ScriptTask.
80 ForwardInputEvent(WebViewId, InputEventAndId, Option<PaintHitTestResult>),
81 /// Request that the given pipeline refresh the cursor by doing a hit test at the most
82 /// recently hovered cursor position and resetting the cursor. This happens after a
83 /// display list update is rendered.
84 RefreshCursor(PipelineId),
85 /// Request to exit from fullscreen mode
86 ExitFullScreen(WebViewId),
87 /// Media session action.
88 MediaSessionAction(MediaSessionActionType),
89 /// Set whether to use less resources, by stopping animations and running timers at a heavily limited rate.
90 SetWebViewThrottled(WebViewId, bool),
91 /// The Servo renderer scrolled and is updating the scroll states of the nodes in the
92 /// given pipeline via the constellation.
93 SetScrollStates(PipelineId, ScrollStateUpdate),
94 /// Notify the constellation that a particular paint metric event has happened for the given pipeline.
95 PaintMetric(PipelineId, PaintMetricEvent),
96 /// Evaluate a JavaScript string in the context of a `WebView`. When execution is complete or an
97 /// error is encountered, a correpsonding message will be sent to the embedding layer.
98 EvaluateJavaScript(WebViewId, JavaScriptEvaluationId, String),
99 /// Create a memory report and return it via the [`GenericCallback`]
100 CreateMemoryReport(GenericCallback<MemoryReportResult>),
101 /// Sends the generated image key to the image cache associated with this pipeline.
102 SendImageKeysForPipeline(PipelineId, Vec<ImageKey>),
103 /// A set of preferences were updated with the given new values.
104 PreferencesUpdated(Vec<(&'static str, PrefValue)>),
105 /// Request preparation for a screenshot of the given WebView. The Constellation will
106 /// send a message to the Embedder when the screenshot is ready to be taken.
107 RequestScreenshotReadiness(WebViewId),
108 /// A response to a request to show an embedder user interface control.
109 EmbedderControlResponse(EmbedderControlId, EmbedderControlResponse),
110 /// An action to perform on the given `UserContentManagerId`.
111 UserContentManagerAction(UserContentManagerId, UserContentManagerAction),
112 /// Update pinch zoom details stored in the top level window
113 UpdatePinchZoomInfos(PipelineId, PinchZoomInfos),
114 /// Activate or deactivate accessibility features for the given `WebView`.
115 SetAccessibilityActive(WebViewId, bool),
116 /// Clears the session history for the `WebView` with the given `WebViewId`, leaving
117 /// the `WebView` with only the current URL in its session history.
118 ClearSessionHistory(WebViewId),
119}
120
121pub enum UserContentManagerAction {
122 AddUserScript(UserScript),
123 DestroyUserContentManager,
124 RemoveUserScript(UserScriptId),
125 AddUserStyleSheet(UserStyleSheet),
126 RemoveUserStyleSheet(UserStyleSheetId),
127}
128
129/// A description of a paint metric that is sent from the Servo renderer to the
130/// constellation.
131pub enum PaintMetricEvent {
132 FirstPaint(CrossProcessInstant, bool /* first_reflow */),
133 FirstContentfulPaint(CrossProcessInstant, bool /* first_reflow */),
134 LargestContentfulPaint(CrossProcessInstant, LCPCandidateID),
135}
136
137impl fmt::Debug for EmbedderToConstellationMessage {
138 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
139 let variant_string: &'static str = self.into();
140 write!(formatter, "ConstellationMsg::{variant_string}")
141 }
142}
143
144/// A log entry reported to the constellation
145/// We don't report all log entries, just serious ones.
146/// We need a separate type for this because `LogLevel` isn't serializable.
147#[derive(Clone, Debug, Deserialize, Serialize)]
148pub enum LogEntry {
149 /// Panic, with a reason and backtrace
150 Panic(String, String),
151 /// Error, with a reason
152 Error(String),
153 /// warning, with a reason
154 Warn(String),
155}
156
157/// The type of window size change.
158#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
159pub enum WindowSizeType {
160 /// Initial load.
161 Initial,
162 /// Window resize.
163 Resize,
164}
165
166/// The direction of a history traversal
167#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
168pub enum TraversalDirection {
169 /// Travel forward the given number of documents.
170 Forward(usize),
171 /// Travel backward the given number of documents.
172 Back(usize),
173}
174
175/// The source of a [`HistoryTraversalRequest`].
176#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
177pub enum HistoryTraversalSource {
178 /// The traversal was triggered from the embedder, which means it is expecting
179 /// a notification when the request has completed.
180 Embedder,
181 /// The traversal was triggered from the script event loop.
182 Script,
183}
184
185/// A history traversal request.
186#[derive(Clone, Debug, Deserialize, Serialize)]
187pub struct SessionHistoryTraversalRequest {
188 /// An identifier that uniquely identifies this [`HistoryTraversalRequest`].
189 pub id: TraversalId,
190 /// The `WebView` that should be traversed.
191 pub webview_id: WebViewId,
192 /// The direction and number of steps that should be traversed.
193 pub direction: TraversalDirection,
194 /// The [`HistoryTraversalSource`] of this [`HistoryTraversalRequest`].
195 pub source: HistoryTraversalSource,
196}
197
198impl SessionHistoryTraversalRequest {
199 /// Create a new [`HistoryTraversalRequest`] either due to an embedder API call
200 /// or a script-initiated history traversal.
201 pub fn new(
202 webview_id: WebViewId,
203 direction: TraversalDirection,
204 source: HistoryTraversalSource,
205 ) -> Self {
206 Self {
207 id: TraversalId::new(),
208 webview_id,
209 direction,
210 source,
211 }
212 }
213}
214
215/// A task on the <https://html.spec.whatwg.org/multipage/#port-message-queue>
216#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
217pub struct PortMessageTask {
218 /// The origin of this task.
219 pub origin: ImmutableOrigin,
220 /// A data-holder for serialized data and transferred objects.
221 pub data: StructuredSerializedData,
222}
223
224/// The information needed by a global to process the transfer of a port.
225#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
226pub struct PortTransferInfo {
227 /// <https://html.spec.whatwg.org/multipage/#port-message-queue>
228 pub port_message_queue: VecDeque<PortMessageTask>,
229 /// A boolean indicating whether the port has been disentangled while in transfer,
230 /// if so, the disentanglement should be completed along with the transfer.
231 /// <https://html.spec.whatwg.org/multipage/#disentangle>
232 pub disentangled: bool,
233}
234
235/// Messages for communication between the constellation and a global managing ports.
236#[derive(Debug, Deserialize, Serialize)]
237#[expect(clippy::large_enum_variant)]
238pub enum MessagePortMsg {
239 /// Complete the transfer for a batch of ports.
240 CompleteTransfer(FxHashMap<MessagePortId, PortTransferInfo>),
241 /// Complete the transfer of a single port,
242 /// whose transfer was pending because it had been requested
243 /// while a previous failed transfer was being rolled-back.
244 CompletePendingTransfer(MessagePortId, PortTransferInfo),
245 /// <https://html.spec.whatwg.org/multipage/#disentangle>
246 CompleteDisentanglement(MessagePortId),
247 /// Handle a new port-message-task.
248 NewTask(MessagePortId, PortMessageTask),
249}
250
251/// A data structure which contains information for the pipeline after a scroll happens in the
252/// embedder-side `WebView`.
253#[derive(Debug, Deserialize, Serialize)]
254pub struct ScrollStateUpdate {
255 /// The [`ExternalScrollId`] of the node that that was scrolled.
256 pub scrolled_node: ExternalScrollId,
257 /// A map containing the scroll offsets of the entire scroll tree. This is necessary,
258 /// because scroll events can cause other nodes to scroll due to sticky positioning.
259 pub offsets: FxHashMap<ExternalScrollId, LayoutVector2D>,
260}