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