use std::borrow::ToOwned;
use std::cell::RefCell;
use std::fs::File;
use std::io::Write;
#[cfg(debug_assertions)]
use std::sync::atomic::{AtomicUsize, Ordering};
use serde::Serialize;
use serde_json::{to_string, to_value, Value};
use crate::flow::GetBaseFlow;
use crate::flow_ref::FlowRef;
thread_local!(static STATE_KEY: RefCell<Option<State>> = const { RefCell::new(None) });
#[cfg(debug_assertions)]
static DEBUG_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
pub struct Scope;
#[macro_export]
macro_rules! layout_debug_scope(
($($arg:tt)*) => (
if cfg!(debug_assertions) {
layout_debug::Scope::new(format!($($arg)*))
} else {
layout_debug::Scope
}
)
);
#[derive(Serialize)]
struct ScopeData {
name: String,
pre: Value,
post: Value,
children: Vec<ScopeData>,
}
impl ScopeData {
fn new(name: String, pre: Value) -> ScopeData {
ScopeData {
name,
pre,
post: Value::Null,
children: vec![],
}
}
}
struct State {
flow_root: FlowRef,
scope_stack: Vec<ScopeData>,
}
impl Scope {
pub fn new(name: String) -> Scope {
STATE_KEY.with(|r| {
if let Some(ref mut state) = *r.borrow_mut() {
let flow_trace = to_value(state.flow_root.base()).unwrap();
let data = Box::new(ScopeData::new(name.clone(), flow_trace));
state.scope_stack.push(*data);
}
});
Scope
}
}
#[cfg(debug_assertions)]
impl Drop for Scope {
fn drop(&mut self) {
STATE_KEY.with(|r| {
if let Some(ref mut state) = *r.borrow_mut() {
let mut current_scope = state.scope_stack.pop().unwrap();
current_scope.post = to_value(state.flow_root.base()).unwrap();
let previous_scope = state.scope_stack.last_mut().unwrap();
previous_scope.children.push(current_scope);
}
});
}
}
#[cfg(debug_assertions)]
pub fn generate_unique_debug_id() -> u16 {
DEBUG_ID_COUNTER.fetch_add(1, Ordering::SeqCst) as u16
}
pub fn begin_trace(flow_root: FlowRef) {
assert!(STATE_KEY.with(|r| r.borrow().is_none()));
STATE_KEY.with(|r| {
let flow_trace = to_value(flow_root.base()).unwrap();
let state = State {
scope_stack: vec![*Box::new(ScopeData::new("root".to_owned(), flow_trace))],
flow_root: flow_root.clone(),
};
*r.borrow_mut() = Some(state);
});
}
pub fn end_trace(generation: u32) {
let mut thread_state = STATE_KEY.with(|r| r.borrow_mut().take().unwrap());
assert_eq!(thread_state.scope_stack.len(), 1);
let mut root_scope = thread_state.scope_stack.pop().unwrap();
root_scope.post = to_value(thread_state.flow_root.base()).unwrap();
let result = to_string(&root_scope).unwrap();
let mut file = File::create(format!("layout_trace-{}.json", generation)).unwrap();
file.write_all(result.as_bytes()).unwrap();
}