script_bindings/
callback.rs1use std::default::Default;
8use std::ffi::CString;
9use std::rc::Rc;
10
11use js::jsapi::{
12 AddRawValueRoot, EnterRealm, Heap, IsCallable, JSObject, LeaveRealm, RemoveRawValueRoot,
13};
14use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue};
15use js::rust::wrappers::{JS_GetProperty, JS_WrapObject};
16use js::rust::{HandleObject, MutableHandleValue, Runtime};
17
18use crate::codegen::GenericBindings::WindowBinding::Window_Binding::WindowMethods;
19use crate::error::{Error, Fallible};
20use crate::inheritance::Castable;
21use crate::interfaces::{DocumentHelpers, DomHelpers, GlobalScopeHelpers};
22use crate::realms::{InRealm, enter_realm};
23use crate::reflector::DomObject;
24use crate::root::Dom;
25use crate::script_runtime::{CanGc, JSContext};
26use crate::settings_stack::{run_a_callback, run_a_script};
27use crate::{DomTypes, cformat};
28
29pub trait ThisReflector {
30 fn jsobject(&self) -> *mut JSObject;
31}
32
33impl<T: DomObject> ThisReflector for T {
34 fn jsobject(&self) -> *mut JSObject {
35 self.reflector().get_jsobject().get()
36 }
37}
38
39impl ThisReflector for HandleObject<'_> {
40 fn jsobject(&self) -> *mut JSObject {
41 self.get()
42 }
43}
44
45#[derive(Clone, Copy, PartialEq)]
47pub enum ExceptionHandling {
48 Report,
50 Rethrow,
52}
53
54#[derive(JSTraceable, MallocSizeOf)]
57#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
58pub struct CallbackObject<D: DomTypes> {
59 #[ignore_malloc_size_of = "measured by mozjs"]
61 callback: Heap<*mut JSObject>,
62 #[ignore_malloc_size_of = "measured by mozjs"]
63 permanent_js_root: Heap<JSVal>,
64
65 incumbent: Option<Dom<D::GlobalScope>>,
77}
78
79impl<D: DomTypes> CallbackObject<D> {
80 #[allow(clippy::new_without_default)]
82 fn new() -> Self {
83 Self {
84 callback: Heap::default(),
85 permanent_js_root: Heap::default(),
86 incumbent: D::GlobalScope::incumbent().map(|i| Dom::from_ref(&*i)),
87 }
88 }
89
90 pub fn get(&self) -> *mut JSObject {
91 self.callback.get()
92 }
93
94 #[expect(unsafe_code)]
95 unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
96 self.callback.set(callback);
97 self.permanent_js_root.set(ObjectValue(callback));
98 unsafe {
99 assert!(AddRawValueRoot(
100 *cx,
101 self.permanent_js_root.get_unsafe(),
102 c"CallbackObject::root".as_ptr()
103 ));
104 }
105 }
106}
107
108impl<D: DomTypes> Drop for CallbackObject<D> {
109 #[expect(unsafe_code)]
110 fn drop(&mut self) {
111 unsafe {
112 if let Some(cx) = Runtime::get() {
113 RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
114 }
115 }
116 }
117}
118
119impl<D: DomTypes> PartialEq for CallbackObject<D> {
120 fn eq(&self, other: &CallbackObject<D>) -> bool {
121 self.callback.get() == other.callback.get()
122 }
123}
124
125pub trait CallbackContainer<D: DomTypes> {
128 unsafe fn new(cx: JSContext, callback: *mut JSObject) -> Rc<Self>;
133 fn callback_holder(&self) -> &CallbackObject<D>;
135 fn callback(&self) -> *mut JSObject {
137 self.callback_holder().get()
138 }
139 fn incumbent(&self) -> Option<&D::GlobalScope> {
144 self.callback_holder().incumbent.as_deref()
145 }
146}
147
148#[derive(JSTraceable, MallocSizeOf, PartialEq)]
150#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
151pub struct CallbackFunction<D: DomTypes> {
152 object: CallbackObject<D>,
153}
154
155impl<D: DomTypes> CallbackFunction<D> {
156 #[expect(clippy::new_without_default)]
159 pub fn new() -> Self {
160 Self {
161 object: CallbackObject::new(),
162 }
163 }
164
165 pub fn callback_holder(&self) -> &CallbackObject<D> {
167 &self.object
168 }
169
170 pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
176 unsafe { self.object.init(cx, callback) };
177 }
178}
179
180#[derive(JSTraceable, MallocSizeOf, PartialEq)]
182#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
183pub struct CallbackInterface<D: DomTypes> {
184 object: CallbackObject<D>,
185}
186
187impl<D: DomTypes> CallbackInterface<D> {
188 #[expect(clippy::new_without_default)]
191 pub fn new() -> Self {
192 Self {
193 object: CallbackObject::new(),
194 }
195 }
196
197 pub fn callback_holder(&self) -> &CallbackObject<D> {
199 &self.object
200 }
201
202 pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
208 unsafe { self.object.init(cx, callback) };
209 }
210
211 pub fn get_callable_property(&self, cx: JSContext, name: &str) -> Fallible<JSVal> {
214 rooted!(in(*cx) let mut callable = UndefinedValue());
215 rooted!(in(*cx) let obj = self.callback_holder().get());
216 unsafe {
217 let c_name = CString::new(name).unwrap();
218 if !JS_GetProperty(*cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) {
219 return Err(Error::JSFailed);
220 }
221
222 if !callable.is_object() || !IsCallable(callable.to_object()) {
223 return Err(Error::Type(cformat!(
224 "The value of the {} property is not callable",
225 name
226 )));
227 }
228 }
229 Ok(callable.get())
230 }
231}
232
233pub(crate) fn wrap_call_this_value<T: ThisReflector>(
235 cx: JSContext,
236 p: &T,
237 mut rval: MutableHandleValue,
238) -> bool {
239 rooted!(in(*cx) let mut obj = p.jsobject());
240
241 if obj.is_null() {
242 rval.set(NullValue());
243 return true;
244 }
245
246 unsafe {
247 if !JS_WrapObject(*cx, obj.handle_mut()) {
248 return false;
249 }
250 }
251
252 rval.set(ObjectValue(*obj));
253 true
254}
255
256pub fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
260 callback: &T,
261 handling: ExceptionHandling,
262 f: impl FnOnce(JSContext) -> R,
263) -> R {
264 let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
267 if let Some(window) = global.downcast::<D::Window>() {
268 window.Document().ensure_safe_to_run_script_or_layout();
269 }
270 let cx = D::GlobalScope::get_cx();
271
272 let global = &global;
273
274 run_a_script::<D, R>(global, move || {
276 let actual_callback = || {
277 let old_realm = unsafe { EnterRealm(*cx, callback.callback()) };
278 let result = f(cx);
279 unsafe {
280 LeaveRealm(*cx, old_realm);
281 }
282 if handling == ExceptionHandling::Report {
283 let ar = enter_realm::<D>(&**global);
284 <D as DomHelpers<D>>::report_pending_exception(
285 cx,
286 InRealm::Entered(&ar),
287 CanGc::note(),
288 );
289 }
290 result
291 };
292 if let Some(incumbent_global) = callback.incumbent() {
293 run_a_callback::<D, R>(incumbent_global, actual_callback)
295 } else {
296 actual_callback()
297 }
298 }) }