1use crate::element::{div, text, Element, IntoElement};
10use crate::engine::VeloxEngine;
11use crate::fmt;
12use crate::pod::FrameScope;
13use crate::solver::Region;
14use crate::style::{Color, Styled};
15
16#[derive(Copy, Clone, PartialEq, Eq, Debug)]
18pub struct InspectorConfig {
19 pub enabled: bool,
20 pub show_box_model: bool,
21 pub show_dirty_rects: bool,
22 pub show_perf_hud: bool,
23}
24
25impl Default for InspectorConfig {
26 fn default() -> Self {
27 Self::ALL
28 }
29}
30
31impl InspectorConfig {
32 pub const OFF: Self = Self {
33 enabled: false,
34 show_box_model: false,
35 show_dirty_rects: false,
36 show_perf_hud: false,
37 };
38
39 pub const ALL: Self = Self {
40 enabled: true,
41 show_box_model: true,
42 show_dirty_rects: true,
43 show_perf_hud: true,
44 };
45}
46
47#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
49pub struct FrameTelemetry {
50 pub layout_solve_count: u32,
51 pub partial_relayout_count: u32,
52 pub relayout_boundary_hits: u32,
53 pub fast_paint_pass_count: u32,
54 pub subview_cache_hits: u32,
55 pub arena_used_bytes: usize,
56 pub draw_op_count: usize,
57 pub hit_region_count: usize,
58 pub dirty_rect_count: usize,
59 pub hovered_bounds: Option<Region>,
60 pub hovered_id: Option<u32>,
61}
62
63pub fn capture_telemetry(engine: &VeloxEngine, pointer_pos: Option<(i16, i16)>) -> FrameTelemetry {
65 let mut hovered_bounds = None;
66 let mut hovered_id = None;
67 if let Some((px, py)) = pointer_pos {
68 for hit in engine.cached_hit_regions().iter().rev() {
69 if hit.bounds.intersect(hit.clip).contains(px, py) {
70 hovered_bounds = Some(hit.bounds);
71 hovered_id = hit.id;
72 break;
73 }
74 }
75 }
76 FrameTelemetry {
77 layout_solve_count: engine.layout_solve_count(),
78 partial_relayout_count: engine.partial_relayout_count(),
79 relayout_boundary_hits: engine.relayout_boundary_hits(),
80 fast_paint_pass_count: engine.fast_paint_pass_count(),
81 subview_cache_hits: engine.subview_cache_hits(),
82 arena_used_bytes: engine.last_arena_used_bytes(),
83 draw_op_count: engine.cached_draw_ops().len(),
84 hit_region_count: engine.cached_hit_regions().len(),
85 dirty_rect_count: engine.last_damage().len(),
86 hovered_bounds,
87 hovered_id,
88 }
89}
90
91pub fn build_inspector_overlay<'a>(
93 cx: &'a FrameScope,
94 telemetry: &FrameTelemetry,
95 dirty_rects: &[Region],
96 cfg: InspectorConfig,
97) -> Element<'a> {
98 if !cfg.enabled {
99 return div().w(0).h(0).into_element(cx);
100 }
101
102 let mut layer = div().overlay().pos(0, 0).w_full().h_full();
103
104 if cfg.show_dirty_rects {
106 for &r in dirty_rects {
107 if !r.is_empty() {
108 layer = layer.child(
109 cx,
110 div()
111 .pos(r.x, r.y)
112 .w(r.w)
113 .h(r.h)
114 .bg(Color::rgba(239, 68, 68, 26))
115 .border(1, Color::rgba(239, 68, 68, 210)),
116 );
117 }
118 }
119 }
120
121 if cfg.show_box_model {
123 if let Some(hb) = telemetry.hovered_bounds {
124 layer = layer.child(
125 cx,
126 div()
127 .pos(hb.x, hb.y)
128 .w(hb.w)
129 .h(hb.h)
130 .bg(Color::rgba(56, 189, 248, 42))
131 .border(1, Color::rgba(56, 189, 248, 235)),
132 );
133 let badge_y = if hb.y >= 20 { hb.y - 18 } else { hb.bottom() + 2 };
134 let label = fmt!(cx, "{}x{} @ ({},{})", hb.w, hb.h, hb.x, hb.y);
135 layer = layer.child(
136 cx,
137 div()
138 .pos(hb.x, badge_y)
139 .px(6)
140 .py(2)
141 .rounded(4)
142 .bg(Color::rgba(15, 23, 42, 230))
143 .child(cx, text(label).size(10).color(Color::rgb(125, 211, 252))),
144 );
145 }
146 }
147
148 if cfg.show_perf_hud {
150 let l1 = fmt!(
151 cx,
152 "Solves:{} L2:{} Pass4:{}",
153 telemetry.layout_solve_count,
154 telemetry.partial_relayout_count,
155 telemetry.fast_paint_pass_count
156 );
157 let l2 = fmt!(
158 cx,
159 "Ops:{} Hits:{} Dirty:{}",
160 telemetry.draw_op_count,
161 telemetry.hit_region_count,
162 telemetry.dirty_rect_count
163 );
164 let l3 = fmt!(
165 cx,
166 "Arena:{}B SubCache:{}",
167 telemetry.arena_used_bytes,
168 telemetry.subview_cache_hits
169 );
170 layer = layer.child(
171 cx,
172 div()
173 .pos(8, 8)
174 .flex_col()
175 .gap(2)
176 .px(8)
177 .py(6)
178 .rounded(6)
179 .bg(Color::rgba(15, 23, 42, 220))
180 .border(1, Color::rgba(99, 102, 241, 180))
181 .child(
182 cx,
183 text("Velox Inspector")
184 .size(11)
185 .color(Color::rgb(165, 180, 252)),
186 )
187 .child(cx, text(l1).size(10).color(Color::rgb(226, 232, 240)))
188 .child(cx, text(l2).size(10).color(Color::rgb(226, 232, 240)))
189 .child(cx, text(l3).size(10).color(Color::rgb(148, 163, 184))),
190 );
191 }
192
193 layer.into_element(cx)
194}
195
196#[derive(Copy, Clone, Debug)]
202pub struct FrameBudgetRing {
203 samples_us: [u32; 64],
204 cursor: usize,
205 count: usize,
206}
207
208impl Default for FrameBudgetRing {
209 #[inline(always)]
210 fn default() -> Self {
211 Self::new()
212 }
213}
214
215impl FrameBudgetRing {
216 #[inline(always)]
217 pub const fn new() -> Self {
218 Self {
219 samples_us: [0; 64],
220 cursor: 0,
221 count: 0,
222 }
223 }
224
225 #[inline]
227 pub fn push_us(&mut self, us: u32) {
228 self.samples_us[self.cursor] = us;
229 self.cursor = (self.cursor + 1) & 63;
230 if self.count < 64 {
231 self.count += 1;
232 }
233 }
234
235 #[inline]
236 pub const fn len(&self) -> usize {
237 self.count
238 }
239
240 #[inline]
241 pub const fn is_empty(&self) -> bool {
242 self.count == 0
243 }
244
245 pub fn avg_us(&self) -> u32 {
247 if self.count == 0 {
248 return 0;
249 }
250 let mut sum = 0u64;
251 for i in 0..self.count {
252 sum += self.samples_us[i] as u64;
253 }
254 (sum / self.count as u64) as u32
255 }
256
257 pub fn max_us(&self) -> u32 {
259 let mut peak = 0u32;
260 for i in 0..self.count {
261 if self.samples_us[i] > peak {
262 peak = self.samples_us[i];
263 }
264 }
265 peak
266 }
267
268 #[inline]
270 pub fn sample_at(&self, idx: usize) -> u32 {
271 if idx >= self.count {
272 return 0;
273 }
274 let start = if self.count < 64 { 0 } else { self.cursor };
275 self.samples_us[(start + idx) & 63]
276 }
277}
278
279#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
281pub struct StyleOverride {
282 pub target_id: u32,
283 pub padding: Option<i8>,
284 pub gap: Option<i8>,
285 pub rounded: Option<u8>,
286 pub bg: Option<Color>,
287 pub border_color: Option<Color>,
288}
289
290#[derive(Clone, Debug)]
292pub struct LiveStyleOverrides {
293 entries: [Option<StyleOverride>; 16],
294 revision: u32,
295}
296
297impl Default for LiveStyleOverrides {
298 #[inline(always)]
299 fn default() -> Self {
300 Self::new()
301 }
302}
303
304impl LiveStyleOverrides {
305 #[inline(always)]
306 pub const fn new() -> Self {
307 Self {
308 entries: [None; 16],
309 revision: 0,
310 }
311 }
312
313 #[inline(always)]
314 pub const fn revision(&self) -> u32 {
315 self.revision
316 }
317
318 pub fn set(&mut self, ov: StyleOverride) -> bool {
320 for slot in &mut self.entries {
321 if let Some(existing) = slot {
322 if existing.target_id == ov.target_id {
323 *existing = ov;
324 self.revision = self.revision.wrapping_add(1);
325 return true;
326 }
327 }
328 }
329 for slot in &mut self.entries {
330 if slot.is_none() {
331 *slot = Some(ov);
332 self.revision = self.revision.wrapping_add(1);
333 return true;
334 }
335 }
336 false
337 }
338
339 #[inline]
341 pub fn get(&self, target_id: u32) -> Option<StyleOverride> {
342 for slot in &self.entries {
343 if let Some(ov) = *slot {
344 if ov.target_id == target_id {
345 return Some(ov);
346 }
347 }
348 }
349 None
350 }
351
352 pub fn apply_to_style(&self, target_id: u32, style: &mut crate::style::Style) -> bool {
354 let Some(ov) = self.get(target_id) else {
355 return false;
356 };
357 if let Some(p) = ov.padding {
358 style.padding = crate::style::Edges::all(p);
359 }
360 if let Some(g) = ov.gap {
361 style.gap = g;
362 }
363 if let Some(r) = ov.rounded {
364 style.set_rounded(r);
365 }
366 if let Some(bg) = ov.bg {
367 style.bg = bg;
368 }
369 if let Some(bc) = ov.border_color {
370 style.border_color = bc;
371 }
372 true
373 }
374
375 pub fn load_hot_reload_sheet(&mut self, sheet: &str) -> usize {
378 let mut applied = 0usize;
379 for raw_line in sheet.lines() {
380 let line = raw_line.trim();
381 if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
382 continue;
383 }
384 let Some((id_str, rest)) = line.split_once(':') else {
385 continue;
386 };
387 let Ok(target_id) = id_str.trim().parse::<u32>() else {
388 continue;
389 };
390 let mut ov = self.get(target_id).unwrap_or(StyleOverride {
391 target_id,
392 ..StyleOverride::default()
393 });
394 for tok in rest.split_whitespace() {
395 if let Some((k, v)) = tok.split_once('=') {
396 match k {
397 "pad" | "padding" => {
398 if let Ok(p) = v.parse::<i8>() {
399 ov.padding = Some(p);
400 }
401 }
402 "gap" => {
403 if let Ok(g) = v.parse::<i8>() {
404 ov.gap = Some(g);
405 }
406 }
407 "rounded" | "radius" => {
408 if let Ok(r) = v.parse::<u8>() {
409 ov.rounded = Some(r);
410 }
411 }
412 "bg" => {
413 if let Some(c) = crate::svg::parse_svg_color(v) {
414 ov.bg = Some(c);
415 }
416 }
417 "border" => {
418 if let Some(c) = crate::svg::parse_svg_color(v) {
419 ov.border_color = Some(c);
420 }
421 }
422 _ => {}
423 }
424 }
425 }
426 if self.set(ov) {
427 applied += 1;
428 }
429 }
430 applied
431 }
432}
433
434#[derive(Clone, Debug, Default)]
436pub struct LiveInspectorState {
437 pub config: InspectorConfig,
438 pub selected_node_id: Option<u32>,
439 pub selected_bounds: Option<Region>,
440 pub budget: FrameBudgetRing,
441 pub overrides: LiveStyleOverrides,
442}
443
444impl LiveInspectorState {
445 pub fn new() -> Self {
446 Self::default()
447 }
448
449 pub fn pick_node_at(&mut self, engine: &VeloxEngine, px: i16, py: i16) -> Option<u32> {
451 for hit in engine.cached_hit_regions().iter().rev() {
452 if hit.bounds.intersect(hit.clip).contains(px, py) {
453 if let Some(id) = hit.id {
454 self.selected_node_id = Some(id);
455 self.selected_bounds = Some(hit.bounds);
456 return Some(id);
457 }
458 }
459 }
460 None
461 }
462}
463
464pub fn build_live_devtools_panel<'a>(
466 cx: &'a FrameScope,
467 state: &LiveInspectorState,
468 telemetry: FrameTelemetry,
469) -> Element<'a> {
470 let mut bars = div().flex_row().items_end().gap(2).h(34);
471 let peak = state.budget.max_us().max(1000);
472 let n = state.budget.len();
473 let start = n.saturating_sub(24);
474 for i in start..n {
475 let us = state.budget.sample_at(i);
476 let bh = ((us as u64 * 30) / peak as u64).clamp(3, 30) as i16;
477 let col = if us > 16_000 {
478 Color::rgb(239, 68, 68)
479 } else if us > 8_000 {
480 Color::rgb(245, 158, 11)
481 } else {
482 Color::rgb(52, 211, 153)
483 };
484 bars = bars.child(cx, div().w(5).h(bh).rounded(2).bg(col));
485 }
486
487 let sel_text = if let (Some(id), Some(b)) = (state.selected_node_id, state.selected_bounds) {
488 fmt!(cx, "Picked #{}: {}x{} @({},{})", id, b.w, b.h, b.x, b.y)
489 } else {
490 crate::arena::StrRef::from("Picked: None (click element to inspect)")
491 };
492 let perf_line = fmt!(
493 cx,
494 "Avg:{}us Peak:{}us | L2:{} Pass4:{} | HotRev:{}",
495 state.budget.avg_us(),
496 state.budget.max_us(),
497 telemetry.partial_relayout_count,
498 telemetry.fast_paint_pass_count,
499 state.overrides.revision()
500 );
501
502 div()
503 .flex_col()
504 .gap(6)
505 .p(10)
506 .rounded(8)
507 .bg(Color::rgba(15, 23, 42, 235))
508 .border(1, Color::rgba(99, 102, 241, 190))
509 .child(
510 cx,
511 text("Velox Live DevTools (Waterfall + Hot Style Reload)")
512 .size(11)
513 .color(Color::rgb(165, 180, 252)),
514 )
515 .child(cx, bars)
516 .child(cx, text(perf_line).size(10).color(Color::rgb(226, 232, 240)))
517 .child(cx, text(sel_text).size(10).color(Color::rgb(125, 211, 252)))
518 .into_element(cx)
519}