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                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    /// Get the JS context.
135    pub(crate) fn get_cx() -> JSContext {
136        GlobalScope::get_cx()
137    }
138
139    /// Evaluate a JS script in this global.
140    pub(crate) fn evaluate_js(
141        &self,
142        script: Cow<'_, str>,
143        cx: &mut js::context::JSContext,
144    ) -> Result<(), JavaScriptEvaluationError> {
145        debug!("Evaluating Dom in a worklet.");
146        rooted!(&in(cx) let mut rval = UndefinedValue());
147        self.globalscope.evaluate_js_on_global(
148            script,
149            "",
150            Some(IntroductionType::WORKLET),
151            rval.handle_mut(),
152            CanGc::from_cx(cx),
153        )
154    }
155
156    /// Register a paint worklet to the script thread.
157    pub(crate) fn register_paint_worklet(
158        &self,
159        name: Atom,
160        properties: Vec<Atom>,
161        painter: Box<dyn Painter>,
162    ) {
163        self.to_script_thread_sender
164            .send(MainThreadScriptMsg::RegisterPaintWorklet {
165                pipeline_id: self.globalscope.pipeline_id(),
166                name,
167                properties,
168                painter,
169            })
170            .expect("Worklet thread outlived script thread.");
171    }
172
173    /// The base URL of this global.
174    pub(crate) fn base_url(&self) -> ServoUrl {
175        self.base_url.clone()
176    }
177
178    /// The worklet executor.
179    pub(crate) fn executor(&self) -> WorkletExecutor {
180        self.executor.clone()
181    }
182
183    /// Perform a worklet task
184    pub(crate) fn perform_a_worklet_task(&self, task: WorkletTask) {
185        match task {
186            #[cfg(feature = "testbinding")]
187            WorkletTask::Test(task) => match self.downcast::<TestWorkletGlobalScope>() {
188                Some(global) => global.perform_a_worklet_task(task),
189                None => warn!("This is not a test worklet."),
190            },
191            WorkletTask::Paint(task) => match self.downcast::<PaintWorkletGlobalScope>() {
192                Some(global) => global.perform_a_worklet_task(task),
193                None => warn!("This is not a paint worklet."),
194            },
195        }
196    }
197}
198
199/// Resources required by workletglobalscopes
200#[derive(Clone)]
201pub(crate) struct WorkletGlobalScopeInit {
202    /// Channel to the main script thread
203    pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
204    /// Channel to a resource thread
205    pub(crate) resource_threads: ResourceThreads,
206    /// Channels to the [`StorageThreads`].
207    pub(crate) storage_threads: StorageThreads,
208    /// Channel to the memory profiler
209    pub(crate) mem_profiler_chan: mem::ProfilerChan,
210    /// Channel to the time profiler
211    pub(crate) time_profiler_chan: time::ProfilerChan,
212    /// Channel to devtools
213    pub(crate) devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
214    /// Messages to send to constellation
215    pub(crate) to_constellation_sender:
216        GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
217    /// Messages to send to the Embedder
218    pub(crate) to_embedder_sender: ScriptToEmbedderChan,
219    /// The image cache
220    pub(crate) image_cache: Arc<dyn ImageCache>,
221    /// Identity manager for WebGPU resources
222    #[cfg(feature = "webgpu")]
223    pub(crate) gpu_id_hub: Arc<IdentityHub>,
224}
225
226/// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type>
227#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
228pub(crate) enum WorkletGlobalScopeType {
229    /// A servo-specific testing worklet
230    #[cfg(feature = "testbinding")]
231    Test,
232    /// A paint worklet
233    Paint,
234}
235
236/// A task which can be performed in the context of a worklet global.
237pub(crate) enum WorkletTask {
238    #[cfg(feature = "testbinding")]
239    Test(TestWorkletTask),
240    Paint(PaintWorkletTask),
241}