datatui/components/
fps.rs1use std::time::Instant;
2
3use color_eyre::Result;
4use ratatui::{
5 Frame,
6 layout::{Constraint, Layout, Rect},
7 style::{Style, Stylize},
8 text::Span,
9 widgets::Paragraph,
10};
11
12use super::Component;
13
14use crate::action::Action;
15
16#[derive(Debug, Clone, PartialEq)]
17pub struct FpsCounter {
18 last_tick_update: Instant,
19 tick_count: u32,
20 ticks_per_second: f64,
21
22 last_frame_update: Instant,
23 frame_count: u32,
24 frames_per_second: f64,
25}
26
27impl Default for FpsCounter {
28 fn default() -> Self {
29 Self::new()
30 }
31}
32
33impl FpsCounter {
34 pub fn new() -> Self {
35 Self {
36 last_tick_update: Instant::now(),
37 tick_count: 0,
38 ticks_per_second: 0.0,
39 last_frame_update: Instant::now(),
40 frame_count: 0,
41 frames_per_second: 0.0,
42 }
43 }
44
45 fn app_tick(&mut self) -> Result<()> {
46 self.tick_count += 1;
47 let now = Instant::now();
48 let elapsed = (now - self.last_tick_update).as_secs_f64();
49 if elapsed >= 1.0 {
50 self.ticks_per_second = self.tick_count as f64 / elapsed;
51 self.last_tick_update = now;
52 self.tick_count = 0;
53 }
54 Ok(())
55 }
56
57 fn render_tick(&mut self) -> Result<()> {
58 self.frame_count += 1;
59 let now = Instant::now();
60 let elapsed = (now - self.last_frame_update).as_secs_f64();
61 if elapsed >= 1.0 {
62 self.frames_per_second = self.frame_count as f64 / elapsed;
63 self.last_frame_update = now;
64 self.frame_count = 0;
65 }
66 Ok(())
67 }
68}
69
70impl Component for FpsCounter {
71 fn update(&mut self, action: Action) -> Result<Option<Action>> {
72 match action {
73 Action::Tick => self.app_tick()?,
74 Action::Render => self.render_tick()?,
75 _ => {}
76 };
77 Ok(None)
78 }
79
80 fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
81 let [top, _] = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(area);
82 let message = format!(
83 "{:.2} ticks/sec, {:.2} FPS",
84 self.ticks_per_second, self.frames_per_second
85 );
86 let span = Span::styled(message, Style::new().dim());
87 let paragraph = Paragraph::new(span).right_aligned();
88 frame.render_widget(paragraph, top);
89 Ok(())
90 }
91}