Debian Codegraph @

src/canvas/widgets/network_graph.rs

raw symbols SCIP
1 use std::borrow::Cow;
2
3 use ratatui::{
4 Frame,
5 layout::{Constraint, Direction, Layout, Rect},
6 text::Text,
7 widgets::{Row, Table},
8 };
9
10 use crate::{
11 app::{App, AppConfigFields, AxisScaling},
12 canvas::{
13 Painter,
14 components::time_series::{AxisBound, ChartScaling, GraphData, LegendConstraints},
15 drawing_utils::{should_hide_x_label, widget_block},
16 widgets::{PacketInfo, calculate_packet_info},
17 },
18 components::time_series::GraphDrawCtx,
19 utils::{
20 data_units::*,
21 general::{saturating_log2, saturating_log10},
22 },
23 };
24
25 impl Painter {
26 pub fn draw_network(
27 &self, f: &mut Frame<'_>, app_state: &mut App, draw_loc: Rect, widget_id: u64,
28 ) {
29 if app_state.app_config_fields.use_old_network_legend {
30 const LEGEND_HEIGHT: u16 = 4;
31 let network_chunk = Layout::default()
32 .direction(Direction::Vertical)
33 .margin(0)
34 .constraints([
35 Constraint::Length(draw_loc.height.saturating_sub(LEGEND_HEIGHT)),
36 Constraint::Length(LEGEND_HEIGHT),
37 ])
38 .split(draw_loc);
39
40 self.draw_network_graph(f, app_state, network_chunk[0], widget_id);
41 self.draw_old_network_labels(f, app_state, network_chunk[1], widget_id);
42 } else {
43 self.draw_network_graph(f, app_state, draw_loc, widget_id);
44 }
45
46 if app_state.should_get_widget_bounds() {
47 // Update draw loc in widget map
48 // Note that in both cases, we always go to the same widget id so it's fine to
49 // do it like this lol.
50 if let Some(network_widget) = app_state.widget_map.get_mut(&widget_id) {
51 network_widget.top_left_corner = Some((draw_loc.x, draw_loc.y));
52 network_widget.bottom_right_corner =
53 Some((draw_loc.x + draw_loc.width, draw_loc.y + draw_loc.height));
54 }
55 }
56 }
57
58 pub fn draw_network_graph(
59 &self, f: &mut Frame<'_>, app_state: &mut App, draw_loc: Rect, widget_id: u64,
60 ) {
61 if let Some(network_widget_state) =
62 app_state.states.net_state.widget_states.get_mut(&widget_id)
63 {
64 let shared_data = app_state.data_store.get_data();
65 let network_latest_data = &(shared_data.network_harvest);
66 let rx_points = &(shared_data.time_series_data.rx);
67 let tx_points = &(shared_data.time_series_data.tx);
68 let times = &(shared_data.time_series_data.time);
69
70 let border_style = self.get_border_style(widget_id, app_state.current_widget.widget_id);
71 let hide_x_labels = should_hide_x_label(
72 app_state.app_config_fields.hide_time,
73 app_state.app_config_fields.autohide_time,
74 network_widget_state.graph.state_mut().autohide_timer_mut(),
75 draw_loc,
76 );
77
78 let y_max = network_widget_state
79 .graph
80 .y_max([rx_points, tx_points].into_iter(), times);
81 let (adjusted_y_max, y_labels) =
82 adjust_network_data_point(y_max, &app_state.app_config_fields);
83 let y_bounds = AxisBound::Max(adjusted_y_max);
84
85 let use_old_network_legend = app_state.app_config_fields.use_old_network_legend;
86 let legend_constraints = if use_old_network_legend {
87 // Always hide it. Note that I could pass in `None` to the position as well but
88 // eh this works.
89 LegendConstraints {
90 width: Constraint::Length(0),
91 height: Constraint::Length(0),
92 }
93 } else {
94 // Hide the legend if the width is 90% of the total widget width
95 // or the height is greater than 75% of the total widget height.
96 LegendConstraints {
97 width: Constraint::Ratio(9, 10),
98 height: Constraint::Ratio(3, 4),
99 }
100 };
101
102 // TODO: Add support for clicking on legend to only show that value on chart.
103 let use_binary_prefix = app_state.app_config_fields.network_use_binary_prefix;
104 let unit_type = app_state.app_config_fields.network_unit_type;
105 let unit = match unit_type {
106 DataUnit::Byte => "B/s",
107 DataUnit::Bit => "b/s",
108 };
109
110 let rx = get_unit_prefix(network_latest_data.rx, use_binary_prefix);
111 let tx = get_unit_prefix(network_latest_data.tx, use_binary_prefix);
112 let total_rx = convert_bits(network_latest_data.total_rx, use_binary_prefix);
113 let total_tx = convert_bits(network_latest_data.total_tx, use_binary_prefix);
114
115 let graph_data = if use_old_network_legend {
116 let mut graph_data = vec![
117 GraphData::default()
118 .time(times)
119 .values(rx_points)
120 .style(self.styles.rx_style),
121 GraphData::default()
122 .time(times)
123 .values(tx_points)
124 .style(self.styles.tx_style),
125 ];
126
127 graph_data.extend([
128 GraphData::default().style(self.styles.total_rx_style),
129 GraphData::default().style(self.styles.total_tx_style),
130 ]);
131
132 graph_data
133 } else {
134 let rx_label = format!("{:.1}{}{}", rx.0, rx.1, unit);
135 let tx_label = format!("{:.1}{}{}", tx.0, tx.1, unit);
136 let total_rx_label = format!("{:.1}{}", total_rx.0, total_rx.1);
137 let total_tx_label = format!("{:.1}{}", total_tx.0, total_tx.1);
138
139 // Add packets information if enabled and there's enough room.
140 const MAX_LEGEND_WIDTH: u16 = 70;
141 let approx_legend_width = draw_loc.width * 3 / 4;
142
143 // FIXME: I'm not really a huge fan of this - I think it may be better to just
144 // not support this and allow for more easily spawning a
145 // separate legend table (basically old legend).
146 if app_state.app_config_fields.network_show_packets
147 && approx_legend_width > MAX_LEGEND_WIDTH
148 {
149 let PacketInfo {
150 rx_packet_rate,
151 tx_packet_rate,
152 avg_rx_packet_size,
153 avg_tx_packet_size,
154 } = calculate_packet_info(network_latest_data, use_binary_prefix);
155
156 let avg_rx_packet_size_label =
157 format!("{:.1}{}", avg_rx_packet_size.0, avg_rx_packet_size.1);
158 let avg_tx_packet_size_label =
159 format!("{:.1}{}", avg_tx_packet_size.0, avg_tx_packet_size.1);
160
161 vec![
162 GraphData::default()
163 .name(format!("RX: {rx_label:<10} All: {total_rx_label:<8} Packets: {rx_packet_rate:>8}pkt/s Avg: {avg_rx_packet_size_label}").into())
164 .time(times)
165 .values(rx_points)
166 .style(self.styles.rx_style),
167 GraphData::default()
168 .name(format!("TX: {tx_label:<10} All: {total_tx_label:<8} Packets: {tx_packet_rate:>8}pkt/s Avg: {avg_tx_packet_size_label}").into())
169 .time(times)
170 .values(tx_points)
171 .style(self.styles.tx_style),
172 ]
173 } else {
174 vec![
175 GraphData::default()
176 .name(format!("RX: {rx_label:<10} All: {total_rx_label}").into())
177 .time(times)
178 .values(rx_points)
179 .style(self.styles.rx_style),
180 GraphData::default()
181 .name(format!("TX: {tx_label:<10} All: {total_tx_label}").into())
182 .time(times)
183 .values(tx_points)
184 .style(self.styles.tx_style),
185 ]
186 }
187 };
188
189 let marker = self.get_marker(app_state.app_config_fields.use_dot);
190
191 let scaling = match app_state.app_config_fields.network_scale_type {
192 AxisScaling::Log => {
193 // TODO: I might change this behaviour later.
194 if app_state.app_config_fields.network_use_binary_prefix {
195 ChartScaling::Log2
196 } else {
197 ChartScaling::Log10
198 }
199 }
200 AxisScaling::Linear => ChartScaling::Linear,
201 };
202
203 let y_labels: Vec<Cow<'_, str>> = y_labels.into_iter().map(Into::into).collect();
204
205 network_widget_state.graph.draw(
206 f,
207 draw_loc,
208 GraphDrawCtx {
209 title: " Network ".into(),
210 border_style,
211 title_style: self.styles.widget_title_style,
212 graph_style: self.styles.graph_style,
213 general_widget_style: self.styles.general_widget_style,
214 border_type: self.styles.border_type,
215 marker,
216 hide_x_labels,
217 is_selected: app_state.current_widget.widget_id == widget_id,
218 is_expanded: app_state.is_expanded,
219 legend_position: app_state.app_config_fields.network_legend_position,
220 legend_constraints: Some(legend_constraints),
221 },
222 y_bounds,
223 &y_labels,
224 scaling,
225 graph_data,
226 );
227 }
228 }
229
230 fn draw_old_network_labels(
231 &self, f: &mut Frame<'_>, app_state: &mut App, draw_loc: Rect, widget_id: u64,
232 ) {
233 let network_latest_data = &(app_state.data_store.get_data().network_harvest);
234 let use_binary_prefix = app_state.app_config_fields.network_use_binary_prefix;
235 let unit_type = app_state.app_config_fields.network_unit_type;
236 let unit = match unit_type {
237 DataUnit::Byte => "B/s",
238 DataUnit::Bit => "b/s",
239 };
240
241 let rx = get_unit_prefix(network_latest_data.rx, use_binary_prefix);
242 let tx = get_unit_prefix(network_latest_data.tx, use_binary_prefix);
243
244 let rx_label = format!("{:.1}{}{}", rx.0, rx.1, unit);
245 let tx_label = format!("{:.1}{}{}", tx.0, tx.1, unit);
246
247 let total_rx = convert_bits(network_latest_data.total_rx, use_binary_prefix);
248 let total_tx = convert_bits(network_latest_data.total_tx, use_binary_prefix);
249 let total_rx_label = format!("{:.1}{}", total_rx.0, total_rx.1);
250 let total_tx_label = format!("{:.1}{}", total_tx.0, total_tx.1);
251
252 let total_network = if app_state.app_config_fields.network_show_packets {
253 let PacketInfo {
254 rx_packet_rate,
255 tx_packet_rate,
256 avg_rx_packet_size,
257 avg_tx_packet_size,
258 } = calculate_packet_info(network_latest_data, use_binary_prefix);
259
260 let avg_rx_packet_size_label =
261 format!("{:.1}{}", avg_rx_packet_size.0, avg_rx_packet_size.1);
262 let avg_tx_packet_size_label =
263 format!("{:.1}{}", avg_tx_packet_size.0, avg_tx_packet_size.1);
264
265 vec![Row::new([
266 Text::styled(rx_label, self.styles.rx_style),
267 Text::styled(tx_label, self.styles.tx_style),
268 Text::styled(total_rx_label, self.styles.total_rx_style),
269 Text::styled(total_tx_label, self.styles.total_tx_style),
270 Text::styled(format!("{rx_packet_rate}pkt/s"), self.styles.rx_style),
271 Text::styled(format!("{tx_packet_rate}pkt/s"), self.styles.tx_style),
272 Text::styled(avg_rx_packet_size_label, self.styles.rx_style),
273 Text::styled(avg_tx_packet_size_label, self.styles.tx_style),
274 ])]
275 } else {
276 vec![Row::new([
277 Text::styled(rx_label, self.styles.rx_style),
278 Text::styled(tx_label, self.styles.tx_style),
279 Text::styled(total_rx_label, self.styles.total_rx_style),
280 Text::styled(total_tx_label, self.styles.total_tx_style),
281 ])]
282 };
283
284 let headers = if app_state.app_config_fields.network_show_packets {
285 vec![
286 "RX", "TX", "Total RX", "Total TX", "RX Pkts", "TX Pkts", "Avg RX", "Avg TX",
287 ]
288 } else {
289 vec!["RX", "TX", "Total RX", "Total TX"]
290 };
291 let num_columns = headers.len();
292
293 let column_width = draw_loc.width.saturating_sub(2) / num_columns as u16;
294
295 // Draw
296 let current_border_style = if app_state.current_widget.widget_id == widget_id {
297 self.styles.highlighted_border_style
298 } else {
299 self.styles.border_style
300 };
301 let block = widget_block(
302 app_state.app_config_fields.use_basic_mode,
303 app_state.current_widget.widget_id == widget_id,
304 self.styles.border_type,
305 self.styles.general_widget_style,
306 )
307 .border_style(current_border_style);
308
309 f.render_widget(
310 Table::new(
311 total_network,
312 &((std::iter::repeat_n(column_width, num_columns))
313 .map(Constraint::Length)
314 .collect::<Vec<_>>()),
315 )
316 .header(Row::new(headers).style(self.styles.table_header_style))
317 .block(block)
318 .style(self.styles.text_style),
319 draw_loc,
320 );
321 }
322 }
323
324 /// Returns the required labels.
325 ///
326 /// TODO: This is _really_ ugly... also there might be a bug with certain
327 /// heights and too many labels. We may need to take draw height into account,
328 /// either here, or in the time graph itself.
329 fn adjust_network_data_point(max_entry: f64, config: &AppConfigFields) -> (f64, Vec<String>) {
330 // So, we're going with an approach like this for linear data:
331 // - Main goal is to maximize the amount of information displayed given a
332 // specific height. We don't want to drown out some data if the ranges are too
333 // far though! Nor do we want to filter out too much data...
334 // - Change the y-axis unit (kilo/kibi, mega/mebi...) dynamically based on max
335 // load.
336 //
337 // The idea is we take the top value, build our scale such that each "point" is
338 // a scaled version of that. So for example, let's say I use 390 Mb/s. If I
339 // drew 4 segments, it would be 97.5, 195, 292.5, 390, and
340 // probably something like 438.75?
341 //
342 // So, how do we do this in ratatui? Well, if we are using intervals that tie
343 // in perfectly to the max value we want... then it's actually not that
344 // hard. Since ratatui accepts a vector as labels and will properly space
345 // them all out... we just work with that and space it out properly.
346 //
347 // Dynamic chart idea based off of FreeNAS's chart design.
348 //
349 // ---
350 //
351 // For log data, we just use the old method of log intervals
352 // (kilo/mega/giga/etc.). Keep it nice and simple.
353
354 // Now just check the largest unit we correspond to... then proceed to build
355 // some entries from there!
356
357 let scale_type = config.network_scale_type;
358 let use_binary_prefix = config.network_use_binary_prefix;
359 let network_unit_type = config.network_unit_type;
360
361 let unit_char = match network_unit_type {
362 DataUnit::Byte => "B",
363 DataUnit::Bit => "b",
364 };
365
366 match scale_type {
367 AxisScaling::Linear => {
368 let (k_limit, m_limit, g_limit, t_limit) = if use_binary_prefix {
369 (
370 KIBI_LIMIT_F64,
371 MEBI_LIMIT_F64,
372 GIBI_LIMIT_F64,
373 TEBI_LIMIT_F64,
374 )
375 } else {
376 (
377 KILO_LIMIT_F64,
378 MEGA_LIMIT_F64,
379 GIGA_LIMIT_F64,
380 TERA_LIMIT_F64,
381 )
382 };
383
384 let max_entry_upper = if max_entry == 0.0 {
385 // If it's 0, then just use a very low value so the labels aren't just "0.0" 4
386 // times. This _also_ prevents the y-axis height range ever
387 // being 0.
388 1.0
389 } else {
390 max_entry * 1.5 // We use the bumped up version to calculate our unit type.
391 };
392
393 let (max_value_scaled, unit_prefix, unit_type): (f64, &str, &str) = {
394 if max_entry_upper < k_limit {
395 (max_entry, "", unit_char)
396 } else if max_entry_upper < m_limit {
397 (
398 max_entry / k_limit,
399 if use_binary_prefix { "Ki" } else { "K" },
400 unit_char,
401 )
402 } else if max_entry_upper < g_limit {
403 (
404 max_entry / m_limit,
405 if use_binary_prefix { "Mi" } else { "M" },
406 unit_char,
407 )
408 } else if max_entry_upper < t_limit {
409 (
410 max_entry / g_limit,
411 if use_binary_prefix { "Gi" } else { "G" },
412 unit_char,
413 )
414 } else {
415 (
416 max_entry / t_limit,
417 if use_binary_prefix { "Ti" } else { "T" },
418 unit_char,
419 )
420 }
421 };
422
423 // Finally, build an acceptable range starting from there, using the given
424 // height! Note we try to put more of a weight on the bottom section
425 // vs. the top, since the top has less data.
426 let base_unit = max_value_scaled;
427 let labels: Vec<String> = vec![
428 format!("0{unit_prefix}{unit_type}"),
429 format!("{:.1}", base_unit * 0.5),
430 format!("{:.1}", base_unit),
431 format!("{:.1}", base_unit * 1.5),
432 ]
433 .into_iter()
434 .map(|s| {
435 // Pull 5 as the longest legend value is generally going to be 5 digits (if they
436 // somehow hit over 5 terabits per second)
437 format!("{s:>5}")
438 })
439 .collect();
440
441 (max_entry_upper, labels)
442 }
443 AxisScaling::Log => {
444 let (m_limit, g_limit, t_limit) = if use_binary_prefix {
445 (LOG_MEBI_LIMIT, LOG_GIBI_LIMIT, LOG_TEBI_LIMIT)
446 } else {
447 (LOG_MEGA_LIMIT, LOG_GIGA_LIMIT, LOG_TERA_LIMIT)
448 };
449
450 // Remember to do saturating log checks as otherwise 0.0 becomes inf, and you
451 // get gaps!
452 let max_entry = if use_binary_prefix {
453 saturating_log2(max_entry)
454 } else {
455 saturating_log10(max_entry)
456 };
457
458 fn get_zero(network_use_binary_prefix: bool, unit_char: &str) -> String {
459 format!(
460 "{}0{}",
461 if network_use_binary_prefix { " " } else { " " },
462 unit_char
463 )
464 }
465
466 fn get_k(network_use_binary_prefix: bool, unit_char: &str) -> String {
467 format!(
468 "1{}{}",
469 if network_use_binary_prefix { "Ki" } else { "K" },
470 unit_char
471 )
472 }
473
474 fn get_m(network_use_binary_prefix: bool, unit_char: &str) -> String {
475 format!(
476 "1{}{}",
477 if network_use_binary_prefix { "Mi" } else { "M" },
478 unit_char
479 )
480 }
481
482 fn get_g(network_use_binary_prefix: bool, unit_char: &str) -> String {
483 format!(
484 "1{}{}",
485 if network_use_binary_prefix { "Gi" } else { "G" },
486 unit_char
487 )
488 }
489
490 fn get_t(network_use_binary_prefix: bool, unit_char: &str) -> String {
491 format!(
492 "1{}{}",
493 if network_use_binary_prefix { "Ti" } else { "T" },
494 unit_char
495 )
496 }
497
498 fn get_p(network_use_binary_prefix: bool, unit_char: &str) -> String {
499 format!(
500 "1{}{}",
501 if network_use_binary_prefix { "Pi" } else { "P" },
502 unit_char
503 )
504 }
505
506 if max_entry < m_limit {
507 (
508 m_limit,
509 vec![
510 get_zero(use_binary_prefix, unit_char),
511 get_k(use_binary_prefix, unit_char),
512 get_m(use_binary_prefix, unit_char),
513 ],
514 )
515 } else if max_entry < g_limit {
516 (
517 g_limit,
518 vec![
519 get_zero(use_binary_prefix, unit_char),
520 get_k(use_binary_prefix, unit_char),
521 get_m(use_binary_prefix, unit_char),
522 get_g(use_binary_prefix, unit_char),
523 ],
524 )
525 } else if max_entry < t_limit {
526 (
527 t_limit,
528 vec![
529 get_zero(use_binary_prefix, unit_char),
530 get_k(use_binary_prefix, unit_char),
531 get_m(use_binary_prefix, unit_char),
532 get_g(use_binary_prefix, unit_char),
533 get_t(use_binary_prefix, unit_char),
534 ],
535 )
536 } else {
537 // I really doubt anyone's transferring beyond petabyte speeds...
538 (
539 if use_binary_prefix {
540 LOG_PEBI_LIMIT
541 } else {
542 LOG_PETA_LIMIT
543 },
544 vec![
545 get_zero(use_binary_prefix, unit_char),
546 get_k(use_binary_prefix, unit_char),
547 get_m(use_binary_prefix, unit_char),
548 get_g(use_binary_prefix, unit_char),
549 get_t(use_binary_prefix, unit_char),
550 get_p(use_binary_prefix, unit_char),
551 ],
552 )
553 }
554 }
555 }
556 }