Skip to main content

script/dom/worklet/
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
5#![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]
52/// <https://drafts.css-houdini.org/worklets/#workletglobalscope>
53pub(crate) struct WorkletGlobalScope {
54    /// The global for this worklet.
55    globalscope: GlobalScope,
56    /// The base URL for this worklet.
57    #[no_trace]
58    base_url: ServoUrl,
59    /// Sender back to the script thread
60    to_script_thread_sender: Sender<MainThreadScriptMsg>,
61    /// Worklet task executor
62    executor: WorkletExecutor,
63
64    #[no_trace]
65    /// The pipeline that created this worklet.
66    pipeline_id: PipelineId,
67
68    #[no_trace]
69    origin: MutableOrigin,
70
71    /// The [`TaskManager`] for this [`WorkletGlobalScope`].
72    #[conditional_malloc_size_of]
73    task_manager: Rc<TaskManager>,
74
75    #[conditional_malloc_size_of]
76    closing: Arc<AtomicBool>,
77
78    /// module map is used when importing JavaScript modules
79    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-module-map>
80    #[ignore_malloc_size_of = "mozjs"]
81    module_map: DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>>,
82}
83
84impl WorkletGlobalScope {
85    /// Create a new heap-allocated `WorkletGlobalScope`.
86    #[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    /// Create a new stack-allocated `WorkletGlobalScope`.
127    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    /// Register a paint worklet to the script thread.
187    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    /// The base URL of this global.
204    pub(crate) fn base_url(&self) -> ServoUrl {
205        self.base_url.clone()
206    }
207
208    /// The worklet executor.
209    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/// Resources required by workletglobalscopes
250#[derive(Clone)]
251pub(crate) struct WorkletGlobalScopeInit {
252    /// Channel to the main script thread
253    pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
254    /// Channel to a resource thread
255    pub(crate) resource_threads: ResourceThreads,
256    /// Channels to the [`StorageThreads`].
257    pub(crate) storage_threads: StorageThreads,
258    /// Channel to the memory profiler
259    pub(crate) mem_profiler_chan: mem::ProfilerChan,
260    /// Channel to the time profiler
261    pub(crate) time_profiler_chan: time::ProfilerChan,
262    /// Channel to devtools
263    #[cfg(feature = "devtools")]
264    pub(crate) devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
265    /// Messages to send to the Embedder
266    pub(crate) to_embedder_sender: ScriptToEmbedderChan,
267    /// The image cache
268    pub(crate) image_cache: Arc<dyn ImageCache>,
269    /// Identity manager for WebGPU resources
270    #[cfg(feature = "webgpu")]
271    pub(crate) gpu_id_hub: Arc<IdentityHub>,
272    pub(crate) script_to_constellation_sender: ScriptToConstellationSender,
273    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set>
274    pub(crate) inherited_upgrade_insecure_navigations_set: HashSet<UpgradeInsecureNavigations>,
275}
276
277/// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type>
278#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
279pub(crate) enum WorkletGlobalScopeType {
280    /// A servo-specific testing worklet
281    #[cfg(feature = "testbinding")]
282    Test,
283    /// A paint worklet
284    Paint,
285}