use std::default::Default;
use std::ffi::CString;
use std::mem::drop;
use std::ptr;
use std::rc::Rc;
use js::jsapi::{
AddRawValueRoot, EnterRealm, Heap, IsCallable, JSObject, LeaveRealm, Realm, RemoveRawValueRoot,
};
use js::jsval::{JSVal, ObjectValue, UndefinedValue};
use js::rust::wrappers::{JS_GetProperty, JS_WrapObject};
use js::rust::{HandleObject, MutableHandleObject, Runtime};
use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
use crate::dom::bindings::error::{report_pending_exception, Error, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript};
use crate::dom::bindings::utils::AsCCharPtrPtr;
use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window;
use crate::realms::{enter_realm, InRealm};
use crate::script_runtime::{CanGc, JSContext};
#[derive(Clone, Copy, PartialEq)]
pub enum ExceptionHandling {
Report,
Rethrow,
}
#[derive(JSTraceable)]
#[crown::unrooted_must_root_lint::must_root]
pub struct CallbackObject {
callback: Heap<*mut JSObject>,
permanent_js_root: Heap<JSVal>,
incumbent: Option<Dom<GlobalScope>>,
}
impl CallbackObject {
#[allow(crown::unrooted_must_root)]
#[allow(clippy::new_without_default)]
fn new() -> CallbackObject {
CallbackObject {
callback: Heap::default(),
permanent_js_root: Heap::default(),
incumbent: 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 Drop for CallbackObject {
#[allow(unsafe_code)]
fn drop(&mut self) {
unsafe {
let cx = Runtime::get();
RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe());
}
}
}
impl PartialEq for CallbackObject {
fn eq(&self, other: &CallbackObject) -> bool {
self.callback.get() == other.callback.get()
}
}
pub trait CallbackContainer {
unsafe fn new(cx: JSContext, callback: *mut JSObject) -> Rc<Self>;
fn callback_holder(&self) -> &CallbackObject;
fn callback(&self) -> *mut JSObject {
self.callback_holder().get()
}
fn incumbent(&self) -> Option<&GlobalScope> {
self.callback_holder().incumbent.as_deref()
}
}
#[derive(JSTraceable, PartialEq)]
#[crown::unrooted_must_root_lint::must_root]
pub struct CallbackFunction {
object: CallbackObject,
}
impl CallbackFunction {
#[allow(crown::unrooted_must_root)]
#[allow(clippy::new_without_default)]
pub fn new() -> CallbackFunction {
CallbackFunction {
object: CallbackObject::new(),
}
}
pub fn callback_holder(&self) -> &CallbackObject {
&self.object
}
pub unsafe fn init(&mut self, cx: JSContext, callback: *mut JSObject) {
self.object.init(cx, callback);
}
}
#[derive(JSTraceable, PartialEq)]
#[crown::unrooted_must_root_lint::must_root]
pub struct CallbackInterface {
object: CallbackObject,
}
impl CallbackInterface {
#[allow(clippy::new_without_default)]
pub fn new() -> CallbackInterface {
CallbackInterface {
object: CallbackObject::new(),
}
}
pub fn callback_holder(&self) -> &CallbackObject {
&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 trait ThisReflector {
fn jsobject(&self) -> *mut JSObject;
}
impl<T: DomObject> ThisReflector for T {
fn jsobject(&self) -> *mut JSObject {
self.reflector().get_jsobject().get()
}
}
impl<'a> ThisReflector for HandleObject<'a> {
fn jsobject(&self) -> *mut JSObject {
self.get()
}
}
pub fn wrap_call_this_object<T: ThisReflector>(
cx: JSContext,
p: &T,
mut rval: MutableHandleObject,
) {
rval.set(p.jsobject());
assert!(!rval.get().is_null());
unsafe {
if !JS_WrapObject(*cx, rval) {
rval.set(ptr::null_mut());
}
}
}
pub struct CallSetup {
exception_global: DomRoot<GlobalScope>,
cx: JSContext,
old_realm: *mut Realm,
handling: ExceptionHandling,
entry_script: Option<AutoEntryScript>,
incumbent_script: Option<AutoIncumbentScript>,
}
impl CallSetup {
#[allow(crown::unrooted_must_root)]
pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = unsafe { GlobalScope::from_object(callback.callback()) };
if let Some(window) = global.downcast::<Window>() {
window.Document().ensure_safe_to_run_script_or_layout();
}
let cx = GlobalScope::get_cx();
let aes = AutoEntryScript::new(&global);
let ais = callback.incumbent().map(AutoIncumbentScript::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 Drop for CallSetup {
fn drop(&mut self) {
unsafe {
LeaveRealm(*self.cx, self.old_realm);
if self.handling == ExceptionHandling::Report {
let ar = enter_realm(&*self.exception_global);
report_pending_exception(*self.cx, true, InRealm::Entered(&ar), CanGc::note());
}
drop(self.incumbent_script.take());
drop(self.entry_script.take().unwrap());
}
}
}