Debian Codegraph @

src/canvas/widgets/disk_io_graph.rs

raw symbols SCIP
1 use std::{
2 borrow::Cow,
3 time::{Duration, Instant},
4 };
5
6 use ratatui::{
7 Frame,
8 layout::{Constraint, Rect},
9 style::Style,
10 };
11 use rustc_hash::FxHashMap;
12 use timeless::data::ChunkedData;
13
14 use crate::{
15 app::App,
16 canvas::{
17 Painter,
18 components::time_series::{AxisBound, ChartScaling, GraphData, LegendConstraints},
19 drawing_utils::should_hide_x_label,
20 },
21 components::time_series::GraphDrawCtx,
22 options::config::disk_io_graph::DiskGraphLegend,
23 utils::data_units::*,
24 };
25
26 impl Painter {
27 pub fn draw_disk_io_graph(
28 &self, f: &mut Frame<'_>, app_state: &mut App, draw_loc: Rect, widget_id: u64,
29 ) {
30 if let Some(widget_state) = app_state
31 .states
32 .disk_io_graph_state
33 .get_mut_widget_state(widget_id)
34 {
35 let shared_data = app_state.data_store.get_data();
36 let read_data = &shared_data.time_series_data.disk_io_read;
37 let write_data = &shared_data.time_series_data.disk_io_write;
38 let times = &shared_data.time_series_data.time;
39
40 let mount_map: FxHashMap<&str, &str> = shared_data
41 .disk_harvest
42 .iter()
43 .map(|d| (d.name.as_str(), d.mount_point.as_str()))
44 .collect();
45
46 let border_style = self.get_border_style(widget_id, app_state.current_widget.widget_id);
47 let graph_state = widget_state.graph.state_mut();
48 let hide_x_labels = should_hide_x_label(
49 app_state.app_config_fields.hide_time,
50 app_state.app_config_fields.autohide_time,
51 graph_state.autohide_timer_mut(),
52 draw_loc,
53 );
54 let current_display_time = graph_state.current_display_time();
55
56 let show_read = widget_state.show_read;
57 let show_write = widget_state.show_write;
58 let use_log = widget_state.use_log;
59 let legend_type = &widget_state.legend;
60
61 let mut device_names: Vec<&String> = read_data
62 .keys()
63 .filter(|name| {
64 let has_read_data = || {
65 read_data
66 .get(*name)
67 .is_some_and(|d| has_data_in_window(d, times, current_display_time))
68 };
69
70 // If there is a mount point and we're in mount legend mode, it must be non-empty
71 // (i.e. actually mounted), or we will short-circuit and ignore it.
72 if let Some(mount_point) = mount_map.get(name.as_str()) {
73 match legend_type {
74 DiskGraphLegend::Disk => true,
75 DiskGraphLegend::Mount => !mount_point.is_empty() && has_read_data(),
76 }
77 } else {
78 match legend_type {
79 DiskGraphLegend::Disk => {
80 // Otherwise, it may have _previously_ been a valid mount point, so keep showing it until it ages out.
81 has_read_data()
82 }
83 DiskGraphLegend::Mount => {
84 // Since it would be misleading in this case, just skip it in mount mode.
85 false
86 }
87 }
88 }
89 })
90 .collect();
91 device_names.sort_unstable();
92
93 // Compute y_max across all visible series.
94 let mut visible_sources: Vec<&_> = Vec::new();
95 for name in &device_names {
96 if show_read && let Some(data) = read_data.get(*name) {
97 visible_sources.push(data);
98 }
99 if show_write && let Some(data) = write_data.get(*name) {
100 visible_sources.push(data);
101 }
102 }
103 let y_max = widget_state.graph.y_max(visible_sources.into_iter(), times);
104
105 let (adjusted_y_max, y_labels) = if use_log {
106 adjust_disk_io_log(y_max)
107 } else {
108 adjust_disk_io_linear(y_max)
109 };
110
111 let legend_constraints = LegendConstraints {
112 width: Constraint::Ratio(9, 10),
113 height: Constraint::Ratio(1, 2),
114 };
115
116 // Removed devices still visible in the window show "N/A".
117 // TODO: Maybe should make it so the colour is based on entry name? As then it may shift.
118 let read_colours = &self.styles.disk_io_read_colour_styles;
119 let write_colours = &self.styles.disk_io_write_colour_styles;
120
121 // Pad the device/mount labels to the widest visible one so the rate columns
122 // line up in the legend (the rate itself is already fixed-width).
123 let name_width = device_names
124 .iter()
125 .map(|name| match legend_type {
126 DiskGraphLegend::Disk => name.len(),
127 DiskGraphLegend::Mount => mount_map
128 .get(name.as_str())
129 .map(|mount| mount.len())
130 .unwrap_or(0),
131 })
132 .max()
133 .unwrap_or(0);
134
135 let mut graph_data: Vec<GraphData<'_, f64>> =
136 Vec::with_capacity(device_names.len() * 2);
137
138 for (idx, name) in device_names.iter().enumerate() {
139 let display_name = match legend_type {
140 DiskGraphLegend::Disk => name.as_str(),
141 DiskGraphLegend::Mount => match mount_map.get(name.as_str()).copied() {
142 Some(mount) => mount,
143 // This wouldn't trigger anyway, we filter out devices without mount points in mount legend mode.
144 None => continue,
145 },
146 };
147
148 let is_active = mount_map.contains_key(name.as_str());
149
150 let read_values = show_read.then(|| read_data.get(*name)).flatten();
151 let write_values = show_write.then(|| write_data.get(*name)).flatten();
152
153 let read_style = if read_colours.is_empty() {
154 Style::default()
155 } else {
156 read_colours[idx % read_colours.len()]
157 };
158 let write_style = if write_colours.is_empty() {
159 Style::default()
160 } else {
161 write_colours[idx % write_colours.len()]
162 };
163
164 // TODO: Combine into one line; probably need to add some kind of multi-styled GraphData.
165 if let Some(values) = read_values {
166 let rate = if is_active {
167 format_rate_fixed(values.last().copied().unwrap_or(0.0))
168 } else {
169 " N/A".to_string()
170 };
171 graph_data.push(
172 GraphData::default()
173 .name(format!("{display_name:<name_width$} R:{rate}").into())
174 .style(read_style)
175 .time(times)
176 .values(values),
177 );
178 }
179
180 if let Some(values) = write_values {
181 let rate = if is_active {
182 format_rate_fixed(values.last().copied().unwrap_or(0.0))
183 } else {
184 " N/A".to_string()
185 };
186 graph_data.push(
187 GraphData::default()
188 .name(format!("{display_name:<name_width$} W:{rate}").into())
189 .style(write_style)
190 .time(times)
191 .values(values),
192 );
193 }
194 }
195
196 let marker = self.get_marker(app_state.app_config_fields.use_dot);
197 let y_bounds = AxisBound::Max(adjusted_y_max);
198 let scaling = if use_log {
199 ChartScaling::Log2
200 } else {
201 ChartScaling::Linear
202 };
203 let y_labels: Vec<Cow<'_, str>> = y_labels.into_iter().map(Into::into).collect();
204
205 widget_state.graph.draw(
206 f,
207 draw_loc,
208 GraphDrawCtx {
209 title: " Disk I/O ".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.disk_io_legend_position,
220 legend_constraints: Some(legend_constraints),
221 },
222 y_bounds,
223 &y_labels,
224 scaling,
225 graph_data,
226 );
227 }
228
229 if app_state.should_get_widget_bounds()
230 && let Some(widget) = app_state.widget_map.get_mut(&widget_id)
231 {
232 widget.top_left_corner = Some((draw_loc.x, draw_loc.y));
233 widget.bottom_right_corner =
234 Some((draw_loc.x + draw_loc.width, draw_loc.y + draw_loc.height));
235 }
236 }
237 }
238
239 /// Returns true if `data` has at least one real (non-gap) data point within the
240 /// visible time window defined by `current_display_time` milliseconds from the end
241 /// of `times`.
242 fn has_data_in_window<F: Copy + Default + Into<f64>>(
243 data: &ChunkedData<F>, times: &[Instant], current_display_time: u64,
244 ) -> bool {
245 let Some(&last_time) = times.last() else {
246 return false;
247 };
248 let display_duration = Duration::from_millis(current_display_time);
249 let oldest = last_time.checked_sub(display_duration).unwrap_or(last_time);
250 data.iter_along_base(times)
251 .next_back()
252 .is_some_and(|(t, _)| *t >= oldest)
253 }
254
255 /// Format a byte/s rate as a fixed-width string (always 11 chars, right-aligned)
256 /// to keep legend labels a stable width and prevent legend box shifting between frames.
257 fn format_rate_fixed(bytes_per_sec: f64) -> String {
258 let (val, unit) = if bytes_per_sec < KIBI_LIMIT_F64 {
259 (bytes_per_sec, "B/s")
260 } else if bytes_per_sec < MEBI_LIMIT_F64 {
261 (bytes_per_sec / KIBI_LIMIT_F64, "KiB/s")
262 } else if bytes_per_sec < GIBI_LIMIT_F64 {
263 (bytes_per_sec / MEBI_LIMIT_F64, "MiB/s")
264 } else if bytes_per_sec < TEBI_LIMIT_F64 {
265 (bytes_per_sec / GIBI_LIMIT_F64, "GiB/s")
266 } else {
267 (bytes_per_sec / TEBI_LIMIT_F64, "TiB/s")
268 };
269 format!("{:>11}", format!("{val:.1}{unit}"))
270 }
271
272 fn adjust_disk_io_linear(max_entry: f64) -> (f64, Vec<String>) {
273 let max_entry_upper = if max_entry == 0.0 {
274 1.0
275 } else {
276 max_entry * 1.5
277 };
278
279 let (max_value_scaled, unit) = if max_entry_upper < KIBI_LIMIT_F64 {
280 (max_entry, "B/s")
281 } else if max_entry_upper < MEBI_LIMIT_F64 {
282 (max_entry / KIBI_LIMIT_F64, "KiB/s")
283 } else if max_entry_upper < GIBI_LIMIT_F64 {
284 (max_entry / MEBI_LIMIT_F64, "MiB/s")
285 } else if max_entry_upper < TEBI_LIMIT_F64 {
286 (max_entry / GIBI_LIMIT_F64, "GiB/s")
287 } else {
288 (max_entry / TEBI_LIMIT_F64, "TiB/s")
289 };
290
291 let labels = vec![
292 format!("0{unit}"),
293 format!("{:.1}", max_value_scaled * 0.5),
294 format!("{:.1}", max_value_scaled),
295 format!("{:.1}", max_value_scaled * 1.5),
296 ]
297 .into_iter()
298 .map(|s| format!("{s:>8}"))
299 .collect();
300
301 (max_entry_upper, labels)
302 }
303
304 fn adjust_disk_io_log(max_entry: f64) -> (f64, Vec<String>) {
305 use crate::utils::general::saturating_log2;
306
307 let log_max = saturating_log2(max_entry);
308
309 if log_max < LOG_MEBI_LIMIT {
310 (
311 LOG_MEBI_LIMIT,
312 vec![" 0B/s".into(), "1KiB/s".into(), "1MiB/s".into()],
313 )
314 } else if log_max < LOG_GIBI_LIMIT {
315 (
316 LOG_GIBI_LIMIT,
317 vec![
318 " 0B/s".into(),
319 "1KiB/s".into(),
320 "1MiB/s".into(),
321 "1GiB/s".into(),
322 ],
323 )
324 } else if log_max < LOG_TEBI_LIMIT {
325 (
326 LOG_TEBI_LIMIT,
327 vec![
328 " 0B/s".into(),
329 "1KiB/s".into(),
330 "1MiB/s".into(),
331 "1GiB/s".into(),
332 "1TiB/s".into(),
333 ],
334 )
335 } else {
336 (
337 LOG_PEBI_LIMIT,
338 vec![
339 " 0B/s".into(),
340 "1KiB/s".into(),
341 "1MiB/s".into(),
342 "1GiB/s".into(),
343 "1TiB/s".into(),
344 "1PiB/s".into(),
345 ],
346 )
347 }
348 }