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