mirador 1.8.0

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
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
//! Network throughput, as two scrolling charts: received and transmitted.
//!
//! Rates are computed from byte deltas divided by the real elapsed time between
//! samples, not by the configured interval, so a stalled or slow tick reports
//! the correct rate instead of an inflated one.

use std::collections::VecDeque;
use std::time::{Duration, Instant};

use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::Span;
use ratatui::widgets::Paragraph;
use sysinfo::Networks;

use crate::chart::BrailleGraph;
use crate::config::NetworkConfig;
use crate::frame::Binding;
use crate::panel::{Panel, RenderContext};
use crate::samples::push_bounded;

/// The network panel.
pub struct NetworkPanel {
    config: NetworkConfig,
    networks: Networks,
    /// Bytes per second received, oldest first.
    rx_history: VecDeque<u64>,
    /// Bytes per second transmitted, oldest first.
    tx_history: VecDeque<u64>,
    rx_rate: u64,
    tx_rate: u64,
    rx_total: u64,
    tx_total: u64,
    /// The since-boot counters as they read at the first sample.
    ///
    /// `sysinfo`'s `total_received` counts from boot, not from when the
    /// `Networks` list was built, so the panel's "session" line was reporting
    /// the machine's whole uptime. On a host up for three weeks it read 128 GB
    /// within a minute of launch. Subtracting the first reading makes the label
    /// true; `None` until that first sample lands.
    since_boot: Option<(u64, u64)>,
    last_sample: Instant,
    /// False until the second sample, since the first has no delta to compare.
    primed: bool,
    /// Cells each graph was last drawn into, so the buffers can grow to fill.
    graph_cells: usize,
}

impl std::fmt::Debug for NetworkPanel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NetworkPanel")
            .field("rx_rate", &self.rx_rate)
            .field("tx_rate", &self.tx_rate)
            .field("samples", &self.rx_history.len())
            .finish_non_exhaustive()
    }
}

impl NetworkPanel {
    /// Build the panel and prime the interface list.
    pub fn new(config: NetworkConfig) -> Self {
        let networks = Networks::new_with_refreshed_list();
        Self {
            rx_history: VecDeque::with_capacity(config.history.max(1)),
            tx_history: VecDeque::with_capacity(config.history.max(1)),
            config,
            networks,
            rx_rate: 0,
            tx_rate: 0,
            graph_cells: 0,
            rx_total: 0,
            tx_total: 0,
            since_boot: None,
            last_sample: Instant::now(),
            primed: false,
        }
    }

    /// Whether an interface should be counted.
    fn includes(&self, name: &str) -> bool {
        if self.config.interfaces.is_empty() {
            !is_loopback(name)
        } else {
            self.config.interfaces.iter().any(|want| want == name)
        }
    }

    /// Sample byte counters and convert them to a rate.
    ///
    /// Returns whether it actually sampled; see `CpuPanel::sample` for why the
    /// answer matters more than it looks.
    fn sample(&mut self) -> bool {
        let interval = Duration::from_secs(self.config.sample_secs.max(1));
        let elapsed = self.last_sample.elapsed();
        if elapsed < interval {
            return false;
        }

        self.networks.refresh(true);

        let mut rx_delta = 0u64;
        let mut tx_delta = 0u64;
        let mut rx_total = 0u64;
        let mut tx_total = 0u64;

        for (name, data) in &self.networks {
            if !self.includes(name) {
                continue;
            }
            rx_delta = rx_delta.saturating_add(data.received());
            tx_delta = tx_delta.saturating_add(data.transmitted());
            rx_total = rx_total.saturating_add(data.total_received());
            tx_total = tx_total.saturating_add(data.total_transmitted());
        }

        // Divide by the time that actually elapsed, not the nominal interval.
        let seconds = elapsed.as_secs_f64().max(0.001);
        self.rx_rate = (rx_delta as f64 / seconds) as u64;
        self.tx_rate = (tx_delta as f64 / seconds) as u64;
        let (rx_base, tx_base) = *self.since_boot.get_or_insert((rx_total, tx_total));
        // Saturating: an interface disappearing takes its counter with it, so
        // the sum can fall below the baseline. Zero is the honest answer then,
        // not a number wrapped around u64.
        self.rx_total = rx_total.saturating_sub(rx_base);
        self.tx_total = tx_total.saturating_sub(tx_base);
        self.last_sample = Instant::now();

        // The first refresh after construction reports the counters since the
        // list was built, which is not a meaningful rate. Drop it.
        if !self.primed {
            self.primed = true;
            self.rx_rate = 0;
            self.tx_rate = 0;
            // Still a change: the panel goes from "no reading" to two zeroes.
            return true;
        }

        let capacity = self.capacity();
        push_bounded(&mut self.rx_history, self.rx_rate, capacity);
        push_bounded(&mut self.tx_history, self.tx_rate, capacity);
        true
    }

    /// How many samples to retain; see [`crate::samples::capacity`].
    fn capacity(&self) -> usize {
        crate::samples::capacity(self.config.history, self.graph_cells)
    }

    /// A shared ceiling for both charts so rx and tx stay visually comparable.
    fn scale(&self) -> u64 {
        self.rx_history
            .iter()
            .chain(self.tx_history.iter())
            .copied()
            .max()
            .unwrap_or(1)
            .max(1)
    }
}

/// Recognise loopback interfaces across platforms.
fn is_loopback(name: &str) -> bool {
    name == "lo" || name == "lo0" || name.starts_with("Loopback")
}

/// Format a byte count as a human-readable rate, e.g. `1.2 MB/s`.
pub fn format_rate(bytes_per_sec: u64) -> String {
    format!("{}/s", format_bytes(bytes_per_sec))
}

/// Format a byte count with a binary-ish scale and one decimal place.
pub fn format_bytes(bytes: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit < UNITS.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes} {}", UNITS[0])
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

/// Keys this panel responds to.
const BINDINGS: &[Binding] = &[];

impl Panel for NetworkPanel {
    fn title(&self) -> String {
        "Network".to_string()
    }

    fn counter(&self) -> Option<String> {
        if self.config.interfaces.is_empty() {
            Some("all".to_string())
        } else {
            Some(self.config.interfaces.join(" "))
        }
    }

    fn bindings(&self) -> &'static [Binding] {
        BINDINGS
    }

    fn refresh_interval(&self) -> Duration {
        Duration::from_millis(500)
    }

    fn tick(&mut self) -> bool {
        self.sample()
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: RenderContext<'_>) {
        let theme = ctx.theme;
        if area.height == 0 || area.width == 0 {
            return;
        }

        let rx_color = ctx.gradients.rx.at(100);
        let tx_color = ctx.gradients.tx.at(100);
        let track = Style::default().fg(theme.track);

        // Two stacked graphs when there is room; one combined readout when not.
        let rows = Layout::vertical([
            Constraint::Length(1),                           // readout
            Constraint::Min(1),                              // rx graph
            Constraint::Min(1),                              // tx graph
            Constraint::Length(u16::from(area.height >= 6)), // totals
        ])
        .split(area);

        // An arrow and the rate it points at are one part, so a pane too narrow
        // for both readouts loses the upload arrow along with its figure. It
        // used to keep the arrow and lose the number, which drew `↑` followed
        // by nothing — a heading over an empty space, which reads as zero
        // rather than as absent. At a middling width it was worse still: `6.4
        // KB` survived where `6.4 KB/s` was meant, and a total is not a rate.
        let rx = format_rate(self.rx_rate);
        let tx = format_rate(self.tx_rate);

        // The figures are padded to a fixed field so they hold still as they
        // change — a rate that shifts sideways every second is the restlessness
        // this dashboard exists not to have. The padding is the first thing
        // given up, though, because losing the upload reading entirely to keep
        // the download's right margin is the wrong trade at the widths where
        // that choice comes up.
        let padded = 2 + 10 + 5 + 10;
        let (rx_text, arrow, tx_text) = if usize::from(rows[0].width) >= padded {
            (format!("{rx:>10}"), "   \u{2191} ", format!("{tx:>10}"))
        } else {
            (rx, " \u{2191} ", tx)
        };

        frame.render_widget(
            Paragraph::new(crate::grid::assemble(
                vec![
                    vec![
                        Span::styled("\u{2193} ", Style::default().fg(rx_color)),
                        Span::styled(
                            rx_text,
                            Style::default().fg(rx_color).add_modifier(Modifier::BOLD),
                        ),
                    ],
                    vec![
                        Span::styled(arrow, Style::default().fg(tx_color)),
                        Span::styled(
                            tx_text,
                            Style::default().fg(tx_color).add_modifier(Modifier::BOLD),
                        ),
                    ],
                ],
                rows[0].width,
            )),
            rows[0],
        );

        // A shared ceiling keeps the two graphs visually comparable: a tall
        // upload spike should not look like a tall download spike at 1% the
        // rate.
        let scale = self.scale();

        // Recorded so the next tick sizes the buffers to the panel.
        self.graph_cells = rows[1].width as usize;

        let rx: Vec<u64> = self.rx_history.iter().copied().collect();
        let tx: Vec<u64> = self.tx_history.iter().copied().collect();
        for (index, (data, gradient)) in [(&rx, &ctx.gradients.rx), (&tx, &ctx.gradients.tx)]
            .into_iter()
            .enumerate()
        {
            let row = rows[index + 1];
            if row.height == 0 {
                continue;
            }
            BrailleGraph::new(data, scale, gradient)
                .track_style(track)
                .render(row, frame.buffer_mut());
        }

        if rows[3].height > 0 {
            let muted = Style::default().fg(theme.muted);
            frame.render_widget(
                Paragraph::new(crate::grid::assemble(
                    vec![
                        vec![Span::styled(
                            crate::glyphs::utility("session"),
                            Style::default()
                                .fg(theme.label)
                                .add_modifier(Modifier::BOLD),
                        )],
                        vec![Span::styled(
                            format!("  \u{2193} {}", format_bytes(self.rx_total)),
                            muted,
                        )],
                        vec![Span::styled(
                            format!("  \u{2191} {}", format_bytes(self.tx_total)),
                            muted,
                        )],
                        vec![Span::styled(
                            format!("   peak {}", format_rate(scale)),
                            muted,
                        )],
                    ],
                    rows[3].width,
                )),
                rows[3],
            );
        }
    }
}

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

    #[test]
    fn bytes_format_across_every_unit() {
        assert_eq!(format_bytes(0), "0 B");
        assert_eq!(format_bytes(512), "512 B");
        assert_eq!(format_bytes(1024), "1.0 KB");
        assert_eq!(format_bytes(1536), "1.5 KB");
        assert_eq!(format_bytes(1024 * 1024), "1.0 MB");
        assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB");
        assert_eq!(format_bytes(1024u64.pow(4)), "1.0 TB");
    }

    #[test]
    fn very_large_values_stay_in_the_top_unit_instead_of_overflowing() {
        let huge = format_bytes(u64::MAX);
        assert!(huge.ends_with("TB"), "got: {huge}");
    }

    #[test]
    fn rates_are_suffixed() {
        assert_eq!(format_rate(0), "0 B/s");
        assert_eq!(format_rate(2048), "2.0 KB/s");
    }

    #[test]
    fn loopback_is_recognised_on_every_platform() {
        assert!(is_loopback("lo"));
        assert!(is_loopback("lo0"));
        assert!(is_loopback("Loopback Pseudo-Interface 1"));
        assert!(!is_loopback("en0"));
        assert!(!is_loopback("eth0"));
        assert!(!is_loopback("wlan0"));
    }

    #[test]
    fn an_empty_interface_list_means_everything_but_loopback() {
        let panel = NetworkPanel::new(NetworkConfig::default());
        assert!(panel.includes("en0"));
        assert!(!panel.includes("lo0"));
    }

    #[test]
    fn an_explicit_interface_list_is_exclusive() {
        let panel = NetworkPanel::new(NetworkConfig {
            interfaces: vec!["en0".into()],
            ..Default::default()
        });
        assert!(panel.includes("en0"));
        assert!(!panel.includes("en1"));
        // An explicit list wins even for loopback.
        let lo = NetworkPanel::new(NetworkConfig {
            interfaces: vec!["lo0".into()],
            ..Default::default()
        });
        assert!(lo.includes("lo0"));
    }

    #[test]
    fn push_bounded_evicts_the_oldest_sample() {
        let mut buffer = VecDeque::new();
        for i in 0..10 {
            push_bounded(&mut buffer, i, 3);
        }
        assert_eq!(buffer.len(), 3);
        assert_eq!(buffer, VecDeque::from(vec![7, 8, 9]));
    }

    #[test]
    fn scale_is_never_zero_so_the_chart_cannot_divide_by_it() {
        let panel = NetworkPanel::new(NetworkConfig::default());
        assert_eq!(panel.scale(), 1, "an empty history must still yield 1");
    }

    #[test]
    fn scale_spans_both_series() {
        let mut panel = NetworkPanel::new(NetworkConfig::default());
        panel.rx_history.extend([10, 20]);
        panel.tx_history.extend([5, 99]);
        assert_eq!(panel.scale(), 99);
    }

    #[test]
    #[ignore = "superseded: the graph now takes the whole history"]
    fn recent_never_over_reads() {
        let history = VecDeque::from(vec![1, 2, 3]);
        let _ = history;
    }
}