script_bindings/
callback.rs1use std::default::Default;
8use std::ffi::CStr;
9use std::rc::Rc;
10
11use js::jsapi::{AddRawValueRoot, Heap, IsCallable, JSObject, RemoveRawValueRoot};
12use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue};
13use js::rust::wrappers2::{EnterRealm, JS_GetProperty, JS_WrapObject, LeaveRealm};
14use js::rust::{HandleObject, MutableHandleValue, Runtime};
15
16use crate::codegen::GenericBindings::WindowBinding::Window_Binding::WindowMethods;
17use crate::error::{Error, Fallible};
18use crate::inheritance::Castable;
19use crate::interfaces::{DocumentHelpers, DomHelpers, GlobalScopeHelpers};
20use crate::realms::{InRealm, enter_auto_realm};
21use crate::reflector::DomObject;
22use crate::root::Dom;
23use crate::script_runtime::{CanGc, JSContext};
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(
212 &self,
213 cx: &mut js::context::JSContext,
214 name: &CStr,
215 ) -> Fallible<JSVal> {
216 rooted!(&in(cx) let mut callable = UndefinedValue());
217 rooted!(&in(cx) let obj = self.callback_holder().get());
218 unsafe {
219 if !JS_GetProperty(cx, obj.handle(), name.as_ptr(), callable.handle_mut()) {
220 return Err(Error::JSFailed);
221 }
222
223 if !callable.is_object() || !IsCallable(callable.to_object()) {
224 return Err(Error::Type(cformat!(
225 "The value of the {} property is not callable",
226 name.to_string_lossy()
227 )));
228 }
229 }
230 Ok(callable.get())
231 }
232}
233
234pub(crate) fn wrap_call_this_value<T: ThisReflector>(
236 cx: &mut js::context::JSContext,
237 p: &T,
238 mut rval: MutableHandleValue,
239) -> bool {
240 rooted!(&in(cx) let mut obj = p.jsobject());
241
242 if obj.is_null() {
243 rval.set(NullValue());
244 return true;
245 }
246
247 unsafe {
248 if !JS_WrapObject(cx, obj.handle_mut()) {
249 return false;
250 }
251 }
252
253 rval.set(ObjectValue(*obj));
254 true
255}
256
257pub fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
261 cx: &mut js::context::JSContext,
262 callback: &T,
263 handling: ExceptionHandling,
264 f: impl FnOnce(&mut js::context::JSContext) -> R,
265) -> R {
266 let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
269 if let Some(window) = global.downcast::<D::Window>() {
270 window.Document().ensure_safe_to_run_script_or_layout();
271 }
272
273 let global = &global;
274
275 run_a_script::<D, R>(global, move || {
277 let actual_callback = || {
278 let old_realm = unsafe { EnterRealm(cx, callback.callback()) };
279 let result = f(cx);
280 unsafe {
281 LeaveRealm(cx, old_realm);
282 }
283 if handling == ExceptionHandling::Report {
284 let mut realm = enter_auto_realm::<D>(cx, &**global);
285 let cx = &mut realm.current_realm();
286
287 let in_realm_proof = cx.into();
288 let in_realm = InRealm::Already(&in_realm_proof);
289
290 <D as DomHelpers<D>>::report_pending_exception(
291 cx.into(),
292 in_realm,
293 CanGc::from_cx(cx),
294 );
295 }
296 result
297 };
298 if let Some(incumbent_global) = callback.incumbent() {
299 run_a_callback::<D, R>(incumbent_global, actual_callback)
301 } else {
302 actual_callback()
303 }
304 }) }