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