Skip to main content

embedder_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//! Types used by the embedding layer and/or exposed to the API. This crate is responsible for
6//! defining types that cross the process boundary from the embedding/rendering layer all the way
7//! to script, thus it should have very minimal dependencies on other parts of Servo. If a type
8//! is not exposed in the API or doesn't involve messages sent to the embedding/libservo layer, it
9//! is probably a better fit for the `servo_constellation_traits` crate.
10
11pub mod embedder_controls;
12pub mod geolocation;
13pub mod input_events;
14pub mod resources;
15pub mod user_contents;
16pub mod webdriver;
17
18use std::collections::HashMap;
19use std::ffi::c_void;
20use std::fmt::{Debug, Display, Error, Formatter};
21use std::hash::Hash;
22use std::ops::Range;
23use std::sync::Arc;
24
25use accesskit::TreeUpdate;
26use content_security_policy::Destination;
27use crossbeam_channel::Sender;
28use euclid::{Box2D, Point2D, Scale, Size2D, Vector2D};
29use http::{HeaderMap, Method, StatusCode};
30use log::warn;
31use malloc_size_of::malloc_size_of_is_0;
32use malloc_size_of_derive::MallocSizeOf;
33use pixels::SharedRasterImage;
34use serde::{Deserialize, Deserializer, Serialize, Serializer};
35use servo_base::Epoch;
36use servo_base::generic_channel::{
37    GenericCallback, GenericSender, GenericSharedMemory, SendResult,
38};
39use servo_base::id::{PipelineId, WebViewId};
40use servo_geometry::{DeviceIndependentIntRect, DeviceIndependentIntSize};
41use servo_url::ServoUrl;
42use strum::{EnumMessage, IntoStaticStr};
43use style::queries::values::PrefersColorScheme;
44use style_traits::CSSPixel;
45use url::Url;
46use uuid::Uuid;
47use webrender_api::ExternalScrollId;
48use webrender_api::units::{
49    DeviceIntPoint, DeviceIntRect, DeviceIntSize, DevicePixel, DevicePoint, DeviceRect,
50    DeviceVector2D, LayoutPoint, LayoutRect, LayoutSize, LayoutVector2D,
51};
52
53pub use crate::embedder_controls::*;
54pub use crate::geolocation::*;
55pub use crate::input_events::*;
56use crate::user_contents::UserContentManagerId;
57pub use crate::webdriver::*;
58
59/// A point in a `WebView`, either expressed in device pixels or page pixels.
60/// Page pixels are CSS pixels, which take into account device pixel scale,
61/// page zoom, and pinch zoom.
62#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
63pub enum WebViewPoint {
64    Device(DevicePoint),
65    Page(Point2D<f32, CSSPixel>),
66}
67
68impl WebViewPoint {
69    #[doc(hidden)]
70    pub fn as_device_point(&self, scale: Scale<f32, CSSPixel, DevicePixel>) -> DevicePoint {
71        match self {
72            Self::Device(point) => *point,
73            Self::Page(point) => *point * scale,
74        }
75    }
76}
77
78impl From<DevicePoint> for WebViewPoint {
79    fn from(point: DevicePoint) -> Self {
80        Self::Device(point)
81    }
82}
83
84impl From<LayoutPoint> for WebViewPoint {
85    fn from(point: LayoutPoint) -> Self {
86        Self::Page(Point2D::new(point.x, point.y))
87    }
88}
89
90impl From<Point2D<f32, CSSPixel>> for WebViewPoint {
91    fn from(point: Point2D<f32, CSSPixel>) -> Self {
92        Self::Page(point)
93    }
94}
95
96/// A rectangle in a `WebView`, either expressed in device pixels or page pixels.
97/// Page pixels are CSS pixels, which take into account device pixel scale,
98/// page zoom, and pinch zoom.
99#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
100pub enum WebViewRect {
101    Device(DeviceRect),
102    Page(Box2D<f32, CSSPixel>),
103}
104
105impl WebViewRect {
106    #[doc(hidden)]
107    pub fn as_device_rect(&self, scale: Scale<f32, CSSPixel, DevicePixel>) -> DeviceRect {
108        match self {
109            Self::Device(rect) => *rect,
110            Self::Page(rect) => *rect * scale,
111        }
112    }
113}
114
115impl From<DeviceRect> for WebViewRect {
116    fn from(rect: DeviceRect) -> Self {
117        Self::Device(rect)
118    }
119}
120
121impl From<LayoutRect> for WebViewRect {
122    fn from(rect: LayoutRect) -> Self {
123        Self::Page(Box2D::new(
124            Point2D::new(rect.min.x, rect.min.y),
125            Point2D::new(rect.max.x, rect.max.y),
126        ))
127    }
128}
129
130impl From<Box2D<f32, CSSPixel>> for WebViewRect {
131    fn from(rect: Box2D<f32, CSSPixel>) -> Self {
132        Self::Page(rect)
133    }
134}
135
136/// A 2D vector in a `WebView`, either expressed in device pixels or page pixels.
137/// Page pixels are CSS pixels, which take into account device pixel scale,
138/// page zoom, and pinch zoom.
139#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
140pub enum WebViewVector {
141    Device(DeviceVector2D),
142    Page(Vector2D<f32, CSSPixel>),
143}
144
145impl WebViewVector {
146    #[doc(hidden)]
147    pub fn as_device_vector(&self, scale: Scale<f32, CSSPixel, DevicePixel>) -> DeviceVector2D {
148        match self {
149            Self::Device(vector) => *vector,
150            Self::Page(vector) => *vector * scale,
151        }
152    }
153}
154
155impl From<DeviceVector2D> for WebViewVector {
156    fn from(vector: DeviceVector2D) -> Self {
157        Self::Device(vector)
158    }
159}
160
161impl From<LayoutVector2D> for WebViewVector {
162    fn from(vector: LayoutVector2D) -> Self {
163        Self::Page(Vector2D::new(vector.x, vector.y))
164    }
165}
166
167impl From<Vector2D<f32, CSSPixel>> for WebViewVector {
168    fn from(vector: Vector2D<f32, CSSPixel>) -> Self {
169        Self::Page(vector)
170    }
171}
172
173/// Represents the destination of a scroll operation.
174#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
175pub enum Scroll {
176    /// An offset to scroll by, with positive offsets revealing more content on the bottom
177    /// and right of the scrollable area.
178    Delta(WebViewVector),
179    /// Scroll to the start of the scrollable area.
180    Start,
181    /// Scroll to the end of the scrollable area.
182    End,
183}
184
185/// Tracks whether Servo isn't shutting down, is in the process of shutting down,
186/// or has finished shutting down.
187#[derive(Clone, Copy, Debug, PartialEq)]
188pub enum ShutdownState {
189    NotShuttingDown,
190    ShuttingDown,
191    FinishedShuttingDown,
192}
193
194/// A cursor for the window. This is different from a CSS cursor (see
195/// `CursorKind`) in that it has no `Auto` value.
196#[repr(u8)]
197#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
198pub enum Cursor {
199    None,
200    #[default]
201    Default,
202    Pointer,
203    ContextMenu,
204    Help,
205    Progress,
206    Wait,
207    Cell,
208    Crosshair,
209    Text,
210    VerticalText,
211    Alias,
212    Copy,
213    Move,
214    NoDrop,
215    NotAllowed,
216    Grab,
217    Grabbing,
218    EResize,
219    NResize,
220    NeResize,
221    NwResize,
222    SResize,
223    SeResize,
224    SwResize,
225    WResize,
226    EwResize,
227    NsResize,
228    NeswResize,
229    NwseResize,
230    ColResize,
231    RowResize,
232    AllScroll,
233    ZoomIn,
234    ZoomOut,
235}
236
237/// A way for Servo to request that the embedder wake up the main event loop.
238///
239/// A trait which embedders should implement to allow Servo to request that the
240/// embedder spin the Servo event loop on the main thread.
241pub trait EventLoopWaker: 'static + Send + Sync {
242    fn clone_box(&self) -> Box<dyn EventLoopWaker>;
243
244    /// This method is called when Servo wants the embedder to wake up the event loop.
245    ///
246    /// Note that this may be called on a different thread than the thread that was used to
247    /// start Servo. When called, the embedder is expected to call [`Servo::spin_event_loop`]
248    /// on the thread where Servo is running.
249    fn wake(&self);
250}
251
252impl Clone for Box<dyn EventLoopWaker> {
253    fn clone(&self) -> Self {
254        self.clone_box()
255    }
256}
257
258/// Sends messages to the embedder.
259pub struct GenericEmbedderProxy<T> {
260    pub sender: Sender<T>,
261    pub event_loop_waker: Box<dyn EventLoopWaker>,
262}
263
264impl<T> GenericEmbedderProxy<T> {
265    pub fn send(&self, message: T) {
266        // Send a message and kick the OS event loop awake.
267        if let Err(err) = self.sender.send(message) {
268            warn!("Failed to send response ({:?}).", err);
269        }
270        self.event_loop_waker.wake();
271    }
272}
273
274impl<T> Clone for GenericEmbedderProxy<T> {
275    fn clone(&self) -> Self {
276        Self {
277            sender: self.sender.clone(),
278            event_loop_waker: self.event_loop_waker.clone(),
279        }
280    }
281}
282
283pub type EmbedderProxy = GenericEmbedderProxy<EmbedderMsg>;
284
285/// A [`RefreshDriver`] is a trait that can be implemented by Servo embedders in
286/// order to drive let Servo know when to start preparing the next frame. For example,
287/// on systems that support Vsync notifications, an embedder may want to implement
288/// this trait to drive Servo animations via those notifications.
289pub trait RefreshDriver {
290    /// Servo will call this method when it wants to be informed of the next frame start
291    /// time. Implementors should call the callback when it is time to start preparing
292    /// the new frame.
293    ///
294    /// Multiple callbacks may be registered for the same frame. It is up to the implementation
295    /// to call *all* callbacks that have been registered since the last frame.
296    fn observe_next_frame(&self, start_frame_callback: Box<dyn Fn() + Send + 'static>);
297}
298
299/// Credentials to use in an HTTP authentication challenge.
300#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
301pub struct AuthenticationResponse {
302    /// Username for HTTP request authentication
303    pub username: String,
304    /// Password for HTTP request authentication
305    pub password: String,
306}
307
308/// A response to a request to allow or deny an action.
309#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
310pub enum AllowOrDeny {
311    Allow,
312    Deny,
313}
314
315#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
316/// Whether a protocol handler is requested to be registered or unregistered.
317pub enum RegisterOrUnregister {
318    Register,
319    Unregister,
320}
321
322/// A request from Servo to embedder to register or unregister a custom
323/// protocol handler for a scheme, typically triggered by web content.
324/// See <https://html.spec.whatwg.org/multipage/#custom-handlers>
325#[derive(Clone, Debug, Deserialize, Serialize)]
326pub struct ProtocolHandlerUpdateRegistration {
327    /// The scheme for the protocol handler.
328    pub scheme: String,
329    /// The URL to navigate to when handling requests for scheme.
330    pub url: ServoUrl,
331    /// Whether this update is to register or unregister the protocol handler.
332    pub register_or_unregister: RegisterOrUnregister,
333}
334
335/// Data about a `WebView` or `<iframe>` viewport: its size and also the
336/// HiDPI scale factor to use when rendering the contents.
337#[derive(Clone, Copy, Debug, Default, Deserialize, MallocSizeOf, PartialEq, Serialize)]
338pub struct ViewportDetails {
339    /// The size of the layout viewport.
340    pub size: Size2D<f32, CSSPixel>,
341
342    /// The scale factor to use to account for HiDPI scaling. This does not take into account
343    /// any page or pinch zoom applied by `Paint` to the contents.
344    pub hidpi_scale_factor: Scale<f32, CSSPixel, DevicePixel>,
345
346    /// The device dimensions that this viewport is displayed within.
347    pub device_size: Size2D<f32, DevicePixel>,
348}
349
350impl ViewportDetails {
351    /// Convert this [`ViewportDetails`] size to a [`LayoutSize`]. This is the same numerical
352    /// value as [`Self::size`], because a `LayoutPixel` is the same as a `CSSPixel`.
353    pub fn layout_size(&self) -> LayoutSize {
354        Size2D::from_untyped(self.size.to_untyped())
355    }
356}
357
358/// Unlike [`ScreenGeometry`], the data is in device-independent pixels
359/// to be used by DOM APIs
360#[derive(Default, Deserialize, Serialize)]
361pub struct ScreenMetrics {
362    pub screen_size: DeviceIndependentIntSize,
363    pub available_size: DeviceIndependentIntSize,
364}
365
366/// An opaque identifier for a single history traversal operation.
367#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
368pub struct TraversalId(Uuid);
369
370impl TraversalId {
371    #[expect(clippy::new_without_default)]
372    pub fn new() -> Self {
373        Self(Uuid::new_v4())
374    }
375}
376
377/// The pixel format of the buffer representing a raster image.
378#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, MallocSizeOf)]
379pub enum PixelFormat {
380    /// Luminance channel only
381    K8,
382    /// Luminance + alpha
383    KA8,
384    /// RGB, 8 bits per channel
385    RGB8,
386    /// RGB + alpha, 8 bits per channel
387    RGBA8,
388    /// BGR + alpha, 8 bits per channel
389    BGRA8,
390}
391
392/// A raster image buffer.
393#[derive(Clone, Deserialize, Serialize, MallocSizeOf)]
394pub struct Image {
395    pub width: u32,
396    pub height: u32,
397    pub format: PixelFormat,
398    /// A shared memory block containing the data of one or more image frames.
399    #[conditional_malloc_size_of]
400    data: Arc<GenericSharedMemory>,
401    range: Range<usize>,
402}
403
404impl Image {
405    /// Creates a new [`Image`] with the given `width` and `height`.
406    ///
407    /// `data` is a shared memory block containing the pixel data of one or more image frames, in
408    /// the given `format`.
409    ///
410    /// `range` is the byte offset within `data` that is the start of the first frame.
411    pub fn new(
412        width: u32,
413        height: u32,
414        data: Arc<GenericSharedMemory>,
415        range: Range<usize>,
416        format: PixelFormat,
417    ) -> Self {
418        Self {
419            width,
420            height,
421            format,
422            data,
423            range,
424        }
425    }
426
427    /// Return the bytes belonging to the first image frame.
428    pub fn data(&self) -> &[u8] {
429        &self.data[self.range.clone()]
430    }
431}
432
433/// The severity level of a message logged by page content.
434#[derive(Clone, Debug, Deserialize, Serialize, MallocSizeOf)]
435#[serde(rename_all = "lowercase")]
436pub enum ConsoleLogLevel {
437    Log,
438    Debug,
439    Info,
440    Warn,
441    Error,
442    Trace,
443    Dir,
444    Table,
445}
446
447impl From<ConsoleLogLevel> for log::Level {
448    fn from(value: ConsoleLogLevel) -> Self {
449        match value {
450            ConsoleLogLevel::Log => log::Level::Info,
451            ConsoleLogLevel::Debug => log::Level::Debug,
452            ConsoleLogLevel::Info => log::Level::Info,
453            ConsoleLogLevel::Warn => log::Level::Warn,
454            ConsoleLogLevel::Error => log::Level::Error,
455            ConsoleLogLevel::Trace => log::Level::Trace,
456            ConsoleLogLevel::Dir => log::Level::Info,
457            ConsoleLogLevel::Table => log::Level::Info,
458        }
459    }
460}
461
462/// Information about a single Bluetooth device.
463#[derive(Clone, Deserialize, Serialize)]
464pub struct BluetoothDeviceDescription {
465    /// The unique address of this device.
466    pub address: String,
467    /// A human-readable name for this device.
468    pub name: String,
469}
470
471/// Messages towards the embedder.
472#[derive(Deserialize, IntoStaticStr, Serialize)]
473pub enum EmbedderMsg {
474    /// A status message to be displayed by the browser chrome.
475    Status(WebViewId, Option<String>),
476    /// Alerts the embedder that the current page has changed its title.
477    ChangePageTitle(WebViewId, Option<String>),
478    /// Move the window to a point
479    MoveTo(WebViewId, DeviceIntPoint),
480    /// Resize the window to size
481    ResizeTo(WebViewId, DeviceIntSize),
482    /// Show the user a [simple dialog](https://html.spec.whatwg.org/multipage/#simple-dialogs) (`alert()`, `confirm()`,
483    /// or `prompt()`). Since their messages are controlled by web content, they should be presented to the user in a
484    /// way that makes them impossible to mistake for browser UI.
485    ShowSimpleDialog(WebViewId, SimpleDialogRequest),
486    /// Request to (un)register protocol handler by page content.
487    AllowProtocolHandlerRequest(
488        WebViewId,
489        ProtocolHandlerUpdateRegistration,
490        GenericSender<AllowOrDeny>,
491    ),
492    /// Wether or not to unload a document
493    AllowUnload(WebViewId, GenericSender<AllowOrDeny>),
494    /// Inform embedder to clear the clipboard
495    ClearClipboard(WebViewId),
496    /// Gets system clipboard contents
497    GetClipboardText(WebViewId, GenericCallback<Result<String, String>>),
498    /// Sets system clipboard contents
499    SetClipboardText(WebViewId, String),
500    /// Changes the cursor.
501    SetCursor(WebViewId, Cursor),
502    /// A favicon was detected
503    NewFavicon(WebViewId, Image),
504    /// Get the device independent window rectangle.
505    GetWindowRect(WebViewId, GenericSender<DeviceIndependentIntRect>),
506    /// Get the device independent screen size and available size.
507    GetScreenMetrics(WebViewId, GenericSender<ScreenMetrics>),
508    /// Entered or exited fullscreen.
509    NotifyFullscreenStateChanged(WebViewId, bool),
510    /// The [`LoadStatus`] of the Given `WebView` has changed.
511    NotifyLoadStatusChanged(WebViewId, LoadStatus),
512    /// Open dialog to select bluetooth device.
513    GetSelectedBluetoothDevice(
514        WebViewId,
515        Vec<BluetoothDeviceDescription>,
516        GenericSender<Option<String>>,
517    ),
518    /// Open interface to request permission specified by prompt.
519    PromptPermission(WebViewId, PermissionFeature, GenericSender<AllowOrDeny>),
520    /// Request permission without blocking the script thread. The callback is invoked with the user's
521    /// decision once it is known.
522    RequestPermission(WebViewId, PermissionFeature, GenericCallback<AllowOrDeny>),
523    /// Request a single geographic position fix. The callback is invoked exactly once.
524    RequestGeolocationPosition(
525        WebViewId,
526        GeolocationRequestOptions,
527        GenericCallback<GeolocationResult>,
528    ),
529    /// Begin delivering continuous position updates for the given watch.
530    StartGeolocationWatch(
531        GeolocationWatchId,
532        GeolocationRequestOptions,
533        GenericCallback<GeolocationResult>,
534    ),
535    /// Stop delivering updates for a watch started by [`EmbedderMsg::StartGeolocationWatch`].
536    StopGeolocationWatch(GeolocationWatchId),
537    /// Report the status of Devtools Server with a token that can be used to bypass the permission prompt.
538    OnDevtoolsStarted(Result<u16, ()>, String),
539    /// Ask the user to allow a devtools client to connect.
540    RequestDevtoolsConnection(GenericSender<AllowOrDeny>),
541    /// Request to play a haptic effect on a connected gamepad.
542    #[cfg(feature = "gamepad")]
543    PlayGamepadHapticEffect(
544        WebViewId,
545        usize,
546        GamepadHapticEffectType,
547        GenericCallback<bool>,
548    ),
549    /// Request to stop a haptic effect on a connected gamepad.
550    #[cfg(feature = "gamepad")]
551    StopGamepadHapticEffect(WebViewId, usize, GenericCallback<bool>),
552    /// Request to display a notification.
553    ShowNotification(Option<WebViewId>, Notification),
554    /// Let the embedder process a DOM Console API message.
555    /// <https://developer.mozilla.org/en-US/docs/Web/API/Console_API>
556    ShowConsoleApiMessage(Option<WebViewId>, ConsoleLogLevel, String),
557    /// Request to the embedder to display a user interace control.
558    ShowEmbedderControl(EmbedderControlId, DeviceIntRect, EmbedderControlRequest),
559    /// Request to the embedder to hide a user interface control.
560    HideEmbedderControl(EmbedderControlId),
561    /// Inform the embedding layer that a particular `InputEvent` was handled by Servo
562    /// and the embedder can continue processing it, if necessary.
563    InputEventsHandled(WebViewId, Vec<InputEventOutcome>),
564    /// Send the embedder an accessibility tree update.
565    AccessibilityTreeUpdate(WebViewId, TreeUpdate, Epoch),
566}
567
568impl Debug for EmbedderMsg {
569    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
570        let string: &'static str = self.into();
571        write!(formatter, "{string}")
572    }
573}
574
575/// <https://w3c.github.io/mediasession/#mediametadata>
576#[derive(Clone, Debug, Deserialize, Serialize, MallocSizeOf)]
577pub struct MediaMetadata {
578    /// Title
579    pub title: String,
580    /// Artist
581    pub artist: String,
582    /// Album
583    pub album: String,
584}
585
586impl MediaMetadata {
587    pub fn new(title: String) -> Self {
588        Self {
589            title,
590            artist: String::new(),
591            album: String::new(),
592        }
593    }
594}
595
596/// <https://w3c.github.io/mediasession/#enumdef-mediasessionplaybackstate>
597#[repr(i32)]
598#[derive(Clone, Debug, Deserialize, Serialize)]
599pub enum MediaSessionPlaybackState {
600    /// The browsing context does not specify whether it’s playing or paused.
601    None_ = 1,
602    /// The browsing context is currently playing media and it can be paused.
603    Playing,
604    /// The browsing context has paused media and it can be resumed.
605    Paused,
606}
607
608/// <https://w3c.github.io/mediasession/#dictdef-mediapositionstate>
609#[derive(Clone, Debug, Deserialize, Serialize)]
610pub struct MediaPositionState {
611    pub duration: f64,
612    pub playback_rate: f64,
613    pub position: f64,
614}
615
616impl MediaPositionState {
617    pub fn new(duration: f64, playback_rate: f64, position: f64) -> Self {
618        Self {
619            duration,
620            playback_rate,
621            position,
622        }
623    }
624}
625
626/// Type of events sent from script to the embedder about the media session.
627#[derive(Clone, Debug, Deserialize, Serialize)]
628pub enum MediaSessionEvent {
629    /// Indicates that the media metadata is available.
630    SetMetadata(MediaMetadata),
631    /// Indicates that the playback state has changed.
632    PlaybackStateChange(MediaSessionPlaybackState),
633    /// Indicates that the position state is set.
634    SetPositionState(MediaPositionState),
635}
636
637/// Enum with variants that match the DOM PermissionName enum
638#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
639pub enum PermissionFeature {
640    Geolocation,
641    Notifications,
642    Push,
643    Midi,
644    Camera,
645    Microphone,
646    Speaker,
647    DeviceInfo,
648    BackgroundSync,
649    Bluetooth,
650    PersistentStorage,
651    ScreenWakeLock(WakeLockType),
652    Gamepad,
653}
654
655/// Used to specify the kind of input method editor appropriate to edit a field.
656/// This is a subset of htmlinputelement::InputType because some variants of InputType
657/// don't make sense in this context.
658#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
659pub enum InputMethodType {
660    Color,
661    Date,
662    DatetimeLocal,
663    Email,
664    Month,
665    Number,
666    Password,
667    Search,
668    Tel,
669    Text,
670    Time,
671    Url,
672    Week,
673}
674
675#[cfg(feature = "gamepad")]
676#[derive(Clone, Debug, Deserialize, Serialize)]
677/// <https://w3.org/TR/gamepad/#dom-gamepadhapticeffecttype-dual-rumble>
678pub struct DualRumbleEffectParams {
679    pub duration: f64,
680    pub start_delay: f64,
681    pub strong_magnitude: f64,
682    pub weak_magnitude: f64,
683}
684
685#[cfg(feature = "gamepad")]
686#[derive(Clone, Debug, Deserialize, Serialize)]
687/// <https://w3.org/TR/gamepad/#dom-gamepadhapticeffecttype>
688pub enum GamepadHapticEffectType {
689    DualRumble(DualRumbleEffectParams),
690}
691
692#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
693pub struct WebResourceRequest {
694    #[serde(
695        deserialize_with = "::hyper_serde::deserialize",
696        serialize_with = "::hyper_serde::serialize"
697    )]
698    pub method: Method,
699    #[serde(
700        deserialize_with = "::hyper_serde::deserialize",
701        serialize_with = "::hyper_serde::serialize"
702    )]
703    pub headers: HeaderMap,
704    pub url: ServoUrl,
705    pub destination: Destination,
706    pub referrer_url: Option<ServoUrl>,
707    pub is_for_main_frame: bool,
708    pub is_redirect: bool,
709}
710
711#[derive(Clone, Deserialize, Serialize)]
712pub enum WebResourceResponseMsg {
713    /// Start an interception of this web resource load. It's expected that the client subsequently
714    /// send either a `CancelLoad` or `FinishLoad` message after optionally sending chunks of body
715    /// data via `SendBodyData`.
716    Start(WebResourceResponse),
717    /// Send a chunk of body data.
718    SendBodyData(Vec<u8>),
719    /// Signal that this load has been finished by the interceptor.
720    FinishLoad,
721    /// Signal that this load has been cancelled by the interceptor.
722    CancelLoad,
723    /// Signal that this load will not be intercepted.
724    DoNotIntercept,
725}
726
727#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
728pub struct WebResourceResponse {
729    pub url: Url,
730    #[serde(
731        deserialize_with = "::hyper_serde::deserialize",
732        serialize_with = "::hyper_serde::serialize"
733    )]
734    pub headers: HeaderMap,
735    #[serde(
736        deserialize_with = "::hyper_serde::deserialize",
737        serialize_with = "::hyper_serde::serialize"
738    )]
739    pub status_code: StatusCode,
740    pub status_message: Vec<u8>,
741}
742
743impl WebResourceResponse {
744    pub fn new(url: Url) -> WebResourceResponse {
745        WebResourceResponse {
746            url,
747            headers: HeaderMap::new(),
748            status_code: StatusCode::OK,
749            status_message: b"OK".to_vec(),
750        }
751    }
752
753    pub fn headers(mut self, headers: HeaderMap) -> WebResourceResponse {
754        self.headers = headers;
755        self
756    }
757
758    pub fn status_code(mut self, status_code: StatusCode) -> WebResourceResponse {
759        self.status_code = status_code;
760        self
761    }
762
763    pub fn status_message(mut self, status_message: Vec<u8>) -> WebResourceResponse {
764        self.status_message = status_message;
765        self
766    }
767}
768
769/// The type of platform theme.
770#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
771pub enum Theme {
772    /// Light theme.
773    Light,
774    /// Dark theme.
775    Dark,
776}
777
778impl From<Theme> for PrefersColorScheme {
779    fn from(value: Theme) -> Self {
780        match value {
781            Theme::Light => PrefersColorScheme::Light,
782            Theme::Dark => PrefersColorScheme::Dark,
783        }
784    }
785}
786
787// The type of MediaSession action.
788/// <https://w3c.github.io/mediasession/#enumdef-mediasessionaction>
789#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
790pub enum MediaSessionActionType {
791    /// The action intent is to resume playback.
792    Play,
793    /// The action intent is to pause the currently active playback.
794    Pause,
795    /// The action intent is to move the playback time backward by a short period (i.e. a few
796    /// seconds).
797    SeekBackward,
798    /// The action intent is to move the playback time forward by a short period (i.e. a few
799    /// seconds).
800    SeekForward,
801    /// The action intent is to either start the current playback from the beginning if the
802    /// playback has a notion, of beginning, or move to the previous item in the playlist if the
803    /// playback has a notion of playlist.
804    PreviousTrack,
805    /// The action is to move to the playback to the next item in the playlist if the playback has
806    /// a notion of playlist.
807    NextTrack,
808    /// The action intent is to skip the advertisement that is currently playing.
809    SkipAd,
810    /// The action intent is to stop the playback and clear the state if appropriate.
811    Stop,
812    /// The action intent is to move the playback time to a specific time.
813    SeekTo,
814}
815
816/// The status of the load in this `WebView`.
817#[repr(i32)]
818#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
819pub enum LoadStatus {
820    /// The load has started, but the headers have not yet been parsed.
821    Started,
822    /// The `<head>` tag has been parsed in the currently loading page. At this point the page's
823    /// `HTMLBodyElement` is now available in the DOM.
824    HeadParsed,
825    /// The `Document` and all subresources have loaded. This is equivalent to
826    /// `document.readyState` == `complete`.
827    /// See <https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState>
828    Complete,
829    /// The current load was stopped, either by the embedder or by script on the page
830    /// (for instance, by calling `window.stop()`).
831    Stopped,
832}
833
834/// Data that could be used to display a desktop notification to the end user
835/// when the [Notification API](<https://notifications.spec.whatwg.org/#notifications>) is called.
836#[derive(Clone, Debug, Deserialize, Serialize)]
837pub struct Notification {
838    /// Title of the notification.
839    pub title: String,
840    /// Body string of the notification.
841    pub body: String,
842    /// An identifier tag for the notification. Notification with the same tag
843    /// can be replaced by another to avoid users' screen being filled up with similar notifications.
844    pub tag: String,
845    /// The tag for the language used in the notification's title, body, and the title of each its actions. [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)
846    pub language: String,
847    /// A boolean value indicates the notification should remain readily available
848    /// until the end user activates or dismisses the notification.
849    pub require_interaction: bool,
850    /// When `true`, indicates no sounds or vibrations should be made. When `None`,
851    /// the device's default settings should be respected.
852    pub silent: Option<bool>,
853    /// The URL of an icon. The icon will be displayed as part of the notification.
854    pub icon_url: Option<ServoUrl>,
855    /// Icon's raw image data and metadata.
856    pub icon_resource: Option<Arc<SharedRasterImage>>,
857    /// The URL of a badge. The badge is used when there is no enough space to display the notification,
858    /// such as on a mobile device's notification bar.
859    pub badge_url: Option<ServoUrl>,
860    /// Badge's raw image data and metadata.
861    pub badge_resource: Option<Arc<SharedRasterImage>>,
862    /// The URL of an image. The image will be displayed as part of the notification.
863    pub image_url: Option<ServoUrl>,
864    /// Image's raw image data and metadata.
865    pub image_resource: Option<Arc<SharedRasterImage>>,
866    /// Actions available for users to choose from for interacting with the notification.
867    pub actions: Vec<NotificationAction>,
868}
869
870/// Actions available for users to choose from for interacting with the notification.
871#[derive(Clone, Debug, Deserialize, Serialize)]
872pub struct NotificationAction {
873    /// A string that identifies the action.
874    pub name: String,
875    /// The title string of the action to be shown to the user.
876    pub title: String,
877    /// The URL of an icon. The icon will be displayed with the action.
878    pub icon_url: Option<ServoUrl>,
879    /// Icon's raw image data and metadata.
880    pub icon_resource: Option<Arc<SharedRasterImage>>,
881}
882
883/// Information about a `WebView`'s screen geometry and offset. This is used
884/// for the [Screen](https://drafts.csswg.org/cssom-view/#the-screen-interface) CSSOM APIs
885/// and `window.screenLeft` / `window.screenX` / `window.screenTop` / `window.screenY` /
886/// `window.moveBy`/ `window.resizeBy` / `window.outerWidth` / `window.outerHeight` /
887/// `window.screen.availHeight` / `window.screen.availWidth`.
888#[derive(Clone, Copy, Debug, Default)]
889pub struct ScreenGeometry {
890    /// The size of the screen in device pixels. This will be converted to
891    /// CSS pixels based on the pixel scaling of the `WebView`.
892    pub size: DeviceIntSize,
893    /// The available size of the screen in device pixels for the purposes of
894    /// the `window.screen.availHeight` / `window.screen.availWidth`. This is the size
895    /// available for web content on the screen, and should be `size` minus any system
896    /// toolbars, docks, and interface elements. This will be converted to
897    /// CSS pixels based on the pixel scaling of the `WebView`.
898    pub available_size: DeviceIntSize,
899    /// The rectangle the `WebView`'s containing window (including OS decorations)
900    /// in device pixels for the purposes of the
901    /// `window.screenLeft`, `window.outerHeight` and similar APIs.
902    /// This will be converted to CSS pixels based on the pixel scaling of the `WebView`.
903    pub window_rect: DeviceIntRect,
904}
905
906impl From<SelectElementOption> for SelectElementOptionOrOptgroup {
907    fn from(value: SelectElementOption) -> Self {
908        Self::Option(value)
909    }
910}
911
912/// The address of a node. Layout sends these back. They must be validated via
913/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
914#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
915pub struct UntrustedNodeAddress(pub *const c_void);
916
917malloc_size_of_is_0!(UntrustedNodeAddress);
918
919#[expect(unsafe_code)]
920unsafe impl Send for UntrustedNodeAddress {}
921
922impl From<style_traits::dom::OpaqueNode> for UntrustedNodeAddress {
923    fn from(o: style_traits::dom::OpaqueNode) -> Self {
924        UntrustedNodeAddress(o.0 as *const c_void)
925    }
926}
927
928impl Serialize for UntrustedNodeAddress {
929    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
930        (self.0 as usize).serialize(s)
931    }
932}
933
934impl<'de> Deserialize<'de> for UntrustedNodeAddress {
935    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
936        let value: usize = Deserialize::deserialize(d)?;
937        Ok(UntrustedNodeAddress::from_id(value))
938    }
939}
940
941impl UntrustedNodeAddress {
942    /// Creates an `UntrustedNodeAddress` from the given pointer address value.
943    #[inline]
944    pub fn from_id(id: usize) -> UntrustedNodeAddress {
945        UntrustedNodeAddress(id as *const c_void)
946    }
947}
948
949/// The result of a hit test in `Paint`.
950#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
951pub struct PaintHitTestResult {
952    /// The pipeline id of the resulting item.
953    pub pipeline_id: PipelineId,
954
955    /// The hit test point in the item's viewport.
956    pub point_in_viewport: Point2D<f32, CSSPixel>,
957
958    /// The [`ExternalScrollId`] of the scroll tree node associated with this hit test item.
959    pub external_scroll_id: ExternalScrollId,
960}
961
962/// For a given pipeline, whether any animations are currently running
963/// and any animation callbacks are queued
964#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
965pub enum AnimationState {
966    /// Animations are active but no callbacks are queued
967    AnimationsPresent,
968    /// Animations are active and callbacks are queued
969    AnimationCallbacksPresent,
970    /// No animations are active and no callbacks are queued
971    NoAnimationsPresent,
972    /// No animations are active but callbacks are queued
973    AnimationCallbacksAbsent,
974}
975
976/// A sequence number generated by a script thread for its pipelines. The
977/// constellation attaches the target pipeline's last seen `FocusSequenceNumber`
978/// to every focus-related message it sends.
979///
980/// This is used to resolve the inconsistency that occurs due to bidirectional
981/// focus state synchronization and provide eventual consistency. Example:
982///
983/// ```text
984/// script                            constellation
985/// -----------------------------------------------------------------------
986/// send ActivateDocument ----------> receive ActivateDocument
987///                             ,---- send FocusDocument
988///                             |
989/// focus an iframe             |
990/// send Focus -----------------|---> receive Focus
991///                             |     focus the iframe's content document
992/// receive FocusDocument <-----'     send FocusDocument to the content pipeline --> ...
993/// unfocus the iframe
994/// focus the document
995///
996/// Final state:                      Final state:
997///  the iframe is not focused         the iframe is focused
998/// ```
999///
1000/// When the above sequence completes, from the script thread's point of view,
1001/// the iframe is unfocused, but from the constellation's point of view, the
1002/// iframe is still focused.
1003///
1004/// This inconsistency can be resolved by associating a sequence number to each
1005/// message. Whenever a script thread initiates a focus operation, it generates
1006/// and sends a brand new sequence number. The constellation attaches the
1007/// last-received sequence number to each message it sends. This way, the script
1008/// thread can discard out-dated incoming focus messages, and eventually, all
1009/// actors converge to the consistent state which is determined based on the
1010/// last focus message received by the constellation.
1011///
1012/// ```text
1013/// script                            constellation
1014/// -----------------------------------------------------------------------
1015/// send ActivateDocument ----------> receive ActivateDocument
1016///                             ,---- send FocusDocument (0)
1017///                             |
1018/// seq_number += 1             |
1019/// focus an iframe             |
1020/// send Focus (1) -------------|---> receive Focus (1)
1021///                             |     focus the iframe's content document
1022/// receive FocusDocument (0) <-'     send FocusDocument to the content pipeline --> ...
1023/// ignore it because 0 < 1
1024///
1025/// Final state:                      Final state:
1026///  the iframe is focused             the iframe is focused
1027/// ```
1028#[derive(
1029    Clone,
1030    Copy,
1031    Debug,
1032    Default,
1033    Deserialize,
1034    Eq,
1035    Hash,
1036    MallocSizeOf,
1037    PartialEq,
1038    Serialize,
1039    PartialOrd,
1040)]
1041pub struct FocusSequenceNumber(pub u64);
1042
1043impl Display for FocusSequenceNumber {
1044    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1045        Display::fmt(&self.0, f)
1046    }
1047}
1048
1049/// An identifier for a particular JavaScript evaluation that is used to track the
1050/// evaluation from the embedding layer to the script layer and then back.
1051#[derive(Clone, Copy, Deserialize, Eq, Hash, PartialEq, Serialize)]
1052pub struct JavaScriptEvaluationId(pub usize);
1053
1054/// A JavaScript value produced by evaluation of a script.
1055#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1056pub enum JSValue {
1057    Undefined,
1058    Null,
1059    Boolean(bool),
1060    Number(f64),
1061    String(String),
1062    Element(String),
1063    ShadowRoot(String),
1064    Frame(String),
1065    Window(String),
1066    Array(Vec<JSValue>),
1067    Object(HashMap<String, JSValue>),
1068}
1069
1070/// Information about a JavaScript error that occured during the evaluation of a script.
1071#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1072pub struct JavaScriptErrorInfo {
1073    pub message: String,
1074    pub filename: String,
1075    pub stack: Option<String>,
1076    pub line_number: u64,
1077    pub column: u64,
1078}
1079
1080/// Indicates the reason that JavaScript evaluation failed due serializing issues the
1081/// result of the evaluation.
1082#[derive(Clone, Debug, Deserialize, EnumMessage, PartialEq, Serialize)]
1083pub enum JavaScriptEvaluationResultSerializationError {
1084    /// Serialization could not complete because a JavaScript value contained a detached
1085    /// shadow root according to <https://w3c.github.io/webdriver/#dfn-internal-json-clone>.
1086    DetachedShadowRoot,
1087    /// Serialization could not complete because a JavaScript value contained a "stale"
1088    /// element reference according to <https://w3c.github.io/webdriver/#dfn-get-a-known-element>.
1089    StaleElementReference,
1090    /// Serialization could not complete because a JavaScript value of an unknown type
1091    /// was encountered.
1092    UnknownType,
1093    /// This is a catch all for other kinds of errors that can happen during JavaScript value
1094    /// serialization. For instances where this can happen, see:
1095    /// <https://w3c.github.io/webdriver/#dfn-clone-an-object>.
1096    OtherJavaScriptError,
1097}
1098
1099/// An error that happens when trying to evaluate JavaScript on a `WebView`.
1100#[derive(Clone, Debug, Deserialize, EnumMessage, PartialEq, Serialize)]
1101pub enum JavaScriptEvaluationError {
1102    /// The `Document` of frame that the script was going to execute in no longer exists.
1103    DocumentNotFound,
1104    /// The script could not be compiled.
1105    CompilationFailure,
1106    /// The script could not be evaluated.
1107    EvaluationFailure(Option<JavaScriptErrorInfo>),
1108    /// An internal Servo error prevented the JavaSript evaluation from completing properly.
1109    /// This indicates a bug in Servo.
1110    InternalError,
1111    /// The `WebView` on which this evaluation request was triggered is not ready. This might
1112    /// happen if the `WebView`'s `Document` is changing due to ongoing load events, for instance.
1113    WebViewNotReady,
1114    /// The script executed successfully, but Servo could not serialize the JavaScript return
1115    /// value into a [`JSValue`].
1116    SerializationError(JavaScriptEvaluationResultSerializationError),
1117}
1118
1119#[repr(i32)]
1120#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1121pub enum ScreenshotCaptureError {
1122    /// The screenshot request failed to read the screenshot image from the `WebView`'s
1123    /// `RenderingContext`.
1124    CouldNotReadImage,
1125    /// The WebView that this screenshot request was made for no longer exists.
1126    WebViewDoesNotExist,
1127}
1128
1129#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
1130pub struct RgbColor {
1131    pub red: u8,
1132    pub green: u8,
1133    pub blue: u8,
1134}
1135
1136/// A Script to Embedder Channel
1137#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
1138pub struct ScriptToEmbedderChan(GenericCallback<EmbedderMsg>);
1139
1140impl ScriptToEmbedderChan {
1141    /// Create a new Channel allowing script to send messages to the Embedder
1142    pub fn new(
1143        embedder_chan: Sender<EmbedderMsg>,
1144        waker: Box<dyn EventLoopWaker>,
1145    ) -> ScriptToEmbedderChan {
1146        let embedder_callback = GenericCallback::new(move |embedder_msg| {
1147            let msg = match embedder_msg {
1148                Ok(embedder_msg) => embedder_msg,
1149                Err(err) => {
1150                    log::warn!("Script to Embedder message error: {err}");
1151                    return;
1152                },
1153            };
1154            let _ = embedder_chan.send(msg);
1155            waker.wake();
1156        })
1157        .expect("Failed to create channel");
1158        ScriptToEmbedderChan(embedder_callback)
1159    }
1160
1161    /// Send a message to and wake the Embedder
1162    pub fn send(&self, msg: EmbedderMsg) -> SendResult {
1163        self.0.send(msg)
1164    }
1165}
1166
1167/// Used for communicating the details of a new `WebView` created by the embedder
1168/// back to the constellation.
1169#[derive(Deserialize, Serialize)]
1170pub struct NewWebViewDetails {
1171    pub webview_id: WebViewId,
1172    pub viewport_details: ViewportDetails,
1173    pub user_content_manager_id: Option<UserContentManagerId>,
1174}
1175
1176#[derive(Serialize, Deserialize, Debug)]
1177/// A request to load a URL. This can be used to trigger a configurable load in a `WebView`.
1178///
1179/// ```
1180///  let mut headers = http::HeaderMap::new();
1181///  headers.append(HeaderName::from_static("CustomHeader"), "Value".parse().unwrap());
1182///  let url_request = URLRequest::new(url).headers(headers);
1183///  webview.load_request(url_request);
1184/// ```
1185pub struct UrlRequest {
1186    pub url: ServoUrl,
1187    #[serde(
1188        deserialize_with = "hyper_serde::deserialize",
1189        serialize_with = "hyper_serde::serialize"
1190    )]
1191    pub headers: HeaderMap,
1192}
1193
1194impl UrlRequest {
1195    pub fn new(url: Url) -> Self {
1196        UrlRequest {
1197            url: url.into(),
1198            headers: HeaderMap::new(),
1199        }
1200    }
1201
1202    /// Set headers that will be added to the Headers
1203    pub fn headers(mut self, headers: HeaderMap) -> Self {
1204        self.headers = headers;
1205        self
1206    }
1207}
1208
1209/// The type of wake lock to acquire or release.
1210#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1211pub enum WakeLockType {
1212    Screen,
1213}
1214
1215/// Trait for platform-specific wake lock support.
1216///
1217/// Implementations are responsible for interacting with the OS to prevent
1218/// the screen (or other resources) from sleeping while a wake lock is held.
1219pub trait WakeLockDelegate: Send + Sync {
1220    /// Acquire a wake lock of the given type, preventing the associated
1221    /// resource from sleeping. Called when the aggregate lock count transitions
1222    /// from 0 to 1. Returns an error if the OS fails to grant the lock.
1223    fn acquire(&self, type_: WakeLockType) -> Result<(), Box<dyn std::error::Error>>;
1224
1225    /// Release a previously acquired wake lock of the given type, allowing
1226    /// the resource to sleep. Called when the aggregate lock count transitions
1227    /// from N to 0.
1228    fn release(&self, type_: WakeLockType) -> Result<(), Box<dyn std::error::Error>>;
1229}