1use 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]
40pub(crate) struct WorkletGlobalScope {
42 globalscope: GlobalScope,
44 #[no_trace]
46 base_url: ServoUrl,
47 to_script_thread_sender: Sender<MainThreadScriptMsg>,
49 executor: WorkletExecutor,
51}
52
53impl WorkletGlobalScope {
54 #[expect(clippy::too_many_arguments)]
55 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 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, ),
126 base_url,
127 to_script_thread_sender: init.to_script_thread_sender.clone(),
128 executor,
129 }
130 }
131
132 pub(crate) fn get_cx() -> JSContext {
134 GlobalScope::get_cx()
135 }
136
137 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 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 pub(crate) fn base_url(&self) -> ServoUrl {
173 self.base_url.clone()
174 }
175
176 pub(crate) fn executor(&self) -> WorkletExecutor {
178 self.executor.clone()
179 }
180
181 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#[derive(Clone)]
199pub(crate) struct WorkletGlobalScopeInit {
200 pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
202 pub(crate) resource_threads: ResourceThreads,
204 pub(crate) storage_threads: StorageThreads,
206 pub(crate) mem_profiler_chan: mem::ProfilerChan,
208 pub(crate) time_profiler_chan: time::ProfilerChan,
210 pub(crate) devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
212 pub(crate) to_constellation_sender:
214 GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
215 pub(crate) to_embedder_sender: ScriptToEmbedderChan,
217 pub(crate) image_cache: Arc<dyn ImageCache>,
219 #[cfg(feature = "webgpu")]
221 pub(crate) gpu_id_hub: Arc<IdentityHub>,
222}
223
224#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
226pub(crate) enum WorkletGlobalScopeType {
227 #[cfg(feature = "testbinding")]
229 Test,
230 Paint,
232}
233
234pub(crate) enum WorkletTask {
236 #[cfg(feature = "testbinding")]
237 Test(TestWorkletTask),
238 Paint(PaintWorkletTask),
239}