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::sync::Arc;
6
7use base::generic_channel::GenericSender;
8use base::id::PipelineId;
9use constellation_traits::{ScriptToConstellationChan, ScriptToConstellationMessage};
10use crossbeam_channel::Sender;
11use devtools_traits::ScriptToDevtoolsControlMsg;
12use dom_struct::dom_struct;
13use embedder_traits::{JavaScriptEvaluationError, ScriptToEmbedderChan};
14use ipc_channel::ipc::IpcSender;
15use js::jsval::UndefinedValue;
16use net_traits::ResourceThreads;
17use net_traits::image_cache::ImageCache;
18use profile_traits::{mem, time};
19use script_bindings::realms::InRealm;
20use script_traits::Painter;
21use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
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_realm;
37use crate::script_module::ScriptFetchOptions;
38use crate::script_runtime::{CanGc, IntroductionType, JSContext};
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    /// Create a new heap-allocated `WorkletGlobalScope`.
56    pub(crate) fn new(
57        scope_type: WorkletGlobalScopeType,
58        pipeline_id: PipelineId,
59        base_url: ServoUrl,
60        executor: WorkletExecutor,
61        init: &WorkletGlobalScopeInit,
62    ) -> DomRoot<WorkletGlobalScope> {
63        let scope: DomRoot<WorkletGlobalScope> = match scope_type {
64            #[cfg(feature = "testbinding")]
65            WorkletGlobalScopeType::Test => DomRoot::upcast(TestWorkletGlobalScope::new(
66                pipeline_id,
67                base_url,
68                executor,
69                init,
70            )),
71            WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new(
72                pipeline_id,
73                base_url,
74                executor,
75                init,
76            )),
77        };
78
79        let realm = enter_realm(&*scope);
80        define_all_exposed_interfaces(scope.upcast(), InRealm::entered(&realm), CanGc::note());
81
82        scope
83    }
84
85    /// Create a new stack-allocated `WorkletGlobalScope`.
86    pub(crate) fn new_inherited(
87        pipeline_id: PipelineId,
88        base_url: ServoUrl,
89        executor: WorkletExecutor,
90        init: &WorkletGlobalScopeInit,
91    ) -> Self {
92        let script_to_constellation_chan = ScriptToConstellationChan {
93            sender: init.to_constellation_sender.clone(),
94            pipeline_id,
95        };
96        Self {
97            globalscope: GlobalScope::new_inherited(
98                pipeline_id,
99                init.devtools_chan.clone(),
100                init.mem_profiler_chan.clone(),
101                init.time_profiler_chan.clone(),
102                script_to_constellation_chan,
103                init.to_embedder_sender.clone(),
104                init.resource_threads.clone(),
105                MutableOrigin::new(ImmutableOrigin::new_opaque()),
106                base_url.clone(),
107                None,
108                Default::default(),
109                #[cfg(feature = "webgpu")]
110                init.gpu_id_hub.clone(),
111                init.inherited_secure_context,
112                false,
113                None, // font_context
114            ),
115            base_url,
116            to_script_thread_sender: init.to_script_thread_sender.clone(),
117            executor,
118        }
119    }
120
121    /// Get the JS context.
122    pub(crate) fn get_cx() -> JSContext {
123        GlobalScope::get_cx()
124    }
125
126    /// Evaluate a JS script in this global.
127    pub(crate) fn evaluate_js(
128        &self,
129        script: &str,
130        can_gc: CanGc,
131    ) -> Result<(), JavaScriptEvaluationError> {
132        debug!("Evaluating Dom in a worklet.");
133        rooted!(in (*GlobalScope::get_cx()) let mut rval = UndefinedValue());
134        self.globalscope.evaluate_js_on_global_with_result(
135            script,
136            rval.handle_mut(),
137            ScriptFetchOptions::default_classic_script(&self.globalscope),
138            self.globalscope.api_base_url(),
139            can_gc,
140            Some(IntroductionType::WORKLET),
141        )
142    }
143
144    /// Register a paint worklet to the script thread.
145    pub(crate) fn register_paint_worklet(
146        &self,
147        name: Atom,
148        properties: Vec<Atom>,
149        painter: Box<dyn Painter>,
150    ) {
151        self.to_script_thread_sender
152            .send(MainThreadScriptMsg::RegisterPaintWorklet {
153                pipeline_id: self.globalscope.pipeline_id(),
154                name,
155                properties,
156                painter,
157            })
158            .expect("Worklet thread outlived script thread.");
159    }
160
161    /// The base URL of this global.
162    pub(crate) fn base_url(&self) -> ServoUrl {
163        self.base_url.clone()
164    }
165
166    /// The worklet executor.
167    pub(crate) fn executor(&self) -> WorkletExecutor {
168        self.executor.clone()
169    }
170
171    /// Perform a worklet task
172    pub(crate) fn perform_a_worklet_task(&self, task: WorkletTask) {
173        match task {
174            #[cfg(feature = "testbinding")]
175            WorkletTask::Test(task) => match self.downcast::<TestWorkletGlobalScope>() {
176                Some(global) => global.perform_a_worklet_task(task),
177                None => warn!("This is not a test worklet."),
178            },
179            WorkletTask::Paint(task) => match self.downcast::<PaintWorkletGlobalScope>() {
180                Some(global) => global.perform_a_worklet_task(task),
181                None => warn!("This is not a paint worklet."),
182            },
183        }
184    }
185}
186
187/// Resources required by workletglobalscopes
188#[derive(Clone)]
189pub(crate) struct WorkletGlobalScopeInit {
190    /// Channel to the main script thread
191    pub(crate) to_script_thread_sender: Sender<MainThreadScriptMsg>,
192    /// Channel to a resource thread
193    pub(crate) resource_threads: ResourceThreads,
194    /// Channel to the memory profiler
195    pub(crate) mem_profiler_chan: mem::ProfilerChan,
196    /// Channel to the time profiler
197    pub(crate) time_profiler_chan: time::ProfilerChan,
198    /// Channel to devtools
199    pub(crate) devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
200    /// Messages to send to constellation
201    pub(crate) to_constellation_sender: GenericSender<(PipelineId, ScriptToConstellationMessage)>,
202    /// Messages to send to the Embedder
203    pub(crate) to_embedder_sender: ScriptToEmbedderChan,
204    /// The image cache
205    pub(crate) image_cache: Arc<dyn ImageCache>,
206    /// Identity manager for WebGPU resources
207    #[cfg(feature = "webgpu")]
208    pub(crate) gpu_id_hub: Arc<IdentityHub>,
209    /// Is considered secure
210    pub(crate) inherited_secure_context: Option<bool>,
211}
212
213/// <https://drafts.css-houdini.org/worklets/#worklet-global-scope-type>
214#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
215pub(crate) enum WorkletGlobalScopeType {
216    /// A servo-specific testing worklet
217    #[cfg(feature = "testbinding")]
218    Test,
219    /// A paint worklet
220    Paint,
221}
222
223/// A task which can be performed in the context of a worklet global.
224pub(crate) enum WorkletTask {
225    #[cfg(feature = "testbinding")]
226    Test(TestWorkletTask),
227    Paint(PaintWorkletTask),
228}