script_bindings/
callback.rs1use std::default::Default;
8use std::ffi::CStr;
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: &CStr) -> Fallible<JSVal> {
214 rooted!(in(*cx) let mut callable = UndefinedValue());
215 rooted!(in(*cx) let obj = self.callback_holder().get());
216 unsafe {
217 if !JS_GetProperty(*cx, obj.handle(), name.as_ptr(), callable.handle_mut()) {
218 return Err(Error::JSFailed);
219 }
220
221 if !callable.is_object() || !IsCallable(callable.to_object()) {
222 return Err(Error::Type(cformat!(
223 "The value of the {} property is not callable",
224 name.to_string_lossy()
225 )));
226 }
227 }
228 Ok(callable.get())
229 }
230}
231
232pub(crate) fn wrap_call_this_value<T: ThisReflector>(
234 cx: JSContext,
235 p: &T,
236 mut rval: MutableHandleValue,
237) -> bool {
238 rooted!(in(*cx) let mut obj = p.jsobject());
239
240 if obj.is_null() {
241 rval.set(NullValue());
242 return true;
243 }
244
245 unsafe {
246 if !JS_WrapObject(*cx, obj.handle_mut()) {
247 return false;
248 }
249 }
250
251 rval.set(ObjectValue(*obj));
252 true
253}
254
255pub fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
259 callback: &T,
260 handling: ExceptionHandling,
261 f: impl FnOnce(JSContext) -> R,
262) -> R {
263 let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
266 if let Some(window) = global.downcast::<D::Window>() {
267 window.Document().ensure_safe_to_run_script_or_layout();
268 }
269 let cx = D::GlobalScope::get_cx();
270
271 let global = &global;
272
273 run_a_script::<D, R>(global, move || {
275 let actual_callback = || {
276 let old_realm = unsafe { EnterRealm(*cx, callback.callback()) };
277 let result = f(cx);
278 unsafe {
279 LeaveRealm(*cx, old_realm);
280 }
281 if handling == ExceptionHandling::Report {
282 let ar = enter_realm::<D>(&**global);
283 <D as DomHelpers<D>>::report_pending_exception(
284 cx,
285 InRealm::Entered(&ar),
286 CanGc::deprecated_note(),
287 );
288 }
289 result
290 };
291 if let Some(incumbent_global) = callback.incumbent() {
292 run_a_callback::<D, R>(incumbent_global, actual_callback)
294 } else {
295 actual_callback()
296 }
297 }) }