Skip to main content

repose_devtools/
lib.rs

1use std::sync::Arc;
2
3use web_time::Instant;
4
5use repose_core::{
6    Brush, Color, FontStyle, FontWeight, Rect, Scene, SceneNode, TextAlign, TextDecoration,
7};
8
9const FPS_HISTORY_LEN: usize = 60;
10
11pub struct Hud {
12    pub inspector_enabled: bool,
13    pub hovered: Option<Rect>,
14    pub hovered_semantics: Option<HoveredInfo>,
15    frame_count: u64,
16    last_frame: Option<Instant>,
17    fps_smooth: f32,
18    fps_history: [f32; FPS_HISTORY_LEN],
19    fps_history_idx: usize,
20    pub metrics: Option<Metrics>,
21    selected_widget: Option<SelectedWidget>,
22}
23
24#[derive(Clone, Debug)]
25pub struct HoveredInfo {
26    pub id: u64,
27    pub role: String,
28    pub label: Option<String>,
29}
30
31#[derive(Clone, Debug)]
32pub struct SelectedWidget {
33    pub id: u64,
34    pub role: String,
35    pub label: Option<String>,
36    pub bounds: Rect,
37}
38
39impl Default for Hud {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl Hud {
46    pub fn new() -> Self {
47        Self {
48            inspector_enabled: false,
49            hovered: None,
50            hovered_semantics: None,
51            frame_count: 0,
52            last_frame: None,
53            fps_smooth: 0.0,
54            fps_history: [0.0; FPS_HISTORY_LEN],
55            fps_history_idx: 0,
56            metrics: None,
57            selected_widget: None,
58        }
59    }
60    pub fn toggle_inspector(&mut self) {
61        self.inspector_enabled = !self.inspector_enabled;
62    }
63    pub fn set_hovered(&mut self, r: Option<Rect>, info: Option<HoveredInfo>) {
64        self.hovered = r;
65        self.hovered_semantics = info;
66    }
67    pub fn select_widget(&mut self, info: SelectedWidget) {
68        self.selected_widget = Some(info);
69    }
70    pub fn clear_selection(&mut self) {
71        self.selected_widget = None;
72    }
73
74    fn update_fps(&mut self, now: Instant) {
75        if let Some(prev) = self.last_frame.replace(now) {
76            let dt = (now - prev).as_secs_f32();
77            if dt > 0.0 && dt < 1.0 {
78                let fps = 1.0 / dt;
79                let a = 0.3;
80                self.fps_smooth = if self.fps_smooth == 0.0 {
81                    fps
82                } else {
83                    (1.0 - a) * self.fps_smooth + a * fps
84                };
85                self.fps_history[self.fps_history_idx] = fps;
86                self.fps_history_idx = (self.fps_history_idx + 1) % FPS_HISTORY_LEN;
87            }
88        }
89    }
90
91    pub fn overlay(&mut self, scene: &mut Scene) {
92        self.frame_count += 1;
93        self.update_fps(Instant::now());
94
95        let bar_x = 8.0;
96        let bar_y = 8.0;
97        let bar_w = 120.0;
98        let bar_h = 24.0;
99
100        if let Some(m) = &self.metrics {
101            scene.nodes.push(SceneNode::Rect {
102                rect: Rect {
103                    x: bar_x,
104                    y: bar_y,
105                    w: bar_w,
106                    h: bar_h,
107                },
108                brush: Brush::Solid(Color::from_hex("#1A1A1ACC")),
109                radius: [4.0; 4],
110            });
111
112            Self::draw_fps_sparkline(
113                scene,
114                bar_x + 2.0,
115                bar_y + bar_h + 4.0,
116                bar_w - 4.0,
117                16.0,
118                &self.fps_history,
119                self.fps_history_idx,
120            );
121
122            let fps_norm = (self.fps_smooth / 60.0).min(1.0);
123            let bar_fill = bar_w * fps_norm;
124            scene.nodes.push(SceneNode::Rect {
125                rect: Rect {
126                    x: bar_x + 2.0,
127                    y: bar_y + 2.0,
128                    w: bar_fill,
129                    h: bar_h - 4.0,
130                },
131                brush: Brush::Solid(if self.fps_smooth >= 50.0 {
132                    Color::from_hex("#44FF44")
133                } else if self.fps_smooth >= 30.0 {
134                    Color::from_hex("#FFAA00")
135                } else {
136                    Color::from_hex("#FF4444")
137                }),
138                radius: [2.0; 4],
139            });
140
141            let mut text_y = bar_y + bar_h + 24.0;
142            Self::push_text(scene, bar_x, text_y, 100.0, &format!("{:.0} fps", self.fps_smooth), "#AAAAAA", 12.0);
143            text_y += 16.0;
144
145            Self::push_text(scene, bar_x, text_y, 100.0, &format!("frame: {}", self.frame_count), "#888888", 11.0);
146            text_y += 14.0;
147            Self::push_text(scene, bar_x, text_y, 120.0, &format!("build: {:.1}ms", m.build_ms), "#888888", 11.0);
148            text_y += 14.0;
149            Self::push_text(scene, bar_x, text_y, 120.0, &format!("layout: {:.1}ms", m.layout_ms), "#888888", 11.0);
150            text_y += 14.0;
151            Self::push_text(scene, bar_x, text_y, 120.0, &format!("paint: {:.1}ms", m.paint_ms), "#888888", 11.0);
152            text_y += 14.0;
153            Self::push_text(scene, bar_x, text_y, 120.0, &format!("widgets: {}", m.widget_count), "#888888", 11.0);
154            text_y += 14.0;
155            Self::push_text(scene, bar_x, text_y, 120.0, &format!("signals: {}", m.signal_count), "#888888", 11.0);
156            text_y += 14.0;
157            Self::push_text(scene, bar_x, text_y, 140.0, &format!("scene: {}", m.scene_nodes), "#888888", 11.0);
158            text_y += 14.0;
159            Self::push_text(
160                scene,
161                bar_x,
162                text_y,
163                200.0,
164                &format!(
165                    "taffy: {:+}/{:+}",
166                    m.taffy_created, m.taffy_reused
167                ),
168                "#888888",
169                11.0,
170            );
171            text_y += 14.0;
172            Self::push_text(
173                scene,
174                bar_x,
175                text_y,
176                200.0,
177                &format!("layout: {}h/{}m", m.layout_hits, m.layout_misses),
178                "#888888",
179                11.0,
180            );
181            text_y += 14.0;
182            Self::push_text(
183                scene,
184                bar_x,
185                text_y,
186                200.0,
187                &format!(
188                    "paint cache: {}h/{}m ({} culled)",
189                    m.paint_cache_hits, m.paint_cache_misses, m.paint_culled
190                ),
191                "#888888",
192                11.0,
193            );
194            text_y += 14.0;
195
196            if let Some(hover) = &self.hovered_semantics {
197                text_y += 6.0;
198                Self::push_text(
199                    scene,
200                    bar_x,
201                    text_y,
202                    200.0,
203                    &format!("↳ {}: {:?}", hover.id, hover.role),
204                    "#44AAFF",
205                    11.0,
206                );
207                if let Some(lbl) = &hover.label {
208                    text_y += 14.0;
209                    Self::push_text(
210                        scene,
211                        bar_x,
212                        text_y,
213                        200.0,
214                        &format!("  \"{}\"", lbl),
215                        "#66CCFF",
216                        10.0,
217                    );
218                }
219            }
220        }
221
222        if let Some(r) = self.hovered {
223            scene.nodes.push(SceneNode::Border {
224                rect: r,
225                color: Color::from_hex("#44AAFF"),
226                width: 2.0,
227                radius: [2.0; 4],
228            });
229        }
230
231        if let Some(sel) = &self.selected_widget {
232            scene.nodes.push(SceneNode::Border {
233                rect: sel.bounds,
234                color: Color::from_hex("#FFAA00"),
235                width: 2.0,
236                radius: [2.0; 4],
237            });
238        }
239    }
240
241    /// Push a single HUD text line.
242    fn push_text(scene: &mut Scene, x: f32, y: f32, w: f32, txt: &str, color: &str, size: f32) {
243        scene.nodes.push(SceneNode::Text {
244            rect: Rect {
245                x,
246                y,
247                w,
248                h: 14.0,
249            },
250            text: Arc::<str>::from(txt.to_string()),
251            color: Color::from_hex(color),
252            size,
253            font_family: None,
254            text_align: TextAlign::Unspecified,
255            font_weight: FontWeight::NORMAL,
256            font_style: FontStyle::Normal,
257            text_decoration: TextDecoration::default(),
258            letter_spacing: 0.0,
259            line_height: 0.0,
260            extra_style: Default::default(),
261            url: None,
262            font_variation_settings: None,
263        });
264    }
265
266    /// Draw a horizontal bar-chart sparkline from a rolling FPS history.
267    ///
268    /// The newest sample is drawn at the right edge; older samples scroll left.
269    fn draw_fps_sparkline(
270        scene: &mut Scene,
271        x: f32,
272        y: f32,
273        w: f32,
274        h: f32,
275        history: &[f32],
276        idx: usize,
277    ) {
278        let n = history.len();
279        if n == 0 || idx == 0 {
280            return;
281        }
282        scene.nodes.push(SceneNode::Rect {
283            rect: Rect { x, y, w, h },
284            brush: Brush::Solid(Color::from_hex("#1A1A1ACC")),
285            radius: [2.0; 4],
286        });
287        let bin_w = w / n as f32;
288        let max_fps = 60.0f32.max(history.iter().copied().fold(0.0f32, f32::max));
289        for i in 0..n {
290            // Walk oldest->newest: idx points one past the newest sample.
291            let sample = history[(i + idx) % n];
292            let frac = (sample / max_fps).min(1.0);
293            let bh = (h - 2.0) * frac;
294            let color = if frac >= 0.83 {
295                "#44FF44"
296            } else if frac >= 0.5 {
297                "#FFAA00"
298            } else {
299                "#FF4444"
300            };
301            scene.nodes.push(SceneNode::Rect {
302                rect: Rect {
303                    x: x + i as f32 * bin_w,
304                    y: y + (h - 2.0) - bh,
305                    w: (bin_w - 1.0).max(0.5),
306                    h: bh.max(1.0),
307                },
308                brush: Brush::Solid(Color::from_hex(color)),
309                radius: [0.0; 4],
310            });
311        }
312    }
313}
314
315#[derive(Clone, Debug, Default)]
316pub struct Metrics {
317    pub build_ms: f32,
318    pub layout_ms: f32,
319    pub paint_ms: f32,
320    pub scene_nodes: usize,
321    pub widget_count: usize,
322    pub signal_count: usize,
323    // Layout engine counters.
324    pub taffy_created: usize,
325    pub taffy_reused: usize,
326    pub layout_hits: usize,
327    pub layout_misses: usize,
328    pub paint_cache_hits: usize,
329    pub paint_cache_misses: usize,
330    pub paint_culled: usize,
331}
332
333pub struct Inspector {
334    pub hud: Hud,
335}
336impl Default for Inspector {
337    fn default() -> Self {
338        Self::new()
339    }
340}
341
342impl Inspector {
343    pub fn new() -> Self {
344        Self { hud: Hud::new() }
345    }
346    pub fn frame(&mut self, scene: &mut Scene) {
347        if self.hud.inspector_enabled {
348            self.hud.overlay(scene);
349        }
350    }
351}