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 base::cross_process_instant::CrossProcessInstant;
19use base::generic_channel::GenericCallback;
20use base::id::{MessagePortId, PipelineId, ScriptEventLoopId, WebViewId};
21use embedder_traits::user_contents::{
22 UserContentManagerId, UserScript, UserScriptId, UserStyleSheet, UserStyleSheetId,
23};
24use embedder_traits::{
25 EmbedderControlId, EmbedderControlResponse, InputEventAndId, JavaScriptEvaluationId,
26 MediaSessionActionType, NewWebViewDetails, PaintHitTestResult, Theme, TraversalId,
27 ViewportDetails, WebDriverCommandMsg,
28};
29pub use from_script_message::*;
30use malloc_size_of_derive::MallocSizeOf;
31use paint_api::PinchZoomInfos;
32use paint_api::largest_contentful_paint_candidate::LargestContentfulPaintType;
33use profile_traits::mem::MemoryReportResult;
34use rustc_hash::FxHashMap;
35use serde::{Deserialize, Serialize};
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.
52 LoadUrl(WebViewId, ServoUrl),
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 /// Panic a top level browsing context.
77 SendError(Option<WebViewId>, String),
78 /// Make a webview focused. [EmbedderMsg::WebViewFocused] will be sent with
79 /// the result of this operation.
80 FocusWebView(WebViewId),
81 /// Make none of the webviews focused.
82 BlurWebView,
83 /// Forward an input event to an appropriate ScriptTask.
84 ForwardInputEvent(WebViewId, InputEventAndId, Option<PaintHitTestResult>),
85 /// Request that the given pipeline refresh the cursor by doing a hit test at the most
86 /// recently hovered cursor position and resetting the cursor. This happens after a
87 /// display list update is rendered.
88 RefreshCursor(PipelineId),
89 /// Enable the sampling profiler, with a given sampling rate and max total sampling duration.
90 ToggleProfiler(Duration, Duration),
91 /// Request to exit from fullscreen mode
92 ExitFullScreen(WebViewId),
93 /// Media session action.
94 MediaSessionAction(MediaSessionActionType),
95 /// Set whether to use less resources, by stopping animations and running timers at a heavily limited rate.
96 SetWebViewThrottled(WebViewId, bool),
97 /// The Servo renderer scrolled and is updating the scroll states of the nodes in the
98 /// given pipeline via the constellation.
99 SetScrollStates(PipelineId, FxHashMap<ExternalScrollId, LayoutVector2D>),
100 /// Notify the constellation that a particular paint metric event has happened for the given pipeline.
101 PaintMetric(PipelineId, PaintMetricEvent),
102 /// Evaluate a JavaScript string in the context of a `WebView`. When execution is complete or an
103 /// error is encountered, a correpsonding message will be sent to the embedding layer.
104 EvaluateJavaScript(WebViewId, JavaScriptEvaluationId, String),
105 /// Create a memory report and return it via the [`GenericCallback`]
106 CreateMemoryReport(GenericCallback<MemoryReportResult>),
107 /// Sends the generated image key to the image cache associated with this pipeline.
108 SendImageKeysForPipeline(PipelineId, Vec<ImageKey>),
109 /// A set of preferences were updated with the given new values.
110 PreferencesUpdated(Vec<(&'static str, PrefValue)>),
111 /// Request preparation for a screenshot of the given WebView. The Constellation will
112 /// send a message to the Embedder when the screenshot is ready to be taken.
113 RequestScreenshotReadiness(WebViewId),
114 /// A response to a request to show an embedder user interface control.
115 EmbedderControlResponse(EmbedderControlId, EmbedderControlResponse),
116 /// An action to perform on the given `UserContentManagerId`.
117 UserContentManagerAction(UserContentManagerId, UserContentManagerAction),
118 /// Update pinch zoom details stored in the top level window
119 UpdatePinchZoomInfos(PipelineId, PinchZoomInfos),
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 LargestContentfulPaintType,
139 ),
140}
141
142impl fmt::Debug for EmbedderToConstellationMessage {
143 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
144 let variant_string: &'static str = self.into();
145 write!(formatter, "ConstellationMsg::{variant_string}")
146 }
147}
148
149/// A log entry reported to the constellation
150/// We don't report all log entries, just serious ones.
151/// We need a separate type for this because `LogLevel` isn't serializable.
152#[derive(Clone, Debug, Deserialize, Serialize)]
153pub enum LogEntry {
154 /// Panic, with a reason and backtrace
155 Panic(String, String),
156 /// Error, with a reason
157 Error(String),
158 /// warning, with a reason
159 Warn(String),
160}
161
162/// The type of window size change.
163#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
164pub enum WindowSizeType {
165 /// Initial load.
166 Initial,
167 /// Window resize.
168 Resize,
169}
170
171/// The direction of a history traversal
172#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
173pub enum TraversalDirection {
174 /// Travel forward the given number of documents.
175 Forward(usize),
176 /// Travel backward the given number of documents.
177 Back(usize),
178}
179
180/// A task on the <https://html.spec.whatwg.org/multipage/#port-message-queue>
181#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
182pub struct PortMessageTask {
183 /// The origin of this task.
184 pub origin: ImmutableOrigin,
185 /// A data-holder for serialized data and transferred objects.
186 pub data: StructuredSerializedData,
187}
188
189/// The information needed by a global to process the transfer of a port.
190#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
191pub struct PortTransferInfo {
192 /// <https://html.spec.whatwg.org/multipage/#port-message-queue>
193 pub port_message_queue: VecDeque<PortMessageTask>,
194 /// A boolean indicating whether the port has been disentangled while in transfer,
195 /// if so, the disentanglement should be completed along with the transfer.
196 /// <https://html.spec.whatwg.org/multipage/#disentangle>
197 pub disentangled: bool,
198}
199
200/// Messages for communication between the constellation and a global managing ports.
201#[derive(Debug, Deserialize, Serialize)]
202#[expect(clippy::large_enum_variant)]
203pub enum MessagePortMsg {
204 /// Complete the transfer for a batch of ports.
205 CompleteTransfer(FxHashMap<MessagePortId, PortTransferInfo>),
206 /// Complete the transfer of a single port,
207 /// whose transfer was pending because it had been requested
208 /// while a previous failed transfer was being rolled-back.
209 CompletePendingTransfer(MessagePortId, PortTransferInfo),
210 /// <https://html.spec.whatwg.org/multipage/#disentangle>
211 CompleteDisentanglement(MessagePortId),
212 /// Handle a new port-message-task.
213 NewTask(MessagePortId, PortMessageTask),
214}