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