feat: update the cpu graph async

This commit is contained in:
electria 2026-08-15 14:38:06 -07:00
commit 2314f67349
Signed by: electria
SSH key fingerprint: SHA256:8LlB3ucPbBHqozqkhsNbaV5oG3SlzzqUj8FZDL6IPQs
3 changed files with 72 additions and 32 deletions

View file

@ -1,48 +1,51 @@
use std::time::Instant;
use iced::{
Color, Element, Length, Renderer, Subscription, Task, Theme, application, theme, widget, window,
Color, Element, Length, Renderer, Task, Theme, application, futures::SinkExt, stream::channel,
theme, widget,
};
use smol::Timer;
use crate::app::cpu_graph::CpuGraph;
mod cpu_graph;
enum Message {
Frame(Instant),
Cpu(f32),
}
struct State {
sys: sysinfo::System,
refreshes: sysinfo::RefreshKind,
last_refresh: Instant,
cpu_graph: CpuGraph,
}
impl State {
fn new() -> Self {
Self {
sys: sysinfo::System::new(),
refreshes: sysinfo::RefreshKind::nothing()
.with_cpu(sysinfo::CpuRefreshKind::nothing().with_cpu_usage()),
fn new() -> (Self, Task<Message>) {
(
Self {
cpu_graph: Default::default(),
},
Task::run(
channel(1, async |mut sender| {
let mut sys = sysinfo::System::new();
let refreshes = sysinfo::RefreshKind::nothing()
.with_cpu(sysinfo::CpuRefreshKind::nothing().with_cpu_usage());
cpu_graph: Default::default(),
last_refresh: Instant::now(),
}
sys.refresh_specifics(refreshes);
Timer::after(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL).await;
loop {
sys.refresh_specifics(refreshes);
Timer::after(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL).await;
sender.send(sys.global_cpu_usage()).await.unwrap();
}
}),
Message::Cpu,
),
)
}
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::Frame(instant) => {
if instant.duration_since(self.last_refresh) >= sysinfo::MINIMUM_CPU_UPDATE_INTERVAL
{
self.sys.refresh_specifics(self.refreshes);
self.cpu_graph.update(self.sys.global_cpu_usage());
self.cpu_graph.cache.clear();
self.last_refresh = instant;
}
Message::Cpu(value) => {
self.cpu_graph.update(value);
self.cpu_graph.cache.clear();
}
}
@ -54,15 +57,10 @@ impl State {
.height(Length::Fill)
.into()
}
fn subscription(&self) -> Subscription<Message> {
window::frames().map(Message::Frame)
}
}
pub fn run() -> Result<(), impl std::error::Error> {
application(State::new, State::update, State::view)
.subscription(State::subscription)
.theme(theme::Theme::custom(
"high-contrast-dark",
theme::Palette {