mirador 1.22.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
//! Disk space: every volume worth watching, how full it is, and what is left.
//!
//! The last quarter of "what compute is available", and the one every monitor
//! this program borrows from shows under memory. It exists to say one thing
//! before it matters: this volume is filling up. So the figure that leads is
//! how full, the one beside it is what is free, and the colour changes only
//! at the thresholds — brass while there is room, amber past
//! `warn_above_pct`, red past `alert_above_pct`, where the status bar says so
//! too. A disk at 60% is not warm the way a die at 60° is, which is why this
//! panel does not share the cpu ramp.
//!
//! **Reading a volume is a blocking call**, and on a network mount that has
//! gone to sleep it can block for a minute — so the reading is done on a
//! thread and polled in `tick`, as weather's is, even though it is local.
//! Every read costs about a tenth of a second on this `MacBook` for two
//! volumes, which would be a visible stall on the main thread anyway.
//!
//! **The panel's real work is `group`.** The platform lists *volumes*, and a
//! person thinks in *devices*: macOS reports `/` and `/System/Volumes/Data`
//! as two entries of one APFS container, with one pool of free space between
//! them, and listing both would show the same disk twice. Linux lists every
//! snap as a read-only squashfs loop that is full by construction. Volumes
//! that share a device are folded into one row named by the shortest mount
//! point, read-only volumes are dropped because nothing can fill them, and
//! what is left is what a person would ask about.
//!
//! Under each device, since 1.16.0, the network panel's face: a `↓ read
//! ↑ write` readout and two braille histories scaled to the device's own
//! peak — floored at a megabyte a second, so the trickle of background
//! writes every disk carries draws low instead of filling a graph that has
//! nothing bigger to show. `i` hides them for anyone who wants the panel as
//! it was.

use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::chart::{BrailleGraph, draw_notice, meter_line, percent};
use crate::config::DiskConfig;
use crate::frame::{Binding, FRAME_HEIGHT};
use crate::keymap::{KeysConfig, Meta, PanelKeymap};
use crate::panel::{Panel, RenderContext};

/// One mounted volume as the platform reports it, before grouping.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Volume {
    pub mount: String,
    /// What the platform calls it: the volume name on macOS, which both
    /// halves of an APFS container share, what it is mounted from on Linux and the
    /// BSDs — a device or a ZFS dataset — and the label on Windows, which may
    /// be empty.
    pub name: String,
    pub file_system: String,
    pub total: u64,
    pub available: u64,
    pub read_only: bool,
    /// Bytes a second since the previous reading.
    pub read_rate: u64,
    pub write_rate: u64,
}

/// One row of the panel: a device, named by its friendliest mount point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Device {
    pub mount: String,
    pub total: u64,
    pub available: u64,
    /// Bytes a second since the previous reading.
    pub read_rate: u64,
    pub write_rate: u64,
}

impl Device {
    fn used(&self) -> u64 {
        self.total.saturating_sub(self.available)
    }

    /// Whole percent used, saturating at 100 and reading 0 for no capacity.
    fn used_pct(&self) -> u16 {
        percent(self.used(), self.total)
    }
}

/// Bytes the way a disk is sold and Finder states it: decimal units, one
/// decimal above a terabyte and below ten gigabytes, whole figures between.
pub(crate) fn human(bytes: u64) -> String {
    const TB: f64 = 1e12;
    const GB: f64 = 1e9;
    const MB: f64 = 1e6;
    let b = bytes as f64;
    if b >= TB {
        format!("{:.1} TB", b / TB)
    } else if b >= 10.0 * GB {
        format!("{:.0} GB", b / GB)
    } else if b >= GB {
        format!("{:.1} GB", b / GB)
    } else if b >= MB {
        format!("{:.0} MB", b / MB)
    } else {
        format!("{} kB", bytes / 1000)
    }
}

/// A read or write rate in the same units as the capacity beside it, with a
/// decimal below ten of a unit: `1.4 MB/s`, `327 kB/s`, and `0 kB/s` for a
/// disk doing nothing, or too little to show.
///
/// Decimal because the network panel's formatter divides by 1024 under the
/// same letters, and borrowing it put two meanings of `MB` on one device.
/// Not [`human`], though it shares the units: a capacity moves by the
/// gigabyte and reads well in whole megabytes, where a rate of 1.4 MB a
/// second shown as `1 MB/s` has lost a third of itself. Rounded half up in
/// integers, so neither `{:.0}`'s ties to even nor a cut decides a figure,
/// and the unit is the first whose rounded figure is under a thousand, so
/// 999.5 kB is `1.0 MB/s` and never `1000 kB/s`.
fn rate(bytes_per_sec: u64) -> String {
    const UNITS: [(u128, &str); 4] = [
        (1_000, "kB"),
        (1_000_000, "MB"),
        (1_000_000_000, "GB"),
        (1_000_000_000_000, "TB"),
    ];
    let bytes = u128::from(bytes_per_sec);
    // Whole units and tenths of one, each rounded half up.
    let whole = |unit: u128| (bytes + unit / 2) / unit;
    let tenths = |unit: u128| (bytes * 10 + unit / 2) / unit;
    let (unit, name) = UNITS
        .into_iter()
        .find(|&(unit, _)| whole(unit) < 1_000)
        .unwrap_or(UNITS[3]);
    match tenths(unit) {
        0 => format!("0 {name}/s"),
        t if t < 100 => format!("{}.{} {name}/s", t / 10, t % 10),
        _ => format!("{} {name}/s", whole(unit)),
    }
}

/// File systems that are never a disk filling up: a snap's squashfs image is
/// full the day it is written, an optical disc cannot be written at all, and
/// the memory-backed ones are memory.
const NOT_A_DISK: &[&str] = &[
    "squashfs", "iso9660", "udf", "tmpfs", "devtmpfs", "ramfs", "autofs", "overlay",
];

/// The least the tight line allows, whatever the capacity. It is there for
/// a container whose two halves do not share a name, which nothing here has
/// met and nothing promises against: they drift apart by what was written
/// between the two reads — 1.8 MB idle on the owner's Mac, 48 MB under a
/// `dd` from `/dev/urandom` — and that does not shrink with the disk, so a
/// ten-thousandth alone, 25 MB on a 256 GB Mac, would split such a
/// container under an ordinary write. It does not hold one through a write
/// at the SSD's own speed, which carried the drift to 641 MB; a shared name
/// is what does that.
const DRIFT_FLOOR: u64 = 128 * 1024 * 1024;

/// The tight line: how far apart two volumes' free space may be and still
/// be one device whatever their names — a ten-thousandth of the capacity,
/// 200 MB on 2 TB, and never less than [`DRIFT_FLOOR`], except that the
/// floor itself stops at a percent, so a disk under about thirteen
/// gigabytes is held exactly as tightly as it always was rather than more
/// loosely.
fn fold_tolerance(total: u64) -> u64 {
    (total / 10_000).max(DRIFT_FLOOR.min(total / 100))
}

/// Whether a volume is the device already seen with this capacity, free
/// space and name. See [`group`] for the rule and its edges.
fn same_device(total: u64, available: u64, name: &str, v: &Volume) -> bool {
    if total != v.total {
        return false;
    }
    let drift = available.abs_diff(v.available);
    drift <= fold_tolerance(total) || (!name.is_empty() && name == v.name && drift <= total / 100)
}

/// Fold the platform's volumes into the devices a person would list.
///
/// Two volumes are one device when they report the same capacity, and
/// either of two things holds:
///
/// - **The same name, and free space within a percent of the capacity.**
///   This is what holds an APFS container whole, and it was the whole rule
///   until two backup disks of one size fifteen gigabytes apart came out as
///   one row; the name is what tells those apart now. The container's two
///   halves share one pool and drift apart only by what was written between
///   the two reads, but a write at the SSD's own speed carries that a long
///   way — to 641 MB on the owner's 2 TB Mac, three times the tight line
///   below — and `sysinfo` names both halves `Macintosh HD`, so they are
///   held to the percent, twenty gigabytes there.
/// - **Free space within [`fold_tolerance`], whatever the names** — 200 MB
///   on 2 TB, 128 MiB on 256 GB. The hedge for a macOS that names the
///   halves apart, as `diskutil` does when it calls the second `Data`: such
///   a container is still one row idle and under an ordinary write, though
///   not under the fastest.
///
/// An empty name is no name, and a Windows volume with no label reports
/// one: two volumes that both lack a name have not been shown to share one,
/// so they are held to the tight line.
///
/// Two edges remain, one on each side, and no free-space rule can see past
/// either. Two disks of one size *and one name* — a pair bought together
/// and both left `Untitled` — whose free space is within a percent are one
/// row, until enough is written to one of them to carry it past: twenty
/// gigabytes on 2 TB. Nothing a volume reports tells them from the halves
/// of a container. And two disks of one size whatever their names are one
/// row while their free space is within the tight line, as a pair
/// formatted the same day is, until 200 MB is written to one on 2 TB.
///
/// The device takes the shortest mount point as its name, the smallest free
/// figure as its free space, and counts as writable if any of its volumes
/// is. Read-only devices are dropped while there is a writable one to show,
/// because a volume nothing can write to is a volume that never fills. Root
/// first, then by mount point, so the list holds still between reads.
pub(crate) fn group(volumes: Vec<Volume>) -> Vec<Device> {
    // Each device with the name of the first volume folded into it, which
    // is the one the rule compares; a second can only differ from it by
    // having come within the tight line.
    let mut devices: Vec<(Device, String, bool)> = Vec::new();
    for v in volumes {
        if v.total == 0 || NOT_A_DISK.contains(&v.file_system.to_ascii_lowercase().as_str()) {
            continue;
        }
        match devices
            .iter_mut()
            .find(|(d, name, _)| same_device(d.total, d.available, name, &v))
        {
            Some((d, _, writable)) => {
                if shorter(&v.mount, &d.mount) {
                    d.mount = v.mount;
                }
                d.available = d.available.min(v.available);
                // The volumes of one device report one set of counters, so
                // the larger is the device's, not the sum.
                d.read_rate = d.read_rate.max(v.read_rate);
                d.write_rate = d.write_rate.max(v.write_rate);
                *writable |= !v.read_only;
            }
            None => devices.push((
                Device {
                    mount: v.mount,
                    total: v.total,
                    available: v.available,
                    read_rate: v.read_rate,
                    write_rate: v.write_rate,
                },
                v.name,
                !v.read_only,
            )),
        }
    }
    if devices.iter().any(|(_, _, writable)| *writable) {
        devices.retain(|(_, _, writable)| *writable);
    }
    let mut out: Vec<Device> = devices.into_iter().map(|(d, _, _)| d).collect();
    out.sort_by(|a, b| shorter_order(&a.mount, &b.mount));
    out
}

fn shorter(a: &str, b: &str) -> bool {
    shorter_order(a, b) == std::cmp::Ordering::Less
}

fn shorter_order(a: &str, b: &str) -> std::cmp::Ordering {
    a.chars()
        .count()
        .cmp(&b.chars().count())
        .then_with(|| a.cmp(b))
}

/// The platform's disk list, kept between readings so the I/O counters
/// are deltas against the last one. Blocking; the thread's job.
struct Reader {
    disks: sysinfo::Disks,
    last: Instant,
    last_listing: Instant,
    /// How often to re-list volumes and re-read capacity, which is the
    /// expensive half; the I/O counters are read every time.
    relist_every: Duration,
}

impl Reader {
    fn new(relist_every: Duration) -> Self {
        use sysinfo::{DiskRefreshKind, Disks};
        let disks = Disks::new_with_refreshed_list_specifics(
            DiskRefreshKind::nothing().with_storage().with_io_usage(),
        );
        let now = Instant::now();
        Self {
            disks,
            last: now,
            last_listing: now,
            relist_every,
        }
    }

    fn read(&mut self) -> Vec<Volume> {
        use sysinfo::DiskRefreshKind;
        let now = Instant::now();
        let elapsed = now.duration_since(self.last).as_secs_f64().max(0.001);
        let relist = now.duration_since(self.last_listing) >= self.relist_every;
        let kind = if relist {
            DiskRefreshKind::nothing().with_storage().with_io_usage()
        } else {
            DiskRefreshKind::nothing().with_io_usage()
        };
        self.disks.refresh_specifics(relist, kind);
        if relist {
            self.last_listing = now;
        }
        self.last = now;
        let per_second = |bytes: u64| (bytes as f64 / elapsed) as u64;
        self.disks
            .list()
            .iter()
            .map(|d| Volume {
                mount: d.mount_point().to_string_lossy().into_owned(),
                name: d.name().to_string_lossy().into_owned(),
                file_system: d.file_system().to_string_lossy().into_owned(),
                total: d.total_space(),
                available: d.available_space(),
                read_only: d.is_read_only(),
                read_rate: per_second(d.usage().read_bytes),
                write_rate: per_second(d.usage().written_bytes),
            })
            .collect()
    }
}

/// The smallest ceiling a device's graphs are drawn against. Every disk
/// carries a trickle of background writes, and scaled to its own peak that
/// trickle would fill the graph; a megabyte a second is where I/O starts
/// to be worth a full-height mark. A decimal megabyte, as the rates beside
/// the graphs are, so `1.0 MB/s` is the first rate drawn at full height.
const SCALE_FLOOR: u64 = 1_000_000;

/// The disk panel.
#[derive(Debug)]
pub struct DiskPanel {
    config: DiskConfig,
    /// `[disk.keys]` over the defaults.
    keys: PanelKeymap<DiskAction>,
    /// The reader's latest list; `None` until the first read lands.
    shared: Arc<Mutex<Option<Vec<Device>>>>,
    /// Bumped by the reader each time it replaces the list.
    generation: Arc<AtomicU64>,
    /// The generation the last tick copied out.
    seen: u64,
    stop: Arc<AtomicBool>,
    /// What the panel draws from: copied out of `shared` once per change, so
    /// `render`, `counter` and `alert` never take the mutex.
    cache: Option<Vec<Device>>,
    /// Read and write rate histories by mount, oldest first, fed one sample
    /// per reading by `tick`.
    histories: HashMap<String, (VecDeque<u64>, VecDeque<u64>)>,
    /// Cells a graph was last drawn into, so the histories can grow to fill it.
    graph_cells: usize,
}

impl DiskPanel {
    /// Start the reader thread and return immediately.
    pub fn new(config: DiskConfig) -> Self {
        let shared: Arc<Mutex<Option<Vec<Device>>>> = Arc::new(Mutex::new(None));
        let generation = Arc::new(AtomicU64::new(0));
        let stop = Arc::new(AtomicBool::new(false));
        let interval = Duration::from_secs(config.io_sample_secs.max(1));
        let relist_every = Duration::from_secs(config.sample_secs.max(1));
        let (state, bump, halt) = (
            Arc::clone(&shared),
            Arc::clone(&generation),
            Arc::clone(&stop),
        );
        std::thread::Builder::new()
            .name("mirador-disk".into())
            .spawn(move || {
                let mut reader = Reader::new(relist_every);
                loop {
                    let devices = group(reader.read());
                    if let Ok(mut slot) = state.lock() {
                        *slot = Some(devices);
                    }
                    bump.fetch_add(1, Ordering::Release);
                    if matches!(
                        crate::poll::wait(interval, &halt, || false),
                        crate::poll::Wake::Stop
                    ) {
                        break;
                    }
                }
            })
            .expect("spawning the disk thread");
        Self {
            keys: PanelKeymap::or_defaults("disk", ACTIONS, &config.keys),
            config,
            shared,
            generation,
            seen: 0,
            stop,
            cache: None,
            histories: HashMap::new(),
            graph_cells: 0,
        }
    }

    /// A panel holding `devices`, with no thread behind it, for tests.
    #[cfg(test)]
    pub(crate) fn with_devices(config: DiskConfig, devices: Vec<Device>) -> Self {
        let mut panel = Self {
            keys: PanelKeymap::or_defaults("disk", ACTIONS, &config.keys),
            config,
            shared: Arc::new(Mutex::new(None)),
            generation: Arc::new(AtomicU64::new(0)),
            seen: 0,
            stop: Arc::new(AtomicBool::new(false)),
            cache: None,
            histories: HashMap::new(),
            graph_cells: 0,
        };
        panel.take(devices);
        panel
    }

    /// Adopt a fresh reading: replace the list, push one sample onto each
    /// device's histories, and forget any device that is gone.
    fn take(&mut self, devices: Vec<Device>) {
        let capacity = crate::samples::capacity(self.config.history, self.graph_cells);
        for device in &devices {
            let (reads, writes) = self.histories.entry(device.mount.clone()).or_default();
            crate::samples::push_bounded(reads, device.read_rate, capacity);
            crate::samples::push_bounded(writes, device.write_rate, capacity);
        }
        self.histories
            .retain(|mount, _| devices.iter().any(|d| &d.mount == mount));
        self.cache = Some(devices);
    }

    /// The ceiling both of a device's graphs are drawn against: its own
    /// peak in either direction, never below `SCALE_FLOOR`.
    fn scale(&self, mount: &str) -> u64 {
        self.histories
            .get(mount)
            .map_or(0, |(r, w)| {
                r.iter().chain(w.iter()).copied().max().unwrap_or(0)
            })
            .max(SCALE_FLOOR)
    }

    /// An internal drive with room and an external one nearly full, for the
    /// sweep and the dump.
    #[cfg(test)]
    pub(crate) fn canned(config: DiskConfig) -> Self {
        Self::with_devices(
            config,
            vec![
                Device {
                    mount: "/".into(),
                    total: 1_995_165_736_960,
                    available: 1_637_809_513_970,
                    read_rate: 0,
                    write_rate: 327_680,
                },
                Device {
                    mount: "/Volumes/T7".into(),
                    total: 2_000_398_934_016,
                    available: 61_203_144_704,
                    read_rate: 52_428_800,
                    write_rate: 0,
                },
            ],
        )
    }

    /// Brass while there is room, amber past the warning line, red past the
    /// alert line. Thresholds rather than a ramp: a disk two-thirds full is
    /// not "warm", it is fine, and a ramp would say otherwise.
    fn colour(&self, pct: u16, theme: &crate::theme::Theme) -> Color {
        if self.config.alert_above_pct > 0 && pct >= self.config.alert_above_pct {
            theme.error
        } else if self.config.warn_above_pct > 0 && pct >= self.config.warn_above_pct {
            theme.warning
        } else {
            theme.accent
        }
    }

    fn devices(&self) -> &[Device] {
        self.cache.as_deref().unwrap_or(&[])
    }
}

impl Drop for DiskPanel {
    /// See `Drop for StocksPanel`: a panel can be dropped without `shutdown`,
    /// and the picker rebuilding the dashboard does exactly that.
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
    }
}

/// What this panel's keys do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiskAction {
    Io,
}

/// This panel's keys, under `[disk.keys]`.
pub const ACTIONS: &[Meta<DiskAction>] = &[Meta {
    action: DiskAction::Io,
    name: "io",
    defaults: &[(KeyCode::Char('i'), KeyModifiers::NONE)],
    label: "i/o",
    primary: true,
    joins: false,
    about: "show or hide the I/O graphs",
}];

/// `[disk.keys]` laid over [`ACTIONS`], or why it cannot be.
pub fn keymap(keys: &KeysConfig) -> Result<PanelKeymap<DiskAction>, String> {
    PanelKeymap::new("disk", ACTIONS, keys)
}

/// Rows a device takes at each spacing: text and meter with a blank between
/// devices, text and meter, or text alone.
fn rows_per_device(height: u16, devices: u16) -> u16 {
    if devices == 0 {
        return 1;
    }
    if height >= devices * 3 - 1 {
        3
    } else if height >= devices * 2 {
        2
    } else {
        1
    }
}

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

    fn counter(&self) -> Option<String> {
        // What is left on the system's own volume: the one figure a glance
        // at the frame is for. The rows inside say the rest.
        let first = self.devices().first()?;
        Some(format!("{} free", human(first.available)))
    }

    fn bindings(&self) -> &[Binding] {
        self.keys.bindings()
    }

    fn set_keys(&mut self, config: &crate::config::Config) {
        self.keys = PanelKeymap::or_defaults("disk", ACTIONS, &config.disk.keys);
    }

    fn max_height(&self) -> Option<u16> {
        // With the graphs on, more height is more history and the panel
        // scales like cpu. Without them: three rows a device with the last
        // blank line unneeded, and the frame — past that every row is space
        // under the last meter.
        if self.config.show_io {
            return None;
        }
        let devices = u16::try_from(self.devices().len()).unwrap_or(u16::MAX);
        (devices > 0).then(|| FRAME_HEIGHT + devices * 3 - 1)
    }

    fn refresh_interval(&self) -> Duration {
        Duration::from_secs(1)
    }

    fn tick(&mut self) -> bool {
        let now = self.generation.load(Ordering::Acquire);
        if now == self.seen {
            return false;
        }
        self.seen = now;
        let fresh = self.shared.lock().ok().and_then(|slot| slot.clone());
        if let Some(devices) = fresh {
            self.take(devices);
        }
        true
    }

    fn handle_key(&mut self, key: ratatui::crossterm::event::KeyEvent) -> crate::panel::KeyOutcome {
        if self.keys.action(key) == Some(DiskAction::Io) {
            self.config.show_io = !self.config.show_io;
            return crate::panel::KeyOutcome::Consumed;
        }
        crate::panel::KeyOutcome::Ignored
    }

    fn alert(&self) -> Option<crate::panel::Alert> {
        // A volume past the alert line gets worse with every file written,
        // and what it breaks — a save, a build, a backup — is not always
        // something that tells you why. The fullest one speaks.
        if self.config.alert_above_pct == 0 {
            return None;
        }
        let fullest = self
            .devices()
            .iter()
            .filter(|d| d.used_pct() >= self.config.alert_above_pct)
            .max_by_key(|d| d.used_pct())?;
        Some(crate::panel::Alert::soon(format!(
            "Disk {} at {}% — {} free",
            fullest.mount,
            fullest.used_pct(),
            human(fullest.available)
        )))
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: RenderContext<'_>) {
        let theme = ctx.theme;
        if area.width == 0 || area.height == 0 {
            return;
        }
        let Some(devices) = self.cache.as_deref() else {
            draw_notice(frame, area, theme, &["Reading disks", ""]);
            return;
        };
        if devices.is_empty() {
            draw_notice(
                frame,
                area,
                theme,
                &["No disks readable", "Nothing listed can fill up"],
            );
            return;
        }

        let count = u16::try_from(devices.len()).unwrap_or(u16::MAX);

        // With the graphs on, every device gets an equal share of the
        // height and the graphs take what its figures leave. Without them,
        // the blocks stack from the top with a blank line between when
        // there is room, and the rest of the panel is the row's to give away.
        let show_io = self.config.show_io && area.height >= 3;
        if show_io {
            // Recorded so the next reading sizes the histories to the panel.
            // Every region is a full-width slice of `area`.
            self.graph_cells = usize::from(area.width);
            let regions = Layout::vertical(vec![Constraint::Fill(1); devices.len()]).split(area);
            for (device, region) in devices.iter().zip(regions.iter()) {
                self.draw_device_with_io(frame, *region, device, ctx);
            }
            return;
        }

        let bottom = area.y + area.height;
        let per = rows_per_device(area.height, count);
        let mut y = area.y;

        for (index, device) in devices.iter().enumerate() {
            if y >= bottom {
                break;
            }
            let pct = device.used_pct();
            let colour = self.colour(pct, theme);
            frame.render_widget(
                Paragraph::new(crate::grid::assemble(
                    figures(device, colour, theme),
                    area.width,
                )),
                Rect::new(area.x, y, area.width, 1),
            );
            y += 1;

            if per >= 2 && y < bottom {
                frame.render_widget(
                    Paragraph::new(Line::from(meter_line(pct, area.width, colour, theme.track))),
                    Rect::new(area.x, y, area.width, 1),
                );
                y += 1;
            }
            if per == 3 && index + 1 < devices.len() {
                y += 1;
            }
        }
    }
}

/// The figures line as parts for `grid::assemble`: mount, how full, the
/// word, what is free, what it holds — dropped from the end, so a narrow
/// panel keeps the mount and the figure that says whether to worry. The
/// word is its own part, so the figure outlives its label rather than the
/// other way round. Each gap travels with the part it introduces.
fn figures(device: &Device, colour: Color, theme: &crate::theme::Theme) -> Vec<Vec<Span<'static>>> {
    let muted = Style::default().fg(theme.muted);
    let pct = device.used_pct();
    vec![
        vec![Span::styled(
            device.mount.clone(),
            Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
        )],
        vec![
            Span::styled(
                format!("   {pct}"),
                Style::default().fg(colour).add_modifier(Modifier::BOLD),
            ),
            Span::styled("%", muted),
        ],
        vec![Span::styled(
            format!(" {}", crate::glyphs::utility("used")),
            Style::default()
                .fg(theme.label)
                .add_modifier(Modifier::BOLD),
        )],
        vec![Span::styled(
            format!("   {} free", human(device.available)),
            muted,
        )],
        vec![Span::styled(
            format!("   of {}", human(device.total)),
            muted,
        )],
    ]
}

impl DiskPanel {
    /// One device with its graphs: figures, meter, the `↓ ↑` readout, and
    /// the rows left split between a read graph and a write graph — or one
    /// graph of both when only a row is left.
    fn draw_device_with_io(
        &self,
        frame: &mut Frame,
        region: Rect,
        device: &Device,
        ctx: RenderContext<'_>,
    ) {
        let theme = ctx.theme;
        if region.height == 0 {
            return;
        }
        let pct = device.used_pct();
        let colour = self.colour(pct, theme);
        let muted = Style::default().fg(theme.muted);
        let track = Style::default().fg(theme.track);
        let gradient = &ctx.gradients.cpu;

        let graph_rows = region.height.saturating_sub(3);
        let rows = Layout::vertical([
            Constraint::Length(1),                             // figures
            Constraint::Length(u16::from(region.height >= 2)), // meter
            Constraint::Length(u16::from(region.height >= 3)), // readout
            Constraint::Length(graph_rows.div_ceil(2)),        // reads
            Constraint::Length(graph_rows / 2),                // writes
        ])
        .split(region);

        frame.render_widget(
            Paragraph::new(crate::grid::assemble(
                figures(device, colour, theme),
                rows[0].width,
            )),
            rows[0],
        );
        if rows[1].height > 0 {
            frame.render_widget(
                Paragraph::new(Line::from(meter_line(
                    pct,
                    rows[1].width,
                    colour,
                    theme.track,
                ))),
                rows[1],
            );
        }
        if rows[2].height > 0 {
            // Two readings, each a whole part: an arrow left over nothing
            // reads as a rate of zero.
            let text = Style::default().fg(theme.text);
            frame.render_widget(
                Paragraph::new(crate::grid::assemble(
                    vec![
                        vec![
                            Span::styled("↓ ", muted),
                            Span::styled(rate(device.read_rate), text),
                        ],
                        vec![
                            Span::styled("   ↑ ", muted),
                            Span::styled(rate(device.write_rate), text),
                        ],
                    ],
                    rows[2].width,
                )),
                rows[2],
            );
        }

        let scale = self.scale(&device.mount);
        let Some((reads, writes)) = self.histories.get(&device.mount) else {
            return;
        };
        if rows[4].height == 0 && rows[3].height > 0 {
            // One row: both directions in one graph, since a reader with a
            // row to spare wants to know whether the disk is busy at all.
            // The sums are a new series, so only the newest two a cell are
            // made — the graph would read no further back than that.
            let shown = usize::from(rows[3].width) * 2;
            let skip = reads.len().min(writes.len()).saturating_sub(shown);
            let both: Vec<u64> = reads
                .iter()
                .zip(writes.iter())
                .skip(skip)
                .map(|(r, w)| r.saturating_add(*w))
                .collect();
            BrailleGraph::new(&both, scale.saturating_mul(2), gradient)
                .track_style(track)
                .render(rows[3], frame.buffer_mut());
            return;
        }
        for (data, rect) in [(reads, rows[3]), (writes, rows[4])] {
            if rect.height > 0 {
                BrailleGraph::of_history(data, scale, gradient)
                    .track_style(track)
                    .render(rect, frame.buffer_mut());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widgets::testing::screen;

    fn volume(mount: &str, fs: &str, total: u64, available: u64, read_only: bool) -> Volume {
        Volume {
            mount: mount.into(),
            name: String::new(),
            file_system: fs.into(),
            total,
            available,
            read_only,
            read_rate: 0,
            write_rate: 0,
        }
    }

    /// A volume carrying the name the platform gives it; [`volume`] gives
    /// none, as an unlabelled Windows volume reports.
    fn named(name: &str, volume: Volume) -> Volume {
        Volume {
            name: name.into(),
            ..volume
        }
    }

    fn device(mount: &str, total: u64, available: u64) -> Device {
        Device {
            mount: mount.into(),
            total,
            available,
            read_rate: 0,
            write_rate: 0,
        }
    }

    /// The panel without its graphs, which is the face the older tests
    /// describe row by row.
    fn quiet() -> DiskConfig {
        DiskConfig {
            show_io: false,
            ..DiskConfig::default()
        }
    }

    fn panel(devices: Vec<Device>) -> DiskPanel {
        DiskPanel::with_devices(quiet(), devices)
    }

    #[test]
    fn bytes_read_the_way_a_disk_is_sold() {
        assert_eq!(human(1_995_165_736_960), "2.0 TB");
        assert_eq!(human(1_637_809_513_970), "1.6 TB");
        assert_eq!(human(357_356_222_990), "357 GB");
        assert_eq!(human(61_203_144_704), "61 GB");
        assert_eq!(human(8_267_366_400), "8.3 GB");
        assert_eq!(human(512_000_000), "512 MB");
        assert_eq!(human(4_096), "4 kB");
        assert_eq!(human(0), "0 kB");
    }

    /// A rate keeps a decimal below ten of its unit, where the capacity
    /// formatter it borrowed gave whole megabytes up to ten gigabytes: a
    /// disk reading 1.4 MB a second said `1 MB/s`, and the trickle every
    /// disk carries read as nothing. Halves round up rather than to even,
    /// which `{:.0}` does — 12.5 MB a second said `12 MB/s` — and kilobytes
    /// are rounded, not cut, so 999 bytes a second is not `0 kB/s`. A figure
    /// that rounds up to the next unit is written in it: `1.0 MB/s`, never
    /// `1000 kB/s`.
    #[test]
    fn a_rate_keeps_a_decimal_below_ten_of_its_unit() {
        for (bytes, expected) in [
            (0, "0 kB/s"),
            (40, "0 kB/s"),
            (50, "0.1 kB/s"),
            (999, "1.0 kB/s"),
            (1_999, "2.0 kB/s"),
            (4_096, "4.1 kB/s"),
            (9_949, "9.9 kB/s"),
            (9_950, "10 kB/s"),
            (327_000, "327 kB/s"),
            (327_680, "328 kB/s"),
            (999_499, "999 kB/s"),
            (999_500, "1.0 MB/s"),
            (1_400_000, "1.4 MB/s"),
            (1_450_000, "1.5 MB/s"),
            (2_500_000, "2.5 MB/s"),
            (12_500_000, "13 MB/s"),
            (52_428_800, "52 MB/s"),
            (100_000_000, "100 MB/s"),
            (999_600_000, "1.0 GB/s"),
            (3_000_000_000, "3.0 GB/s"),
            (u64::MAX, "18446744 TB/s"),
        ] {
            assert_eq!(rate(bytes), expected, "{bytes} bytes a second");
        }
    }

    #[test]
    fn a_percentage_saturates_and_never_divides_by_zero() {
        assert_eq!(percent(0, 0), 0);
        assert_eq!(percent(1, 4), 25);
        assert_eq!(percent(9, 4), 100);
        assert_eq!(percent(u64::MAX, u64::MAX), 100);
        assert_eq!(device("/", 0, 0).used_pct(), 0);
        assert_eq!(
            device("/", 100, 150).used(),
            0,
            "free past total reads as nothing used, not as underflow"
        );
    }

    /// The macOS pair — `/` sealed and read-only, `/System/Volumes/Data`
    /// writable, one container between them — is one device named `/`,
    /// with the smaller free figure, and writable because one of them is.
    #[test]
    fn the_volumes_of_one_container_are_one_device_named_by_its_root() {
        let devices = group(vec![
            named(
                "Macintosh HD",
                volume("/", "apfs", 1_995_165_736_960, 1_637_885_797_874, true),
            ),
            named(
                "Macintosh HD",
                volume(
                    "/System/Volumes/Data",
                    "apfs",
                    1_995_165_736_960,
                    1_637_809_513_970,
                    false,
                ),
            ),
        ]);
        assert_eq!(
            devices,
            vec![device("/", 1_995_165_736_960, 1_637_809_513_970)]
        );
    }

    /// Two disks that happen to be the same size are two disks: what folds
    /// them is the shared free space, not the capacity.
    #[test]
    fn two_disks_of_one_size_with_different_fill_stay_separate() {
        let devices = group(vec![
            volume("/", "ext4", 1_000_000_000_000, 400_000_000_000, false),
            volume("/home", "ext4", 1_000_000_000_000, 900_000_000_000, false),
        ]);
        assert_eq!(devices.len(), 2, "{devices:?}");
        assert_eq!(devices[0].mount, "/", "root first");
        assert_eq!(devices[1].mount, "/home");
    }

    /// And they stay two when their fill is close, not only when it is half
    /// a disk apart. Two 2 TB backup disks fifteen gigabytes apart — three
    /// quarters of a percent — were one row under the old one-percent rule,
    /// named after the first and carrying the second's free space, so a disk
    /// vanished from the panel that exists to say when one is full. Two
    /// names say two disks; so does no name at all, which is what an
    /// unlabelled Windows volume reports, because two volumes that both lack
    /// a name have not been shown to share one.
    #[test]
    fn two_disks_of_one_size_and_nearly_one_fill_stay_separate() {
        for (a, b) in [("Backup A", "Backup B"), ("", "")] {
            let devices = group(vec![
                named(
                    a,
                    volume(
                        "/Volumes/Backup A",
                        "apfs",
                        2_000_000_000_000,
                        1_990_000_000_000,
                        false,
                    ),
                ),
                named(
                    b,
                    volume(
                        "/Volumes/Backup B",
                        "apfs",
                        2_000_000_000_000,
                        1_975_000_000_000,
                        false,
                    ),
                ),
            ]);
            assert_eq!(devices.len(), 2, "named {a:?} and {b:?}: {devices:?}");
        }
    }

    /// The tight line must not become looser than the old rule on a disk too
    /// small for its floor. A fixed 128 MiB is more than a percent of
    /// anything under about thirteen gigabytes, so on its own it would fold
    /// two 8 GB sticks 100 MB apart, and any two same-size volumes under
    /// 128 MiB whatever their fill — an empty one and a full one, one row,
    /// named after the empty one and showing the full one's free space. The
    /// floor stops at a percent, and so does a shared name: two FAT sticks
    /// both called `NO NAME`, the label a fresh one carries, are held no
    /// looser than two with nothing in common.
    #[test]
    fn small_disks_of_one_size_are_held_no_looser_than_a_percent() {
        for name in ["", "NO NAME"] {
            for (total, a, b) in [
                (8_000_000_000, 4_000_000_000, 3_900_000_000),
                (100_000_000, 99_000_000, 1_000_000),
            ] {
                let devices = group(vec![
                    named(name, volume("/media/stick-a", "vfat", total, a, false)),
                    named(name, volume("/media/stick-b", "vfat", total, b, false)),
                ]);
                assert_eq!(
                    devices.len(),
                    2,
                    "{total}-byte pair named {name:?}: {devices:?}"
                );
            }
        }
    }

    /// What separating two disks must not do is split the container the
    /// fold exists for. The two volumes of one APFS container drift apart
    /// between readings by what was written between the two reads, not by a
    /// share of the disk, and a fast write moves a lot of it: on the owner's
    /// 2 TB Mac, 1.8 MB idle, 48 MB under a `dd` from `/dev/urandom` (which
    /// is that source's speed, not the disk's), and 260 MB and then 641 MB
    /// under a 30 GB write from a cached file at the SSD's own speed. Both
    /// halves are named `Macintosh HD`, so they are held to the old percent:
    /// twenty gigabytes there, thirty times the largest reading, and 2.5 GB
    /// on a 256 GB Mac. Split, the read-only `/`
    /// drops and the row renames itself `/System/Volumes/Data` for a
    /// reading, taking the I/O history with it — during the very write the
    /// graph is there to show.
    #[test]
    fn a_container_read_during_a_write_is_still_one_device() {
        for total in [245_107_195_904, 494_384_795_648, 1_995_165_736_960] {
            for drift in [1_793_984, 47_857_664, 260_132_864, 641_363_968] {
                let free = total / 2;
                let devices = group(vec![
                    named("Macintosh HD", volume("/", "apfs", total, free, true)),
                    named(
                        "Macintosh HD",
                        volume("/System/Volumes/Data", "apfs", total, free - drift, false),
                    ),
                ]);
                assert_eq!(
                    devices,
                    vec![device("/", total, free - drift)],
                    "a {total}-byte container {drift} bytes apart"
                );
            }
        }
    }

    /// The edge the shared name leaves, pinned so that moving it is a
    /// decision: two disks of one size and one name — a pair of drives
    /// bought together and both left `Untitled` — whose free space is within
    /// a percent are one row, exactly as every disk was before the tight
    /// line, until enough is written to one of them to carry it past.
    /// Nothing a volume reports tells them from the two halves of a
    /// container.
    #[test]
    fn two_disks_of_one_size_and_one_name_within_a_percent_are_one_row() {
        let devices = group(vec![
            named(
                "Untitled",
                volume(
                    "/Volumes/Untitled",
                    "apfs",
                    2_000_000_000_000,
                    1_990_000_000_000,
                    false,
                ),
            ),
            named(
                "Untitled",
                volume(
                    "/Volumes/Untitled 1",
                    "apfs",
                    2_000_000_000_000,
                    1_975_000_000_000,
                    false,
                ),
            ),
        ]);
        assert_eq!(
            devices,
            vec![device(
                "/Volumes/Untitled",
                2_000_000_000_000,
                1_975_000_000_000
            )]
        );
    }

    /// The hedge for a macOS that names its halves apart — `diskutil` calls
    /// the data volume `Data` where `sysinfo` reads `Macintosh HD` — is the
    /// tight line, which folds any two volumes of one size whatever their
    /// names: idle and under an ordinary write the container is still one
    /// row there. A write fast enough to carry the halves past the line
    /// would split it for a reading, which is the price of the name not
    /// being the only test.
    #[test]
    fn a_container_whose_halves_are_named_apart_still_folds_within_the_tight_line() {
        for total in [245_107_195_904, 494_384_795_648, 1_995_165_736_960] {
            for drift in [1_793_984, 47_857_664] {
                let free = total / 2;
                let devices = group(vec![
                    named("Macintosh HD", volume("/", "apfs", total, free, true)),
                    named(
                        "Data",
                        volume("/System/Volumes/Data", "apfs", total, free - drift, false),
                    ),
                ]);
                assert_eq!(
                    devices,
                    vec![device("/", total, free - drift)],
                    "a {total}-byte container named apart, {drift} bytes apart"
                );
            }
        }
    }

    /// A snap's squashfs, a DVD and the memory-backed pseudo file systems
    /// are not disks that fill; a read-only volume is dropped while there is
    /// a writable one to show, and nothing with no capacity is listed.
    #[test]
    fn what_cannot_fill_up_is_not_listed() {
        let devices = group(vec![
            volume("/", "ext4", 500_000_000_000, 200_000_000_000, false),
            volume("/snap/core/1234", "squashfs", 60_000_000, 0, true),
            volume("/media/dvd", "iso9660", 4_700_000_000, 0, true),
            volume("/run", "tmpfs", 8_000_000_000, 7_900_000_000, false),
            volume("/mnt/ro", "ext4", 100_000_000_000, 10_000_000_000, true),
            volume("/mnt/empty", "ext4", 0, 0, false),
        ]);
        assert_eq!(devices, vec![device("/", 500_000_000_000, 200_000_000_000)]);
    }

    /// A machine with only read-only volumes still shows them rather than
    /// nothing; the rule drops read-only devices only in favour of a writable one.
    #[test]
    fn only_read_only_volumes_are_still_shown_rather_than_nothing() {
        let devices = group(vec![volume(
            "/",
            "ext4",
            500_000_000_000,
            200_000_000_000,
            true,
        )]);
        assert_eq!(devices.len(), 1);
    }

    /// Windows drive letters and a long external mount sort root first and
    /// then by name, so the list holds still between reads.
    #[test]
    fn devices_are_listed_root_first_then_by_mount() {
        let devices = group(vec![
            volume(
                "/Volumes/Time Machine",
                "apfs",
                4_000_000_000_000,
                1_000_000_000_000,
                false,
            ),
            volume(
                "/Volumes/T7",
                "exfat",
                2_000_000_000_000,
                61_000_000_000,
                false,
            ),
            volume("/", "apfs", 1_995_165_736_960, 1_637_809_513_970, false),
        ]);
        let mounts: Vec<&str> = devices.iter().map(|d| d.mount.as_str()).collect();
        assert_eq!(mounts, ["/", "/Volumes/T7", "/Volumes/Time Machine"]);
        let devices = group(vec![
            volume("D:\\", "NTFS", 2_000_000_000_000, 1_000_000_000_000, false),
            volume("C:\\", "NTFS", 1_000_000_000_000, 100_000_000_000, false),
        ]);
        let mounts: Vec<&str> = devices.iter().map(|d| d.mount.as_str()).collect();
        assert_eq!(mounts, ["C:\\", "D:\\"]);
    }

    /// Thresholds, not a ramp: brass to the warning line, amber to the alert
    /// line, red past it — and both lines inclusive, since "above 80%" is
    /// what the config says and 80 is not above 80.
    #[test]
    fn the_colour_changes_only_at_the_thresholds() {
        let theme = crate::theme::Theme::default();
        let p = panel(vec![]);
        assert_eq!(p.colour(0, &theme), theme.accent);
        assert_eq!(p.colour(79, &theme), theme.accent);
        assert_eq!(p.colour(80, &theme), theme.warning);
        assert_eq!(p.colour(94, &theme), theme.warning);
        assert_eq!(p.colour(95, &theme), theme.error);
        assert_eq!(p.colour(100, &theme), theme.error);
        let off = DiskPanel::with_devices(
            DiskConfig {
                warn_above_pct: 0,
                alert_above_pct: 0,
                ..DiskConfig::default()
            },
            vec![],
        );
        assert_eq!(off.colour(100, &theme), theme.accent, "zero disables");
    }

    /// The status bar names the fullest volume past the alert line, in the
    /// terms someone would use, and nothing below it.
    #[test]
    fn the_alert_names_the_fullest_volume_past_the_line() {
        let p = panel(vec![
            device("/", 1_000_000_000_000, 40_000_000_000),
            device("/Volumes/T7", 2_000_000_000_000, 20_000_000_000),
        ]);
        assert_eq!(
            p.alert().map(|a| a.text),
            Some("Disk /Volumes/T7 at 99% — 20 GB free".to_string())
        );
        assert!(
            panel(vec![device("/", 1_000_000_000_000, 60_000_000_000)])
                .alert()
                .is_none(),
            "94% is below the line"
        );
        assert!(
            DiskPanel::with_devices(
                DiskConfig {
                    alert_above_pct: 0,
                    ..DiskConfig::default()
                },
                vec![device("/", 100, 0)],
            )
            .alert()
            .is_none(),
            "zero disables"
        );
        assert!(panel(vec![]).alert().is_none());
    }

    #[test]
    fn the_border_carries_what_is_free_on_the_first_volume() {
        assert_eq!(
            DiskPanel::canned(DiskConfig::default())
                .counter()
                .as_deref(),
            Some("1.6 TB free")
        );
        assert_eq!(panel(vec![]).counter(), None);
        assert_eq!(panel(vec![]).max_height(), None);
        assert_eq!(
            DiskPanel::canned(quiet()).max_height(),
            Some(FRAME_HEIGHT + 5),
            "two devices: text, meter, blank, text, meter"
        );
        assert_eq!(
            DiskPanel::canned(DiskConfig::default()).max_height(),
            None,
            "with the graphs on, more height is more history"
        );
    }

    /// Each device is a line of figures over a meter, a blank line between
    /// devices when there is room, and the figures are dropped whole from
    /// the end at any width — never a fragment.
    #[test]
    fn each_device_is_figures_over_a_meter_and_never_a_fragment() {
        let mut p = DiskPanel::canned(quiet());
        let rows = screen(&mut p, 60, 5);
        assert_eq!(
            rows[0], "/   17% USED   1.6 TB free   of 2.0 TB",
            "{rows:?}"
        );
        assert!(
            rows[1].starts_with("■■■") && rows[1].chars().count() == 60,
            "{rows:?}"
        );
        assert_eq!(rows[2], "", "a blank line between devices: {rows:?}");
        assert_eq!(
            rows[3], "/Volumes/T7   96% USED   61 GB free   of 2.0 TB",
            "{rows:?}"
        );
        assert!(rows[4].starts_with('■'), "{rows:?}");

        let tight = screen(&mut p, 60, 4);
        assert_eq!(
            tight[2], "/Volumes/T7   96% USED   61 GB free   of 2.0 TB",
            "no blank when there is no room: {tight:?}"
        );
        let tighter = screen(&mut p, 60, 2);
        assert!(
            tighter[1].starts_with("/Volumes/T7"),
            "one row each: {tighter:?}"
        );

        for width in 1..=40u16 {
            for height in 1..=6u16 {
                for row in screen(&mut p, width, height) {
                    let t = row.trim();
                    for bad in ["fre", "of 2", "of 2.", "USE", "1.6 T", "61 G", " 1", " 9"] {
                        assert!(!t.ends_with(bad), "fragment {t:?} at {width}x{height}");
                    }
                    assert!(
                        !t.contains("17") || t.contains("17%"),
                        "a figure without its unit: {t:?} at {width}x{height}"
                    );
                }
            }
        }
    }

    #[test]
    fn a_machine_with_nothing_readable_says_so_and_before_the_first_read_says_it_is_reading() {
        let mut none = panel(vec![]);
        let rows = screen(&mut none, 44, 3).join("\n");
        assert!(rows.contains("No disks readable"), "{rows}");
        assert!(!rows.contains('■'), "no meter for nothing: {rows}");
        let mut waiting = panel(vec![]);
        waiting.cache = None;
        let rows = screen(&mut waiting, 44, 3).join("\n");
        assert!(rows.contains("Reading disks"), "{rows}");
    }

    /// With the graphs on, each device is figures, meter, a `↓ ↑` readout
    /// and two graphs sharing the rows left — the network panel's face, per
    /// device — and no fragment of any figure at any size.
    #[test]
    fn with_io_each_device_is_figures_meter_readout_and_two_graphs() {
        let mut p = DiskPanel::canned(DiskConfig::default());
        let rows = screen(&mut p, 60, 10);
        assert_eq!(
            rows[0], "/   17% USED   1.6 TB free   of 2.0 TB",
            "{rows:?}"
        );
        assert!(rows[1].starts_with('■'), "{rows:?}");
        assert_eq!(rows[2], "↓ 0 kB/s   ↑ 328 kB/s", "{rows:?}");
        assert!(
            rows[3].starts_with('⣀') && rows[4].starts_with('⣀'),
            "two graphs: {rows:?}"
        );
        assert!(rows[5].starts_with("/Volumes/T7"), "{rows:?}");
        assert_eq!(rows[7], "↓ 52 MB/s   ↑ 0 kB/s", "{rows:?}");

        for width in 1..=40u16 {
            for height in 1..=12u16 {
                for row in screen(&mut p, width, height) {
                    let t = row.trim();
                    for bad in ["B/", "kB", "MB", "↑", "↓", "fre", "USE"] {
                        assert!(!t.ends_with(bad), "fragment {t:?} at {width}x{height}");
                    }
                }
            }
        }
    }

    /// The rates are stated in the units the capacity beside them is, so a
    /// `MB` on the readout is the `MB` in `61 GB free`'s scale. They went
    /// through the network panel's formatter, which divides by 1024 under
    /// the same letters, and a disk moving a hundred million bytes a second
    /// read `95.4 MB/s` over a capacity counted in powers of ten.
    #[test]
    fn the_rates_are_stated_in_the_units_of_the_capacity_beside_them() {
        let mut busy = device("/", 1_000_000_000_000, 400_000_000_000);
        busy.read_rate = 100_000_000;
        busy.write_rate = 4_096;
        let mut p = DiskPanel::with_devices(DiskConfig::default(), vec![busy]);
        let rows = screen(&mut p, 60, 5);
        assert_eq!(
            rows[0], "/   60% USED   400 GB free   of 1.0 TB",
            "{rows:?}"
        );
        assert_eq!(rows[2], "↓ 100 MB/s   ↑ 4.1 kB/s", "{rows:?}");
    }

    /// A panel wider than `history` covers grows the histories to fill it
    /// (invariant 12): drawn at 100 columns, the next readings keep two a
    /// cell, not the configured 120. The width is recorded by `render` once
    /// for every device, which nothing checked when it moved there.
    #[test]
    fn a_wide_panel_keeps_enough_history_to_fill_its_graphs() {
        let mut p = DiskPanel::with_devices(DiskConfig::default(), vec![device("/", 100, 50)]);
        screen(&mut p, 100, 8);
        for _ in 0..300 {
            p.take(vec![device("/", 100, 50)]);
        }
        assert_eq!(p.histories["/"].0.len(), 200);
        assert_eq!(p.histories["/"].1.len(), 200);
    }

    /// With one row for graphs, reads and writes are summed into one, and
    /// the sums are of the newest samples: a history longer than the graph
    /// is wide shows its right-hand end, as every other graph does. Tried
    /// both ways round, so a graph showing the oldest end fails one of them.
    #[test]
    fn the_one_row_graph_sums_the_newest_samples() {
        let idle = "⣀".repeat(10);
        for (old, new, busy_now) in [(100_000_000, 0, false), (0, 100_000_000, true)] {
            let mut p = DiskPanel::with_devices(DiskConfig::default(), vec![]);
            for i in 0..100 {
                let mut d = device("/", 100, 50);
                d.write_rate = if i < 80 { old } else { new };
                p.take(vec![d]);
            }
            assert_eq!(p.histories["/"].1.len(), 100, "longer than 2 × 10 cells");
            let rows = screen(&mut p, 10, 4);
            assert!(
                rows[2].starts_with('↓'),
                "one row left for graphs: {rows:?}"
            );
            if busy_now {
                assert!(!rows[3].contains('⣀'), "busy at the end: {rows:?}");
            } else {
                assert_eq!(rows[3], idle, "idle at the end: {rows:?}");
            }
        }
    }

    /// A tick adopts the reading and pushes one sample per device onto its
    /// histories; a device that vanishes takes its history with it.
    #[test]
    fn each_reading_feeds_the_histories_and_a_gone_device_is_forgotten() {
        let mut p = DiskPanel::canned(DiskConfig::default());
        assert_eq!(p.histories["/"].1.len(), 1);
        let mut root = device("/", 100, 50);
        root.read_rate = 7;
        p.take(vec![root]);
        assert_eq!(
            p.histories["/"].0.iter().copied().collect::<Vec<_>>(),
            [0, 7]
        );
        assert!(
            !p.histories.contains_key("/Volumes/T7"),
            "gone: {:?}",
            p.histories.keys()
        );
    }

    /// The graphs' ceiling is the device's own peak in either direction,
    /// never below a megabyte a second, so a trickle of background writes
    /// does not fill the graph.
    #[test]
    fn the_scale_is_the_devices_peak_floored_at_a_megabyte() {
        let p = DiskPanel::canned(DiskConfig::default());
        assert_eq!(p.scale("/"), SCALE_FLOOR, "328 kB/s is under the floor");
        assert_eq!(p.scale("/Volumes/T7"), 52_428_800);
        assert_eq!(p.scale("/nowhere"), SCALE_FLOOR);
    }

    #[test]
    fn i_toggles_the_graphs_and_is_documented() {
        use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        let mut p = DiskPanel::canned(DiskConfig::default());
        assert!(p.config.show_io);
        let outcome = p.handle_key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE));
        assert_eq!(outcome, crate::panel::KeyOutcome::Consumed);
        assert!(!p.config.show_io);
        assert!(p.bindings().iter().any(|b| b.key == "i"));
        assert_eq!(
            p.handle_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE)),
            crate::panel::KeyOutcome::Ignored,
            "every other key stays global"
        );
    }

    /// The rows a device gets: three with a blank between, two, or one, and
    /// a device count of zero cannot divide anything.
    #[test]
    fn rows_per_device_gives_way_from_the_blank_line_down() {
        assert_eq!(rows_per_device(5, 2), 3);
        assert_eq!(rows_per_device(4, 2), 2);
        assert_eq!(rows_per_device(3, 2), 1);
        assert_eq!(
            rows_per_device(2, 1),
            3,
            "one device needs two rows for three-spacing"
        );
        assert_eq!(rows_per_device(1, 1), 1);
        assert_eq!(rows_per_device(0, 0), 1);
    }
}