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::Epoch;
19use base::cross_process_instant::CrossProcessInstant;
20use base::id::{MessagePortId, PipelineId, WebViewId};
21use embedder_traits::{
22    CompositorHitTestResult, FocusId, InputEvent, JavaScriptEvaluationId, MediaSessionActionType,
23    Theme, TraversalId, ViewportDetails, WebDriverCommandMsg, WebDriverCommandResponse,
24};
25use fnv::FnvHashMap;
26pub use from_script_message::*;
27use ipc_channel::ipc::IpcSender;
28use malloc_size_of_derive::MallocSizeOf;
29use profile_traits::mem::MemoryReportResult;
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    /// Query the constellation to see if the current compositor output is stable
45    IsReadyToSaveImage(FnvHashMap<PipelineId, Epoch>),
46    /// Whether to allow script to navigate.
47    AllowNavigationResponse(PipelineId, bool),
48    /// Request to load a page.
49    LoadUrl(WebViewId, ServoUrl),
50    /// Clear the network cache.
51    ClearCache,
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<WebViewId>, Option<String>, LogEntry),
71    /// Create a new top level browsing context.
72    NewWebView(ServoUrl, WebViewId, ViewportDetails),
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, FocusId),
80    /// Make none of the webviews focused.
81    BlurWebView,
82    /// Forward an input event to an appropriate ScriptTask.
83    ForwardInputEvent(WebViewId, InputEvent, Option<CompositorHitTestResult>),
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, FnvHashMap<ExternalScrollId, LayoutVector2D>),
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 ipc sender
105    CreateMemoryReport(IpcSender<MemoryReportResult>),
106    /// Sends the generated image key to the image cache associated with this pipeline.
107    SendImageKeysForPipeline(PipelineId, Vec<ImageKey>),
108    /// Set WebDriver input event handled sender.
109    SetWebDriverResponseSender(IpcSender<WebDriverCommandResponse>),
110    /// A set of preferences were updated with the given new values.
111    PreferencesUpdated(Vec<(&'static str, PrefValue)>),
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(FnvHashMap<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}