Skip to main content

cbtop/app/
mod.rs

1//! cbtop Application State Machine
2//!
3//! Manages the TUI application lifecycle using presentar-terminal.
4//! Implements REAL load generation using trueno compute bricks.
5//!
6//! Citations:
7//! - [Gregg 2020] "Systems Performance" 2nd ed. Addison-Wesley. ISBN:978-0-13-682015-4
8//! - [Hennessy & Patterson 2017] "Computer Architecture" 6th ed. ISBN:978-0-12-811905-1
9
10mod hardware;
11mod input;
12mod metrics;
13mod panels;
14mod render;
15
16pub use hardware::{DiskMetrics, HardwareInfo, LoadMetrics, MemoryBreakdown, NetworkMetrics};
17pub use panels::ActivePanel;
18
19use std::time::{Duration, Instant};
20
21use presentar_terminal::direct::{CellBuffer, DiffRenderer};
22use presentar_terminal::{ColorMode, Theme};
23
24use crate::bricks::generators::SimdLoadBrick;
25use crate::bricks::panels::{
26    ConfigPanelBrick, CpuPanelBrick, GpuPanelBrick, HelpPanelBrick, LoadControlPanelBrick,
27    MemoryPanelBrick, OverviewPanelBrick, PciePanelBrick, ThermalPanelBrick,
28};
29use crate::config::{ComputeBackend, Config, WorkloadType};
30use crate::error::CbtopError;
31use crate::ring_buffer::RingBuffer;
32
33/// Application state
34pub struct CbtopApp {
35    /// Configuration
36    pub(crate) config: Config,
37    /// Active panel
38    pub(crate) active_panel: ActivePanel,
39    /// Is load generation running
40    pub(crate) is_running: bool,
41    /// Current load intensity
42    pub(crate) intensity: f64,
43    /// Current backend
44    pub(crate) backend: ComputeBackend,
45    /// Current workload
46    pub(crate) workload: WorkloadType,
47    /// Problem size
48    pub(crate) problem_size: usize,
49
50    /// Hardware information
51    pub(crate) hardware: HardwareInfo,
52    /// SIMD load generator (real compute)
53    pub(crate) simd_generator: SimdLoadBrick,
54    /// Real-time load metrics
55    pub(crate) load_metrics: LoadMetrics,
56
57    /// CPU usage history (REAL from /proc/stat)
58    pub(crate) cpu_history: RingBuffer<f64>,
59    /// Bricks/sec history
60    pub(crate) bricks_history: RingBuffer<f64>,
61    /// Frame times for FPS calculation
62    pub(crate) frame_times: RingBuffer<f64>,
63    /// Last CPU stat for delta calculation
64    pub(crate) last_cpu_stat: Option<(u64, u64)>,
65    /// Last network stat for rate calculation (rx_bytes, tx_bytes, time)
66    pub(crate) last_network_stat: Option<(u64, u64, Instant)>,
67
68    /// Panel Bricks
69    pub(crate) overview_panel: OverviewPanelBrick,
70    pub(crate) cpu_panel: CpuPanelBrick,
71    pub(crate) gpu_panel: GpuPanelBrick,
72    pub(crate) help_panel: HelpPanelBrick,
73    pub(crate) memory_panel: MemoryPanelBrick,
74    pub(crate) thermal_panel: ThermalPanelBrick,
75    pub(crate) pcie_panel: PciePanelBrick,
76    pub(crate) load_panel: LoadControlPanelBrick,
77    pub(crate) config_panel: ConfigPanelBrick,
78
79    /// Terminal buffer
80    pub(crate) buffer: CellBuffer,
81    /// Renderer
82    pub(crate) renderer: DiffRenderer,
83    /// Theme for colors
84    pub(crate) theme: Theme,
85    /// Last frame time
86    pub(crate) last_frame: Instant,
87    /// Frame count
88    pub(crate) frame_count: u64,
89
90    /// Should quit
91    pub(crate) should_quit: bool,
92}
93
94impl CbtopApp {
95    /// Create new application with config
96    pub fn new(config: Config) -> Result<Self, CbtopError> {
97        let (width, height) = crossterm::terminal::size()?;
98        Ok(Self::with_size(config, width, height))
99    }
100
101    /// Build the application for a terminal of known size (no terminal query).
102    pub(crate) fn with_size(config: Config, width: u16, height: u16) -> Self {
103        // Detect hardware at startup
104        let hardware = HardwareInfo::detect();
105
106        // Create SIMD load generator with configured problem size
107        let mut simd_generator = SimdLoadBrick::new(config.problem_size);
108        simd_generator.set_intensity(config.load_profile.intensity());
109
110        Self {
111            config: config.clone(),
112            active_panel: ActivePanel::Overview,
113            is_running: false,
114            intensity: config.load_profile.intensity(),
115            backend: config.backend,
116            workload: config.workload,
117            problem_size: config.problem_size,
118            hardware,
119            simd_generator,
120            load_metrics: LoadMetrics::default(),
121            cpu_history: RingBuffer::new(120),
122            bricks_history: RingBuffer::new(120),
123            frame_times: RingBuffer::new(60),
124            last_cpu_stat: None,
125            last_network_stat: None,
126            overview_panel: OverviewPanelBrick::new(),
127            cpu_panel: CpuPanelBrick::new(),
128            gpu_panel: GpuPanelBrick::new(),
129            help_panel: HelpPanelBrick::new(),
130            memory_panel: MemoryPanelBrick::new(),
131            thermal_panel: ThermalPanelBrick::new(),
132            pcie_panel: PciePanelBrick::new(),
133            load_panel: LoadControlPanelBrick::new(),
134            config_panel: ConfigPanelBrick::new(),
135            buffer: CellBuffer::new(width, height),
136            renderer: DiffRenderer::with_color_mode(ColorMode::TrueColor),
137            theme: Theme::tokyo_night(),
138            last_frame: Instant::now(),
139            frame_count: 0,
140            should_quit: false,
141        }
142    }
143
144    /// Run the application main loop
145    pub fn run(&mut self) -> Result<(), CbtopError> {
146        use crossterm::{
147            event::{self, Event, KeyEventKind},
148            terminal::{
149                disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
150            },
151            ExecutableCommand,
152        };
153        use std::io::stdout;
154
155        // Enter TUI mode
156        enable_raw_mode()?;
157        stdout().execute(EnterAlternateScreen)?;
158        stdout().execute(crossterm::cursor::Hide)?;
159
160        let refresh = Duration::from_millis(self.config.refresh_ms);
161
162        while !self.should_quit {
163            // Handle events
164            if event::poll(refresh)? {
165                if let Event::Key(key) = event::read()? {
166                    if key.kind == KeyEventKind::Press {
167                        self.handle_key(key.code);
168                    }
169                }
170            }
171
172            // Run REAL load generation if enabled
173            if self.is_running {
174                self.run_load_iteration();
175            }
176
177            // Collect REAL metrics
178            self.collect_real_metrics();
179
180            // Render
181            self.render()?;
182        }
183
184        // Cleanup
185        stdout().execute(crossterm::cursor::Show)?;
186        stdout().execute(LeaveAlternateScreen)?;
187        disable_raw_mode()?;
188
189        Ok(())
190    }
191}
192
193#[cfg(test)]
194mod sparklines_tests;