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