Skip to main content

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 accesskit::ActionRequest;
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::display_list::PaintTimingInfo;
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::{
36    ContainerTimingID, LCPCandidateID, MessagePortId, PipelineId, ScriptEventLoopId, WebViewId,
37};
38use servo_canvas_traits::webgl::GenericSender;
39use servo_config::prefs::PrefValue;
40use servo_url::{ImmutableOrigin, ServoUrl};
41pub use structured_data::*;
42use strum::IntoStaticStr;
43use webrender_api::units::LayoutVector2D;
44use webrender_api::{ExternalScrollId, ImageKey};
45
46/// Messages to the Constellation from the embedding layer, whether from `ServoRenderer` or
47/// from `libservo` itself.
48#[derive(IntoStaticStr)]
49pub enum EmbedderToConstellationMessage {
50    /// Exit the constellation.
51    Exit,
52    /// Whether to allow script to navigate.
53    AllowNavigationResponse(PipelineId, bool),
54    /// Request to load a page, with optionally additional data in [`URLRequest`].
55    LoadUrl(WebViewId, UrlRequest),
56    /// Request to traverse the joint session history of the provided browsing context.
57    TraverseHistory(SessionHistoryTraversalRequest),
58    /// Inform the Constellation that a `WebView`'s [`ViewportDetails`] have changed.
59    ChangeViewportDetails(WebViewId, ViewportDetails, WindowSizeType),
60    /// Inform the constellation of a theme change.
61    ThemeChange(WebViewId, Theme),
62    /// Requests that the constellation instruct script/layout to try to layout again and tick
63    /// animations.
64    TickAnimation(Vec<WebViewId>),
65    /// Notify the `ScriptThread` that the Servo renderer is no longer waiting on
66    /// asynchronous image uploads for the given `Pipeline`. These are mainly used
67    /// by canvas to perform uploads while the display list is being built.
68    NoLongerWaitingOnAsynchronousImageUpdates(Vec<PipelineId>),
69    /// Dispatch a webdriver command
70    WebDriverCommand(WebDriverCommandMsg),
71    /// Reload a top-level browsing context.
72    Reload(WebViewId),
73    /// A log entry, with the top-level browsing context id and thread name
74    LogEntry(Option<ScriptEventLoopId>, Option<String>, LogEntry),
75    /// Create a new top level browsing context.
76    NewWebView(ServoUrl, NewWebViewDetails),
77    /// Close a top level browsing context.
78    CloseWebView(WebViewId),
79    /// Set whether a WebView has system focus. This corresponds to the [HTML
80    /// specification's] concept of "system focus" and is distinct from the browsing
81    /// context or element that has focus within the WebView.
82    SetWebViewHasSystemFocus(WebViewId, bool),
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    /// Request to exit from fullscreen mode
90    ExitFullScreen(WebViewId),
91    /// Media session action.
92    MediaSessionAction(MediaSessionActionType),
93    /// Notify the Constellation that a WebView has been hidden. Hidden `WebView`s are throttled,
94    /// which means they use less resources, by stopping animations and running timers at a
95    /// heavily limited rate.
96    SetWebViewHidden(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, ScrollStateUpdate),
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    /// Activate or deactivate accessibility features for the given `WebView`.
121    SetAccessibilityActive(WebViewId, bool),
122    /// Forward an incoming [`accesskit::ActionRequest`] to the correct pipeline.
123    ForwardAccessibilityAction(ActionRequest),
124    /// Clears the session history for the `WebView` with the given `WebViewId`, leaving
125    /// the `WebView` with only the current URL in its session history.
126    ClearSessionHistory(WebViewId),
127    /// Inform the `Constellation` that the embedder has changed the network
128    /// online state.
129    SetNetworkOnlineState(bool),
130    /// Stores the http cache to disk and sends a message back when it is done.
131    StoreCacheToDisk(GenericSender<()>),
132}
133
134pub enum UserContentManagerAction {
135    AddUserScript(UserScript),
136    DestroyUserContentManager,
137    RemoveUserScript(UserScriptId),
138    AddUserStyleSheet(UserStyleSheet),
139    RemoveUserStyleSheet(UserStyleSheetId),
140}
141
142/// A description of a paint metric that is sent from the Servo renderer to the
143/// constellation and then forwarded to the script thread.
144#[derive(Clone, Debug, Deserialize, Serialize)]
145pub enum PaintMetricEvent {
146    FirstPaint(PaintTimingInfo, bool /* first_reflow */),
147    FirstContentfulPaint(PaintTimingInfo, bool /* first_reflow */),
148    LargestContentfulPaint(PaintTimingInfo, LCPCandidateID),
149    /// The Container Timing updates presented in a single composited frame. Script holds
150    /// the records these IDs refer to; all paint contributes is the frame's paint time.
151    /// <https://wicg.github.io/container-timing/>
152    ContainerTiming(CrossProcessInstant, Vec<ContainerTimingID>),
153}
154
155impl fmt::Debug for EmbedderToConstellationMessage {
156    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
157        let variant_string: &'static str = self.into();
158        write!(formatter, "ConstellationMsg::{variant_string}")
159    }
160}
161
162/// A log entry reported to the constellation
163/// We don't report all log entries, just serious ones.
164/// We need a separate type for this because `LogLevel` isn't serializable.
165#[derive(Clone, Debug, Deserialize, Serialize)]
166pub enum LogEntry {
167    /// Panic, with a reason and backtrace
168    Panic(String, String),
169    /// Error, with a reason
170    Error(String),
171    /// warning, with a reason
172    Warn(String),
173}
174
175/// The type of window size change.
176#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
177pub enum WindowSizeType {
178    /// Initial load.
179    Initial,
180    /// Window resize.
181    Resize,
182}
183
184/// The direction of a history traversal
185#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
186pub enum TraversalDirection {
187    /// Travel forward the given number of documents.
188    Forward(usize),
189    /// Travel backward the given number of documents.
190    Back(usize),
191}
192
193/// The source of a [`HistoryTraversalRequest`].
194#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
195pub enum HistoryTraversalSource {
196    /// The traversal was triggered from the embedder, which means it is expecting
197    /// a notification when the request has completed.
198    Embedder,
199    /// The traversal was triggered from the script event loop.
200    Script,
201}
202
203/// A history traversal request.
204#[derive(Clone, Debug, Deserialize, Serialize)]
205pub struct SessionHistoryTraversalRequest {
206    /// An identifier that uniquely identifies this [`HistoryTraversalRequest`].
207    pub id: TraversalId,
208    /// The `WebView` that should be traversed.
209    pub webview_id: WebViewId,
210    /// The direction and number of steps that should be traversed.
211    pub direction: TraversalDirection,
212    /// The [`HistoryTraversalSource`] of this [`HistoryTraversalRequest`].
213    pub source: HistoryTraversalSource,
214}
215
216impl SessionHistoryTraversalRequest {
217    /// Create a new [`HistoryTraversalRequest`] either due to an embedder API call
218    /// or a script-initiated history traversal.
219    pub fn new(
220        webview_id: WebViewId,
221        direction: TraversalDirection,
222        source: HistoryTraversalSource,
223    ) -> Self {
224        Self {
225            id: TraversalId::new(),
226            webview_id,
227            direction,
228            source,
229        }
230    }
231}
232
233/// A task on the <https://html.spec.whatwg.org/multipage/#port-message-queue>
234#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
235pub struct PortMessageTask {
236    /// The origin of this task.
237    pub origin: ImmutableOrigin,
238    /// A data-holder for serialized data and transferred objects.
239    pub data: StructuredSerializedData,
240}
241
242/// The information needed by a global to process the transfer of a port.
243#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
244pub struct PortTransferInfo {
245    /// <https://html.spec.whatwg.org/multipage/#port-message-queue>
246    pub port_message_queue: VecDeque<PortMessageTask>,
247    /// A boolean indicating whether the port has been disentangled while in transfer,
248    /// if so, the disentanglement should be completed along with the transfer.
249    /// <https://html.spec.whatwg.org/multipage/#disentangle>
250    pub disentangled: bool,
251}
252
253/// Messages for communication between the constellation and a global managing ports.
254#[derive(Debug, Deserialize, Serialize)]
255#[expect(clippy::large_enum_variant)]
256pub enum MessagePortMsg {
257    /// Complete the transfer for a batch of ports.
258    CompleteTransfer(FxHashMap<MessagePortId, PortTransferInfo>),
259    /// Complete the transfer of a single port,
260    /// whose transfer was pending because it had been requested
261    /// while a previous failed transfer was being rolled-back.
262    CompletePendingTransfer(MessagePortId, PortTransferInfo),
263    /// <https://html.spec.whatwg.org/multipage/#disentangle>
264    CompleteDisentanglement(MessagePortId),
265    /// Handle a new port-message-task.
266    NewTask(MessagePortId, PortMessageTask),
267}
268
269/// A data structure which contains information for the pipeline after a scroll happens in the
270/// embedder-side `WebView`.
271#[derive(Debug, Deserialize, Serialize)]
272pub struct ScrollStateUpdate {
273    /// The [`ExternalScrollId`] of the node that that was scrolled.
274    pub scrolled_node: ExternalScrollId,
275    /// A map containing the scroll offsets of the entire scroll tree. This is necessary,
276    /// because scroll events can cause other nodes to scroll due to sticky positioning.
277    pub offsets: FxHashMap<ExternalScrollId, LayoutVector2D>,
278}