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 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 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, ),
128 base_url,
129 to_script_thread_sender: init.to_script_thread_sender.clone(),
130 executor,
131 }
132 }
133
134 pub(crate) fn get_cx() -> JSContext {
136 GlobalScope::get_cx()
137 }
138
139 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 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 pub(crate) fn base_url(&self) -> ServoUrl {
175 self.base_url.clone()
176 }
177
178 pub(crate) fn executor(&self) -> WorkletExecutor {
180 self.executor.clone()
181 }
182
183 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#[derive(Clone)]
201pub(crate) struct WorkletGlobalScopeInit {
202 pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
204 pub(crate) resource_threads: ResourceThreads,
206 pub(crate) storage_threads: StorageThreads,
208 pub(crate) mem_profiler_chan: mem::ProfilerChan,
210 pub(crate) time_profiler_chan: time::ProfilerChan,
212 pub(crate) devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
214 pub(crate) to_constellation_sender:
216 GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
217 pub(crate) to_embedder_sender: ScriptToEmbedderChan,
219 pub(crate) image_cache: Arc<dyn ImageCache>,
221 #[cfg(feature = "webgpu")]
223 pub(crate) gpu_id_hub: Arc<IdentityHub>,
224}
225
226#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
228pub(crate) enum WorkletGlobalScopeType {
229 #[cfg(feature = "testbinding")]
231 Test,
232 Paint,
234}
235
236pub(crate) enum WorkletTask {
238 #[cfg(feature = "testbinding")]
239 Test(TestWorkletTask),
240 Paint(PaintWorkletTask),
241}