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::inheritance::Castable;
20use crate::interfaces::{DocumentHelpers, DomHelpers, GlobalScopeHelpers};
21use crate::realms::enter_auto_realm;
22use crate::reflector::DomObject;
23use crate::root::Dom;
24use crate::settings_stack::{run_a_callback, run_a_script};
25use crate::{DomTypes, cformat};
26
27pub trait ThisReflector {
28 fn jsobject(&self) -> *mut JSObject;
29}
30
31impl<T: DomObject> ThisReflector for T {
32 fn jsobject(&self) -> *mut JSObject {
33 self.reflector().get_jsobject().get()
34 }
35}
36
37impl ThisReflector for HandleObject<'_> {
38 fn jsobject(&self) -> *mut JSObject {
39 self.get()
40 }
41}
42
43#[derive(Clone, Copy, PartialEq)]
45pub enum ExceptionHandling {
46 Report,
48 Rethrow,
50}
51
52#[derive(JSTraceable, MallocSizeOf)]
55#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
56pub struct CallbackObject<D: DomTypes> {
57 #[ignore_malloc_size_of = "measured by mozjs"]
59 callback: Heap<*mut JSObject>,
60 #[ignore_malloc_size_of = "measured by mozjs"]
61 permanent_js_root: Heap<JSVal>,
62
63 incumbent: Option<Dom<D::GlobalScope>>,
75}
76
77impl<D: DomTypes> CallbackObject<D> {
78 #[allow(clippy::new_without_default)]
80 fn new() -> Self {
81 Self {
82 callback: Heap::default(),
83 permanent_js_root: Heap::default(),
84 incumbent: D::GlobalScope::incumbent().map(|i| Dom::from_ref(&*i)),
85 }
86 }
87
88 pub fn get(&self) -> *mut JSObject {
89 self.callback.get()
90 }
91
92 #[expect(unsafe_code)]
93 unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
94 self.callback.set(callback);
95 self.permanent_js_root.set(ObjectValue(callback));
96 unsafe {
97 assert!(AddRawValueRoot(
98 cx,
99 self.permanent_js_root.get_unsafe(),
100 c"CallbackObject::root".as_ptr()
101 ));
102 }
103 }
104}
105
106impl<D: DomTypes> Drop for CallbackObject<D> {
107 #[expect(unsafe_code)]
108 fn drop(&mut self) {
109 unsafe {
110 if let Some(cx) = Runtime::get() {
111 RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
112 }
113 }
114 }
115}
116
117impl<D: DomTypes> PartialEq for CallbackObject<D> {
118 fn eq(&self, other: &CallbackObject<D>) -> bool {
119 self.callback.get() == other.callback.get()
120 }
121}
122
123pub trait CallbackContainer<D: DomTypes> {
126 unsafe fn new(cx: &JSContext, callback: *mut JSObject) -> Rc<Self>;
131 fn callback_holder(&self) -> &CallbackObject<D>;
133 fn callback(&self) -> *mut JSObject {
135 self.callback_holder().get()
136 }
137 fn incumbent(&self) -> Option<&D::GlobalScope> {
142 self.callback_holder().incumbent.as_deref()
143 }
144}
145
146#[derive(JSTraceable, MallocSizeOf, PartialEq)]
148#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
149pub struct CallbackFunction<D: DomTypes> {
150 object: CallbackObject<D>,
151}
152
153impl<D: DomTypes> CallbackFunction<D> {
154 #[expect(clippy::new_without_default)]
157 pub fn new() -> Self {
158 Self {
159 object: CallbackObject::new(),
160 }
161 }
162
163 pub fn callback_holder(&self) -> &CallbackObject<D> {
165 &self.object
166 }
167
168 pub unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
174 unsafe { self.object.init(cx, callback) };
175 }
176}
177
178#[derive(JSTraceable, MallocSizeOf, PartialEq)]
180#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
181pub struct CallbackInterface<D: DomTypes> {
182 object: CallbackObject<D>,
183}
184
185impl<D: DomTypes> CallbackInterface<D> {
186 #[expect(clippy::new_without_default)]
189 pub fn new() -> Self {
190 Self {
191 object: CallbackObject::new(),
192 }
193 }
194
195 pub fn callback_holder(&self) -> &CallbackObject<D> {
197 &self.object
198 }
199
200 pub unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
206 unsafe { self.object.init(cx, callback) };
207 }
208
209 pub fn get_callable_property(&self, cx: &mut JSContext, name: &CStr) -> Fallible<JSVal> {
212 rooted!(&in(cx) let mut callable = UndefinedValue());
213 rooted!(&in(cx) let obj = self.callback_holder().get());
214 unsafe {
215 if !JS_GetProperty(cx, obj.handle(), name.as_ptr(), callable.handle_mut()) {
216 return Err(Error::JSFailed);
217 }
218
219 if !callable.is_object() || !IsCallable(callable.to_object()) {
220 return Err(Error::Type(cformat!(
221 "The value of the {} property is not callable",
222 name.to_string_lossy()
223 )));
224 }
225 }
226 Ok(callable.get())
227 }
228}
229
230pub(crate) fn wrap_call_this_value<T: ThisReflector>(
232 cx: &mut JSContext,
233 p: &T,
234 mut rval: MutableHandleValue,
235) -> bool {
236 rooted!(&in(cx) let mut obj = p.jsobject());
237
238 if obj.is_null() {
239 rval.set(NullValue());
240 return true;
241 }
242
243 unsafe {
244 if !JS_WrapObject(cx, obj.handle_mut()) {
245 return false;
246 }
247 }
248
249 rval.set(ObjectValue(*obj));
250 true
251}
252
253pub fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
257 cx: &mut JSContext,
258 callback: &T,
259 handling: ExceptionHandling,
260 f: impl FnOnce(&mut JSContext) -> R,
261) -> R {
262 let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
265 if let Some(window) = global.downcast::<D::Window>() {
266 window.Document().ensure_safe_to_run_script_or_layout();
267 }
268
269 let global = &global;
270
271 run_a_script::<D, R, _>(cx, global, move |cx| {
273 let actual_callback = || {
274 let old_realm = unsafe { EnterRealm(cx, callback.callback()) };
275 let result = f(cx);
276 unsafe {
277 LeaveRealm(cx, old_realm);
278 }
279 if handling == ExceptionHandling::Report {
280 let mut realm = enter_auto_realm::<D>(cx, &**global);
281 let cx = &mut realm.current_realm();
282 <D as DomHelpers<D>>::report_pending_exception(cx);
283 }
284 result
285 };
286 if let Some(incumbent_global) = callback.incumbent() {
287 run_a_callback::<D, R>(incumbent_global, actual_callback)
289 } else {
290 actual_callback()
291 }
292 }) }