use super::gles::{BackgroundMode, GpuFrameTiming, RenderStats};
use crate::{Key as UiKey, MotionPreference};
use std::{
fs::File,
io::{BufWriter, Write},
path::PathBuf,
time::Duration,
};
#[derive(Clone, Debug)]
pub(super) struct EnvOverrides {
pub(super) size: Option<[u32; 2]>,
pub(super) reduced_motion: bool,
pub(super) bg_mode: BackgroundMode,
pub(super) bg_scale: Option<f32>,
pub(super) bg_interval: Option<f64>,
}
impl EnvOverrides {
pub(super) fn from_env() -> Self {
let size = std::env::var("BHOO_WINDOW_SIZE").ok().and_then(|raw| {
let (w, h) = raw.split_once('x').or_else(|| raw.split_once('X'))?;
let w = w.trim().parse::<u32>().ok()?;
let h = h.trim().parse::<u32>().ok()?;
(w > 0 && h > 0).then_some([w, h])
});
let reduced_motion = matches!(
std::env::var("BHOO_REDUCED_MOTION").as_deref(),
Ok("1") | Ok("true") | Ok("TRUE") | Ok("yes")
);
let bg_mode = match std::env::var("BHOO_BG_MODE").as_deref() {
Ok("bypass") => BackgroundMode::Bypass,
Ok("frozen") => BackgroundMode::Frozen,
_ => BackgroundMode::Normal,
};
let bg_scale = std::env::var("BHOO_BG_SCALE")
.ok()
.and_then(|v| v.trim().parse::<f32>().ok())
.filter(|v| v.is_finite() && *v > 0.0);
let bg_interval = std::env::var("BHOO_BG_INTERVAL_MS")
.ok()
.and_then(|v| v.trim().parse::<f64>().ok())
.filter(|v| v.is_finite() && *v >= 0.0)
.map(|ms| ms / 1000.0);
Self {
size,
reduced_motion,
bg_mode,
bg_scale,
bg_interval,
}
}
pub(super) fn apply_motion(&self, default: MotionPreference) -> MotionPreference {
if self.reduced_motion {
MotionPreference::Reduced
} else {
default
}
}
}
#[derive(Clone, Debug)]
pub(super) enum ScriptAction {
Tag(String),
Resize(u32, u32),
Move(f32, f32),
Press(f32, f32),
Release(f32, f32),
Scroll(f32, f32),
Key(UiKey, bool),
Exit,
}
#[derive(Clone, Debug)]
pub(super) struct ScriptEvent {
pub(super) at_ns: u64,
pub(super) action: ScriptAction,
}
pub(super) struct InputScript {
events: Vec<ScriptEvent>,
cursor: usize,
current_tag: String,
}
impl InputScript {
pub(super) fn from_env() -> Option<Self> {
let path = std::env::var_os("BHOO_INPUT_SCRIPT")?;
let text = std::fs::read_to_string(&path).ok()?;
let mut events = Vec::new();
for raw_line in text.lines() {
let line = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 2 {
continue;
}
let Ok(secs) = parts[0].parse::<f64>() else {
continue;
};
let at_ns = (secs.max(0.0) * 1e9) as u64;
match parts[1] {
"tag" if parts.len() >= 3 => {
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Tag(parts[2..].join(" ")),
});
}
"resize" if parts.len() >= 4 => {
if let (Ok(w), Ok(h)) = (parts[2].parse(), parts[3].parse()) {
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Resize(w, h),
});
}
}
"move" if parts.len() >= 4 => {
if let (Ok(x), Ok(y)) = (parts[2].parse(), parts[3].parse()) {
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Move(x, y),
});
}
}
"click" if parts.len() >= 4 => {
if let (Ok(x), Ok(y)) = (parts[2].parse::<f32>(), parts[3].parse::<f32>()) {
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Move(x, y),
});
events.push(ScriptEvent {
at_ns: at_ns + 16_000_000,
action: ScriptAction::Press(x, y),
});
events.push(ScriptEvent {
at_ns: at_ns + 50_000_000,
action: ScriptAction::Release(x, y),
});
}
}
"drag" if parts.len() >= 8 => {
if let (Ok(x0), Ok(y0), Ok(x1), Ok(y1), Ok(dur), Ok(steps)) = (
parts[2].parse::<f32>(),
parts[3].parse::<f32>(),
parts[4].parse::<f32>(),
parts[5].parse::<f32>(),
parts[6].parse::<f64>(),
parts[7].parse::<u32>(),
) {
let steps = steps.max(2);
let dur_ns = (dur.max(0.05) * 1e9) as u64;
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Move(x0, y0),
});
events.push(ScriptEvent {
at_ns: at_ns + 10_000_000,
action: ScriptAction::Press(x0, y0),
});
for i in 1..=steps {
let frac = i as f32 / steps as f32;
let t = at_ns + 10_000_000 + (dur_ns * u64::from(i)) / u64::from(steps);
events.push(ScriptEvent {
at_ns: t,
action: ScriptAction::Move(
x0 + (x1 - x0) * frac,
y0 + (y1 - y0) * frac,
),
});
}
events.push(ScriptEvent {
at_ns: at_ns + 10_000_000 + dur_ns + 10_000_000,
action: ScriptAction::Release(x1, y1),
});
}
}
"scroll" if parts.len() >= 4 => {
if let (Ok(dx), Ok(dy)) = (parts[2].parse(), parts[3].parse()) {
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Scroll(dx, dy),
});
}
}
"text" if parts.len() >= 3 => {
let s = parts[2..].join(" ");
let mut t = at_ns;
for ch in s.chars() {
let key = if ch == ' ' {
UiKey::Space
} else {
UiKey::Character(ch)
};
events.push(ScriptEvent {
at_ns: t,
action: ScriptAction::Key(key, true),
});
events.push(ScriptEvent {
at_ns: t + 15_000_000,
action: ScriptAction::Key(key, false),
});
t += 45_000_000;
}
}
"key" if parts.len() >= 3 => {
let key = match parts[2] {
"Enter" => Some(UiKey::Enter),
"Backspace" => Some(UiKey::Character('\u{8}')),
"Space" => Some(UiKey::Space),
"Tab" => Some(UiKey::Tab),
"Escape" => Some(UiKey::Escape),
_ => None,
};
if let Some(key) = key {
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Key(key, true),
});
events.push(ScriptEvent {
at_ns: at_ns + 15_000_000,
action: ScriptAction::Key(key, false),
});
}
}
"exit" => {
events.push(ScriptEvent {
at_ns,
action: ScriptAction::Exit,
});
}
_ => {}
}
}
events.sort_by_key(|ev| ev.at_ns);
Some(Self {
events,
cursor: 0,
current_tag: "warmup".into(),
})
}
pub(super) fn next_deadline_ns(&self) -> Option<u64> {
self.events.get(self.cursor).map(|ev| ev.at_ns)
}
pub(super) fn pop_due(&mut self, now_ns: u64) -> Option<ScriptAction> {
let ev = self.events.get(self.cursor)?;
if now_ns >= ev.at_ns {
let action = ev.action.clone();
self.cursor += 1;
if let ScriptAction::Tag(ref tag) = action {
self.current_tag = tag.clone();
}
Some(action)
} else {
None
}
}
pub(super) fn tag(&self) -> &str {
&self.current_tag
}
}
#[derive(Clone, Debug)]
pub(super) struct FrameSample {
pub(super) frame: u64,
pub(super) tag: String,
pub(super) logical_w: f32,
pub(super) logical_h: f32,
pub(super) phys_w: u32,
pub(super) phys_h: u32,
pub(super) scale: f32,
pub(super) input_enqueued_ns: Option<u64>,
pub(super) wake_deadline_ns: Option<u64>,
pub(super) wake_fired_ns: Option<u64>,
pub(super) draw_start_ns: u64,
pub(super) ui_build_end_ns: u64,
pub(super) render_end_ns: u64,
pub(super) swap_end_ns: u64,
pub(super) cmd_count: u32,
pub(super) stats: RenderStats,
pub(super) action: u8,
pub(super) needs_redraw: bool,
pub(super) font_check_us: Option<u32>,
pub(super) gpu_bg_ns: Option<u64>,
pub(super) gpu_fg_ns: Option<u64>,
pub(super) gpu_disjoint: bool,
}
#[derive(Clone, Copy, Debug, Default)]
struct ProcCpuSample {
utime_ticks: u64,
stime_ticks: u64,
rss_kb: u64,
}
fn read_proc_cpu() -> ProcCpuSample {
let mut out = ProcCpuSample::default();
if let Ok(stat) = std::fs::read_to_string("/proc/self/stat")
&& let Some(rparen) = stat.rfind(')')
{
let fields: Vec<&str> = stat[rparen + 2..].split_whitespace().collect();
if fields.len() > 12 {
out.utime_ticks = fields[11].parse().unwrap_or(0);
out.stime_ticks = fields[12].parse().unwrap_or(0);
}
}
if let Ok(status) = std::fs::read_to_string("/proc/self/status") {
for line in status.lines() {
if let Some(rest) = line.strip_prefix("VmRSS:") {
out.rss_kb = rest
.split_whitespace()
.next()
.and_then(|s| s.parse().ok())
.unwrap_or(0);
break;
}
}
}
out
}
pub(super) struct Profiler {
output: PathBuf,
duration_ns: Option<u64>,
warmup_ns: u64,
gl_version: String,
gl_renderer: String,
gpu_timers_supported: bool,
bg_mode: &'static str,
reduced_motion: bool,
startup_graphics_ns: u64,
first_swap_ns: Option<u64>,
cpu_start: ProcCpuSample,
cpu_warmup: Option<(u64, ProcCpuSample)>,
samples: Vec<FrameSample>,
frame_to_idx: Vec<(u64, usize)>,
}
impl Profiler {
pub(super) fn from_env(overrides: &EnvOverrides) -> Option<Self> {
let raw = std::env::var_os("BHOO_PROFILE")?;
if raw.is_empty() {
return None;
}
let duration_ns = std::env::var("BHOO_PROFILE_DURATION_S")
.ok()
.and_then(|v| v.parse::<f64>().ok())
.filter(|v| v.is_finite() && *v > 0.0)
.map(|v| (v * 1e9) as u64);
let warmup_ns = std::env::var("BHOO_PROFILE_WARMUP_S")
.ok()
.and_then(|v| v.parse::<f64>().ok())
.filter(|v| v.is_finite() && *v >= 0.0)
.map_or(5_000_000_000, |v| (v * 1e9) as u64);
let bg_mode = match overrides.bg_mode {
BackgroundMode::Normal => "normal",
BackgroundMode::Bypass => "bypass",
BackgroundMode::Frozen => "frozen",
};
Some(Self {
output: PathBuf::from(raw),
duration_ns,
warmup_ns,
gl_version: String::new(),
gl_renderer: String::new(),
gpu_timers_supported: false,
bg_mode,
reduced_motion: overrides.reduced_motion,
startup_graphics_ns: 0,
first_swap_ns: None,
cpu_start: read_proc_cpu(),
cpu_warmup: None,
samples: Vec::with_capacity(4096),
frame_to_idx: Vec::with_capacity(4096),
})
}
pub(super) fn set_gl_info(
&mut self,
version: String,
renderer: String,
gpu_timers_supported: bool,
startup_graphics_ns: u64,
) {
self.gl_version = version;
self.gl_renderer = renderer;
self.gpu_timers_supported = gpu_timers_supported;
self.startup_graphics_ns = startup_graphics_ns;
}
pub(super) fn duration_deadline(&self) -> Option<Duration> {
self.duration_ns.map(Duration::from_nanos)
}
pub(super) fn should_exit(&self, now_ns: u64) -> bool {
self.duration_ns.is_some_and(|limit| now_ns >= limit)
}
pub(super) fn record_frame(&mut self, sample: FrameSample) {
if self.first_swap_ns.is_none() {
self.first_swap_ns = Some(sample.swap_end_ns);
}
if self.cpu_warmup.is_none() && sample.swap_end_ns >= self.warmup_ns {
self.cpu_warmup = Some((sample.swap_end_ns, read_proc_cpu()));
}
let idx = self.samples.len();
self.frame_to_idx.push((sample.frame, idx));
self.samples.push(sample);
}
pub(super) fn merge_gpu_timings(&mut self, timings: &[GpuFrameTiming]) {
for timing in timings {
if let Ok(pos) = self
.frame_to_idx
.binary_search_by_key(&timing.frame, |(f, _)| *f)
{
let idx = self.frame_to_idx[pos].1;
if let Some(sample) = self.samples.get_mut(idx) {
sample.gpu_bg_ns = timing.bg_ns;
sample.gpu_fg_ns = timing.fg_ns;
sample.gpu_disjoint = timing.disjoint;
}
}
}
}
pub(super) fn dump(&self, total_elapsed_ns: u64) {
let cpu_end = read_proc_cpu();
let (warm_start_ns, warm_cpu_start) = self.cpu_warmup.unwrap_or((0, self.cpu_start));
let warm_elapsed_ns = total_elapsed_ns.saturating_sub(warm_start_ns);
let warm_utime = cpu_end
.utime_ticks
.saturating_sub(warm_cpu_start.utime_ticks);
let warm_stime = cpu_end
.stime_ticks
.saturating_sub(warm_cpu_start.stime_ticks);
let to_stderr = self.output.as_os_str() == "1" || self.output.as_os_str() == "stderr";
let result: std::io::Result<()> = if to_stderr {
let stderr = std::io::stderr();
self.write_json(
&mut BufWriter::new(stderr.lock()),
total_elapsed_ns,
cpu_end,
warm_elapsed_ns,
warm_utime,
warm_stime,
)
} else {
File::create(&self.output).and_then(|file| {
self.write_json(
&mut BufWriter::new(file),
total_elapsed_ns,
cpu_end,
warm_elapsed_ns,
warm_utime,
warm_stime,
)
})
};
if let Err(err) = result {
eprintln!("Bhoo profiler write error ({}): {err}", self.output.display());
}
}
fn write_json(
&self,
w: &mut impl Write,
total_elapsed_ns: u64,
cpu_end: ProcCpuSample,
warm_elapsed_ns: u64,
warm_utime_ticks: u64,
warm_stime_ticks: u64,
) -> std::io::Result<()> {
writeln!(w, "{{")?;
writeln!(w, " \"interval_basis\": \"swap_completion_proxy\",")?;
writeln!(w, " \"gl_version\": \"{}\",", escape_json(&self.gl_version))?;
writeln!(
w,
" \"gl_renderer\": \"{}\",",
escape_json(&self.gl_renderer)
)?;
writeln!(
w,
" \"gpu_timers_supported\": {},",
self.gpu_timers_supported
)?;
writeln!(w, " \"bg_mode\": \"{}\",", self.bg_mode)?;
writeln!(w, " \"reduced_motion\": {},", self.reduced_motion)?;
writeln!(w, " \"startup_graphics_ns\": {},", self.startup_graphics_ns)?;
writeln!(
w,
" \"first_swap_ns\": {},",
self.first_swap_ns
.map_or_else(|| "null".into(), |v| v.to_string())
)?;
writeln!(w, " \"warmup_ns\": {},", self.warmup_ns)?;
writeln!(w, " \"total_elapsed_ns\": {},", total_elapsed_ns)?;
writeln!(w, " \"warm_elapsed_ns\": {},", warm_elapsed_ns)?;
writeln!(w, " \"clk_tck_hz\": 100,")?;
writeln!(w, " \"warm_cpu_utime_ticks\": {},", warm_utime_ticks)?;
writeln!(w, " \"warm_cpu_stime_ticks\": {},", warm_stime_ticks)?;
writeln!(w, " \"end_rss_kb\": {},", cpu_end.rss_kb)?;
writeln!(w, " \"frames\": [")?;
for (i, s) in self.samples.iter().enumerate() {
let comma = if i + 1 < self.samples.len() { "," } else { "" };
writeln!(
w,
" {{\"f\":{},\"tag\":\"{}\",\"lw\":{:.1},\"lh\":{:.1},\"pw\":{},\"ph\":{},\"sc\":{:.3},\"in\":{},\"wd\":{},\"wf\":{},\"ds\":{},\"ue\":{},\"re\":{},\"se\":{},\"cmd\":{},\"q\":{},\"fl\":{},\"ly\":{},\"gr\":{},\"ir\":{},\"act\":{},\"nr\":{},\"fc\":{},\"gbg\":{},\"gfg\":{},\"gdj\":{}}}{comma}",
s.frame,
escape_json(&s.tag),
s.logical_w,
s.logical_h,
s.phys_w,
s.phys_h,
s.scale,
opt_u64(s.input_enqueued_ns),
opt_u64(s.wake_deadline_ns),
opt_u64(s.wake_fired_ns),
s.draw_start_ns,
s.ui_build_end_ns,
s.render_end_ns,
s.swap_end_ns,
s.cmd_count,
s.stats.quads,
s.stats.flushes,
s.stats.layers,
s.stats.glyph_rows,
s.stats.image_rows,
s.action,
s.needs_redraw,
opt_u32(s.font_check_us),
opt_u64(s.gpu_bg_ns),
opt_u64(s.gpu_fg_ns),
s.gpu_disjoint,
)?;
}
writeln!(w, " ]")?;
writeln!(w, "}}")?;
w.flush()
}
}
fn opt_u64(v: Option<u64>) -> String {
v.map_or_else(|| "null".into(), |n| n.to_string())
}
fn opt_u32(v: Option<u32>) -> String {
v.map_or_else(|| "null".into(), |n| n.to_string())
}
fn escape_json(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => {}
c => out.push(c),
}
}
out
}