use std::cell::Cell;
use std::rc::Rc;
use dom_struct::dom_struct;
use js::rust::{HandleObject, MutableHandleValue};
use crate::dom::bindings::callback::ExceptionHandling;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceEntryList as DOMPerformanceEntryList;
use crate::dom::bindings::codegen::Bindings::PerformanceObserverBinding::{
PerformanceObserverCallback, PerformanceObserverInit, PerformanceObserverMethods,
};
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object_with_proto, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::console::Console;
use crate::dom::globalscope::GlobalScope;
use crate::dom::performance::PerformanceEntryList;
use crate::dom::performanceentry::PerformanceEntry;
use crate::dom::performanceobserverentrylist::PerformanceObserverEntryList;
use crate::script_runtime::{CanGc, JSContext};
pub const VALID_ENTRY_TYPES: &[&str] = &[
"mark", "measure", "navigation", "paint", "resource", ];
#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
enum ObserverType {
Undefined,
Single,
Multiple,
}
#[dom_struct]
pub struct PerformanceObserver {
reflector_: Reflector,
#[ignore_malloc_size_of = "can't measure Rc values"]
callback: Rc<PerformanceObserverCallback>,
entries: DomRefCell<DOMPerformanceEntryList>,
observer_type: Cell<ObserverType>,
}
impl PerformanceObserver {
fn new_inherited(
callback: Rc<PerformanceObserverCallback>,
entries: DomRefCell<DOMPerformanceEntryList>,
) -> PerformanceObserver {
PerformanceObserver {
reflector_: Reflector::new(),
callback,
entries,
observer_type: Cell::new(ObserverType::Undefined),
}
}
pub fn new(
global: &GlobalScope,
callback: Rc<PerformanceObserverCallback>,
entries: DOMPerformanceEntryList,
can_gc: CanGc,
) -> DomRoot<PerformanceObserver> {
Self::new_with_proto(global, None, callback, entries, can_gc)
}
#[allow(crown::unrooted_must_root)]
fn new_with_proto(
global: &GlobalScope,
proto: Option<HandleObject>,
callback: Rc<PerformanceObserverCallback>,
entries: DOMPerformanceEntryList,
can_gc: CanGc,
) -> DomRoot<PerformanceObserver> {
let observer = PerformanceObserver::new_inherited(callback, DomRefCell::new(entries));
reflect_dom_object_with_proto(Box::new(observer), global, proto, can_gc)
}
pub fn queue_entry(&self, entry: &PerformanceEntry) {
self.entries.borrow_mut().push(DomRoot::from_ref(entry));
}
pub fn notify(&self) {
if self.entries.borrow().is_empty() {
return;
}
let entry_list = PerformanceEntryList::new(self.entries.borrow_mut().drain(..).collect());
let observer_entry_list = PerformanceObserverEntryList::new(&self.global(), entry_list);
let _ = self
.callback
.Call_(self, &observer_entry_list, self, ExceptionHandling::Report);
}
pub fn callback(&self) -> Rc<PerformanceObserverCallback> {
self.callback.clone()
}
pub fn entries(&self) -> DOMPerformanceEntryList {
self.entries.borrow().clone()
}
pub fn set_entries(&self, entries: DOMPerformanceEntryList) {
*self.entries.borrow_mut() = entries;
}
}
impl PerformanceObserverMethods for PerformanceObserver {
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
callback: Rc<PerformanceObserverCallback>,
) -> Fallible<DomRoot<PerformanceObserver>> {
Ok(PerformanceObserver::new_with_proto(
global,
proto,
callback,
Vec::new(),
can_gc,
))
}
fn SupportedEntryTypes(cx: JSContext, global: &GlobalScope, retval: MutableHandleValue) {
global.supported_performance_entry_types(cx, retval)
}
fn Observe(&self, options: &PerformanceObserverInit) -> Fallible<()> {
if options.entryTypes.is_none() && options.type_.is_none() {
return Err(Error::Syntax);
}
if options.entryTypes.is_some() && (options.buffered.is_some() || options.type_.is_some()) {
return Err(Error::Syntax);
}
match self.observer_type.get() {
ObserverType::Undefined => {
if options.entryTypes.is_some() {
self.observer_type.set(ObserverType::Multiple);
} else {
self.observer_type.set(ObserverType::Single);
}
},
ObserverType::Single => {
if options.entryTypes.is_some() {
return Err(Error::InvalidModification);
}
},
ObserverType::Multiple => {
if options.type_.is_some() {
return Err(Error::InvalidModification);
}
},
}
if let Some(entry_types) = &options.entryTypes {
let entry_types = entry_types
.iter()
.filter(|e| VALID_ENTRY_TYPES.contains(&e.as_ref()))
.cloned()
.collect::<Vec<DOMString>>();
if entry_types.is_empty() {
Console::internal_warn(
&self.global(),
DOMString::from("No valid entry type provided to observe()."),
);
return Ok(());
}
self.global()
.performance()
.add_multiple_type_observer(self, entry_types);
Ok(())
} else if let Some(entry_type) = &options.type_ {
if !VALID_ENTRY_TYPES.contains(&entry_type.as_ref()) {
Console::internal_warn(
&self.global(),
DOMString::from("No valid entry type provided to observe()."),
);
return Ok(());
}
self.global().performance().add_single_type_observer(
self,
entry_type,
options.buffered.unwrap_or(false),
);
Ok(())
} else {
unreachable!()
}
}
fn Disconnect(&self) {
self.global().performance().remove_observer(self);
self.entries.borrow_mut().clear();
}
fn TakeRecords(&self) -> Vec<DomRoot<PerformanceEntry>> {
let mut entries = self.entries.borrow_mut();
let taken = entries
.iter()
.map(|entry| DomRoot::from_ref(&**entry))
.collect();
entries.clear();
taken
}
}