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 embedder_traits::{
21 CompositorHitTestResult, InputEvent, JavaScriptEvaluationId, MediaSessionActionType, Theme,
22 TraversalId, ViewportDetails, WebDriverCommandMsg, WebDriverCommandResponse,
23};
24pub use from_script_message::*;
25use ipc_channel::ipc::IpcSender;
26use malloc_size_of_derive::MallocSizeOf;
27use profile_traits::mem::MemoryReportResult;
28use rustc_hash::FxHashMap;
29use serde::{Deserialize, Serialize};
30use servo_config::prefs::PrefValue;
31use servo_url::{ImmutableOrigin, ServoUrl};
32pub use structured_data::*;
33use strum_macros::IntoStaticStr;
34use webrender_api::units::LayoutVector2D;
35use webrender_api::{ExternalScrollId, ImageKey};
36
37/// Messages to the Constellation from the embedding layer, whether from `ServoRenderer` or
38/// from `libservo` itself.
39#[derive(IntoStaticStr)]
40pub enum EmbedderToConstellationMessage {
41 /// Exit the constellation.
42 Exit,
43 /// Whether to allow script to navigate.
44 AllowNavigationResponse(PipelineId, bool),
45 /// Request to load a page.
46 LoadUrl(WebViewId, ServoUrl),
47 /// Clear the network cache.
48 ClearCache,
49 /// Request to traverse the joint session history of the provided browsing context.
50 TraverseHistory(WebViewId, TraversalDirection, TraversalId),
51 /// Inform the Constellation that a `WebView`'s [`ViewportDetails`] have changed.
52 ChangeViewportDetails(WebViewId, ViewportDetails, WindowSizeType),
53 /// Inform the constellation of a theme change.
54 ThemeChange(WebViewId, Theme),
55 /// Requests that the constellation instruct script/layout to try to layout again and tick
56 /// animations.
57 TickAnimation(Vec<WebViewId>),
58 /// Notify the `ScriptThread` that the Servo renderer is no longer waiting on
59 /// asynchronous image uploads for the given `Pipeline`. These are mainly used
60 /// by canvas to perform uploads while the display list is being built.
61 NoLongerWaitingOnAsynchronousImageUpdates(Vec<PipelineId>),
62 /// Dispatch a webdriver command
63 WebDriverCommand(WebDriverCommandMsg),
64 /// Reload a top-level browsing context.
65 Reload(WebViewId),
66 /// A log entry, with the top-level browsing context id and thread name
67 LogEntry(Option<WebViewId>, Option<String>, LogEntry),
68 /// Create a new top level browsing context.
69 NewWebView(ServoUrl, WebViewId, ViewportDetails),
70 /// Close a top level browsing context.
71 CloseWebView(WebViewId),
72 /// Panic a top level browsing context.
73 SendError(Option<WebViewId>, String),
74 /// Make a webview focused. [EmbedderMsg::WebViewFocused] will be sent with
75 /// the result of this operation.
76 FocusWebView(WebViewId),
77 /// Make none of the webviews focused.
78 BlurWebView,
79 /// Forward an input event to an appropriate ScriptTask.
80 ForwardInputEvent(WebViewId, InputEvent, Option<CompositorHitTestResult>),
81 /// Request that the given pipeline refresh the cursor by doing a hit test at the most
82 /// recently hovered cursor position and resetting the cursor. This happens after a
83 /// display list update is rendered.
84 RefreshCursor(PipelineId),
85 /// Enable the sampling profiler, with a given sampling rate and max total sampling duration.
86 ToggleProfiler(Duration, Duration),
87 /// Request to exit from fullscreen mode
88 ExitFullScreen(WebViewId),
89 /// Media session action.
90 MediaSessionAction(MediaSessionActionType),
91 /// Set whether to use less resources, by stopping animations and running timers at a heavily limited rate.
92 SetWebViewThrottled(WebViewId, bool),
93 /// The Servo renderer scrolled and is updating the scroll states of the nodes in the
94 /// given pipeline via the constellation.
95 SetScrollStates(PipelineId, FxHashMap<ExternalScrollId, LayoutVector2D>),
96 /// Notify the constellation that a particular paint metric event has happened for the given pipeline.
97 PaintMetric(PipelineId, PaintMetricEvent),
98 /// Evaluate a JavaScript string in the context of a `WebView`. When execution is complete or an
99 /// error is encountered, a correpsonding message will be sent to the embedding layer.
100 EvaluateJavaScript(WebViewId, JavaScriptEvaluationId, String),
101 /// Create a memory report and return it via the ipc sender
102 CreateMemoryReport(IpcSender<MemoryReportResult>),
103 /// Sends the generated image key to the image cache associated with this pipeline.
104 SendImageKeysForPipeline(PipelineId, Vec<ImageKey>),
105 /// Set WebDriver input event handled sender.
106 SetWebDriverResponseSender(IpcSender<WebDriverCommandResponse>),
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}
113
114/// A description of a paint metric that is sent from the Servo renderer to the
115/// constellation.
116pub enum PaintMetricEvent {
117 FirstPaint(CrossProcessInstant, bool /* first_reflow */),
118 FirstContentfulPaint(CrossProcessInstant, bool /* first_reflow */),
119}
120
121impl fmt::Debug for EmbedderToConstellationMessage {
122 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
123 let variant_string: &'static str = self.into();
124 write!(formatter, "ConstellationMsg::{variant_string}")
125 }
126}
127
128/// A log entry reported to the constellation
129/// We don't report all log entries, just serious ones.
130/// We need a separate type for this because `LogLevel` isn't serializable.
131#[derive(Clone, Debug, Deserialize, Serialize)]
132pub enum LogEntry {
133 /// Panic, with a reason and backtrace
134 Panic(String, String),
135 /// Error, with a reason
136 Error(String),
137 /// warning, with a reason
138 Warn(String),
139}
140
141/// The type of window size change.
142#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
143pub enum WindowSizeType {
144 /// Initial load.
145 Initial,
146 /// Window resize.
147 Resize,
148}
149
150/// The direction of a history traversal
151#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
152pub enum TraversalDirection {
153 /// Travel forward the given number of documents.
154 Forward(usize),
155 /// Travel backward the given number of documents.
156 Back(usize),
157}
158
159/// A task on the <https://html.spec.whatwg.org/multipage/#port-message-queue>
160#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
161pub struct PortMessageTask {
162 /// The origin of this task.
163 pub origin: ImmutableOrigin,
164 /// A data-holder for serialized data and transferred objects.
165 pub data: StructuredSerializedData,
166}
167
168/// The information needed by a global to process the transfer of a port.
169#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
170pub struct PortTransferInfo {
171 /// <https://html.spec.whatwg.org/multipage/#port-message-queue>
172 pub port_message_queue: VecDeque<PortMessageTask>,
173 /// A boolean indicating whether the port has been disentangled while in transfer,
174 /// if so, the disentanglement should be completed along with the transfer.
175 /// <https://html.spec.whatwg.org/multipage/#disentangle>
176 pub disentangled: bool,
177}
178
179/// Messages for communication between the constellation and a global managing ports.
180#[derive(Debug, Deserialize, Serialize)]
181#[allow(clippy::large_enum_variant)]
182pub enum MessagePortMsg {
183 /// Complete the transfer for a batch of ports.
184 CompleteTransfer(FxHashMap<MessagePortId, PortTransferInfo>),
185 /// Complete the transfer of a single port,
186 /// whose transfer was pending because it had been requested
187 /// while a previous failed transfer was being rolled-back.
188 CompletePendingTransfer(MessagePortId, PortTransferInfo),
189 /// <https://html.spec.whatwg.org/multipage/#disentangle>
190 CompleteDisentanglement(MessagePortId),
191 /// Handle a new port-message-task.
192 NewTask(MessagePortId, PortMessageTask),
193}