1#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::collections::HashSet;
8use std::rc::Rc;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11
12use crossbeam_channel::Sender;
13#[cfg(feature = "devtools")]
14use devtools_traits::ScriptToDevtoolsControlMsg;
15use dom_struct::dom_struct;
16use embedder_traits::ScriptToEmbedderChan;
17use js::context::JSContext;
18use net_traits::ResourceThreads;
19use net_traits::image_cache::ImageCache;
20use net_traits::request::UpgradeInsecureNavigations;
21use profile_traits::{mem, time};
22use script_bindings::cell::DomRefCell;
23use script_traits::Painter;
24#[cfg(feature = "devtools")]
25use servo_base::generic_channel::GenericCallback;
26use servo_base::id::PipelineId;
27use servo_constellation_traits::ScriptToConstellationSender;
28use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
29use storage_traits::StorageThreads;
30use stylo_atoms::Atom;
31
32use crate::dom::Window;
33use crate::dom::bindings::inheritance::Castable;
34use crate::dom::bindings::root::DomRoot;
35use crate::dom::bindings::trace::{CustomTraceable, HashMapTracedValues};
36use crate::dom::bindings::utils::define_all_exposed_interfaces;
37use crate::dom::globalscope::GlobalScope;
38use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope;
39#[cfg(feature = "testbinding")]
40use crate::dom::testworkletglobalscope::TestWorkletGlobalScope;
41#[cfg(feature = "webgpu")]
42use crate::dom::webgpu::identityhub::IdentityHub;
43use crate::dom::worklet::WorkletExecutor;
44use crate::messaging::MainThreadScriptMsg;
45use crate::realms::enter_auto_realm;
46use crate::runtime::job_queue::job_queue_microtask_checkpoint;
47use crate::scripting::script_module::{ModuleRequest, ModuleStatus};
48use crate::tasks::task::TaskCanceller;
49use crate::tasks::task_manager::TaskManager;
50
51#[dom_struct]
52pub(crate) struct WorkletGlobalScope {
54 globalscope: GlobalScope,
56 #[no_trace]
58 base_url: ServoUrl,
59 to_script_thread_sender: Sender<MainThreadScriptMsg>,
61 executor: WorkletExecutor,
63
64 #[no_trace]
65 pipeline_id: PipelineId,
67
68 #[no_trace]
69 origin: MutableOrigin,
70
71 #[conditional_malloc_size_of]
73 task_manager: Rc<TaskManager>,
74
75 #[conditional_malloc_size_of]
76 closing: Arc<AtomicBool>,
77
78 #[ignore_malloc_size_of = "mozjs"]
81 module_map: DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>>,
82}
83
84impl WorkletGlobalScope {
85 #[allow(clippy::too_many_arguments)]
87 pub(crate) fn new(
88 scope_type: WorkletGlobalScopeType,
89 pipeline_id: PipelineId,
90 base_url: ServoUrl,
91 inherited_secure_context: Option<bool>,
92 executor: WorkletExecutor,
93 init: &WorkletGlobalScopeInit,
94 cx: &mut JSContext,
95 closing: Arc<AtomicBool>,
96 ) -> DomRoot<WorkletGlobalScope> {
97 let scope: DomRoot<WorkletGlobalScope> = match scope_type {
98 #[cfg(feature = "testbinding")]
99 WorkletGlobalScopeType::Test => DomRoot::upcast(TestWorkletGlobalScope::new(
100 pipeline_id,
101 base_url,
102 inherited_secure_context,
103 executor,
104 init,
105 cx,
106 closing,
107 )),
108 WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new(
109 cx,
110 pipeline_id,
111 base_url,
112 inherited_secure_context,
113 executor,
114 init,
115 closing,
116 )),
117 };
118
119 let mut realm = enter_auto_realm(cx, &*scope);
120 let mut realm = realm.current_realm();
121 define_all_exposed_interfaces(&mut realm, scope.upcast());
122
123 scope
124 }
125
126 pub(crate) fn new_inherited(
128 pipeline_id: PipelineId,
129 base_url: ServoUrl,
130 inherited_secure_context: Option<bool>,
131 executor: WorkletExecutor,
132 init: &WorkletGlobalScopeInit,
133 closing: Arc<AtomicBool>,
134 ) -> Self {
135 let script_event_loop_sender = executor.event_loop_sender();
136
137 Self {
138 globalscope: GlobalScope::new_inherited(
139 #[cfg(feature = "devtools")]
140 init.devtools_chan.clone(),
141 init.mem_profiler_chan.clone(),
142 init.time_profiler_chan.clone(),
143 init.script_to_constellation_sender.clone(),
144 init.to_embedder_sender.clone(),
145 init.resource_threads.clone(),
146 init.storage_threads.clone(),
147 base_url.clone(),
148 None,
149 #[cfg(feature = "webgpu")]
150 init.gpu_id_hub.clone(),
151 inherited_secure_context,
152 init.inherited_upgrade_insecure_navigations_set.clone(),
153 false,
154 ),
155 base_url,
156 to_script_thread_sender: init.to_script_thread_sender.clone(),
157 executor,
158 pipeline_id,
159 task_manager: Rc::new(TaskManager::new(
160 Some(script_event_loop_sender),
161 pipeline_id,
162 Some(TaskCanceller {
163 cancelled: closing.clone(),
164 }),
165 )),
166 origin: MutableOrigin::new(ImmutableOrigin::new_opaque()),
167 closing,
168 module_map: Default::default(),
169 }
170 }
171
172 pub(crate) fn module_map(
173 &self,
174 ) -> &DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>> {
175 &self.module_map
176 }
177
178 pub(crate) fn origin(&self) -> MutableOrigin {
179 self.origin.clone()
180 }
181
182 pub(crate) fn pipeline_id(&self) -> PipelineId {
183 self.pipeline_id
184 }
185
186 pub(crate) fn register_paint_worklet(
188 &self,
189 name: Atom,
190 properties: Vec<Atom>,
191 painter: Box<dyn Painter>,
192 ) {
193 self.to_script_thread_sender
194 .send(MainThreadScriptMsg::RegisterPaintWorklet {
195 pipeline_id: self.globalscope.pipeline_id(),
196 name,
197 properties,
198 painter,
199 })
200 .expect("Worklet thread outlived script thread.");
201 }
202
203 pub(crate) fn base_url(&self) -> ServoUrl {
205 self.base_url.clone()
206 }
207
208 pub(crate) fn executor(&self) -> WorkletExecutor {
210 self.executor.clone()
211 }
212
213 pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
214 self.task_manager.clone()
215 }
216
217 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
218 if !self.closing.load(Ordering::SeqCst) {
219 job_queue_microtask_checkpoint(cx, vec![DomRoot::from_ref(&self.globalscope)]);
220 }
221 }
222}
223
224impl From<&Window> for WorkletGlobalScopeInit {
225 fn from(window: &Window) -> Self {
226 let global_scope = window.as_global_scope();
227
228 WorkletGlobalScopeInit {
229 to_script_thread_sender: window.main_thread_script_chan().clone(),
230 resource_threads: global_scope.resource_threads().clone(),
231 storage_threads: global_scope.storage_threads().clone(),
232 mem_profiler_chan: global_scope.mem_profiler_chan().clone(),
233 time_profiler_chan: global_scope.time_profiler_chan().clone(),
234 #[cfg(feature = "devtools")]
235 devtools_chan: global_scope.devtools_chan().cloned(),
236 script_to_constellation_sender: global_scope.script_to_constellation_chan().sender,
237 to_embedder_sender: global_scope.script_to_embedder_chan().clone(),
238 image_cache: global_scope.image_cache(),
239 #[cfg(feature = "webgpu")]
240 gpu_id_hub: global_scope.wgpu_id_hub(),
241 inherited_upgrade_insecure_navigations_set: window
242 .as_global_scope()
243 .upgrade_insecure_navigations_set()
244 .clone(),
245 }
246 }
247}
248
249#[derive(Clone)]
251pub(crate) struct WorkletGlobalScopeInit {
252 pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
254 pub(crate) resource_threads: ResourceThreads,
256 pub(crate) storage_threads: StorageThreads,
258 pub(crate) mem_profiler_chan: mem::ProfilerChan,
260 pub(crate) time_profiler_chan: time::ProfilerChan,
262 #[cfg(feature = "devtools")]
264 pub(crate) devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
265 pub(crate) to_embedder_sender: ScriptToEmbedderChan,
267 pub(crate) image_cache: Arc<dyn ImageCache>,
269 #[cfg(feature = "webgpu")]
271 pub(crate) gpu_id_hub: Arc<IdentityHub>,
272 pub(crate) script_to_constellation_sender: ScriptToConstellationSender,
273 pub(crate) inherited_upgrade_insecure_navigations_set: HashSet<UpgradeInsecureNavigations>,
275}
276
277#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
279pub(crate) enum WorkletGlobalScopeType {
280 #[cfg(feature = "testbinding")]
282 Test,
283 Paint,
285}