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