Skip to main content

script_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//! This module contains traits in script used generically in the rest of Servo.
6//! The traits are here instead of in script so that these modules won't have
7//! to depend on script.
8
9#![deny(missing_docs)]
10#![deny(unsafe_code)]
11
12use std::cell::Cell;
13use std::fmt;
14
15use accesskit::ActionRequest;
16use bitflags::bitflags;
17use crossbeam_channel::RecvTimeoutError;
18#[cfg(feature = "devtools")]
19use devtools_traits::ScriptToDevtoolsControlMsg;
20use embedder_traits::user_contents::{UserContentManagerId, UserContents};
21use embedder_traits::{
22    EmbedderControlId, EmbedderControlResponse, FocusSequenceNumber, InputEvent, InputEventAndId,
23    JavaScriptEvaluationId, MediaSessionActionType, MouseButton, PaintHitTestResult,
24    ScriptToEmbedderChan, Theme, ViewportDetails, WebDriverScriptCommand,
25};
26use euclid::{Scale, Size2D};
27use fonts_traits::{SystemFontServiceProxySender, WebFontLoadEvent};
28use keyboard_types::Modifiers;
29use malloc_size_of::malloc_size_of_is_0;
30use malloc_size_of_derive::MallocSizeOf;
31use media::WindowGLContext;
32use net_traits::ResourceThreads;
33use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
34use pixels::PixelFormat;
35use profile_traits::mem;
36use rustc_hash::FxHashMap;
37use serde::{Deserialize, Serialize};
38use servo_base::Epoch;
39#[cfg(feature = "devtools")]
40use servo_base::generic_channel::GenericCallback;
41use servo_base::generic_channel::{GenericReceiver, GenericSender};
42use servo_base::id::{
43    BrowsingContextId, HistoryStateId, LCPCandidateID, PipelineId, PipelineNamespaceId,
44    PipelineNamespaceRequest, ScriptEventLoopId, WebViewId,
45};
46#[cfg(feature = "bluetooth")]
47use servo_bluetooth_traits::BluetoothRequest;
48#[cfg(feature = "webgl")]
49use servo_canvas_traits::webgl::WebGLPipeline;
50use servo_config::prefs::PrefValue;
51use servo_constellation_traits::{
52    KeyboardScroll, LoadData, NavigationHistoryBehavior, PaintMetricEvent, RemoteFocusOperation,
53    ScriptToConstellationSender, ScrollStateUpdate, StructuredSerializedData, TargetSnapshotParams,
54    WindowSizeType,
55};
56use servo_url::{ImmutableOrigin, OriginSnapshot, ServoUrl};
57use storage_traits::StorageThreads;
58use storage_traits::webstorage_thread::WebStorageType;
59use strum::IntoStaticStr;
60use style_traits::{CSSPixel, SpeculativePainter};
61use stylo_atoms::Atom;
62#[cfg(feature = "webgpu")]
63use webgpu_traits::WebGPUMsg;
64use webrender_api::ImageKey;
65use webrender_api::units::DevicePixel;
66
67/// A representation of the `WebView` state that is kept in each `EventLoop`
68/// and in the `Constellation`.
69#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
70pub struct WebViewState {
71    /// The [`WebViewId`] of this `WebView`.
72    pub id: WebViewId,
73    /// The platform [`Theme`] to use for this `WebView`.
74    pub theme: Cell<Theme>,
75    /// Whether or not the `WebView` has system focus. More than one `WebView` may have
76    /// system focus at one time.
77    pub has_system_focus: Cell<bool>,
78}
79
80/// The initial data required to create a new `Pipeline` attached to an existing `ScriptThread`.
81#[derive(Clone, Debug, Deserialize, Serialize)]
82pub struct NewPipelineInfo {
83    /// The [`WebViewState`] of the `WebView` that this pipeline belongs to.
84    pub webview_state: WebViewState,
85    /// The ID of the parent pipeline and frame type, if any.
86    /// If `None`, this is a root pipeline.
87    pub parent_info: Option<PipelineId>,
88    /// Id of the newly-created pipeline.
89    pub new_pipeline_id: PipelineId,
90    /// Id of the browsing context associated with this pipeline.
91    pub browsing_context_id: BrowsingContextId,
92    /// Id of the opener, if any
93    pub opener: Option<BrowsingContextId>,
94    /// Network request data which will be initiated by the script thread.
95    pub load_data: LoadData,
96    /// Initial [`ViewportDetails`] for this layout.
97    pub viewport_details: ViewportDetails,
98    /// The ID of the `UserContentManager` associated with this new pipeline's `WebView`.
99    pub user_content_manager_id: Option<UserContentManagerId>,
100    /// A snapshot of the navigation parameters of the target of this navigation.
101    pub target_snapshot_params: TargetSnapshotParams,
102    /// Name of this iframe, if any
103    pub frame_name: Option<String>,
104}
105
106/// When a pipeline is closed, should its browsing context be discarded too?
107#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
108pub enum DiscardBrowsingContext {
109    /// Discard the browsing context
110    Yes,
111    /// Don't discard the browsing context
112    No,
113}
114
115/// Is a document fully active, active or inactive?
116/// A document is active if it is the current active document in its session history,
117/// it is fuly active if it is active and all of its ancestors are active,
118/// and it is inactive otherwise.
119///
120/// * <https://html.spec.whatwg.org/multipage/#active-document>
121/// * <https://html.spec.whatwg.org/multipage/#fully-active>
122#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
123pub enum DocumentActivity {
124    /// An inactive document
125    Inactive,
126    /// An active but not fully active document
127    Active,
128    /// A fully active document
129    FullyActive,
130}
131
132/// Type of recorded progressive web metric
133#[derive(Clone, Debug, Deserialize, Serialize)]
134pub enum ProgressiveWebMetricType {
135    /// Time to first Paint
136    FirstPaint,
137    /// Time to first contentful paint
138    FirstContentfulPaint,
139    /// Time for the largest contentful paint
140    LargestContentfulPaint {
141        /// The identity of the element, if any.
142        id: LCPCandidateID,
143    },
144    /// Time to interactive
145    TimeToInteractive,
146}
147
148/// The reason why the pipeline id of an iframe is being updated.
149#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
150pub enum UpdatePipelineIdReason {
151    /// The pipeline id is being updated due to a navigation.
152    Navigation,
153    /// The pipeline id is being updated due to a history traversal.
154    Traversal,
155}
156
157/// Messages sent to the `ScriptThread` event loop from the `Constellation`, `Paint`, and (for
158/// now) `Layout`.
159#[derive(Deserialize, IntoStaticStr, Serialize)]
160pub enum ScriptThreadMessage {
161    /// Span a new `Pipeline` in this `ScriptThread` and start fetching the contents
162    /// according to the provided `LoadData`. This will ultimately create a `Window`
163    /// and all associated data structures such as `Layout` in the `ScriptThread`.
164    SpawnPipeline(NewPipelineInfo),
165    /// Takes the associated window proxy out of "delaying-load-events-mode",
166    /// used if a scheduled navigated was refused by the embedder.
167    /// <https://html.spec.whatwg.org/multipage/#delaying-load-events-mode>
168    StopDelayingLoadEventsMode(PipelineId),
169    /// Window resized.  Sends a DOM event eventually, but first we combine events.
170    Resize(PipelineId, ViewportDetails, WindowSizeType),
171    /// Inform the ScriptThread that some aspect of the WebViewState has changed.
172    UpdateWebViewState(WebViewState),
173    /// Notifies script that window has been resized but to not take immediate action.
174    ResizeInactive(PipelineId, ViewportDetails),
175    /// Window switched from fullscreen mode.
176    ExitFullScreen(PipelineId),
177    /// Notifies the script that the document associated with this pipeline should 'unload'.
178    UnloadDocument(PipelineId),
179    /// Notifies the script that a pipeline should be closed.
180    ExitPipeline(WebViewId, PipelineId, DiscardBrowsingContext),
181    /// Notifies the script that the whole thread should be closed.
182    ExitScriptThread,
183    /// Sends a DOM event.
184    SendInputEvent(WebViewId, PipelineId, ConstellationInputEvent),
185    /// Request that the given pipeline refresh the cursor by doing a hit test at the most
186    /// recently hovered cursor position and resetting the cursor. This happens after a
187    /// display list update is rendered.
188    RefreshCursor(PipelineId),
189    /// Requests that the script thread immediately send the constellation the title of a pipeline.
190    GetTitle(PipelineId),
191    /// Retrieve the origin of a document for a pipeline, in case a child needs to retrieve the
192    /// origin of a parent in a different script thread.
193    GetDocumentOrigin(PipelineId, GenericSender<Option<OriginSnapshot>>),
194    /// Retrieve the origin and internal ancestor origin objects list of a
195    /// `Document` for a given `PipelineId`, in case a child needs to retrieve
196    /// the origin of a parent in a different event loop.
197    GetDocumentOriginDetails(
198        PipelineId,
199        GenericSender<Option<(OriginSnapshot, Vec<ImmutableOrigin>)>>,
200    ),
201    /// Notifies script thread of a change to one of its document's activity
202    SetDocumentActivity(PipelineId, DocumentActivity),
203    /// Set whether to use less resources by running timers at a heavily limited rate.
204    SetThrottled(PipelineId, bool),
205    /// Notifies script thread that a url should be loaded in this iframe.
206    /// PipelineId is for the parent, BrowsingContextId is for the nested browsing context
207    NavigateIframe(
208        PipelineId,
209        BrowsingContextId,
210        LoadData,
211        NavigationHistoryBehavior,
212        TargetSnapshotParams,
213    ),
214    /// Post a message to a given window.
215    PostMessage {
216        /// The target of the message.
217        target: PipelineId,
218        /// The webview associated with the source pipeline.
219        source_webview: WebViewId,
220        /// The ancestry of browsing context associated with the source,
221        /// starting with the source itself.
222        source_with_ancestry: Vec<BrowsingContextId>,
223        /// The expected origin of the target.
224        target_origin: Option<ImmutableOrigin>,
225        /// The source origin of the message.
226        /// <https://html.spec.whatwg.org/multipage/#dom-messageevent-origin>
227        source_origin: ImmutableOrigin,
228        /// The data to be posted.
229        data: Box<StructuredSerializedData>,
230    },
231    /// Updates the current pipeline ID of a given iframe.
232    /// First PipelineId is for the parent, second is the new PipelineId for the frame.
233    UpdatePipelineId(
234        PipelineId,
235        BrowsingContextId,
236        WebViewId,
237        PipelineId,
238        UpdatePipelineIdReason,
239    ),
240    /// Updates the history state and url of a given pipeline.
241    UpdateHistoryState(PipelineId, Option<HistoryStateId>, ServoUrl),
242    /// Removes inaccesible history states.
243    RemoveHistoryStates(PipelineId, Vec<HistoryStateId>),
244    /// Focus a `Document` as part of the focusing steps which focuses all parent `Document`s of a
245    /// newly focused `<iframe>`. Note that this is not used for the `Document` and `Element` that
246    /// is gaining focus as that is handled locally in the originating `ScriptThread`.
247    FocusDocumentAsPartOfFocusingSteps(PipelineId, FocusSequenceNumber, Option<BrowsingContextId>),
248    /// Unfocus a `Document` as part of the focusing steps which unfocuses all parent `Document`s of an
249    /// `<iframe>` losing focus. This does not do anything for a top-level `Document`, which can never
250    /// lose focus (apart from losing system focus, which is a separate concept).
251    UnfocusDocumentAsPartOfFocusingSteps(PipelineId, FocusSequenceNumber),
252    /// Focus a `Document` and run the focusing steps. This is used in two situations:
253    /// - When calling the DOM `focus()` API on a remote `Window` as well as from
254    ///   WebDriver. The difference between this and `FocusDocumentAsPartOfFocusingSteps` is that this
255    ///   version actually does run the focusing steps and may result in blur and focus events firing
256    ///   up the frame tree.
257    /// - When doing sequential focus navigation into and out of frames.
258    FocusDocument(PipelineId, RemoteFocusOperation),
259    /// Passes a webdriver command to the script thread for execution
260    WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
261    /// Notifies script thread that all animations are done
262    TickAllAnimations(Vec<WebViewId>),
263    /// Notifies the script thread that a web font has finished loading.
264    ///
265    /// This is sent if either the web font loaded successfully, or to notify the script thread
266    /// that it should try to resolve `document.fonts.ready` because the font was the last one
267    /// loading.
268    WebFontLoadFinished(PipelineId, WebFontLoadEvent),
269    /// Cause a `load` event to be dispatched at the appropriate iframe element.
270    DispatchIFrameLoadEvent {
271        /// The frame that has been marked as loaded.
272        target: BrowsingContextId,
273        /// The pipeline that contains a frame loading the target pipeline.
274        parent: PipelineId,
275        /// The pipeline that has completed loading.
276        child: PipelineId,
277    },
278    /// Cause a `storage` event to be dispatched at the appropriate window.
279    /// The strings are key, old value and new value.
280    DispatchStorageEvent(
281        PipelineId,
282        WebStorageType,
283        ServoUrl,
284        Option<String>,
285        Option<String>,
286        Option<String>,
287    ),
288    /// Report an error from a CSS parser for the given pipeline
289    #[cfg(feature = "devtools")]
290    ReportCSSError(PipelineId, String, u32, u32, String),
291    /// Reload the given page.
292    Reload(PipelineId),
293    /// Notifies the script thread about a new recorded paint metric.
294    PaintMetric(PipelineId, PaintMetricEvent),
295    /// Notifies the media session about a user requested media session action.
296    MediaSessionAction(PipelineId, MediaSessionActionType),
297    /// Notifies script thread that WebGPU server has started
298    #[cfg(feature = "webgpu")]
299    SetWebGPUPort(GenericReceiver<WebGPUMsg>),
300    /// `Paint` scrolled and is updating the scroll states of the nodes in the given
301    /// pipeline via the Constellation.
302    SetScrollStates(PipelineId, ScrollStateUpdate),
303    /// Evaluate the given JavaScript and return a result via a corresponding message
304    /// to the Constellation.
305    EvaluateJavaScript(WebViewId, PipelineId, JavaScriptEvaluationId, String),
306    /// A new batch of keys for the image cache for the specific pipeline.
307    SendImageKeysBatch(PipelineId, Vec<ImageKey>),
308    /// Preferences were updated in the parent process.
309    PreferencesUpdated(Vec<(String, PrefValue)>),
310    /// Notify the `ScriptThread` that the Servo renderer is no longer waiting on
311    /// asynchronous image uploads for the given `Pipeline`. These are mainly used
312    /// by canvas to perform uploads while the display list is being built.
313    NoLongerWaitingOnAsychronousImageUpdates(PipelineId),
314    /// Forward a keyboard scroll operation from an `<iframe>` to a parent pipeline.
315    ForwardKeyboardScroll(PipelineId, KeyboardScroll),
316    /// Request readiness for a screenshot from the given pipeline. The pipeline will
317    /// respond when it is ready to take the screenshot or will not be able to take it
318    /// in the future.
319    RequestScreenshotReadiness(WebViewId, PipelineId),
320    /// A response to a request to show an embedder user interface control.
321    EmbedderControlResponse(EmbedderControlId, EmbedderControlResponse),
322    /// Set the `UserContents` for the given `UserContentManagerId`. A `ScriptThread` can host many
323    /// `WebView`s which share the same `UserContentManager`. Only documents loaded after
324    /// the processing of this message will observe the new `UserContents` of the specified
325    /// `UserContentManagerId`.
326    SetUserContents(UserContentManagerId, UserContents),
327    /// Release all data for the given `UserContentManagerId` from the `ScriptThread`'s
328    /// `user_contents_for_manager_id` map.
329    DestroyUserContentManager(UserContentManagerId),
330    /// Update the pinch zoom details of a pipeline. Each `Window` stores a `VisualViewport` DOM
331    /// instance that gets updated according to the changes from the `Compositor``.
332    UpdatePinchZoomInfos(PipelineId, PinchZoomInfos),
333    /// Activate or deactivate accessibility features for the given pipeline, assuming it represents
334    /// a document.
335    ///
336    /// Why only one pipeline? In the Servo API, accessibility is activated on a per-webview basis,
337    /// and webviews have a simple one-to-many mapping to pipelines that represent documents. But
338    /// those pipelines run in script threads, which complicates things: the pipelines in a webview
339    /// may be split across multiple script threads, and the pipelines in a script thread may belong
340    /// to multiple webviews. So the simplest approach is to activate it for one pipeline at a time.
341    SetAccessibilityActive(PipelineId, bool, Epoch),
342    /// Forward the given [`accesskit::ActionRequest`] to the given pipeline.
343    ForwardAccessibilityAction(PipelineId, ActionRequest),
344    /// Force a garbage collection in this script thread.
345    TriggerGarbageCollection,
346}
347
348impl fmt::Debug for ScriptThreadMessage {
349    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
350        let variant_string: &'static str = self.into();
351        write!(formatter, "ConstellationControlMsg::{variant_string}")
352    }
353}
354
355/// Used to determine if a script has any pending asynchronous activity.
356#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
357pub enum DocumentState {
358    /// The document has been loaded and is idle.
359    Idle,
360    /// The document is either loading or waiting on an event.
361    Pending,
362}
363
364bitflags! {
365    #[derive(Clone, Copy, Default, Debug, Deserialize, Eq, PartialEq, Serialize)]
366    /// <https://w3c.github.io/pointerevents/#dom-mouseevent-buttons>
367    pub struct MouseButtons: u16 {
368        /// > 1 MUST indicate the primary button of the device (in general, the left
369        /// > button or the only button on single-button devices, used to activate a user
370        /// > interface control or select text).
371        const Primary = 1;
372        /// > 2 MUST indicate the secondary button (in general, the right button, often
373        /// > used to display a context menu), if present.
374        const Secondary = 2;
375        /// > 4 MUST indicate the auxiliary button (in general, the middle button, often
376        /// > combined with a mouse wheel).
377        const Auxiliary = 4;
378        /// The 'back' button:
379        ///
380        /// > Some pointing devices provide or simulate more buttons. To represent such
381        /// > buttons, the value MUST be doubled for each successive button (in the binary
382        /// > series 8, 16, 32, ... ).
383        const Back = 8;
384        /// The 'forward' button:
385        ///
386        /// > Some pointing devices provide or simulate more buttons. To represent such
387        /// > buttons, the value MUST be doubled for each successive button (in the binary
388        /// > series 8, 16, 32, ... ).
389        const Forward = 16;
390    }
391}
392
393impl MouseButtons {
394    /// Returns whether exactly one button is pressed.
395    pub fn exactly_one_button_pressed(&self) -> bool {
396        // Exactly one button is pressed iff mouse_button_state is a power of 2
397        !self.is_empty() && (self.bits() & (self.bits() - 1)) == 0
398    }
399}
400
401malloc_size_of_is_0!(MouseButtons);
402
403impl TryFrom<MouseButton> for MouseButtons {
404    type Error = ();
405
406    fn try_from(button: MouseButton) -> Result<Self, Self::Error> {
407        match button {
408            MouseButton::Primary => Ok(Self::Primary),
409            MouseButton::Secondary => Ok(Self::Secondary),
410            MouseButton::Auxiliary => Ok(Self::Auxiliary),
411            MouseButton::Back => Ok(Self::Back),
412            MouseButton::Forward => Ok(Self::Forward),
413            MouseButton::None | MouseButton::Other(_) => Err(()),
414        }
415    }
416}
417
418/// Input events from the embedder that are sent via the `Constellation`` to the `ScriptThread`.
419#[derive(Clone, Debug, Deserialize, Serialize)]
420pub struct ConstellationInputEvent {
421    /// The hit test result of this input event, if any.
422    pub hit_test_result: Option<PaintHitTestResult>,
423    /// The pressed mouse button state of the constellation when this input
424    /// event was triggered.
425    pub pressed_mouse_buttons: MouseButtons,
426    /// The currently active keyboard modifiers.
427    pub active_keyboard_modifiers: Modifiers,
428    /// The [`InputEventAndId`] itself.
429    pub event: InputEventAndId,
430}
431
432impl ConstellationInputEvent {
433    /// Returns whether `pressed_mouse_buttons` includes the primary button
434    pub fn primary_button_is_pressed(&self) -> bool {
435        self.pressed_mouse_buttons.contains(MouseButtons::Primary)
436    }
437
438    /// Returns whether `pressed_mouse_buttons` includes the auxiliary (middle) button
439    pub fn auxiliary_button_is_pressed(&self) -> bool {
440        self.pressed_mouse_buttons.contains(MouseButtons::Auxiliary)
441    }
442
443    /// Returns whether this is a compatibility mouse event synthesized for a touch.
444    pub fn is_compatibility_event_for_touch(&self) -> bool {
445        match self.event.event {
446            InputEvent::MouseMove(ref event) => event.is_compatibility_event_for_touch,
447            InputEvent::MouseButton(ref event) => event.is_compatibility_event_for_touch,
448            _ => false,
449        }
450    }
451}
452
453/// All of the information necessary to create a new [`ScriptThread`] for a new [`EventLoop`].
454///
455/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
456/// do! Use IPC senders and receivers instead.
457#[derive(Deserialize, Serialize)]
458pub struct InitialScriptState {
459    /// The id of the script event loop that this state will start. This is used to uniquely
460    /// identify an event loop.
461    pub id: ScriptEventLoopId,
462    /// The sender to use to install the `Pipeline` namespace into this process (if necessary).
463    pub namespace_request_sender: GenericSender<PipelineNamespaceRequest>,
464    /// A channel with which messages can be sent to us (the script thread).
465    pub constellation_to_script_sender: GenericSender<ScriptThreadMessage>,
466    /// A port on which messages sent by the constellation to script can be received.
467    pub constellation_to_script_receiver: GenericReceiver<ScriptThreadMessage>,
468    /// A channel on which messages can be sent to the constellation from script.
469    pub script_to_constellation_sender: ScriptToConstellationSender,
470    /// A channel which allows script to send messages directly to the Embedder
471    /// This will pump the embedder event loop.
472    pub script_to_embedder_sender: ScriptToEmbedderChan,
473    /// An IpcSender to the `SystemFontService` used to create a `SystemFontServiceProxy`.
474    pub system_font_service: SystemFontServiceProxySender,
475    /// A channel to the resource manager thread.
476    pub resource_threads: ResourceThreads,
477    /// A channel to the storage manager thread.
478    pub storage_threads: StorageThreads,
479    /// A channel to the bluetooth thread.
480    #[cfg(feature = "bluetooth")]
481    pub bluetooth_sender: GenericSender<BluetoothRequest>,
482    /// A channel to the time profiler thread.
483    pub time_profiler_sender: profile_traits::time::ProfilerChan,
484    /// A channel to the memory profiler thread.
485    pub memory_profiler_sender: mem::ProfilerChan,
486    /// A channel to the developer tools, if applicable.
487    #[cfg(feature = "devtools")]
488    pub devtools_server_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
489    /// The ID of the pipeline namespace for this script thread.
490    pub pipeline_namespace_id: PipelineNamespaceId,
491    /// A channel to the WebGL thread used in this pipeline.
492    #[cfg(feature = "webgl")]
493    pub webgl_chan: Option<WebGLPipeline>,
494    /// The XR device registry
495    pub webxr_registry: Option<webxr_api::Registry>,
496    /// Access to `Paint` across a process boundary.
497    pub cross_process_paint_api: CrossProcessPaintApi,
498    /// Application window's GL Context for Media player
499    pub player_context: WindowGLContext,
500    /// A list of URLs that can access privileged internal APIs.
501    pub privileged_urls: Vec<ServoUrl>,
502    /// A copy of constellation's `UserContentManagerId` to `UserContents` map.
503    pub user_contents_for_manager_id: FxHashMap<UserContentManagerId, UserContents>,
504}
505
506/// Errors from executing a paint worklet
507#[derive(Clone, Debug, Deserialize, Serialize)]
508pub enum PaintWorkletError {
509    /// Execution timed out.
510    Timeout,
511    /// No such worklet.
512    WorkletNotFound,
513}
514
515impl From<RecvTimeoutError> for PaintWorkletError {
516    fn from(_: RecvTimeoutError) -> PaintWorkletError {
517        PaintWorkletError::Timeout
518    }
519}
520
521/// Execute paint code in the worklet thread pool.
522pub trait Painter: SpeculativePainter {
523    /// <https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image>
524    fn draw_a_paint_image(
525        &self,
526        size: Size2D<f32, CSSPixel>,
527        zoom: Scale<f32, CSSPixel, DevicePixel>,
528        properties: Vec<(Atom, String)>,
529        arguments: Vec<String>,
530    ) -> Result<DrawAPaintImageResult, PaintWorkletError>;
531}
532
533impl fmt::Debug for dyn Painter {
534    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
535        fmt.debug_tuple("Painter")
536            .field(&format_args!(".."))
537            .finish()
538    }
539}
540
541/// The result of executing paint code: the image together with any image URLs that need to be loaded.
542///
543/// TODO: this should return a WR display list. <https://github.com/servo/servo/issues/17497>
544#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
545pub struct DrawAPaintImageResult {
546    /// The image height
547    pub width: u32,
548    /// The image width
549    pub height: u32,
550    /// The image format
551    pub format: PixelFormat,
552    /// The image drawn, or None if an invalid paint image was drawn
553    pub image_key: Option<ImageKey>,
554    /// Drawing the image might have requested loading some image URLs.
555    pub missing_image_urls: Vec<ServoUrl>,
556}