返回 CodeWhale
data.rs
1 //! Live data displays: `cargo run --example data`.
2 //!
3 //! A sparkline takes a new value every 400 ms, the trend draws in, and the
4 //! bars glide to new values every three seconds. r replays, m switches
5 //! between full and reduced motion, q or Escape exits.
6 //!
7 //! `--json FILE` shows one agent-sent [`DataDisplay`] instead.
8 //! `--text` prints the final frame and each display's plain description.
9 //! `--svg DIR` writes frames at fixed draw-in points.
10
11 use std::{
12 io,
13 path::PathBuf,
14 time::{Duration, Instant},
15 };
16
17 use codewhale_ratatui::{
18 DataBarItem, DataDisplay, DataWords, MotionEasing, MotionMode, MotionPolicy, MotionStep,
19 MotionTiming, Paint, Role, Theme,
20 testing::{self, Profile},
21 };
22 use crossterm::{
23 event::{self, Event, KeyCode, KeyEventKind},
24 execute,
25 terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
26 };
27 use ratatui::{Terminal, backend::CrosstermBackend, buffer::Buffer, layout::Rect};
28
29 const TICK: Duration = Duration::from_millis(400);
30 const RESHUFFLE: Duration = Duration::from_secs(3);
31 const DRAW_IN: MotionTiming =
32 MotionTiming::space(Duration::from_millis(1_400), MotionEasing::EaseOut);
33 const GLIDE: MotionTiming = MotionTiming::PANEL;
34
35 struct Noise(u64);
36
37 impl Noise {
38 fn next(&mut self) -> f64 {
39 self.0 = self
40 .0
41 .wrapping_mul(6_364_136_223_846_793_005)
42 .wrapping_add(1);
43 (self.0 >> 33) as f64 / f64::from(1u32 << 31)
44 }
45 }
46
47 struct Board {
48 noise: Noise,
49 requests: Vec<f64>,
50 latency: Vec<f64>,
51 bars: DataDisplay,
52 bars_before: DataDisplay,
53 draw: MotionStep,
54 glide: MotionStep,
55 agent: Option<DataDisplay>,
56 }
57
58 fn crate_bars(noise: &mut Noise) -> DataDisplay {
59 DataDisplay::Bars {
60 label: "Tests by crate".into(),
61 unit: "tests".into(),
62 items: ["engine", "tui", "runtime", "protocol", "config"]
63 .into_iter()
64 .map(|name| DataBarItem::new(name, (40.0 + noise.next() * 400.0).round()))
65 .collect(),
66 }
67 }
68
69 impl Board {
70 fn new(agent: Option<DataDisplay>) -> Self {
71 let mut noise = Noise(7);
72 let latency = (0..96)
73 .map(|i| 80.0 + 45.0 * (f64::from(i) / 9.0).sin() + noise.next() * 30.0)
74 .collect();
75 let requests = (0..40).map(|_| 20.0 + noise.next() * 60.0).collect();
76 let bars = crate_bars(&mut noise);
77 Self {
78 noise,
79 requests,
80 latency,
81 bars_before: DataDisplay::Bars {
82 label: String::new(),
83 unit: String::new(),
84 items: Vec::new(),
85 },
86 bars,
87 draw: MotionStep::at_rest(0.0),
88 glide: MotionStep::at_rest(1.0),
89 agent,
90 }
91 }
92
93 fn replay(&mut self, now: Instant, policy: MotionPolicy) {
94 self.draw = MotionStep::at_rest(0.0);
95 self.draw.go(1.0, now, DRAW_IN, policy);
96 }
97
98 fn tick(&mut self) {
99 let last = self.requests.last().copied().unwrap_or(50.0);
100 let next = (last + (self.noise.next() - 0.5) * 30.0).clamp(5.0, 120.0);
101 self.requests.push(next.round());
102 if self.requests.len() > 200 {
103 self.requests.remove(0);
104 }
105 }
106
107 fn reshuffle(&mut self, now: Instant, policy: MotionPolicy) {
108 self.bars_before = std::mem::replace(&mut self.bars, crate_bars(&mut self.noise));
109 self.glide = MotionStep::at_rest(0.0);
110 self.glide.go(1.0, now, GLIDE, policy);
111 }
112
113 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme, draw: f32, glide: f32) {
114 buf.set_style(area, theme.bg(Role::Background));
115 let inner = Rect::new(
116 area.x + 2,
117 area.y + 1,
118 area.width.saturating_sub(4),
119 area.height.saturating_sub(2),
120 );
121 if let Some(agent) = &self.agent {
122 agent.view().drawn(draw).paint(inner, buf, theme);
123 return;
124 }
125 let row =
126 |y: u16, h: u16| Rect::new(inner.x, inner.y + y, inner.width, h).intersection(inner);
127 let requests = DataDisplay::Sparkline {
128 label: "Requests".into(),
129 unit: "rpm".into(),
130 values: self.requests.clone(),
131 };
132 let latency = DataDisplay::Trend {
133 label: "Latency".into(),
134 unit: "ms".into(),
135 values: self.latency.clone(),
136 rows: Some(9),
137 };
138 requests.view().drawn(draw).paint(row(0, 1), buf, theme);
139 latency.view().drawn(draw).paint(row(2, 9), buf, theme);
140 self.bars
141 .view()
142 .from(&self.bars_before)
143 .drawn(glide.min(draw))
144 .paint(row(12, 6), buf, theme);
145 }
146
147 fn displays(&self) -> Vec<DataDisplay> {
148 if let Some(agent) = &self.agent {
149 return vec![agent.clone()];
150 }
151 vec![
152 DataDisplay::Sparkline {
153 label: "Requests".into(),
154 unit: "rpm".into(),
155 values: self.requests.clone(),
156 },
157 DataDisplay::Trend {
158 label: "Latency".into(),
159 unit: "ms".into(),
160 values: self.latency.clone(),
161 rows: Some(9),
162 },
163 self.bars.clone(),
164 ]
165 }
166 }
167
168 fn main() -> io::Result<()> {
169 let args: Vec<String> = std::env::args().skip(1).collect();
170 let value = |flag: &str| {
171 args.iter()
172 .position(|a| a == flag)
173 .and_then(|i| args.get(i + 1))
174 .cloned()
175 };
176 let agent = match value("--json") {
177 Some(path) => {
178 let json = std::fs::read_to_string(&path)?;
179 match DataDisplay::from_json(&json) {
180 Ok(shown) => Some(shown),
181 Err(e) => {
182 eprintln!("{path}: {e}");
183 std::process::exit(2);
184 }
185 }
186 }
187 None => None,
188 };
189 let board = Board::new(agent);
190
191 if args.iter().any(|a| a == "--text") {
192 let buf = testing::render(84, 20, |area, buf| {
193 board.paint(area, buf, &Profile::DarkTrue.theme(), 1.0, 1.0);
194 });
195 println!("{}", testing::text(&buf));
196 for shown in board.displays() {
197 println!("{}", shown.describe(&DataWords::default()));
198 }
199 return Ok(());
200 }
201 if let Some(dir) = value("--svg") {
202 let dir = PathBuf::from(dir);
203 std::fs::create_dir_all(&dir)?;
204 let theme = Profile::DarkTrue.theme();
205 for (i, at) in [0.2_f32, 0.5, 0.8, 1.0].into_iter().enumerate() {
206 let buf = testing::render(84, 20, |area, buf| board.paint(area, buf, &theme, at, at));
207 let path = dir.join(format!("data-{i}.svg"));
208 std::fs::write(&path, testing::svg(&buf, &theme))?;
209 println!("{}", path.display());
210 }
211 return Ok(());
212 }
213 run(board)
214 }
215
216 fn run(mut board: Board) -> io::Result<()> {
217 enable_raw_mode()?;
218 let mut out = io::stdout();
219 execute!(out, EnterAlternateScreen)?;
220 let mut terminal = Terminal::new(CrosstermBackend::new(out))?;
221 let theme = Theme::detect().tui();
222 let mut mode = MotionMode::Full;
223 let mut policy = MotionPolicy::new(mode, &theme);
224 let start = Instant::now();
225 board.replay(start, policy);
226 let (mut next_tick, mut next_shuffle) = (start + TICK, start + RESHUFFLE);
227
228 let result = loop {
229 let now = Instant::now();
230 if now >= next_tick {
231 board.tick();
232 next_tick = now + TICK;
233 }
234 if now >= next_shuffle {
235 board.reshuffle(now, policy);
236 next_shuffle = now + RESHUFFLE;
237 }
238 let (draw, glide) = (
239 board.draw.drawn(now, policy),
240 board.glide.drawn(now, policy),
241 );
242 terminal.draw(|f| board.paint(f.area(), f.buffer_mut(), &theme, draw, glide))?;
243
244 let due = [
245 board.draw.next_frame_at(now, policy),
246 board.glide.next_frame_at(now, policy),
247 ]
248 .into_iter()
249 .flatten()
250 .chain([next_tick, next_shuffle])
251 .min()
252 .unwrap_or(next_tick);
253 if event::poll(due.saturating_duration_since(Instant::now()))?
254 && let Event::Key(key) = event::read()?
255 && key.kind != KeyEventKind::Release
256 {
257 match key.code {
258 KeyCode::Char('q') | KeyCode::Esc => break Ok(()),
259 KeyCode::Char('r') => board.replay(Instant::now(), policy),
260 KeyCode::Char('m') => {
261 mode = if mode == MotionMode::Full {
262 MotionMode::Reduced
263 } else {
264 MotionMode::Full
265 };
266 policy = MotionPolicy::new(mode, &theme);
267 }
268 _ => {}
269 }
270 }
271 };
272
273 disable_raw_mode()?;
274 execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
275 result
276 }
277
277 lines RUST