Color CPU graph based on usage; green idle, red full utilization.

This commit is contained in:
Bill Thiede 2019-09-22 10:26:33 -07:00
parent 6f6fd13b94
commit ccd9cf5002

View File

@ -2,8 +2,7 @@ use std::collections::vec_deque::VecDeque;
use std::fs::File;
use std::io::{BufRead, BufReader, Result};
use i3monkit::Block;
use i3monkit::{Widget, WidgetUpdate};
use i3monkit::{Block, ColorRGB, Widget, WidgetUpdate};
use crate::spark;
@ -23,6 +22,19 @@ pub struct CpuWidget {
history: VecDeque<f32>,
}
fn color_lerp(c1: ColorRGB, c2: ColorRGB, alpha: f32) -> ColorRGB {
// TODO(wathiede): actual lerp.
ColorRGB(
(c1.0 as f32 * (1. - alpha) + c2.0 as f32 * alpha) as u8,
(c1.1 as f32 * (1. - alpha) + c2.1 as f32 * alpha) as u8,
(c1.2 as f32 * (1. - alpha) + c2.2 as f32 * alpha) as u8,
)
}
fn color_to_string(c: ColorRGB) -> String {
format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
}
impl CpuWidget {
fn read_status(id: u32) -> Result<(u64, u64, u64, u64)> {
let name = format!("cpu{}", id);
@ -87,7 +99,21 @@ impl CpuWidget {
min: Some(0.),
max: Some(1.),
};
Some(g.render(&self.history.iter().cloned().collect::<Vec<f32>>()))
let sg = g.render(&self.history.iter().cloned().collect::<Vec<f32>>());
let colored_sg = self
.history
.iter()
.zip(sg.chars())
.map(|(v, g)| {
let c = color_lerp(ColorRGB::green(), ColorRGB::red(), *v);
format!(
r##"<span foreground="{}">{}</span>"##,
color_to_string(c),
g
)
})
.collect();
Some(colored_sg)
} else {
Some("N/A".to_string())
}
@ -138,7 +164,7 @@ impl Widget for CpuWidget {
let mut data = Block::new();
data.use_pango();
data.append_full_text(&format!("{}: {}", self.id + 1, history));
data.append_full_text(&history);
return Some(WidgetUpdate {
refresh_interval: std::time::Duration::new(1, 0),