Debian Codegraph @

src/canvas/widgets/cpu_basic.rs

raw symbols SCIP
1 use std::cmp::min;
2
3 use itertools::Itertools;
4 use ratatui::{
5 Frame,
6 layout::{Constraint, Direction, Layout, Rect},
7 style::Style,
8 };
9
10 use crate::{
11 app::App,
12 canvas::{
13 Painter,
14 components::pipe_gauge::{LabelLimit, PipeGauge},
15 drawing_utils::widget_block,
16 },
17 collection::cpu::{CpuData, CpuDataType},
18 };
19
20 impl Painter {
21 /// Inspired by htop.
22 pub fn draw_basic_cpu(
23 &self, f: &mut Frame<'_>, app_state: &mut App, mut draw_loc: Rect, widget_id: u64,
24 ) {
25 let cpu_data = &app_state.data_store.get_data().cpu_harvest;
26
27 // This is a bit complicated, but basically, we want to draw SOME number
28 // of columns to draw all CPUs. Ideally, as well, we want to not have
29 // to ever scroll.
30 //
31 // **General logic** - count number of elements in cpu_data. Then see how
32 // many rows and columns we have in draw_loc (-2 on both sides for border?).
33 // I think what we can do is try to fit in as many in one column as possible.
34 // If not, then add a new column. Then, from this, split the row space across
35 // ALL columns. From there, generate the desired lengths.
36
37 f.render_widget(
38 widget_block(
39 true,
40 app_state.current_widget.widget_id == widget_id,
41 self.styles.border_type,
42 self.styles.general_widget_style,
43 )
44 .border_style(self.styles.highlighted_border_style),
45 draw_loc,
46 );
47
48 // TODO: This is pretty ugly. Is there a better way of doing it?
49 let mut avg_index = cpu_data.len() + 1;
50 let mut avg_row_count = 0;
51 let show_decimal = app_state.app_config_fields.show_cpu_decimal;
52 if app_state.app_config_fields.dedicated_average_row
53 && app_state.app_config_fields.show_average_cpu
54 && let Some((index, avg)) = cpu_data
55 .iter()
56 .find_position(|&datum| matches!(datum.data_type, CpuDataType::Avg))
57 {
58 let (outer, inner, ratio, style) = self.cpu_info(avg, show_decimal);
59 let [cores_loc, mut avg_loc] =
60 Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).areas(draw_loc);
61
62 // The cores section all have horizontal margin, so to line up with the cores we
63 // need to add some margin ourselves.
64 avg_loc.x += 1;
65 avg_loc.width -= 2;
66
67 f.render_widget(
68 PipeGauge::default()
69 .gauge_style(style)
70 .label_style(style)
71 .inner_label(inner)
72 .start_label(outer)
73 .ratio(ratio.into()),
74 avg_loc,
75 );
76 avg_row_count += 1;
77 avg_index = index;
78 draw_loc = cores_loc;
79 }
80
81 if draw_loc.height > 0 {
82 let remaining_height = usize::from(draw_loc.height);
83 const REQUIRED_COLUMNS: usize = 4;
84
85 let col_constraints =
86 vec![Constraint::Percentage((100 / REQUIRED_COLUMNS) as u16); REQUIRED_COLUMNS];
87 let columns = Layout::default()
88 .constraints(col_constraints)
89 .direction(Direction::Horizontal)
90 .split(draw_loc);
91
92 let mut gauge_info = cpu_data.iter().enumerate().filter_map(|(index, cpu)| {
93 if index == avg_index {
94 None
95 } else {
96 Some(self.cpu_info(cpu, show_decimal))
97 }
98 });
99
100 // Very ugly way to sync the gauge limit across all gauges.
101 let hide_parts = columns
102 .first()
103 .map(|col| {
104 if col.width >= 12 {
105 LabelLimit::None
106 } else if col.width >= 10 {
107 LabelLimit::Bars
108 } else {
109 LabelLimit::StartLabel
110 }
111 })
112 .unwrap_or_default();
113
114 let num_entries = cpu_data.len() - avg_row_count;
115 let mut row_counter = num_entries;
116 for (itx, column) in columns.iter().enumerate() {
117 if REQUIRED_COLUMNS > itx {
118 let to_divide = REQUIRED_COLUMNS - itx;
119 let num_taken = min(
120 remaining_height,
121 (row_counter / to_divide)
122 + usize::from(!row_counter.is_multiple_of(to_divide)),
123 );
124 row_counter -= num_taken;
125 let chunk = (&mut gauge_info).take(num_taken);
126
127 let rows = Layout::default()
128 .direction(Direction::Vertical)
129 .constraints(vec![Constraint::Length(1); remaining_height])
130 .horizontal_margin(1)
131 .split(*column);
132
133 for ((start_label, inner_label, ratio, style), row) in chunk.zip(rows.iter()) {
134 f.render_widget(
135 PipeGauge::default()
136 .gauge_style(style)
137 .label_style(style)
138 .inner_label(inner_label)
139 .start_label(start_label)
140 .ratio(ratio.into())
141 .hide_parts(hide_parts),
142 *row,
143 );
144 }
145 }
146 }
147 }
148
149 if app_state.should_get_widget_bounds() {
150 // Update draw loc in widget map
151 if let Some(widget) = app_state.widget_map.get_mut(&widget_id) {
152 widget.top_left_corner = Some((draw_loc.x, draw_loc.y));
153 widget.bottom_right_corner =
154 Some((draw_loc.x + draw_loc.width, draw_loc.y + draw_loc.height));
155 }
156 }
157 }
158
159 #[inline]
160 fn cpu_info(&self, data: &CpuData, show_decimal: bool) -> (String, String, f32, Style) {
161 let (outer, style) = match data.data_type {
162 CpuDataType::Avg => ("AVG".to_string(), self.styles.avg_cpu_colour),
163 CpuDataType::Cpu(index) => (
164 format!("{index:<3}",),
165 self.styles.cpu_colour_styles[index % self.styles.cpu_colour_styles.len()],
166 ),
167 };
168
169 let inner = if show_decimal {
170 format!("{:>5.1}%", data.usage)
171 } else {
172 format!("{:>3.0}%", data.usage.round())
173 };
174 let ratio = data.usage / 100.0;
175
176 (outer, inner, ratio, style)
177 }
178 }