use std::default::Default;
use std::ffi::CStr;
use std::rc::Rc;
use js::jsapi::{AddRawValueRoot, Heap, IsCallable, JSObject, RemoveRawValueRoot};
use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue};
use js::rust::wrappers2::{EnterRealm, JS_GetProperty, JS_WrapObject, LeaveRealm};
use js::rust::{HandleObject, MutableHandleValue, Runtime};
use crate::codegen::GenericBindings::WindowBinding::Window_Binding::WindowMethods;
use crate::error::{Error, Fallible};
use crate::inheritance::Castable;
use crate::interfaces::{DocumentHelpers, DomHelpers, GlobalScopeHelpers};
use crate::realms::enter_auto_realm;
use crate::reflector::DomObject;
use crate::root::Dom;
use crate::script_runtime::JSContext;
use crate::settings_stack::{run_a_callback, run_a_script};
use crate::{DomTypes, cformat};
pub trait ThisReflector {
fn jsobject(&self) -> *mut JSObject;
}
impl<T: DomObject> ThisReflector for T {
fn jsobject(&self) -> *mut JSObject {
self.reflector().get_jsobject().get()
}
}
impl ThisReflector for HandleObject<'_> {
fn jsobject(&self) -> *mut JSObject {
self.get()
}
}
#[derive(Clone, Copy, PartialEq)]
pub enum ExceptionHandling {
Report,
Rethrow,
}
#[derive(JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub struct CallbackObject<D: DomTypes> {
#[ignore_malloc_size_of = "measured by mozjs"]
callback: Heap<*mut JSObject>,
#[ignore_malloc_size_of = "measured by mozjs"]
permanent_js_root: Heap<JSVal>,
incumbent: Option<Dom<D::GlobalScope>>,
}
impl<D: DomTypes> CallbackObject<D> {
#[allow(clippy::new_without_default)]
fn new() -> Self {
Self {
callback: Heap::default(),
permanent_js_root: Heap::default(),
incumbent: D::GlobalScope::incumbent().map(|i| Dom::from_ref(&*i)),
}
}
pub fn get(&self) -> *mut JSObject {
self.callback.get()
}
#[expect(unsafe_code)]
unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
self.callback.set(callback);
self.permanent_js_root.set(ObjectValue(callback));
unsafe {
assert!(AddRawValueRoot(
*cx,
self.permanent_js_root.get_unsafe(),
c"CallbackObject::root".as_ptr()
));
}
}
}
impl<D: DomTypes> Drop for CallbackObject<D> {
#[expect(unsafe_code)]
fn drop(&mut self) {
unsafe {
if let Some(cx) = Runtime::get() {
RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
}
}
}
}
impl<D: DomTypes> PartialEq for CallbackObject<D> {
fn eq(&self, other: &CallbackObject<D>) -> bool {
self.callback.get() == other.callback.get()
}
}
pub trait CallbackContainer<D: DomTypes> {
unsafe fn new(cx: JSContext, callback: *mut JSObject) -> Rc<Self>;
fn callback_holder(&self) -> &CallbackObject<D>;
fn callback(&self) -> *mut JSObject {
self.callback_holder().get()
}
fn incumbent(&self) -> Option<&D::GlobalScope> {
self.callback_holder().incumbent.as_deref()
}
}
#[derive(JSTraceable, MallocSizeOf, PartialEq)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub struct CallbackFunction<D: DomTypes> {
object: CallbackObject<D>,
}
impl<D: DomTypes> CallbackFunction<D> {
#[expect(clippy::new_without_default)]
pub fn new() -> Self {
Self {
object: CallbackObject::new(),
}
}
pub fn callback_holder(&self) -> &CallbackObject<D> {
&self.object
}
pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
unsafe { self.object.init(cx, callback) };
}
}
#[derive(JSTraceable, MallocSizeOf, PartialEq)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub struct CallbackInterface<D: DomTypes> {
object: CallbackObject<D>,
}
impl<D: DomTypes> CallbackInterface<D> {
#[expect(clippy::new_without_default)]
pub fn new() -> Self {
Self {
object: CallbackObject::new(),
}
}
pub fn callback_holder(&self) -> &CallbackObject<D> {
&self.object
}
pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
unsafe { self.object.init(cx, callback) };
}
pub fn get_callable_property(
&self,
cx: &mut js::context::JSContext,
name: &CStr,
) -> Fallible<JSVal> {
rooted!(&in(cx) let mut callable = UndefinedValue());
rooted!(&in(cx) let obj = self.callback_holder().get());
unsafe {
if !JS_GetProperty(cx, obj.handle(), name.as_ptr(), callable.handle_mut()) {
return Err(Error::JSFailed);
}
if !callable.is_object() || !IsCallable(callable.to_object()) {
return Err(Error::Type(cformat!(
"The value of the {} property is not callable",
name.to_string_lossy()
)));
}
}
Ok(callable.get())
}
}
pub(crate) fn wrap_call_this_value<T: ThisReflector>(
cx: &mut js::context::JSContext,
p: &T,
mut rval: MutableHandleValue,
) -> bool {
rooted!(&in(cx) let mut obj = p.jsobject());
if obj.is_null() {
rval.set(NullValue());
return true;
}
unsafe {
if !JS_WrapObject(cx, obj.handle_mut()) {
return false;
}
}
rval.set(ObjectValue(*obj));
true
}
pub fn call_setup<D: DomTypes, T: CallbackContainer<D>, R>(
cx: &mut js::context::JSContext,
callback: &T,
handling: ExceptionHandling,
f: impl FnOnce(&mut js::context::JSContext) -> R,
) -> R {
let global = unsafe { D::GlobalScope::from_object(callback.callback()) };
if let Some(window) = global.downcast::<D::Window>() {
window.Document().ensure_safe_to_run_script_or_layout();
}
let global = &global;
run_a_script::<D, R>(global, move || {
let actual_callback = || {
let old_realm = unsafe { EnterRealm(cx, callback.callback()) };
let result = f(cx);
unsafe {
LeaveRealm(cx, old_realm);
}
if handling == ExceptionHandling::Report {
let mut realm = enter_auto_realm::<D>(cx, &**global);
let cx = &mut realm.current_realm();
<D as DomHelpers<D>>::report_pending_exception(cx);
}
result
};
if let Some(incumbent_global) = callback.incumbent() {
run_a_callback::<D, R>(incumbent_global, actual_callback)
} else {
actual_callback()
}
}) }