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>),
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,
632}
633
634/// Used to specify the kind of input method editor appropriate to edit a field.
635/// This is a subset of htmlinputelement::InputType because some variants of InputType
636/// don't make sense in this context.
637#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
638pub enum InputMethodType {
639    Color,
640    Date,
641    DatetimeLocal,
642    Email,
643    Month,
644    Number,
645    Password,
646    Search,
647    Tel,
648    Text,
649    Time,
650    Url,
651    Week,
652}
653
654#[cfg(feature = "gamepad")]
655#[derive(Clone, Debug, Deserialize, Serialize)]
656/// <https://w3.org/TR/gamepad/#dom-gamepadhapticeffecttype-dual-rumble>
657pub struct DualRumbleEffectParams {
658    pub duration: f64,
659    pub start_delay: f64,
660    pub strong_magnitude: f64,
661    pub weak_magnitude: f64,
662}
663
664#[cfg(feature = "gamepad")]
665#[derive(Clone, Debug, Deserialize, Serialize)]
666/// <https://w3.org/TR/gamepad/#dom-gamepadhapticeffecttype>
667pub enum GamepadHapticEffectType {
668    DualRumble(DualRumbleEffectParams),
669}
670
671#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
672pub struct WebResourceRequest {
673    #[serde(
674        deserialize_with = "::hyper_serde::deserialize",
675        serialize_with = "::hyper_serde::serialize"
676    )]
677    pub method: Method,
678    #[serde(
679        deserialize_with = "::hyper_serde::deserialize",
680        serialize_with = "::hyper_serde::serialize"
681    )]
682    pub headers: HeaderMap,
683    pub url: Url,
684    pub destination: Destination,
685    pub referrer_url: Option<Url>,
686    pub is_for_main_frame: bool,
687    pub is_redirect: bool,
688}
689
690#[derive(Clone, Deserialize, Serialize)]
691pub enum WebResourceResponseMsg {
692    /// Start an interception of this web resource load. It's expected that the client subsequently
693    /// send either a `CancelLoad` or `FinishLoad` message after optionally sending chunks of body
694    /// data via `SendBodyData`.
695    Start(WebResourceResponse),
696    /// Send a chunk of body data.
697    SendBodyData(Vec<u8>),
698    /// Signal that this load has been finished by the interceptor.
699    FinishLoad,
700    /// Signal that this load has been cancelled by the interceptor.
701    CancelLoad,
702    /// Signal that this load will not be intercepted.
703    DoNotIntercept,
704}
705
706#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
707pub struct WebResourceResponse {
708    pub url: Url,
709    #[serde(
710        deserialize_with = "::hyper_serde::deserialize",
711        serialize_with = "::hyper_serde::serialize"
712    )]
713    #[ignore_malloc_size_of = "Defined in hyper"]
714    pub headers: HeaderMap,
715    #[serde(
716        deserialize_with = "::hyper_serde::deserialize",
717        serialize_with = "::hyper_serde::serialize"
718    )]
719    #[ignore_malloc_size_of = "Defined in hyper"]
720    pub status_code: StatusCode,
721    pub status_message: Vec<u8>,
722}
723
724impl WebResourceResponse {
725    pub fn new(url: Url) -> WebResourceResponse {
726        WebResourceResponse {
727            url,
728            headers: HeaderMap::new(),
729            status_code: StatusCode::OK,
730            status_message: b"OK".to_vec(),
731        }
732    }
733
734    pub fn headers(mut self, headers: HeaderMap) -> WebResourceResponse {
735        self.headers = headers;
736        self
737    }
738
739    pub fn status_code(mut self, status_code: StatusCode) -> WebResourceResponse {
740        self.status_code = status_code;
741        self
742    }
743
744    pub fn status_message(mut self, status_message: Vec<u8>) -> WebResourceResponse {
745        self.status_message = status_message;
746        self
747    }
748}
749
750/// The type of platform theme.
751#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
752pub enum Theme {
753    /// Light theme.
754    Light,
755    /// Dark theme.
756    Dark,
757}
758
759impl From<Theme> for PrefersColorScheme {
760    fn from(value: Theme) -> Self {
761        match value {
762            Theme::Light => PrefersColorScheme::Light,
763            Theme::Dark => PrefersColorScheme::Dark,
764        }
765    }
766}
767
768// The type of MediaSession action.
769/// <https://w3c.github.io/mediasession/#enumdef-mediasessionaction>
770#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
771pub enum MediaSessionActionType {
772    /// The action intent is to resume playback.
773    Play,
774    /// The action intent is to pause the currently active playback.
775    Pause,
776    /// The action intent is to move the playback time backward by a short period (i.e. a few
777    /// seconds).
778    SeekBackward,
779    /// The action intent is to move the playback time forward by a short period (i.e. a few
780    /// seconds).
781    SeekForward,
782    /// The action intent is to either start the current playback from the beginning if the
783    /// playback has a notion, of beginning, or move to the previous item in the playlist if the
784    /// playback has a notion of playlist.
785    PreviousTrack,
786    /// The action is to move to the playback to the next item in the playlist if the playback has
787    /// a notion of playlist.
788    NextTrack,
789    /// The action intent is to skip the advertisement that is currently playing.
790    SkipAd,
791    /// The action intent is to stop the playback and clear the state if appropriate.
792    Stop,
793    /// The action intent is to move the playback time to a specific time.
794    SeekTo,
795}
796
797/// The status of the load in this `WebView`.
798#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
799pub enum LoadStatus {
800    /// The load has started, but the headers have not yet been parsed.
801    Started,
802    /// The `<head>` tag has been parsed in the currently loading page. At this point the page's
803    /// `HTMLBodyElement` is now available in the DOM.
804    HeadParsed,
805    /// The `Document` and all subresources have loaded. This is equivalent to
806    /// `document.readyState` == `complete`.
807    /// See <https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState>
808    Complete,
809}
810
811/// Data that could be used to display a desktop notification to the end user
812/// when the [Notification API](<https://notifications.spec.whatwg.org/#notifications>) is called.
813#[derive(Clone, Debug, Deserialize, Serialize)]
814pub struct Notification {
815    /// Title of the notification.
816    pub title: String,
817    /// Body string of the notification.
818    pub body: String,
819    /// An identifier tag for the notification. Notification with the same tag
820    /// can be replaced by another to avoid users' screen being filled up with similar notifications.
821    pub tag: String,
822    /// 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)
823    pub language: String,
824    /// A boolean value indicates the notification should remain readily available
825    /// until the end user activates or dismisses the notification.
826    pub require_interaction: bool,
827    /// When `true`, indicates no sounds or vibrations should be made. When `None`,
828    /// the device's default settings should be respected.
829    pub silent: Option<bool>,
830    /// The URL of an icon. The icon will be displayed as part of the notification.
831    pub icon_url: Option<ServoUrl>,
832    /// Icon's raw image data and metadata.
833    pub icon_resource: Option<Arc<SharedRasterImage>>,
834    /// The URL of a badge. The badge is used when there is no enough space to display the notification,
835    /// such as on a mobile device's notification bar.
836    pub badge_url: Option<ServoUrl>,
837    /// Badge's raw image data and metadata.
838    pub badge_resource: Option<Arc<SharedRasterImage>>,
839    /// The URL of an image. The image will be displayed as part of the notification.
840    pub image_url: Option<ServoUrl>,
841    /// Image's raw image data and metadata.
842    pub image_resource: Option<Arc<SharedRasterImage>>,
843    /// Actions available for users to choose from for interacting with the notification.
844    pub actions: Vec<NotificationAction>,
845}
846
847/// Actions available for users to choose from for interacting with the notification.
848#[derive(Clone, Debug, Deserialize, Serialize)]
849pub struct NotificationAction {
850    /// A string that identifies the action.
851    pub name: String,
852    /// The title string of the action to be shown to the user.
853    pub title: String,
854    /// The URL of an icon. The icon will be displayed with the action.
855    pub icon_url: Option<ServoUrl>,
856    /// Icon's raw image data and metadata.
857    pub icon_resource: Option<Arc<SharedRasterImage>>,
858}
859
860/// Information about a `WebView`'s screen geometry and offset. This is used
861/// for the [Screen](https://drafts.csswg.org/cssom-view/#the-screen-interface) CSSOM APIs
862/// and `window.screenLeft` / `window.screenX` / `window.screenTop` / `window.screenY` /
863/// `window.moveBy`/ `window.resizeBy` / `window.outerWidth` / `window.outerHeight` /
864/// `window.screen.availHeight` / `window.screen.availWidth`.
865#[derive(Clone, Copy, Debug, Default)]
866pub struct ScreenGeometry {
867    /// The size of the screen in device pixels. This will be converted to
868    /// CSS pixels based on the pixel scaling of the `WebView`.
869    pub size: DeviceIntSize,
870    /// The available size of the screen in device pixels for the purposes of
871    /// the `window.screen.availHeight` / `window.screen.availWidth`. This is the size
872    /// available for web content on the screen, and should be `size` minus any system
873    /// toolbars, docks, and interface elements. This will be converted to
874    /// CSS pixels based on the pixel scaling of the `WebView`.
875    pub available_size: DeviceIntSize,
876    /// The rectangle the `WebView`'s containing window (including OS decorations)
877    /// in device pixels for the purposes of the
878    /// `window.screenLeft`, `window.outerHeight` and similar APIs.
879    /// This will be converted to CSS pixels based on the pixel scaling of the `WebView`.
880    pub window_rect: DeviceIntRect,
881}
882
883impl From<SelectElementOption> for SelectElementOptionOrOptgroup {
884    fn from(value: SelectElementOption) -> Self {
885        Self::Option(value)
886    }
887}
888
889/// The address of a node. Layout sends these back. They must be validated via
890/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
891#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
892pub struct UntrustedNodeAddress(pub *const c_void);
893
894malloc_size_of_is_0!(UntrustedNodeAddress);
895
896#[expect(unsafe_code)]
897unsafe impl Send for UntrustedNodeAddress {}
898
899impl From<style_traits::dom::OpaqueNode> for UntrustedNodeAddress {
900    fn from(o: style_traits::dom::OpaqueNode) -> Self {
901        UntrustedNodeAddress(o.0 as *const c_void)
902    }
903}
904
905impl Serialize for UntrustedNodeAddress {
906    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
907        (self.0 as usize).serialize(s)
908    }
909}
910
911impl<'de> Deserialize<'de> for UntrustedNodeAddress {
912    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
913        let value: usize = Deserialize::deserialize(d)?;
914        Ok(UntrustedNodeAddress::from_id(value))
915    }
916}
917
918impl UntrustedNodeAddress {
919    /// Creates an `UntrustedNodeAddress` from the given pointer address value.
920    #[inline]
921    pub fn from_id(id: usize) -> UntrustedNodeAddress {
922        UntrustedNodeAddress(id as *const c_void)
923    }
924}
925
926/// The result of a hit test in `Paint`.
927#[derive(Clone, Debug, Deserialize, Serialize)]
928pub struct PaintHitTestResult {
929    /// The pipeline id of the resulting item.
930    pub pipeline_id: PipelineId,
931
932    /// The hit test point in the item's viewport.
933    pub point_in_viewport: Point2D<f32, CSSPixel>,
934
935    /// The [`ExternalScrollId`] of the scroll tree node associated with this hit test item.
936    pub external_scroll_id: ExternalScrollId,
937}
938
939/// For a given pipeline, whether any animations are currently running
940/// and any animation callbacks are queued
941#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
942pub enum AnimationState {
943    /// Animations are active but no callbacks are queued
944    AnimationsPresent,
945    /// Animations are active and callbacks are queued
946    AnimationCallbacksPresent,
947    /// No animations are active and no callbacks are queued
948    NoAnimationsPresent,
949    /// No animations are active but callbacks are queued
950    NoAnimationCallbacksPresent,
951}
952
953/// A sequence number generated by a script thread for its pipelines. The
954/// constellation attaches the target pipeline's last seen `FocusSequenceNumber`
955/// to every focus-related message it sends.
956///
957/// This is used to resolve the inconsistency that occurs due to bidirectional
958/// focus state synchronization and provide eventual consistency. Example:
959///
960/// ```text
961/// script                            constellation
962/// -----------------------------------------------------------------------
963/// send ActivateDocument ----------> receive ActivateDocument
964///                             ,---- send FocusDocument
965///                             |
966/// focus an iframe             |
967/// send Focus -----------------|---> receive Focus
968///                             |     focus the iframe's content document
969/// receive FocusDocument <-----'     send FocusDocument to the content pipeline --> ...
970/// unfocus the iframe
971/// focus the document
972///
973/// Final state:                      Final state:
974///  the iframe is not focused         the iframe is focused
975/// ```
976///
977/// When the above sequence completes, from the script thread's point of view,
978/// the iframe is unfocused, but from the constellation's point of view, the
979/// iframe is still focused.
980///
981/// This inconsistency can be resolved by associating a sequence number to each
982/// message. Whenever a script thread initiates a focus operation, it generates
983/// and sends a brand new sequence number. The constellation attaches the
984/// last-received sequence number to each message it sends. This way, the script
985/// thread can discard out-dated incoming focus messages, and eventually, all
986/// actors converge to the consistent state which is determined based on the
987/// last focus message received by the constellation.
988///
989/// ```text
990/// script                            constellation
991/// -----------------------------------------------------------------------
992/// send ActivateDocument ----------> receive ActivateDocument
993///                             ,---- send FocusDocument (0)
994///                             |
995/// seq_number += 1             |
996/// focus an iframe             |
997/// send Focus (1) -------------|---> receive Focus (1)
998///                             |     focus the iframe's content document
999/// receive FocusDocument (0) <-'     send FocusDocument to the content pipeline --> ...
1000/// ignore it because 0 < 1
1001///
1002/// Final state:                      Final state:
1003///  the iframe is focused             the iframe is focused
1004/// ```
1005#[derive(
1006    Clone,
1007    Copy,
1008    Debug,
1009    Default,
1010    Deserialize,
1011    Eq,
1012    Hash,
1013    MallocSizeOf,
1014    PartialEq,
1015    Serialize,
1016    PartialOrd,
1017)]
1018pub struct FocusSequenceNumber(pub u64);
1019
1020impl Display for FocusSequenceNumber {
1021    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1022        Display::fmt(&self.0, f)
1023    }
1024}
1025
1026/// An identifier for a particular JavaScript evaluation that is used to track the
1027/// evaluation from the embedding layer to the script layer and then back.
1028#[derive(Clone, Copy, Deserialize, Eq, Hash, PartialEq, Serialize)]
1029pub struct JavaScriptEvaluationId(pub usize);
1030
1031/// A JavaScript value produced by evaluation of a script.
1032#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1033pub enum JSValue {
1034    Undefined,
1035    Null,
1036    Boolean(bool),
1037    Number(f64),
1038    String(String),
1039    Element(String),
1040    ShadowRoot(String),
1041    Frame(String),
1042    Window(String),
1043    Array(Vec<JSValue>),
1044    Object(HashMap<String, JSValue>),
1045}
1046
1047/// Information about a JavaScript error that occured during the evaluation of a script.
1048#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1049pub struct JavaScriptErrorInfo {
1050    pub message: String,
1051    pub filename: String,
1052    pub stack: Option<String>,
1053    pub line_number: u64,
1054    pub column: u64,
1055}
1056
1057/// Indicates the reason that JavaScript evaluation failed due serializing issues the
1058/// result of the evaluation.
1059#[derive(Clone, Debug, Deserialize, EnumMessage, PartialEq, Serialize)]
1060pub enum JavaScriptEvaluationResultSerializationError {
1061    /// Serialization could not complete because a JavaScript value contained a detached
1062    /// shadow root according to <https://w3c.github.io/webdriver/#dfn-internal-json-clone>.
1063    DetachedShadowRoot,
1064    /// Serialization could not complete because a JavaScript value contained a "stale"
1065    /// element reference according to <https://w3c.github.io/webdriver/#dfn-get-a-known-element>.
1066    StaleElementReference,
1067    /// Serialization could not complete because a JavaScript value of an unknown type
1068    /// was encountered.
1069    UnknownType,
1070    /// This is a catch all for other kinds of errors that can happen during JavaScript value
1071    /// serialization. For instances where this can happen, see:
1072    /// <https://w3c.github.io/webdriver/#dfn-clone-an-object>.
1073    OtherJavaScriptError,
1074}
1075
1076/// An error that happens when trying to evaluate JavaScript on a `WebView`.
1077#[derive(Clone, Debug, Deserialize, EnumMessage, PartialEq, Serialize)]
1078pub enum JavaScriptEvaluationError {
1079    /// The `Document` of frame that the script was going to execute in no longer exists.
1080    DocumentNotFound,
1081    /// The script could not be compiled.
1082    CompilationFailure,
1083    /// The script could not be evaluated.
1084    EvaluationFailure(Option<JavaScriptErrorInfo>),
1085    /// An internal Servo error prevented the JavaSript evaluation from completing properly.
1086    /// This indicates a bug in Servo.
1087    InternalError,
1088    /// The `WebView` on which this evaluation request was triggered is not ready. This might
1089    /// happen if the `WebView`'s `Document` is changing due to ongoing load events, for instance.
1090    WebViewNotReady,
1091    /// The script executed successfully, but Servo could not serialize the JavaScript return
1092    /// value into a [`JSValue`].
1093    SerializationError(JavaScriptEvaluationResultSerializationError),
1094}
1095
1096#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1097pub enum ScreenshotCaptureError {
1098    /// The screenshot request failed to read the screenshot image from the `WebView`'s
1099    /// `RenderingContext`.
1100    CouldNotReadImage,
1101    /// The WebView that this screenshot request was made for no longer exists.
1102    WebViewDoesNotExist,
1103}
1104
1105#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
1106pub struct RgbColor {
1107    pub red: u8,
1108    pub green: u8,
1109    pub blue: u8,
1110}
1111
1112/// A Script to Embedder Channel
1113#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
1114pub struct ScriptToEmbedderChan(GenericCallback<EmbedderMsg>);
1115
1116impl ScriptToEmbedderChan {
1117    /// Create a new Channel allowing script to send messages to the Embedder
1118    pub fn new(
1119        embedder_chan: Sender<EmbedderMsg>,
1120        waker: Box<dyn EventLoopWaker>,
1121    ) -> ScriptToEmbedderChan {
1122        let embedder_callback = GenericCallback::new(move |embedder_msg| {
1123            let msg = match embedder_msg {
1124                Ok(embedder_msg) => embedder_msg,
1125                Err(err) => {
1126                    log::warn!("Script to Embedder message error: {err}");
1127                    return;
1128                },
1129            };
1130            let _ = embedder_chan.send(msg);
1131            waker.wake();
1132        })
1133        .expect("Failed to create channel");
1134        ScriptToEmbedderChan(embedder_callback)
1135    }
1136
1137    /// Send a message to and wake the Embedder
1138    pub fn send(&self, msg: EmbedderMsg) -> SendResult {
1139        self.0.send(msg)
1140    }
1141}
1142
1143/// Used for communicating the details of a new `WebView` created by the embedder
1144/// back to the constellation.
1145#[derive(Deserialize, Serialize)]
1146pub struct NewWebViewDetails {
1147    pub webview_id: WebViewId,
1148    pub viewport_details: ViewportDetails,
1149    pub user_content_manager_id: Option<UserContentManagerId>,
1150}
1151
1152#[derive(Serialize, Deserialize, Debug)]
1153/// A request to load a URL. This can be used to trigger a configurable load in a `WebView`.
1154///
1155/// ```
1156///  let mut headers = http::HeaderMap::new();
1157///  headers.append(HeaderName::from_static("CustomHeader"), "Value".parse().unwrap());
1158///  let url_request = URLRequest::new(url).headers(headers);
1159///  webview.load_request(url_request);
1160/// ```
1161pub struct UrlRequest {
1162    pub url: ServoUrl,
1163    #[serde(
1164        deserialize_with = "hyper_serde::deserialize",
1165        serialize_with = "hyper_serde::serialize"
1166    )]
1167    pub headers: HeaderMap,
1168}
1169
1170impl UrlRequest {
1171    pub fn new(url: Url) -> Self {
1172        UrlRequest {
1173            url: url.into(),
1174            headers: HeaderMap::new(),
1175        }
1176    }
1177
1178    /// Set headers that will be added to the Headers
1179    pub fn headers(mut self, headers: HeaderMap) -> Self {
1180        self.headers = headers;
1181        self
1182    }
1183}
1184
1185/// The type of wake lock to acquire or release.
1186#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1187pub enum WakeLockType {
1188    Screen,
1189}
1190
1191/// Trait for platform-specific wake lock support.
1192///
1193/// Implementations are responsible for interacting with the OS to prevent
1194/// the screen (or other resources) from sleeping while a wake lock is held.
1195pub trait WakeLockDelegate: Send + Sync {
1196    /// Acquire a wake lock of the given type, preventing the associated
1197    /// resource from sleeping. Called when the aggregate lock count transitions
1198    /// from 0 to 1. Returns an error if the OS fails to grant the lock.
1199    fn acquire(&self, type_: WakeLockType) -> Result<(), Box<dyn std::error::Error>>;
1200
1201    /// Release a previously acquired wake lock of the given type, allowing
1202    /// the resource to sleep. Called when the aggregate lock count transitions
1203    /// from N to 0.
1204    fn release(&self, type_: WakeLockType) -> Result<(), Box<dyn std::error::Error>>;
1205}