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 base::generic_channel::{GenericCallback, GenericSender};
9use base::id::{PipelineId, WebViewId};
10use constellation_traits::{ScriptToConstellationChan, ScriptToConstellationMessage};
11use crossbeam_channel::Sender;
12use devtools_traits::ScriptToDevtoolsControlMsg;
13use dom_struct::dom_struct;
14use embedder_traits::{JavaScriptEvaluationError, ScriptToEmbedderChan};
15use js::jsval::UndefinedValue;
16use net_traits::ResourceThreads;
17use net_traits::image_cache::ImageCache;
18use profile_traits::{mem, time};
19use script_traits::Painter;
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::{CanGc, IntroductionType, JSContext};
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 js::context::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            )),
76            WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new(
77                webview_id,
78                pipeline_id,
79                base_url,
80                inherited_secure_context,
81                executor,
82                init,
83            )),
84        };
85
86        let mut realm = enter_auto_realm(cx, &*scope);
87        let mut realm = realm.current_realm();
88        define_all_exposed_interfaces(&mut realm, scope.upcast());
89
90        scope
91    }
92
93    /// Create a new stack-allocated `WorkletGlobalScope`.
94    pub(crate) fn new_inherited(
95        webview_id: WebViewId,
96        pipeline_id: PipelineId,
97        base_url: ServoUrl,
98        inherited_secure_context: Option<bool>,
99        executor: WorkletExecutor,
100        init: &WorkletGlobalScopeInit,
101    ) -> Self {
102        let script_to_constellation_chan = ScriptToConstellationChan {
103            sender: init.to_constellation_sender.clone(),
104            webview_id,
105            pipeline_id,
106        };
107        Self {
108            globalscope: GlobalScope::new_inherited(
109                pipeline_id,
110                init.devtools_chan.clone(),
111                init.mem_profiler_chan.clone(),
112                init.time_profiler_chan.clone(),
113                script_to_constellation_chan,
114                init.to_embedder_sender.clone(),
115                init.resource_threads.clone(),
116                init.storage_threads.clone(),
117                MutableOrigin::new(ImmutableOrigin::new_opaque()),
118                base_url.clone(),
119                None,
120                #[cfg(feature = "webgpu")]
121                init.gpu_id_hub.clone(),
122                inherited_secure_context,
123                false,
124                None, // font_context
125            ),
126            base_url,
127            to_script_thread_sender: init.to_script_thread_sender.clone(),
128            executor,
129        }
130    }
131
132    /// Get the JS context.
133    pub(crate) fn get_cx() -> JSContext {
134        GlobalScope::get_cx()
135    }
136
137    /// Evaluate a JS script in this global.
138    pub(crate) fn evaluate_js(
139        &self,
140        script: Cow<'_, str>,
141        can_gc: CanGc,
142    ) -> Result<(), JavaScriptEvaluationError> {
143        debug!("Evaluating Dom in a worklet.");
144        rooted!(in (*GlobalScope::get_cx()) let mut rval = UndefinedValue());
145        self.globalscope.evaluate_js_on_global(
146            script,
147            "",
148            Some(IntroductionType::WORKLET),
149            rval.handle_mut(),
150            can_gc,
151        )
152    }
153
154    /// Register a paint worklet to the script thread.
155    pub(crate) fn register_paint_worklet(
156        &self,
157        name: Atom,
158        properties: Vec<Atom>,
159        painter: Box<dyn Painter>,
160    ) {
161        self.to_script_thread_sender
162            .send(MainThreadScriptMsg::RegisterPaintWorklet {
163                pipeline_id: self.globalscope.pipeline_id(),
164                name,
165                properties,
166                painter,
167            })
168            .expect("Worklet thread outlived script thread.");
169    }
170
171    /// The base URL of this global.
172    pub(crate) fn base_url(&self) -> ServoUrl {
173        self.base_url.clone()
174    }
175
176    /// The worklet executor.
177    pub(crate) fn executor(&self) -> WorkletExecutor {
178        self.executor.clone()
179    }
180
181    /// Perform a worklet task
182    pub(crate) fn perform_a_worklet_task(&self, task: WorkletTask) {
183        match task {
184            #[cfg(feature = "testbinding")]
185            WorkletTask::Test(task) => match self.downcast::<TestWorkletGlobalScope>() {
186                Some(global) => global.perform_a_worklet_task(task),
187                None => warn!("This is not a test worklet."),
188            },
189            WorkletTask::Paint(task) => match self.downcast::<PaintWorkletGlobalScope>() {
190                Some(global) => global.perform_a_worklet_task(task),
191                None => warn!("This is not a paint worklet."),
192            },
193        }
194    }
195}
196
197/// Resources required by workletglobalscopes
198#[derive(Clone)]
199pub(crate) struct WorkletGlobalScopeInit {
200    /// Channel to the main script thread
201    pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
202    /// Channel to a resource thread
203    pub(crate) resource_threads: ResourceThreads,
204    /// Channels to the [`StorageThreads`].
205    pub(crate) storage_threads: StorageThreads,
206    /// Channel to the memory profiler
207    pub(crate) mem_profiler_chan: mem::ProfilerChan,
208    /// Channel to the time profiler
209    pub(crate) time_profiler_chan: time::ProfilerChan,
210    /// Channel to devtools
211    pub(crate) devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
212    /// Messages to send to constellation
213    pub(crate) to_constellation_sender:
214        GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
215    /// Messages to send to the Embedder
216    pub(crate) to_embedder_sender: ScriptToEmbedderChan,
217    /// The image cache
218    pub(crate) image_cache: Arc<dyn ImageCache>,
219    /// Identity manager for WebGPU resources
220    #[cfg(feature = "webgpu")]
221    pub(crate) gpu_id_hub: Arc<IdentityHub>,
222}
223
224/// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type>
225#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
226pub(crate) enum WorkletGlobalScopeType {
227    /// A servo-specific testing worklet
228    #[cfg(feature = "testbinding")]
229    Test,
230    /// A paint worklet
231    Paint,
232}
233
234/// A task which can be performed in the context of a worklet global.
235pub(crate) enum WorkletTask {
236    #[cfg(feature = "testbinding")]
237    Test(TestWorkletTask),
238    Paint(PaintWorkletTask),
239}