use std::cell::RefCell;
use js::jsapi::{GetScriptedCallerGlobal, JSTracer};
use js::rust::Runtime;
use script_bindings::settings_stack::*;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::trace::JSTraceable;
use crate::dom::globalscope::GlobalScope;
thread_local!(pub(super) static STACK: RefCell<Vec<StackEntry<crate::DomTypeHolder>>> = const {
RefCell::new(Vec::new())
});
pub(crate) unsafe fn trace(tracer: *mut JSTracer) {
STACK.with(|stack| {
unsafe { stack.borrow().trace(tracer) };
})
}
pub(crate) fn is_execution_stack_empty() -> bool {
STACK.with(|stack| stack.borrow().is_empty())
}
pub(crate) 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(crate) 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))
})
}