Debian Codegraph @

src/canvas/widgets/battery_display.rs

raw symbols SCIP
1 use std::cmp::min;
2
3 use ratatui::{
4 Frame,
5 layout::{Constraint, Direction, Layout, Rect},
6 symbols::{self, line},
7 text::{Line, Span},
8 widgets::{Cell, Paragraph, Row, Table, Tabs},
9 };
10 use unicode_width::UnicodeWidthStr;
11
12 use crate::{
13 app::App,
14 canvas::{Painter, drawing_utils::widget_block},
15 collection::batteries::BatteryState,
16 constants::*,
17 options::config::flags::TableGap,
18 };
19
20 /// Calculate how many bars are to be drawn within basic mode's components.
21 fn calculate_basic_use_bars(use_percentage: f64, num_bars_available: usize) -> usize {
22 min(
23 (num_bars_available as f64 * use_percentage / 100.0).round() as usize,
24 num_bars_available,
25 )
26 }
27
28 impl Painter {
29 pub fn draw_battery(
30 &self, f: &mut Frame<'_>, app_state: &mut App, draw_loc: Rect, widget_id: u64,
31 ) {
32 let should_get_widget_bounds = app_state.should_get_widget_bounds();
33 if let Some(battery_widget_state) = app_state
34 .states
35 .battery_state
36 .widget_states
37 .get_mut(&widget_id)
38 {
39 let is_selected = widget_id == app_state.current_widget.widget_id;
40 let border_style = if is_selected {
41 self.styles.highlighted_border_style
42 } else {
43 self.styles.border_style
44 };
45 let table_gap_setting = app_state.app_config_fields.table_gap;
46 let table_gap = if draw_loc.height < TABLE_GAP_HEIGHT_LIMIT {
47 0
48 } else {
49 table_gap_setting.height()
50 };
51
52 let block = {
53 let mut block = widget_block(
54 app_state.app_config_fields.use_basic_mode,
55 is_selected,
56 self.styles.border_type,
57 self.styles.general_widget_style,
58 )
59 .border_style(border_style)
60 .title_top(Line::styled(" Battery ", self.styles.widget_title_style));
61
62 if app_state.is_expanded {
63 block = block.title_top(
64 Line::styled(" Esc to go back ", self.styles.widget_title_style)
65 .right_aligned(),
66 )
67 }
68
69 block
70 };
71
72 let battery_harvest = &(app_state.data_store.get_data().battery_harvest);
73 if battery_harvest.len() > 1 {
74 let battery_names = battery_harvest
75 .iter()
76 .enumerate()
77 .map(|(itx, _)| format!("Battery {itx}"))
78 .collect::<Vec<_>>();
79
80 let tab_draw_loc = Layout::default()
81 .constraints([
82 Constraint::Length(1),
83 Constraint::Length(2),
84 Constraint::Min(0),
85 ])
86 .direction(Direction::Vertical)
87 .split(draw_loc)[1];
88
89 f.render_widget(
90 Tabs::new(
91 battery_names
92 .iter()
93 .map(|name| Line::from((*name).clone()))
94 .collect::<Vec<_>>(),
95 )
96 .divider(symbols::line::VERTICAL)
97 .style(self.styles.text_style)
98 .highlight_style(self.styles.selected_text_style)
99 .select(battery_widget_state.currently_selected_battery_index),
100 tab_draw_loc,
101 );
102
103 if should_get_widget_bounds {
104 let mut current_x = tab_draw_loc.x;
105 let current_y = tab_draw_loc.y;
106 let mut tab_click_locs: Vec<((u16, u16), (u16, u16))> = vec![];
107 for battery in battery_names {
108 // +1 because there's a space after the tab label.
109 let width = UnicodeWidthStr::width(battery.as_str()) as u16;
110 tab_click_locs
111 .push(((current_x, current_y), (current_x + width, current_y)));
112
113 // +4 because we want to go one space, then one space past to get to the
114 // '|', then 2 more to start at the blank space
115 // before the tab label.
116 current_x += width + 4;
117 }
118 battery_widget_state.tab_click_locs = Some(tab_click_locs);
119 }
120 }
121
122 let is_basic = app_state.app_config_fields.use_basic_mode;
123
124 let [margined_draw_loc] = Layout::default()
125 .constraints([Constraint::Percentage(100)])
126 .horizontal_margin(u16::from(is_basic && !is_selected))
127 .direction(Direction::Horizontal)
128 .areas(draw_loc);
129
130 if let Some(battery_details) =
131 battery_harvest.get(battery_widget_state.currently_selected_battery_index)
132 {
133 let full_width = draw_loc.width.saturating_sub(2);
134 let bar_length = usize::from(full_width.saturating_sub(6));
135 let charge_percent = battery_details.charge_percent;
136
137 let num_bars = calculate_basic_use_bars(charge_percent, bar_length);
138 let bars = format!(
139 "[{}{}{:3.0}%]",
140 "|".repeat(num_bars),
141 " ".repeat(bar_length - num_bars),
142 charge_percent,
143 );
144
145 let mut battery_charge_rows = Vec::with_capacity(2);
146 battery_charge_rows.push(Row::new([
147 Cell::from("Charge").style(self.styles.text_style)
148 ]));
149 battery_charge_rows.push(Row::new([Cell::from(bars).style(
150 if charge_percent < 10.0 {
151 self.styles.low_battery
152 } else if charge_percent < 50.0 {
153 self.styles.medium_battery
154 } else {
155 self.styles.high_battery
156 },
157 )]));
158
159 let mut battery_rows = Vec::with_capacity(3);
160 let watt_consumption = battery_details.watt_consumption();
161 let health = battery_details.health();
162
163 battery_rows.push(Row::new([""]).bottom_margin(table_gap + 1));
164 battery_rows
165 .push(Row::new(["Rate", &watt_consumption]).style(self.styles.text_style));
166
167 battery_rows.push(
168 Row::new(["State", battery_details.state.as_str()])
169 .style(self.styles.text_style),
170 );
171
172 let mut time: String; // Keep string lifetime in scope.
173 {
174 let style = self.styles.text_style;
175 let time_width = (full_width / 2) as usize;
176
177 match &battery_details.state {
178 BatteryState::Charging {
179 time_to_full: Some(secs),
180 } => {
181 time = long_time(*secs);
182
183 if time_width >= time.len() {
184 battery_rows.push(Row::new(["Time to full", &time]).style(style));
185 } else {
186 time = short_time(*secs);
187 battery_rows.push(Row::new(["To full", &time]).style(style));
188 }
189 }
190 BatteryState::Discharging {
191 time_to_empty: Some(secs),
192 } => {
193 time = long_time(*secs);
194
195 if time_width >= time.len() {
196 battery_rows.push(Row::new(["Time to empty", &time]).style(style));
197 } else {
198 time = short_time(*secs);
199 battery_rows.push(Row::new(["To empty", &time]).style(style));
200 }
201 }
202 _ => {}
203 }
204 }
205
206 battery_rows.push(Row::new(["Health", &health]).style(self.styles.text_style));
207
208 let header = if battery_harvest.len() > 1 {
209 Row::new([""]).bottom_margin(table_gap)
210 } else {
211 Row::default()
212 };
213
214 let block_inner = block.inner(margined_draw_loc);
215
216 // Draw bar
217 f.render_widget(
218 Table::new(battery_charge_rows, [Constraint::Percentage(100)])
219 .block(block.clone())
220 .header(header.clone()),
221 margined_draw_loc,
222 );
223
224 // Draw info
225 f.render_widget(
226 Table::new(
227 battery_rows,
228 [Constraint::Percentage(50), Constraint::Percentage(50)],
229 )
230 .block(block)
231 .header(header),
232 margined_draw_loc,
233 );
234
235 if table_gap > 0 && table_gap_setting == TableGap::Line && battery_harvest.len() > 1
236 {
237 let y = block_inner.y + 1;
238 let buf = f.buffer_mut();
239
240 for x in (margined_draw_loc.x + 1)
241 ..(margined_draw_loc.x + margined_draw_loc.width - 1)
242 {
243 if let Some(cell) = buf.cell_mut((x, y)) {
244 cell.set_symbol(line::NORMAL.horizontal);
245 cell.set_style(border_style);
246 }
247 }
248
249 if !is_basic || is_selected {
250 if let Some(cell) = buf.cell_mut((margined_draw_loc.x, y)) {
251 cell.set_symbol(line::NORMAL.vertical_right);
252 cell.set_style(border_style);
253 }
254
255 if let Some(cell) =
256 buf.cell_mut((margined_draw_loc.x + margined_draw_loc.width - 1, y))
257 {
258 cell.set_symbol(line::NORMAL.vertical_left);
259 cell.set_style(border_style);
260 }
261 }
262 }
263 } else {
264 let mut contents = vec![Line::default(); table_gap.into()];
265
266 contents.push(Line::from(Span::styled(
267 "No data found for this battery",
268 self.styles.text_style,
269 )));
270
271 f.render_widget(Paragraph::new(contents).block(block), margined_draw_loc);
272 }
273
274 if should_get_widget_bounds {
275 // Update draw loc in widget map
276 if let Some(widget) = app_state.widget_map.get_mut(&widget_id) {
277 widget.top_left_corner = Some((margined_draw_loc.x, margined_draw_loc.y));
278 widget.bottom_right_corner = Some((
279 margined_draw_loc.x + margined_draw_loc.width,
280 margined_draw_loc.y + margined_draw_loc.height,
281 ));
282 }
283 }
284 }
285 }
286 }
287
288 fn get_hms(secs: u32) -> (u32, u32, u32) {
289 let hours = secs / (60 * 60);
290 let minutes = (secs / 60) - hours * 60;
291 let seconds = secs - minutes * 60 - hours * 60 * 60;
292
293 (hours, minutes, seconds)
294 }
295
296 fn long_time(secs: u32) -> String {
297 let (hours, minutes, seconds) = get_hms(secs);
298
299 if hours > 0 {
300 let h = if hours == 1 { "hour" } else { "hours" };
301 let m = if minutes == 1 { "minute" } else { "minutes" };
302 let s = if seconds == 1 { "second" } else { "seconds" };
303
304 format!("{hours} {h}, {minutes} {m}, {seconds} {s}")
305 } else {
306 let m = if minutes == 1 { "minute" } else { "minutes" };
307 let s = if seconds == 1 { "second" } else { "seconds" };
308
309 format!("{minutes} {m}, {seconds} {s}")
310 }
311 }
312
313 fn short_time(secs: u32) -> String {
314 let (hours, minutes, seconds) = get_hms(secs);
315
316 if hours > 0 {
317 format!("{hours}h {minutes}m {seconds}s")
318 } else {
319 format!("{minutes}m {seconds}s")
320 }
321 }
322
323 #[cfg(test)]
324 mod tests {
325 use super::*;
326
327 #[test]
328 fn test_get_hms() {
329 assert_eq!(get_hms(10), (0, 0, 10));
330 assert_eq!(get_hms(60), (0, 1, 0));
331 assert_eq!(get_hms(61), (0, 1, 1));
332 assert_eq!(get_hms(3600), (1, 0, 0));
333 assert_eq!(get_hms(3601), (1, 0, 1));
334 assert_eq!(get_hms(3661), (1, 1, 1));
335 }
336
337 #[test]
338 fn test_long_time() {
339 assert_eq!(long_time(1), "0 minutes, 1 second".to_string());
340 assert_eq!(long_time(10), "0 minutes, 10 seconds".to_string());
341 assert_eq!(long_time(60), "1 minute, 0 seconds".to_string());
342 assert_eq!(long_time(61), "1 minute, 1 second".to_string());
343 assert_eq!(long_time(3600), "1 hour, 0 minutes, 0 seconds".to_string());
344 assert_eq!(long_time(3601), "1 hour, 0 minutes, 1 second".to_string());
345 assert_eq!(long_time(3661), "1 hour, 1 minute, 1 second".to_string());
346 }
347
348 #[test]
349 fn test_short_time() {
350 assert_eq!(short_time(1), "0m 1s".to_string());
351 assert_eq!(short_time(10), "0m 10s".to_string());
352 assert_eq!(short_time(60), "1m 0s".to_string());
353 assert_eq!(short_time(61), "1m 1s".to_string());
354 assert_eq!(short_time(3600), "1h 0m 0s".to_string());
355 assert_eq!(short_time(3601), "1h 0m 1s".to_string());
356 assert_eq!(short_time(3661), "1h 1m 1s".to_string());
357 }
358
359 #[test]
360 fn test_calculate_basic_use_bars() {
361 // Testing various breakpoints and edge cases.
362 assert_eq!(calculate_basic_use_bars(0.0, 15), 0);
363 assert_eq!(calculate_basic_use_bars(1.0, 15), 0);
364 assert_eq!(calculate_basic_use_bars(5.0, 15), 1);
365 assert_eq!(calculate_basic_use_bars(10.0, 15), 2);
366 assert_eq!(calculate_basic_use_bars(40.0, 15), 6);
367 assert_eq!(calculate_basic_use_bars(45.0, 15), 7);
368 assert_eq!(calculate_basic_use_bars(50.0, 15), 8);
369 assert_eq!(calculate_basic_use_bars(100.0, 15), 15);
370 assert_eq!(calculate_basic_use_bars(150.0, 15), 15);
371 }
372 }