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