Skip to main content

script/dom/
workletglobalscope.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
5use std::borrow::Cow;
6use std::sync::Arc;
7
8use crossbeam_channel::Sender;
9use devtools_traits::ScriptToDevtoolsControlMsg;
10use dom_struct::dom_struct;
11use embedder_traits::{JavaScriptEvaluationError, ScriptToEmbedderChan};
12use js::context::JSContext;
13use net_traits::ResourceThreads;
14use net_traits::image_cache::ImageCache;
15use profile_traits::{mem, time};
16use script_traits::Painter;
17use servo_base::generic_channel::{GenericCallback, GenericSender};
18use servo_base::id::{PipelineId, WebViewId};
19use servo_constellation_traits::{ScriptToConstellationChan, ScriptToConstellationMessage};
20use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
21use storage_traits::StorageThreads;
22use stylo_atoms::Atom;
23
24use crate::dom::bindings::inheritance::Castable;
25use crate::dom::bindings::root::DomRoot;
26use crate::dom::bindings::trace::CustomTraceable;
27use crate::dom::bindings::utils::define_all_exposed_interfaces;
28use crate::dom::globalscope::GlobalScope;
29use crate::dom::paintworkletglobalscope::{PaintWorkletGlobalScope, PaintWorkletTask};
30#[cfg(feature = "testbinding")]
31use crate::dom::testworkletglobalscope::{TestWorkletGlobalScope, TestWorkletTask};
32#[cfg(feature = "webgpu")]
33use crate::dom::webgpu::identityhub::IdentityHub;
34use crate::dom::worklet::WorkletExecutor;
35use crate::messaging::MainThreadScriptMsg;
36use crate::realms::enter_auto_realm;
37use crate::script_runtime::IntroductionType;
38
39#[dom_struct]
40/// <https://drafts.css-houdini.org/worklets/#workletglobalscope>
41pub(crate) struct WorkletGlobalScope {
42    /// The global for this worklet.
43    globalscope: GlobalScope,
44    /// The base URL for this worklet.
45    #[no_trace]
46    base_url: ServoUrl,
47    /// Sender back to the script thread
48    to_script_thread_sender: Sender<MainThreadScriptMsg>,
49    /// Worklet task executor
50    executor: WorkletExecutor,
51}
52
53impl WorkletGlobalScope {
54    #[expect(clippy::too_many_arguments)]
55    /// Create a new heap-allocated `WorkletGlobalScope`.
56    pub(crate) fn new(
57        scope_type: WorkletGlobalScopeType,
58        webview_id: WebViewId,
59        pipeline_id: PipelineId,
60        base_url: ServoUrl,
61        inherited_secure_context: Option<bool>,
62        executor: WorkletExecutor,
63        init: &WorkletGlobalScopeInit,
64        cx: &mut JSContext,
65    ) -> DomRoot<WorkletGlobalScope> {
66        let scope: DomRoot<WorkletGlobalScope> = match scope_type {
67            #[cfg(feature = "testbinding")]
68            WorkletGlobalScopeType::Test => DomRoot::upcast(TestWorkletGlobalScope::new(
69                webview_id,
70                pipeline_id,
71                base_url,
72                inherited_secure_context,
73                executor,
74                init,
75                cx,
76            )),
77            WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new(
78                webview_id,
79                pipeline_id,
80                base_url,
81                inherited_secure_context,
82                executor,
83                init,
84                cx,
85            )),
86        };
87
88        let mut realm = enter_auto_realm(cx, &*scope);
89        let mut realm = realm.current_realm();
90        define_all_exposed_interfaces(&mut realm, scope.upcast());
91
92        scope
93    }
94
95    /// Create a new stack-allocated `WorkletGlobalScope`.
96    pub(crate) fn new_inherited(
97        webview_id: WebViewId,
98        pipeline_id: PipelineId,
99        base_url: ServoUrl,
100        inherited_secure_context: Option<bool>,
101        executor: WorkletExecutor,
102        init: &WorkletGlobalScopeInit,
103    ) -> Self {
104        let script_to_constellation_chan = ScriptToConstellationChan {
105            sender: init.to_constellation_sender.clone(),
106            webview_id,
107            pipeline_id,
108        };
109        Self {
110            globalscope: GlobalScope::new_inherited(
111                pipeline_id,
112                init.devtools_chan.clone(),
113                init.mem_profiler_chan.clone(),
114                init.time_profiler_chan.clone(),
115                script_to_constellation_chan,
116                init.to_embedder_sender.clone(),
117                init.resource_threads.clone(),
118                init.storage_threads.clone(),
119                MutableOrigin::new(ImmutableOrigin::new_opaque()),
120                base_url.clone(),
121                None,
122                #[cfg(feature = "webgpu")]
123                init.gpu_id_hub.clone(),
124                inherited_secure_context,
125                false,
126                None, // font_context
127            ),
128            base_url,
129            to_script_thread_sender: init.to_script_thread_sender.clone(),
130            executor,
131        }
132    }
133
134    /// Evaluate a JS script in this global.
135    pub(crate) fn evaluate_js(
136        &self,
137        script: Cow<'_, str>,
138        cx: &mut JSContext,
139    ) -> Result<(), JavaScriptEvaluationError> {
140        let mut realm = enter_auto_realm(cx, self);
141        let cx = &mut realm.current_realm();
142
143        debug!("Evaluating Dom in a worklet.");
144        self.globalscope.evaluate_js_on_global(
145            cx,
146            script,
147            "",
148            Some(IntroductionType::WORKLET),
149            None,
150        )
151    }
152
153    /// Register a paint worklet to the script thread.
154    pub(crate) fn register_paint_worklet(
155        &self,
156        name: Atom,
157        properties: Vec<Atom>,
158        painter: Box<dyn Painter>,
159    ) {
160        self.to_script_thread_sender
161            .send(MainThreadScriptMsg::RegisterPaintWorklet {
162                pipeline_id: self.globalscope.pipeline_id(),
163                name,
164                properties,
165                painter,
166            })
167            .expect("Worklet thread outlived script thread.");
168    }
169
170    /// The base URL of this global.
171    pub(crate) fn base_url(&self) -> ServoUrl {
172        self.base_url.clone()
173    }
174
175    /// The worklet executor.
176    pub(crate) fn executor(&self) -> WorkletExecutor {
177        self.executor.clone()
178    }
179
180    /// Perform a worklet task
181    pub(crate) fn perform_a_worklet_task(&self, cx: &mut JSContext, task: WorkletTask) {
182        match task {
183            #[cfg(feature = "testbinding")]
184            WorkletTask::Test(task) => match self.downcast::<TestWorkletGlobalScope>() {
185                Some(global) => global.perform_a_worklet_task(task),
186                None => warn!("This is not a test worklet."),
187            },
188            WorkletTask::Paint(task) => match self.downcast::<PaintWorkletGlobalScope>() {
189                Some(global) => global.perform_a_worklet_task(cx, task),
190                None => warn!("This is not a paint worklet."),
191            },
192        }
193    }
194}
195
196/// Resources required by workletglobalscopes
197#[derive(Clone)]
198pub(crate) struct WorkletGlobalScopeInit {
199    /// Channel to the main script thread
200    pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
201    /// Channel to a resource thread
202    pub(crate) resource_threads: ResourceThreads,
203    /// Channels to the [`StorageThreads`].
204    pub(crate) storage_threads: StorageThreads,
205    /// Channel to the memory profiler
206    pub(crate) mem_profiler_chan: mem::ProfilerChan,
207    /// Channel to the time profiler
208    pub(crate) time_profiler_chan: time::ProfilerChan,
209    /// Channel to devtools
210    pub(crate) devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
211    /// Messages to send to constellation
212    pub(crate) to_constellation_sender:
213        GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
214    /// Messages to send to the Embedder
215    pub(crate) to_embedder_sender: ScriptToEmbedderChan,
216    /// The image cache
217    pub(crate) image_cache: Arc<dyn ImageCache>,
218    /// Identity manager for WebGPU resources
219    #[cfg(feature = "webgpu")]
220    pub(crate) gpu_id_hub: Arc<IdentityHub>,
221}
222
223/// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type>
224#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
225pub(crate) enum WorkletGlobalScopeType {
226    /// A servo-specific testing worklet
227    #[cfg(feature = "testbinding")]
228    Test,
229    /// A paint worklet
230    Paint,
231}
232
233/// A task which can be performed in the context of a worklet global.
234pub(crate) enum WorkletTask {
235    #[cfg(feature = "testbinding")]
236    Test(TestWorkletTask),
237    Paint(PaintWorkletTask),
238}