use std::cell::RefCell;
use std::thread;
use js::jsapi::{GetScriptedCallerGlobal, HideScriptedCaller, JSTracer, UnhideScriptedCaller};
use js::rust::Runtime;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::JSTraceable;
use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
thread_local!(static STACK: RefCell<Vec<StackEntry>> = const { RefCell::new(Vec::new()) });
#[derive(Debug, Eq, JSTraceable, PartialEq)]
enum StackEntryKind {
Incumbent,
Entry,
}
#[allow(crown::unrooted_must_root)]
#[derive(JSTraceable)]
struct StackEntry {
global: Dom<GlobalScope>,
kind: StackEntryKind,
}
pub unsafe fn trace(tracer: *mut JSTracer) {
STACK.with(|stack| {
stack.borrow().trace(tracer);
})
}
pub fn is_execution_stack_empty() -> bool {
STACK.with(|stack| stack.borrow().is_empty())
}
pub struct AutoEntryScript {
global: DomRoot<GlobalScope>,
#[cfg(feature = "tracing")]
span: tracing::span::EnteredSpan,
}
impl AutoEntryScript {
pub fn new(global: &GlobalScope) -> Self {
STACK.with(|stack| {
trace!("Prepare to run script with {:p}", global);
let mut stack = stack.borrow_mut();
stack.push(StackEntry {
global: Dom::from_ref(global),
kind: StackEntryKind::Entry,
});
AutoEntryScript {
global: DomRoot::from_ref(global),
#[cfg(feature = "tracing")]
span: tracing::info_span!(
"ScriptEvaluate",
servo_profiling = true,
url = global.get_url().to_string(),
)
.entered(),
}
})
}
}
impl Drop for AutoEntryScript {
fn drop(&mut self) {
STACK.with(|stack| {
let mut stack = stack.borrow_mut();
let entry = stack.pop().unwrap();
assert_eq!(
&*entry.global as *const GlobalScope, &*self.global as *const GlobalScope,
"Dropped AutoEntryScript out of order."
);
assert_eq!(entry.kind, StackEntryKind::Entry);
trace!("Clean up after running script with {:p}", &*entry.global);
});
if !thread::panicking() && incumbent_global().is_none() {
self.global.perform_a_microtask_checkpoint(CanGc::note());
}
}
}
pub fn entry_global() -> DomRoot<GlobalScope> {
STACK
.with(|stack| {
stack
.borrow()
.iter()
.rev()
.find(|entry| entry.kind == StackEntryKind::Entry)
.map(|entry| DomRoot::from_ref(&*entry.global))
})
.unwrap()
}
pub struct AutoIncumbentScript {
global: usize,
}
impl AutoIncumbentScript {
pub fn new(global: &GlobalScope) -> Self {
unsafe {
let cx =
Runtime::get().expect("Creating a new incumbent script after runtime shutdown");
HideScriptedCaller(cx.as_ptr());
}
STACK.with(|stack| {
trace!("Prepare to run a callback with {:p}", global);
let mut stack = stack.borrow_mut();
stack.push(StackEntry {
global: Dom::from_ref(global),
kind: StackEntryKind::Incumbent,
});
AutoIncumbentScript {
global: global as *const _ as usize,
}
})
}
}
impl Drop for AutoIncumbentScript {
fn drop(&mut self) {
STACK.with(|stack| {
let mut stack = stack.borrow_mut();
let entry = stack.pop().unwrap();
assert_eq!(
&*entry.global as *const GlobalScope as usize, self.global,
"Dropped AutoIncumbentScript out of order."
);
assert_eq!(entry.kind, StackEntryKind::Incumbent);
trace!(
"Clean up after running a callback with {:p}",
&*entry.global
);
});
unsafe {
if let Some(cx) = Runtime::get() {
UnhideScriptedCaller(cx.as_ptr());
}
}
}
}
pub fn incumbent_global() -> Option<DomRoot<GlobalScope>> {
unsafe {
let Some(cx) = Runtime::get() else {
return None;
};
let global = GetScriptedCallerGlobal(cx.as_ptr());
if !global.is_null() {
return Some(GlobalScope::from_object(global));
}
}
STACK.with(|stack| {
stack
.borrow()
.last()
.map(|entry| DomRoot::from_ref(&*entry.global))
})
}