script_bindings/
callback.rs1use std::default::Default;
8use std::ffi::CStr;
9use std::rc::Rc;
10
11use js::context::JSContext;
12use js::jsapi::{Heap, IsCallable, JSObject, RemoveRawValueRoot};
13use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue};
14use js::rust::wrappers2::{AddRawValueRoot, EnterRealm, JS_GetProperty, JS_WrapObject, LeaveRealm};
15use js::rust::{HandleObject, MutableHandleValue, Runtime};
16
17use crate::codegen::GenericBindings::WindowBinding::Window_Binding::WindowMethods;
18use crate::error::{Error, Fallible};
19use crate::interfaces::{DocumentHelpers, DomHelpers, GlobalScopeHelpers};
20use crate::realms::enter_auto_realm;
21use crate::reflector::DomObject;
22use crate::root::Dom;
23use crate::settings_stack::{run_a_callback, run_a_script};
24use crate::{DomTypes, cformat};
25
26pub trait ThisReflector {
27 fn jsobject(&self) -> *mut JSObject;
28}
29
30pub trait OwnerWindow<D: DomTypes> {
36 fn owner_window(&self) -> Option<crate::root::DomRoot<D::Window>> {
37 None
38 }
39}
40
41impl<T: DomObject> ThisReflector for T {
42 fn jsobject(&self) -> *mut JSObject {
43 self.reflector().get_jsobject().get()
44 }
45}
46
47impl ThisReflector for HandleObject<'_> {
48 fn jsobject(&self) -> *mut JSObject {
49 self.get()
50 }
51}
52
53impl<D: DomTypes> OwnerWindow<D> for HandleObject<'_> {}
54
55#[derive(Clone, Copy, PartialEq)]
57pub enum ExceptionHandling {
58 Report,
60 Rethrow,
62}
63
64#[derive(JSTraceable)]
65pub struct RootedCallback<T>(Rc<T>);
66
67impl<T> RootedCallback<T> {
68 pub fn to_traced(&self) -> TracedCallback<T> {
69 TracedCallback(self.0.clone())
70 }
71}
72
73impl<T> Clone for RootedCallback<T> {
74 fn clone(&self) -> Self {
75 Self(self.0.clone())
76 }
77}
78
79impl<T> std::ops::Deref for RootedCallback<T> {
80 type Target = T;
81 fn deref(&self) -> &Self::Target {
82 &self.0
83 }
84}
85
86impl<T> From<Rc<T>> for RootedCallback<T> {
87 fn from(callback: Rc<T>) -> Self {
88 Self(callback)
89 }
90}
91
92impl<T: js::conversions::ToJSValConvertible> js::conversions::ToJSValConvertible
93 for RootedCallback<T>
94{
95 fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue<'_>) {
96 self.0.to_jsval(cx, rval)
97 }
98}
99
100#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
101#[derive(JSTraceable, MallocSizeOf)]
102pub struct TracedCallback<T>(#[conditional_malloc_size_of] Rc<T>);
103
104impl<T: crate::JSTraceable> js::gc::Rootable for TracedCallback<T> {}
105
106impl<T> Clone for TracedCallback<T> {
107 fn clone(&self) -> Self {
108 Self(self.0.clone())
109 }
110}
111
112impl<T> std::ops::Deref for TracedCallback<T> {
113 type Target = T;
114 fn deref(&self) -> &Self::Target {
115 &self.0
116 }
117}
118
119#[derive(JSTraceable, MallocSizeOf)]
122#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
123pub struct CallbackObject<D: DomTypes> {
124 #[ignore_malloc_size_of = "measured by mozjs"]
126 callback: Heap<*mut JSObject>,
127 #[ignore_malloc_size_of = "measured by mozjs"]
128 permanent_js_root: Heap<JSVal>,
129
130 incumbent: Option<Dom<D::GlobalScope>>,
142}
143
144impl<D: DomTypes> CallbackObject<D> {
145 #[allow(clippy::new_without_default)]
147 fn new() -> Self {
148 Self {
149 callback: Heap::default(),
150 permanent_js_root: Heap::default(),
151 incumbent: D::GlobalScope::incumbent().map(|i| Dom::from_ref(&*i)),
152 }
153 }
154
155 pub fn get(&self) -> *mut JSObject {
156 self.callback.get()
157 }
158
159 #[expect(unsafe_code)]
160 unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
161 self.callback.set(callback);
162 self.permanent_js_root.set(ObjectValue(callback));
163 unsafe {
164 assert!(AddRawValueRoot(
165 cx,
166 self.permanent_js_root.get_unsafe(),
167 c"CallbackObject::root".as_ptr()
168 ));
169 }
170 }
171}
172
173impl<D: DomTypes> Drop for CallbackObject<D> {
174 #[expect(unsafe_code)]
175 fn drop(&mut self) {
176 unsafe {
177 if let Some(cx) = Runtime::get() {
178 RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
179 }
180 }
181 }
182}
183
184impl<D: DomTypes> PartialEq for CallbackObject<D> {
185 fn eq(&self, other: &CallbackObject<D>) -> bool {
186 self.callback.get() == other.callback.get()
187 }
188}
189
190pub trait CallbackContainer<D: DomTypes> {
193 unsafe fn new(cx: &JSContext, callback: *mut JSObject) -> Rc<Self>;
198 fn callback_holder(&self) -> &CallbackObject<D>;
200 fn callback(&self) -> *mut JSObject {
202 self.callback_holder().get()
203 }
204 fn incumbent(&self) -> Option<&D::GlobalScope> {
209 self.callback_holder().incumbent.as_deref()
210 }
211}
212
213#[derive(JSTraceable, MallocSizeOf, PartialEq)]
215#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
216pub struct CallbackFunction<D: DomTypes> {
217 object: CallbackObject<D>,
218}
219
220impl<D: DomTypes> CallbackFunction<D> {
221 #[expect(clippy::new_without_default)]
224 pub fn new() -> Self {
225 Self {
226 object: CallbackObject::new(),
227 }
228 }
229
230 pub fn callback_holder(&self) -> &CallbackObject<D> {
232 &self.object
233 }
234
235 pub unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
241 unsafe { self.object.init(cx, callback) };
242 }
243}
244
245#[derive(JSTraceable, MallocSizeOf, PartialEq)]
247#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
248pub struct CallbackInterface<D: DomTypes> {
249 object: CallbackObject<D>,
250}
251
252impl<D: DomTypes> CallbackInterface<D> {
253 #[expect(clippy::new_without_default)]
256 pub fn new() -> Self {
257 Self {
258 object: CallbackObject::new(),
259 }
260 }
261
262 pub fn callback_holder(&self) -> &CallbackObject<D> {
264 &self.object
265 }
266
267 pub unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
273 unsafe { self.object.init(cx, callback) };
274 }
275
276 pub fn get_callable_property(&self, cx: &mut JSContext, name: &CStr) -> Fallible<JSVal> {
279 rooted!(&in(cx) let mut callable = UndefinedValue());
280 rooted!(&in(cx) let obj = self.callback_holder().get());
281 unsafe {
282 if !JS_GetProperty(cx, obj.handle(), name.as_ptr(), callable.handle_mut()) {
283 return Err(Error::JSFailed);
284 }
285
286 if !callable.is_object() || !IsCallable(callable.to_object()) {
287 return Err(Error::Type(cformat!(
288 "The value of the {} property is not callable",
289 name.to_string_lossy()
290 )));
291 }
292 }
293 Ok(callable.get())
294 }
295}
296
297pub(crate) fn wrap_call_this_value<T: ThisReflector>(
299 cx: &mut JSContext,
300 p: &T,
301 mut rval: MutableHandleValue,
302) -> bool {
303 rooted!(&in(cx) let mut obj = p.jsobject());
304
305 if obj.is_null() {
306 rval.set(NullValue());
307 return true;
308 }
309
310 unsafe {
311 if !JS_WrapObject(cx, obj.handle_mut()) {
312 return false;
313 }
314 }
315
316 rval.set(ObjectValue(*obj));
317 true
318}
319
320pub(crate) fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
324 cx: &mut JSContext,
325 callback: &T,
326 owner_window: Option<&D::Window>,
327 handling: ExceptionHandling,
328 f: impl FnOnce(&mut JSContext) -> R,
329) -> R {
330 if let Some(window) = owner_window {
331 window.Document().ensure_safe_to_run_script_or_layout();
332 }
333
334 let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
337 let global = &global;
338
339 run_a_script::<D, R, _>(cx, global, move |cx| {
341 let actual_callback = || {
342 let old_realm = unsafe { EnterRealm(cx, callback.callback()) };
343 let result = f(cx);
344 unsafe {
345 LeaveRealm(cx, old_realm);
346 }
347 if handling == ExceptionHandling::Report {
348 let mut realm = enter_auto_realm::<D>(cx, &**global);
349 let cx = &mut realm.current_realm();
350 <D as DomHelpers<D>>::report_pending_exception(cx);
351 }
352 result
353 };
354 if let Some(incumbent_global) = callback.incumbent() {
355 run_a_callback::<D, R>(incumbent_global, actual_callback)
357 } else {
358 actual_callback()
359 }
360 }) }