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::id::{MessagePortId, PipelineId, WebViewId};
20use compositing_traits::largest_contentful_paint_candidate::LargestContentfulPaintType;
21use embedder_traits::{
22    CompositorHitTestResult, EmbedderControlId, EmbedderControlResponse, InputEventAndId,
23    JavaScriptEvaluationId, MediaSessionActionType, Theme, TraversalId, ViewportDetails,
24    WebDriverCommandMsg,
25};
26pub use from_script_message::*;
27use ipc_channel::ipc::IpcSender;
28use malloc_size_of_derive::MallocSizeOf;
29use profile_traits::mem::MemoryReportResult;
30use rustc_hash::FxHashMap;
31use serde::{Deserialize, Serialize};
32use servo_config::prefs::PrefValue;
33use servo_url::{ImmutableOrigin, ServoUrl};
34pub use structured_data::*;
35use strum_macros::IntoStaticStr;
36use webrender_api::units::LayoutVector2D;
37use webrender_api::{ExternalScrollId, ImageKey};
38
39/// Messages to the Constellation from the embedding layer, whether from `ServoRenderer` or
40/// from `libservo` itself.
41#[derive(IntoStaticStr)]
42pub enum EmbedderToConstellationMessage {
43    /// Exit the constellation.
44    Exit,
45    /// Whether to allow script to navigate.
46    AllowNavigationResponse(PipelineId, bool),
47    /// Request to load a page.
48    LoadUrl(WebViewId, ServoUrl),
49    /// Clear the network cache.
50    ClearCache,
51    /// Request to traverse the joint session history of the provided browsing context.
52    TraverseHistory(WebViewId, TraversalDirection, TraversalId),
53    /// Inform the Constellation that a `WebView`'s [`ViewportDetails`] have changed.
54    ChangeViewportDetails(WebViewId, ViewportDetails, WindowSizeType),
55    /// Inform the constellation of a theme change.
56    ThemeChange(WebViewId, Theme),
57    /// Requests that the constellation instruct script/layout to try to layout again and tick
58    /// animations.
59    TickAnimation(Vec<WebViewId>),
60    /// Notify the `ScriptThread` that the Servo renderer is no longer waiting on
61    /// asynchronous image uploads for the given `Pipeline`. These are mainly used
62    /// by canvas to perform uploads while the display list is being built.
63    NoLongerWaitingOnAsynchronousImageUpdates(Vec<PipelineId>),
64    /// Dispatch a webdriver command
65    WebDriverCommand(WebDriverCommandMsg),
66    /// Reload a top-level browsing context.
67    Reload(WebViewId),
68    /// A log entry, with the top-level browsing context id and thread name
69    LogEntry(Option<WebViewId>, Option<String>, LogEntry),
70    /// Create a new top level browsing context.
71    NewWebView(ServoUrl, WebViewId, ViewportDetails),
72    /// Close a top level browsing context.
73    CloseWebView(WebViewId),
74    /// Panic a top level browsing context.
75    SendError(Option<WebViewId>, String),
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<CompositorHitTestResult>),
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, FxHashMap<ExternalScrollId, LayoutVector2D>),
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 ipc sender
104    CreateMemoryReport(IpcSender<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}
115
116/// A description of a paint metric that is sent from the Servo renderer to the
117/// constellation.
118pub enum PaintMetricEvent {
119    FirstPaint(CrossProcessInstant, bool /* first_reflow */),
120    FirstContentfulPaint(CrossProcessInstant, bool /* first_reflow */),
121    LargestContentfulPaint(
122        CrossProcessInstant,
123        usize, /* area */
124        LargestContentfulPaintType,
125    ),
126}
127
128impl fmt::Debug for EmbedderToConstellationMessage {
129    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
130        let variant_string: &'static str = self.into();
131        write!(formatter, "ConstellationMsg::{variant_string}")
132    }
133}
134
135/// A log entry reported to the constellation
136/// We don't report all log entries, just serious ones.
137/// We need a separate type for this because `LogLevel` isn't serializable.
138#[derive(Clone, Debug, Deserialize, Serialize)]
139pub enum LogEntry {
140    /// Panic, with a reason and backtrace
141    Panic(String, String),
142    /// Error, with a reason
143    Error(String),
144    /// warning, with a reason
145    Warn(String),
146}
147
148/// The type of window size change.
149#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
150pub enum WindowSizeType {
151    /// Initial load.
152    Initial,
153    /// Window resize.
154    Resize,
155}
156
157/// The direction of a history traversal
158#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
159pub enum TraversalDirection {
160    /// Travel forward the given number of documents.
161    Forward(usize),
162    /// Travel backward the given number of documents.
163    Back(usize),
164}
165
166/// A task on the <https://html.spec.whatwg.org/multipage/#port-message-queue>
167#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
168pub struct PortMessageTask {
169    /// The origin of this task.
170    pub origin: ImmutableOrigin,
171    /// A data-holder for serialized data and transferred objects.
172    pub data: StructuredSerializedData,
173}
174
175/// The information needed by a global to process the transfer of a port.
176#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
177pub struct PortTransferInfo {
178    /// <https://html.spec.whatwg.org/multipage/#port-message-queue>
179    pub port_message_queue: VecDeque<PortMessageTask>,
180    /// A boolean indicating whether the port has been disentangled while in transfer,
181    /// if so, the disentanglement should be completed along with the transfer.
182    /// <https://html.spec.whatwg.org/multipage/#disentangle>
183    pub disentangled: bool,
184}
185
186/// Messages for communication between the constellation and a global managing ports.
187#[derive(Debug, Deserialize, Serialize)]
188#[allow(clippy::large_enum_variant)]
189pub enum MessagePortMsg {
190    /// Complete the transfer for a batch of ports.
191    CompleteTransfer(FxHashMap<MessagePortId, PortTransferInfo>),
192    /// Complete the transfer of a single port,
193    /// whose transfer was pending because it had been requested
194    /// while a previous failed transfer was being rolled-back.
195    CompletePendingTransfer(MessagePortId, PortTransferInfo),
196    /// <https://html.spec.whatwg.org/multipage/#disentangle>
197    CompleteDisentanglement(MessagePortId),
198    /// Handle a new port-message-task.
199    NewTask(MessagePortId, PortMessageTask),
200}