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;
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 profile_traits::mem::MemoryReportResult;
30use rustc_hash::FxHashMap;
31use serde::{Deserialize, Serialize};
32use servo_base::cross_process_instant::CrossProcessInstant;
33use servo_base::generic_channel::GenericCallback;
34use servo_base::id::{MessagePortId, PipelineId, ScriptEventLoopId, WebViewId};
35use servo_config::prefs::PrefValue;
36use servo_url::{ImmutableOrigin, ServoUrl};
37pub use structured_data::*;
38use strum::IntoStaticStr;
39use webrender_api::units::LayoutVector2D;
40use webrender_api::{ExternalScrollId, ImageKey};
41
42/// Messages to the Constellation from the embedding layer, whether from `ServoRenderer` or
43/// from `libservo` itself.
44#[derive(IntoStaticStr)]
45pub enum EmbedderToConstellationMessage {
46    /// Exit the constellation.
47    Exit,
48    /// Whether to allow script to navigate.
49    AllowNavigationResponse(PipelineId, bool),
50    /// Request to load a page, with optionally additional data in [`URLRequest`].
51    LoadUrl(WebViewId, UrlRequest),
52    /// Request to traverse the joint session history of the provided browsing context.
53    TraverseHistory(WebViewId, TraversalDirection, TraversalId),
54    /// Inform the Constellation that a `WebView`'s [`ViewportDetails`] have changed.
55    ChangeViewportDetails(WebViewId, ViewportDetails, WindowSizeType),
56    /// Inform the constellation of a theme change.
57    ThemeChange(WebViewId, Theme),
58    /// Requests that the constellation instruct script/layout to try to layout again and tick
59    /// animations.
60    TickAnimation(Vec<WebViewId>),
61    /// Notify the `ScriptThread` that the Servo renderer is no longer waiting on
62    /// asynchronous image uploads for the given `Pipeline`. These are mainly used
63    /// by canvas to perform uploads while the display list is being built.
64    NoLongerWaitingOnAsynchronousImageUpdates(Vec<PipelineId>),
65    /// Dispatch a webdriver command
66    WebDriverCommand(WebDriverCommandMsg),
67    /// Reload a top-level browsing context.
68    Reload(WebViewId),
69    /// A log entry, with the top-level browsing context id and thread name
70    LogEntry(Option<ScriptEventLoopId>, Option<String>, LogEntry),
71    /// Create a new top level browsing context.
72    NewWebView(ServoUrl, NewWebViewDetails),
73    /// Close a top level browsing context.
74    CloseWebView(WebViewId),
75    /// Make a webview focused. [EmbedderMsg::WebViewFocused] will be sent with
76    /// the result of this operation.
77    FocusWebView(WebViewId),
78    /// Make none of the webviews focused.
79    BlurWebView,
80    /// Forward an input event to an appropriate ScriptTask.
81    ForwardInputEvent(WebViewId, InputEventAndId, Option<PaintHitTestResult>),
82    /// Request that the given pipeline refresh the cursor by doing a hit test at the most
83    /// recently hovered cursor position and resetting the cursor. This happens after a
84    /// display list update is rendered.
85    RefreshCursor(PipelineId),
86    /// Enable the sampling profiler, with a given sampling rate and max total sampling duration.
87    ToggleProfiler(Duration, Duration),
88    /// Request to exit from fullscreen mode
89    ExitFullScreen(WebViewId),
90    /// Media session action.
91    MediaSessionAction(MediaSessionActionType),
92    /// Set whether to use less resources, by stopping animations and running timers at a heavily limited rate.
93    SetWebViewThrottled(WebViewId, bool),
94    /// The Servo renderer scrolled and is updating the scroll states of the nodes in the
95    /// given pipeline via the constellation.
96    SetScrollStates(PipelineId, ScrollStateUpdate),
97    /// Notify the constellation that a particular paint metric event has happened for the given pipeline.
98    PaintMetric(PipelineId, PaintMetricEvent),
99    /// Evaluate a JavaScript string in the context of a `WebView`. When execution is complete or an
100    /// error is encountered, a correpsonding message will be sent to the embedding layer.
101    EvaluateJavaScript(WebViewId, JavaScriptEvaluationId, String),
102    /// Create a memory report and return it via the [`GenericCallback`]
103    CreateMemoryReport(GenericCallback<MemoryReportResult>),
104    /// Sends the generated image key to the image cache associated with this pipeline.
105    SendImageKeysForPipeline(PipelineId, Vec<ImageKey>),
106    /// A set of preferences were updated with the given new values.
107    PreferencesUpdated(Vec<(&'static str, PrefValue)>),
108    /// Request preparation for a screenshot of the given WebView. The Constellation will
109    /// send a message to the Embedder when the screenshot is ready to be taken.
110    RequestScreenshotReadiness(WebViewId),
111    /// A response to a request to show an embedder user interface control.
112    EmbedderControlResponse(EmbedderControlId, EmbedderControlResponse),
113    /// An action to perform on the given `UserContentManagerId`.
114    UserContentManagerAction(UserContentManagerId, UserContentManagerAction),
115    /// Update pinch zoom details stored in the top level window
116    UpdatePinchZoomInfos(PipelineId, PinchZoomInfos),
117    /// Activate or deactivate accessibility features for the given `WebView`.
118    SetAccessibilityActive(WebViewId, bool),
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, usize /* area */, Option<ServoUrl>),
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/// A task on the <https://html.spec.whatwg.org/multipage/#port-message-queue>
176#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
177pub struct PortMessageTask {
178    /// The origin of this task.
179    pub origin: ImmutableOrigin,
180    /// A data-holder for serialized data and transferred objects.
181    pub data: StructuredSerializedData,
182}
183
184/// The information needed by a global to process the transfer of a port.
185#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
186pub struct PortTransferInfo {
187    /// <https://html.spec.whatwg.org/multipage/#port-message-queue>
188    pub port_message_queue: VecDeque<PortMessageTask>,
189    /// A boolean indicating whether the port has been disentangled while in transfer,
190    /// if so, the disentanglement should be completed along with the transfer.
191    /// <https://html.spec.whatwg.org/multipage/#disentangle>
192    pub disentangled: bool,
193}
194
195/// Messages for communication between the constellation and a global managing ports.
196#[derive(Debug, Deserialize, Serialize)]
197#[expect(clippy::large_enum_variant)]
198pub enum MessagePortMsg {
199    /// Complete the transfer for a batch of ports.
200    CompleteTransfer(FxHashMap<MessagePortId, PortTransferInfo>),
201    /// Complete the transfer of a single port,
202    /// whose transfer was pending because it had been requested
203    /// while a previous failed transfer was being rolled-back.
204    CompletePendingTransfer(MessagePortId, PortTransferInfo),
205    /// <https://html.spec.whatwg.org/multipage/#disentangle>
206    CompleteDisentanglement(MessagePortId),
207    /// Handle a new port-message-task.
208    NewTask(MessagePortId, PortMessageTask),
209}
210
211/// A data structure which contains information for the pipeline after a scroll happens in the
212/// embedder-side `WebView`.
213#[derive(Debug, Deserialize, Serialize)]
214pub struct ScrollStateUpdate {
215    /// The [`ExternalScrollId`] of the node that that was scrolled.
216    pub scrolled_node: ExternalScrollId,
217    /// A map containing the scroll offsets of the entire scroll tree. This is necessary,
218    /// because scroll events can cause other nodes to scroll due to sticky positioning.
219    pub offsets: FxHashMap<ExternalScrollId, LayoutVector2D>,
220}