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