use std::cell::{Cell, RefCell};
use std::sync::Arc;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum ObserveLevel {
Commands,
Calls,
Arguments,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandPhase {
Begin,
End,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CommandEvent {
pub command: i32,
pub name: &'static str,
pub phase: CommandPhase,
pub duration: Option<Duration>,
pub error: Option<i32>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SuiteCallEvent {
pub suite: &'static str,
pub function: &'static str,
pub args: Vec<(&'static str, String)>,
pub result: Option<String>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AllocationEvent {
pub kind: AllocationKind,
pub allocated: bool,
pub address: usize,
pub bytes: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AllocationKind {
Handle,
World,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CheckoutEvent {
pub kind: CheckoutKind,
pub id: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CheckoutKind {
DeclareLayer,
CheckoutLayerPixels,
CheckinLayerPixels,
CheckoutParam,
CheckinParam,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum UnsupportedKind {
MissingSuite,
Stub,
Declined,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct UnsupportedEvent {
pub kind: UnsupportedKind,
pub name: String,
pub detail: String,
}
impl UnsupportedEvent {
pub fn new(kind: UnsupportedKind, name: impl Into<String>, detail: impl Into<String>) -> Self {
Self {
kind,
name: name.into(),
detail: detail.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LiveAllocation {
pub kind: AllocationKind,
pub address: usize,
pub bytes: usize,
pub allocated_in: &'static str,
}
pub trait Observer: Send + Sync {
fn command(&self, _event: &CommandEvent) {}
fn suite_call(&self, _event: &SuiteCallEvent) {}
fn allocation(&self, _event: &AllocationEvent) {}
fn checkout(&self, _event: &CheckoutEvent) {}
fn unsupported(&self, _event: &UnsupportedEvent) {}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct LogObserver;
impl Observer for LogObserver {
fn command(&self, event: &CommandEvent) {
match (event.phase, event.duration) {
(CommandPhase::End, Some(duration)) => match event.error {
Some(code) => log::debug!("PF_Cmd_{} failed with {code} after {duration:?}", event.name),
None => log::debug!("PF_Cmd_{} took {duration:?}", event.name),
},
_ => log::debug!("PF_Cmd_{} begins", event.name),
}
}
fn suite_call(&self, event: &SuiteCallEvent) {
let args: Vec<String> = event
.args
.iter()
.map(|(name, value)| format!("{name}: {value}"))
.collect();
match &event.result {
Some(result) => log::debug!("{}::{}({}) -> {result}", event.suite, event.function, args.join(", ")),
None => log::debug!("{}::{}({})", event.suite, event.function, args.join(", ")),
}
}
fn allocation(&self, event: &AllocationEvent) {
let verb = if event.allocated { "allocated" } else { "disposed" };
log::debug!("{verb} {:?} {:#x} ({} bytes)", event.kind, event.address, event.bytes);
}
fn checkout(&self, event: &CheckoutEvent) {
log::debug!("{:?} #{}", event.kind, event.id);
}
fn unsupported(&self, event: &UnsupportedEvent) {
log::debug!("unsupported ({:?}): {} {}", event.kind, event.name, event.detail);
}
}
pub fn command_name(command: i32) -> &'static str {
use crate::sys::*;
const NAMES: &[(u32, &str)] = &[
(PF_Cmd_ABOUT as u32, "ABOUT"),
(PF_Cmd_GLOBAL_SETUP as u32, "GLOBAL_SETUP"),
(PF_Cmd_GLOBAL_SETDOWN as u32, "GLOBAL_SETDOWN"),
(PF_Cmd_PARAMS_SETUP as u32, "PARAMS_SETUP"),
(PF_Cmd_SEQUENCE_SETUP as u32, "SEQUENCE_SETUP"),
(PF_Cmd_SEQUENCE_RESETUP as u32, "SEQUENCE_RESETUP"),
(PF_Cmd_SEQUENCE_FLATTEN as u32, "SEQUENCE_FLATTEN"),
(PF_Cmd_SEQUENCE_SETDOWN as u32, "SEQUENCE_SETDOWN"),
(PF_Cmd_DO_DIALOG as u32, "DO_DIALOG"),
(PF_Cmd_FRAME_SETUP as u32, "FRAME_SETUP"),
(PF_Cmd_RENDER as u32, "RENDER"),
(PF_Cmd_FRAME_SETDOWN as u32, "FRAME_SETDOWN"),
(PF_Cmd_USER_CHANGED_PARAM as u32, "USER_CHANGED_PARAM"),
(PF_Cmd_UPDATE_PARAMS_UI as u32, "UPDATE_PARAMS_UI"),
(PF_Cmd_EVENT as u32, "EVENT"),
(PF_Cmd_GET_EXTERNAL_DEPENDENCIES as u32, "GET_EXTERNAL_DEPENDENCIES"),
(PF_Cmd_COMPLETELY_GENERAL as u32, "COMPLETELY_GENERAL"),
(PF_Cmd_QUERY_DYNAMIC_FLAGS as u32, "QUERY_DYNAMIC_FLAGS"),
(PF_Cmd_AUDIO_RENDER as u32, "AUDIO_RENDER"),
(PF_Cmd_AUDIO_SETUP as u32, "AUDIO_SETUP"),
(PF_Cmd_AUDIO_SETDOWN as u32, "AUDIO_SETDOWN"),
(PF_Cmd_ARBITRARY_CALLBACK as u32, "ARBITRARY_CALLBACK"),
(PF_Cmd_SMART_PRE_RENDER as u32, "SMART_PRE_RENDER"),
(PF_Cmd_SMART_RENDER as u32, "SMART_RENDER"),
(PF_Cmd_GET_FLATTENED_SEQUENCE_DATA as u32, "GET_FLATTENED_SEQUENCE_DATA"),
(PF_Cmd_TRANSLATE_PARAMS_TO_PREFS as u32, "TRANSLATE_PARAMS_TO_PREFS"),
(PF_Cmd_SMART_RENDER_GPU as u32, "SMART_RENDER_GPU"),
(PF_Cmd_GPU_DEVICE_SETUP as u32, "GPU_DEVICE_SETUP"),
(PF_Cmd_GPU_DEVICE_SETDOWN as u32, "GPU_DEVICE_SETDOWN"),
];
NAMES
.iter()
.find(|(value, _)| *value == command as u32)
.map_or("UNKNOWN", |(_, name)| name)
}
#[derive(Clone)]
pub(crate) struct Installed {
pub(crate) observer: Arc<dyn Observer>,
pub(crate) level: ObserveLevel,
}
thread_local! {
static CALLS: RefCell<Option<Arc<dyn Observer>>> = const { RefCell::new(None) };
static ANY: RefCell<Option<Arc<dyn Observer>>> = const { RefCell::new(None) };
static DETAILS: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn enter(installed: Option<&Installed>) -> CallsGuard {
let any = installed.map(|i| i.observer.clone());
let calls = installed
.filter(|i| i.level >= ObserveLevel::Calls)
.map(|i| i.observer.clone());
let details = installed.is_some_and(|i| i.level >= ObserveLevel::Arguments);
CallsGuard {
previous_any: ANY.with(|a| std::mem::replace(&mut *a.borrow_mut(), any)),
previous: CALLS.with(|c| std::mem::replace(&mut *c.borrow_mut(), calls)),
previous_details: DETAILS.with(|d| d.replace(details)),
}
}
pub(crate) struct CallsGuard {
previous_any: Option<Arc<dyn Observer>>,
previous: Option<Arc<dyn Observer>>,
previous_details: bool,
}
impl Drop for CallsGuard {
fn drop(&mut self) {
let previous_any = self.previous_any.take();
ANY.with(|a| *a.borrow_mut() = previous_any);
let previous = self.previous.take();
CALLS.with(|c| *c.borrow_mut() = previous);
DETAILS.with(|d| d.set(self.previous_details));
}
}
pub(crate) fn unsupported(kind: UnsupportedKind, name: impl Into<String>, detail: impl Into<String>) {
let event = UnsupportedEvent::new(kind, name, detail);
log::warn!("unsupported ({:?}): {} {}", event.kind, event.name, event.detail);
ANY.with(|a| {
if let Some(observer) = a.borrow().as_ref() {
observer.unsupported(&event);
}
});
}
pub(crate) fn wants_details() -> bool {
DETAILS.with(Cell::get)
}
pub(crate) fn suite_call(name: &'static str) {
CALLS.with(|c| {
if let Some(observer) = c.borrow().as_ref() {
let (suite, function) = name.split_once('/').unwrap_or(("", name));
observer.suite_call(&SuiteCallEvent {
suite,
function,
args: Vec::new(),
result: None,
});
}
});
}
pub(crate) fn suite_call_detailed(name: &'static str, args: Vec<(&'static str, String)>, result: Option<String>) {
let (args, result) = if wants_details() {
(args, result)
} else {
(Vec::new(), None)
};
CALLS.with(|c| {
if let Some(observer) = c.borrow().as_ref() {
let (suite, function) = name.split_once('/').unwrap_or(("", name));
observer.suite_call(&SuiteCallEvent {
suite,
function,
args,
result,
});
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[derive(Default)]
struct Recorder(Mutex<Vec<String>>);
impl Observer for Recorder {
fn suite_call(&self, event: &SuiteCallEvent) {
self.0
.lock()
.unwrap()
.push(format!("{}::{}", event.suite, event.function));
}
fn unsupported(&self, event: &UnsupportedEvent) {
self.0
.lock()
.unwrap()
.push(format!("{:?} {} {}", event.kind, event.name, event.detail));
}
}
fn installed(observer: Arc<Recorder>, level: ObserveLevel) -> Installed {
Installed { observer, level }
}
#[test]
fn names_commands_by_sdk_name() {
assert_eq!(command_name(crate::sys::PF_Cmd_SMART_RENDER), "SMART_RENDER");
assert_eq!(command_name(-5), "UNKNOWN");
}
#[test]
fn suite_calls_reach_only_the_entered_observer() {
let recorder = Arc::new(Recorder::default());
suite_call("Ignored/Before");
{
let _guard = enter(Some(&installed(recorder.clone(), ObserveLevel::Calls)));
suite_call("PF_WorldSuite2/PF_NewWorld");
{
let _inner = enter(None);
assert!(!wants_details(), "no observer, no details");
suite_call("Ignored/Nested");
}
suite_call("PF_HandleSuite1/host_new_handle");
}
suite_call("Ignored/After");
assert_eq!(
*recorder.0.lock().unwrap(),
["PF_WorldSuite2::PF_NewWorld", "PF_HandleSuite1::host_new_handle"]
);
}
#[test]
fn unsupported_reaches_an_observer_at_every_level() {
let recorder = Arc::new(Recorder::default());
unsupported(UnsupportedKind::Stub, "Ignored/Before", "");
{
let _guard = enter(Some(&installed(recorder.clone(), ObserveLevel::Commands)));
suite_call("Ignored/NotAtCommands");
unsupported(UnsupportedKind::MissingSuite, "AEGP Mask Suite", "v6");
{
let _inner = enter(None);
unsupported(UnsupportedKind::Stub, "Ignored/Nested", "");
}
unsupported(UnsupportedKind::Declined, "PF_WorldSuite2/PF_NewWorld", "format=7");
}
unsupported(UnsupportedKind::Stub, "Ignored/After", "");
assert_eq!(
*recorder.0.lock().unwrap(),
[
"MissingSuite AEGP Mask Suite v6",
"Declined PF_WorldSuite2/PF_NewWorld format=7"
]
);
}
}