tablero 0.6.0

A fast, native Wayland status bar for Hyprland
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! System-pressure source: CPU and memory load from procfs.
//!
//! Samples the kernel's `/proc/stat` and `/proc/meminfo` on a fixed cadence and
//! emits typed [`Msg::System`] snapshots through the [producer bridge](crate::producer),
//! so system stats reach the render loop the same way every other message does —
//! the rendering code never reads procfs directly.
//!
//! CPU load is a *rate*, not an instantaneous value: `/proc/stat` reports
//! cumulative jiffies spent in each state since boot, so the producer keeps the
//! previous sample and reports the busy fraction *between* samples. Memory is a
//! single read of total vs. available. Both are normalized into a [`SystemStats`]
//! and emitted on each tick. The parsing lives in pure functions
//! ([`parse_cpu_times`], [`cpu_usage`], [`parse_mem_usage`]) the tests drive
//! directly — the full procfs text → message → widget path is covered without
//! sampling the live machine.

use std::fs;
use std::time::Duration;

use log::warn;
use tokio::time::interval;

use crate::widget::{Msg, SystemStats};

use crate::producer::{MsgSender, Producer, ProducerFuture, ProducerResult};

/// How often the producer samples system load.
///
/// Three seconds is frequent enough to track pressure as it moves but far too
/// coarse to keep the loop busy: between ticks the producer is parked on a timer
/// and the render loop is idle, woken only by a sample that changes a visible
/// percent. Configurable per widget as `interval`.
pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(3);

/// A point-in-time reading of the kernel's aggregate CPU time counters.
///
/// Both fields are cumulative jiffies since boot: `total` across every state and
/// `idle` for the idle states (idle + iowait). CPU load is the busy fraction of
/// the change in these between two readings — see [`cpu_usage`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CpuTimes {
    /// Jiffies spent idle (idle + iowait).
    idle: u64,
    /// Jiffies spent in all states.
    total: u64,
}

/// Parse the aggregate `cpu` line of `/proc/stat` into its time counters.
///
/// `/proc/stat` opens with an aggregate `cpu` line (whose first token is exactly
/// `cpu`) followed by per-core `cpu0`, `cpu1`, … lines; only the aggregate is
/// read. The numeric fields are `user nice system idle iowait irq softirq steal
/// guest guest_nice`; `total` sums them and `idle` is `idle + iowait`. Returns
/// `None` if the aggregate line is missing or malformed. Pure over its input.
#[hotpath::measure]
pub fn parse_cpu_times(proc_stat: &str) -> Option<CpuTimes> {
    let line = proc_stat
        .lines()
        .find(|l| l.split_whitespace().next() == Some("cpu"))?;
    let (mut fields, mut total, mut idle) = (0, 0_u64, 0_u64);
    for token in line.split_whitespace().skip(1) {
        let value = token.parse::<u64>().ok()?;
        total += value;
        // Fields 3 and 4 are idle and iowait.
        if matches!(fields, 3 | 4) {
            idle += value;
        }
        fields += 1;
    }
    // Need at least user/nice/system/idle; iowait and the rest are optional on
    // older kernels.
    if fields < 4 {
        return None;
    }
    Some(CpuTimes { idle, total })
}

/// The busy fraction (0.0–100.0) of CPU time between two readings.
///
/// Load is `busy / total` over the *change* in counters from `prev` to `cur`.
/// A zero or backwards delta (no elapsed time, or a counter reset) degrades to
/// `0.0` rather than dividing by zero or underflowing.
pub fn cpu_usage(prev: CpuTimes, cur: CpuTimes) -> f64 {
    let total = cur.total.saturating_sub(prev.total);
    if total == 0 {
        return 0.0;
    }
    let idle = cur.idle.saturating_sub(prev.idle);
    let busy = total.saturating_sub(idle);
    busy as f64 / total as f64 * 100.0
}

/// Parse `/proc/meminfo` into memory load (0.0–100.0): used as a fraction of total.
///
/// Used memory is `MemTotal - MemAvailable` — `MemAvailable` is the kernel's own
/// estimate of what is reclaimable for new work, the figure a user reads as
/// "free", so this matches what tools like `free` report. Returns `None` if
/// either field is missing or `MemTotal` is zero. Pure over its input.
#[hotpath::measure]
pub fn parse_mem_usage(proc_meminfo: &str) -> Option<f64> {
    let (used, total) = parse_mem_kib(proc_meminfo)?;
    Some(used as f64 / total as f64 * 100.0)
}

/// Parse `/proc/meminfo` into `(used, total)` kibibytes, where used is
/// `MemTotal - MemAvailable`. Returns `None` if either field is missing or
/// `MemTotal` is zero. Pure over its input.
pub fn parse_mem_kib(proc_meminfo: &str) -> Option<(u64, u64)> {
    let mut total = None;
    let mut available = None;
    for line in proc_meminfo.lines() {
        if let Some(rest) = line.strip_prefix("MemTotal:") {
            total = parse_kb(rest);
        } else if let Some(rest) = line.strip_prefix("MemAvailable:") {
            available = parse_kb(rest);
        }
    }
    let total = total?;
    let available = available?;
    if total == 0 {
        return None;
    }
    Some((total.saturating_sub(available), total))
}

/// Parse the leading kibibyte value of a `/proc/meminfo` field (e.g. `  16384 kB`).
fn parse_kb(field: &str) -> Option<u64> {
    field.split_whitespace().next()?.parse().ok()
}

/// Reads procfs files into one buffer kept across samples.
#[derive(Default)]
struct ProcReader {
    buf: String,
}

impl ProcReader {
    /// The current contents of `path`.
    fn read(&mut self, path: &str) -> std::io::Result<&str> {
        use std::io::Read;
        self.buf.clear();
        fs::File::open(path)?.read_to_string(&mut self.buf)?;
        Ok(&self.buf)
    }
}

/// Read and parse the current CPU counters, logging and degrading to `None` on
/// any failure so a transient read error never ends the stream.
#[hotpath::measure]
fn read_cpu_times(reader: &mut ProcReader) -> Option<CpuTimes> {
    // procfs reads are served from kernel memory, not disk, so this does not
    // meaningfully block the runtime.
    match reader.read("/proc/stat") {
        Ok(stat) => parse_cpu_times(stat),
        Err(e) => {
            warn!("sysmon: reading /proc/stat failed: {e}");
            None
        }
    }
}

/// Read and parse the current `(used, total)` memory in kibibytes, logging and
/// degrading to `None` on any failure.
#[hotpath::measure]
fn read_mem_kib(reader: &mut ProcReader) -> Option<(u64, u64)> {
    match reader.read("/proc/meminfo") {
        Ok(meminfo) => parse_mem_kib(meminfo),
        Err(e) => {
            warn!("sysmon: reading /proc/meminfo failed: {e}");
            None
        }
    }
}

/// A [`Producer`] that samples CPU and memory load on a fixed cadence.
///
/// Construct with [`new`](SystemProducer::new) and hand it to the producer
/// bridge; it seeds a CPU baseline, then on every tick reports the load since the
/// previous sample until the render loop shuts down.
pub struct SystemProducer {
    interval: Duration,
}

impl SystemProducer {
    /// Create a system-stats producer sampling at the default cadence.
    pub fn new() -> Self {
        Self {
            interval: DEFAULT_INTERVAL,
        }
    }

    /// Create a producer sampling at a custom `interval`.
    pub fn with_interval(interval: Duration) -> Self {
        Self { interval }
    }
}

impl Default for SystemProducer {
    fn default() -> Self {
        Self::new()
    }
}

impl Producer for SystemProducer {
    fn name(&self) -> String {
        "system-stats".to_string()
    }

    fn run(self: Box<Self>, tx: MsgSender) -> ProducerFuture {
        Box::pin(run(tx, self.interval))
    }
}

/// Drive the sampling loop: seed a CPU baseline, then emit load on each tick.
///
/// CPU load needs two readings to form a delta, so the first tick (which a Tokio
/// [`interval`] fires immediately) only seeds the baseline; every tick after that
/// emits a [`SystemStats`] if it differs from the last one sent — the snapshot is
/// whole percents, so a steady machine sends nothing and the render loop sleeps
/// on. A failed CPU read degrades that tick's CPU figure to
/// `0` and keeps the last good baseline; a failed memory read degrades to `0`.
/// Returns `Ok(())` once the render loop drops its receiver.
async fn run(tx: MsgSender, period: Duration) -> ProducerResult {
    let mut ticker = interval(period);

    // The first tick completes immediately; use it only to seed the CPU baseline
    // so the first emitted sample reflects real elapsed time.
    ticker.tick().await;
    let mut reader = ProcReader::default();
    let mut prev = read_cpu_times(&mut reader);
    let mut sent = None;

    loop {
        ticker.tick().await;

        let cur = read_cpu_times(&mut reader);
        let cpu = match (prev, cur) {
            (Some(p), Some(c)) => cpu_usage(p, c),
            // No baseline yet (or this read failed): report 0 this tick.
            _ => 0.0,
        };
        if cur.is_some() {
            prev = cur;
        }

        let stats = match read_mem_kib(&mut reader) {
            Some((used, total)) => {
                SystemStats::new(cpu, used as f64 / total as f64 * 100.0).with_memory(used, total)
            }
            None => SystemStats::new(cpu, 0.0),
        };

        if !send_if_changed(&tx, &mut sent, stats) {
            return Ok(());
        }
    }
}

/// Send `stats` unless it is what the widget already shows. Returns `false`
/// once the render loop has gone away.
fn send_if_changed(tx: &MsgSender, sent: &mut Option<SystemStats>, stats: SystemStats) -> bool {
    if *sent == Some(stats) {
        return true;
    }
    *sent = Some(stats);
    tx.send(Msg::System(stats)).is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    // An aggregate `cpu` line (idle + iowait = 800 + 30 = 830; total = 1000)
    // followed by a per-core line the parser must skip, plus unrelated fields.
    const PROC_STAT: &str = "cpu  100 0 50 800 30 0 20 0 0 0
cpu0 50 0 25 400 15 0 10 0 0 0
intr 12345 0 0
ctxt 67890
";

    const PROC_MEMINFO: &str = "MemTotal:       16000000 kB
MemFree:         2000000 kB
MemAvailable:    8000000 kB
Buffers:          500000 kB
Cached:          3000000 kB
";

    #[test]
    fn the_proc_reader_reuses_its_buffer_across_reads() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("stat");
        let path = path.to_str().unwrap();
        let mut reader = ProcReader::default();

        // Once grown to the larger file, later samples fit in place.
        assert!(PROC_MEMINFO.len() > PROC_STAT.len());
        fs::write(path, PROC_MEMINFO).unwrap();
        assert_eq!(reader.read(path).unwrap(), PROC_MEMINFO);
        let buffer = reader.buf.as_ptr();
        fs::write(path, PROC_STAT).unwrap();
        assert_eq!(reader.read(path).unwrap(), PROC_STAT);
        assert_eq!(
            reader.buf.as_ptr(),
            buffer,
            "a sample reallocated the buffer"
        );
        fs::write(path, PROC_MEMINFO).unwrap();
        assert_eq!(reader.read(path).unwrap(), PROC_MEMINFO);
        assert_eq!(
            reader.buf.as_ptr(),
            buffer,
            "a sample reallocated the buffer"
        );
        assert!(reader.read("/nonexistent/stat").is_err());
    }

    #[test]
    fn an_unchanged_whole_percent_reading_is_not_sent_again() {
        let (bridge, channel) = crate::producer::ProducerBridge::new().unwrap();
        let tx = bridge.sender();
        let mut sent = None;

        assert!(send_if_changed(
            &tx,
            &mut sent,
            SystemStats::new(12.2, 47.0)
        ));
        // Moves within the displayed percent: the widget would show the same.
        assert!(send_if_changed(
            &tx,
            &mut sent,
            SystemStats::new(12.4, 47.3)
        ));
        assert!(send_if_changed(
            &tx,
            &mut sent,
            SystemStats::new(13.0, 47.0)
        ));

        let received: Vec<_> = std::iter::from_fn(|| channel.try_recv().ok())
            .map(|msg| match msg {
                Msg::System(stats) => stats,
                other => panic!("unexpected message: {other:?}"),
            })
            .collect();
        assert_eq!(
            received,
            [SystemStats::new(12.0, 47.0), SystemStats::new(13.0, 47.0)]
        );
    }

    #[test]
    fn a_closed_render_loop_ends_the_producer_on_the_next_change() {
        let (bridge, channel) = crate::producer::ProducerBridge::new().unwrap();
        let tx = bridge.sender();
        drop((bridge, channel));
        assert!(!send_if_changed(&tx, &mut None, SystemStats::new(1.0, 1.0)));
    }

    #[test]
    fn parse_cpu_times_reads_the_aggregate_line() {
        let times = parse_cpu_times(PROC_STAT).expect("aggregate cpu line");
        assert_eq!(times.total, 1000);
        assert_eq!(times.idle, 830);
    }

    #[test]
    fn parse_cpu_times_rejects_input_without_an_aggregate_line() {
        // Only per-core lines: no aggregate `cpu` line to read.
        assert_eq!(parse_cpu_times("cpu0 1 2 3 4\nintr 5\n"), None);
        assert_eq!(parse_cpu_times("not proc stat"), None);
    }

    #[test]
    fn parse_cpu_times_rejects_a_truncated_aggregate_line() {
        // Fewer than the four required fields (user/nice/system/idle).
        assert_eq!(parse_cpu_times("cpu 1 2 3\n"), None);
    }

    #[test]
    fn cpu_usage_is_the_busy_fraction_between_samples() {
        // 100 jiffies elapsed, 50 of them idle: 50% busy.
        let prev = CpuTimes {
            idle: 80,
            total: 100,
        };
        let cur = CpuTimes {
            idle: 130,
            total: 200,
        };
        assert!((cpu_usage(prev, cur) - 50.0).abs() < 1e-6);
    }

    #[test]
    fn cpu_usage_handles_no_elapsed_time() {
        let same = CpuTimes {
            idle: 80,
            total: 100,
        };
        assert_eq!(cpu_usage(same, same), 0.0);
    }

    #[test]
    fn cpu_usage_handles_a_counter_reset() {
        // A backwards delta (e.g. after a reset) must not underflow; report 0.
        let prev = CpuTimes {
            idle: 130,
            total: 200,
        };
        let cur = CpuTimes {
            idle: 80,
            total: 100,
        };
        assert_eq!(cpu_usage(prev, cur), 0.0);
    }

    #[test]
    fn parse_mem_usage_is_used_over_total() {
        // 16000000 total, 8000000 available -> 8000000 used -> 50%.
        let mem = parse_mem_usage(PROC_MEMINFO).expect("mem fields present");
        assert!((mem - 50.0).abs() < 1e-6);
    }

    #[test]
    fn parse_mem_kib_is_used_and_total() {
        assert_eq!(parse_mem_kib(PROC_MEMINFO), Some((8_000_000, 16_000_000)));
        assert_eq!(parse_mem_kib("MemTotal: 16000000 kB\n"), None);
    }

    #[test]
    fn parse_mem_usage_requires_both_fields() {
        assert_eq!(parse_mem_usage("MemTotal: 16000000 kB\n"), None);
        assert_eq!(parse_mem_usage("MemAvailable: 8000000 kB\n"), None);
    }

    #[test]
    fn parse_mem_usage_rejects_zero_total() {
        assert_eq!(
            parse_mem_usage("MemTotal: 0 kB\nMemAvailable: 0 kB\n"),
            None
        );
    }
}