use std::default::Default;
use std::ffi::CString;
use std::mem::drop;
use std::rc::Rc;
use js::jsapi::{
AddRawValueRoot, EnterRealm, Heap, IsCallable, JSObject, LeaveRealm, Realm, RemoveRawValueRoot,
};
use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue};
use js::rust::wrappers::{JS_GetProperty, JS_WrapObject};
use js::rust::{HandleObject, MutableHandleValue, Runtime};
use crate::DomTypes;
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::{InRealm, enter_realm};
use crate::reflector::DomObject;
use crate::root::{Dom, DomRoot};
use crate::script_runtime::{CanGc, JSContext};
use crate::settings_stack::{GenericAutoEntryScript, GenericAutoIncumbentScript};
use crate::utils::AsCCharPtrPtr;
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)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub struct CallbackObject<D: DomTypes> {
callback: Heap<*mut JSObject>,
permanent_js_root: Heap<JSVal>,
incumbent: Option<Dom<D::GlobalScope>>,
}
impl<D: DomTypes> CallbackObject<D> {
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
#[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()
}
#[allow(unsafe_code)]
unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
self.callback.set(callback);
self.permanent_js_root.set(ObjectValue(callback));
assert!(AddRawValueRoot(
*cx,
self.permanent_js_root.get_unsafe(),
b"CallbackObject::root\n".as_c_char_ptr()
));
}
}
impl<D: DomTypes> Drop for CallbackObject<D> {
#[allow(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, PartialEq)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub struct CallbackFunction<D: DomTypes> {
object: CallbackObject<D>,
}
impl<D: DomTypes> CallbackFunction<D> {
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
#[allow(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) {
self.object.init(cx, callback);
}
}
#[derive(JSTraceable, PartialEq)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub struct CallbackInterface<D: DomTypes> {
object: CallbackObject<D>,
}
impl<D: DomTypes> CallbackInterface<D> {
#[allow(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) {
self.object.init(cx, callback);
}
pub fn get_callable_property(&self, cx: JSContext, name: &str) -> Fallible<JSVal> {
rooted!(in(*cx) let mut callable = UndefinedValue());
rooted!(in(*cx) let obj = self.callback_holder().get());
unsafe {
let c_name = CString::new(name).unwrap();
if !JS_GetProperty(*cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) {
return Err(Error::JSFailed);
}
if !callable.is_object() || !IsCallable(callable.to_object()) {
return Err(Error::Type(format!(
"The value of the {} property is not callable",
name
)));
}
}
Ok(callable.get())
}
}
pub(crate) fn wrap_call_this_value<T: ThisReflector>(
cx: 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 struct CallSetup<D: DomTypes> {
exception_global: DomRoot<D::GlobalScope>,
cx: JSContext,
old_realm: *mut Realm,
handling: ExceptionHandling,
entry_script: Option<GenericAutoEntryScript<D>>,
incumbent_script: Option<GenericAutoIncumbentScript<D>>,
}
impl<D: DomTypes> CallSetup<D> {
#[cfg_attr(crown, allow(crown::unrooted_must_root))]
pub fn new<T: CallbackContainer<D>>(callback: &T, handling: ExceptionHandling) -> Self {
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 cx = D::GlobalScope::get_cx();
let aes = GenericAutoEntryScript::<D>::new(&global);
let ais = callback.incumbent().map(GenericAutoIncumbentScript::new);
CallSetup {
exception_global: global,
cx,
old_realm: unsafe { EnterRealm(*cx, callback.callback()) },
handling,
entry_script: Some(aes),
incumbent_script: ais,
}
}
pub fn get_context(&self) -> JSContext {
self.cx
}
}
impl<D: DomTypes> Drop for CallSetup<D> {
fn drop(&mut self) {
unsafe {
LeaveRealm(*self.cx, self.old_realm);
}
if self.handling == ExceptionHandling::Report {
let ar = enter_realm::<D>(&*self.exception_global);
<D as DomHelpers<D>>::report_pending_exception(
self.cx,
true,
InRealm::Entered(&ar),
CanGc::note(),
);
}
drop(self.incumbent_script.take());
drop(self.entry_script.take().unwrap());
}
}