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, MallocSizeOf)]
67#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
68pub struct CallbackObject<D: DomTypes> {
69 #[ignore_malloc_size_of = "measured by mozjs"]
71 callback: Heap<*mut JSObject>,
72 #[ignore_malloc_size_of = "measured by mozjs"]
73 permanent_js_root: Heap<JSVal>,
74
75 incumbent: Option<Dom<D::GlobalScope>>,
87}
88
89impl<D: DomTypes> CallbackObject<D> {
90 #[allow(clippy::new_without_default)]
92 fn new() -> Self {
93 Self {
94 callback: Heap::default(),
95 permanent_js_root: Heap::default(),
96 incumbent: D::GlobalScope::incumbent().map(|i| Dom::from_ref(&*i)),
97 }
98 }
99
100 pub fn get(&self) -> *mut JSObject {
101 self.callback.get()
102 }
103
104 #[expect(unsafe_code)]
105 unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
106 self.callback.set(callback);
107 self.permanent_js_root.set(ObjectValue(callback));
108 unsafe {
109 assert!(AddRawValueRoot(
110 cx,
111 self.permanent_js_root.get_unsafe(),
112 c"CallbackObject::root".as_ptr()
113 ));
114 }
115 }
116}
117
118impl<D: DomTypes> Drop for CallbackObject<D> {
119 #[expect(unsafe_code)]
120 fn drop(&mut self) {
121 unsafe {
122 if let Some(cx) = Runtime::get() {
123 RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
124 }
125 }
126 }
127}
128
129impl<D: DomTypes> PartialEq for CallbackObject<D> {
130 fn eq(&self, other: &CallbackObject<D>) -> bool {
131 self.callback.get() == other.callback.get()
132 }
133}
134
135pub trait CallbackContainer<D: DomTypes> {
138 unsafe fn new(cx: &JSContext, callback: *mut JSObject) -> Rc<Self>;
143 fn callback_holder(&self) -> &CallbackObject<D>;
145 fn callback(&self) -> *mut JSObject {
147 self.callback_holder().get()
148 }
149 fn incumbent(&self) -> Option<&D::GlobalScope> {
154 self.callback_holder().incumbent.as_deref()
155 }
156}
157
158#[derive(JSTraceable, MallocSizeOf, PartialEq)]
160#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
161pub struct CallbackFunction<D: DomTypes> {
162 object: CallbackObject<D>,
163}
164
165impl<D: DomTypes> CallbackFunction<D> {
166 #[expect(clippy::new_without_default)]
169 pub fn new() -> Self {
170 Self {
171 object: CallbackObject::new(),
172 }
173 }
174
175 pub fn callback_holder(&self) -> &CallbackObject<D> {
177 &self.object
178 }
179
180 pub unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
186 unsafe { self.object.init(cx, callback) };
187 }
188}
189
190#[derive(JSTraceable, MallocSizeOf, PartialEq)]
192#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
193pub struct CallbackInterface<D: DomTypes> {
194 object: CallbackObject<D>,
195}
196
197impl<D: DomTypes> CallbackInterface<D> {
198 #[expect(clippy::new_without_default)]
201 pub fn new() -> Self {
202 Self {
203 object: CallbackObject::new(),
204 }
205 }
206
207 pub fn callback_holder(&self) -> &CallbackObject<D> {
209 &self.object
210 }
211
212 pub unsafe fn init(&mut self, cx: &JSContext, callback: *mut JSObject) {
218 unsafe { self.object.init(cx, callback) };
219 }
220
221 pub fn get_callable_property(&self, cx: &mut JSContext, name: &CStr) -> Fallible<JSVal> {
224 rooted!(&in(cx) let mut callable = UndefinedValue());
225 rooted!(&in(cx) let obj = self.callback_holder().get());
226 unsafe {
227 if !JS_GetProperty(cx, obj.handle(), name.as_ptr(), callable.handle_mut()) {
228 return Err(Error::JSFailed);
229 }
230
231 if !callable.is_object() || !IsCallable(callable.to_object()) {
232 return Err(Error::Type(cformat!(
233 "The value of the {} property is not callable",
234 name.to_string_lossy()
235 )));
236 }
237 }
238 Ok(callable.get())
239 }
240}
241
242pub(crate) fn wrap_call_this_value<T: ThisReflector>(
244 cx: &mut JSContext,
245 p: &T,
246 mut rval: MutableHandleValue,
247) -> bool {
248 rooted!(&in(cx) let mut obj = p.jsobject());
249
250 if obj.is_null() {
251 rval.set(NullValue());
252 return true;
253 }
254
255 unsafe {
256 if !JS_WrapObject(cx, obj.handle_mut()) {
257 return false;
258 }
259 }
260
261 rval.set(ObjectValue(*obj));
262 true
263}
264
265pub(crate) fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
269 cx: &mut JSContext,
270 callback: &T,
271 owner_window: Option<&D::Window>,
272 handling: ExceptionHandling,
273 f: impl FnOnce(&mut JSContext) -> R,
274) -> R {
275 if let Some(window) = owner_window {
276 window.Document().ensure_safe_to_run_script_or_layout();
277 }
278
279 let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
282 let global = &global;
283
284 run_a_script::<D, R, _>(cx, global, move |cx| {
286 let actual_callback = || {
287 let old_realm = unsafe { EnterRealm(cx, callback.callback()) };
288 let result = f(cx);
289 unsafe {
290 LeaveRealm(cx, old_realm);
291 }
292 if handling == ExceptionHandling::Report {
293 let mut realm = enter_auto_realm::<D>(cx, &**global);
294 let cx = &mut realm.current_realm();
295 <D as DomHelpers<D>>::report_pending_exception(cx);
296 }
297 result
298 };
299 if let Some(incumbent_global) = callback.incumbent() {
300 run_a_callback::<D, R>(incumbent_global, actual_callback)
302 } else {
303 actual_callback()
304 }
305 }) }