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