rigtop-gui 0.13.0

Native GUI system monitor for workstations, laptops and NAS, a btop alternative: resizable panels, storage health, per-process GPU usage and many hosts over SSH
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
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
//! Application state, the resizable tile layout and the per-frame entry point.

use std::path::PathBuf;
use std::thread;
use std::time::{Duration, Instant};

use egui::{
    Color32, CornerRadius, FontId, Id, Margin, RichText, Sense, Stroke, TextStyle, Ui, Visuals,
};
use egui_tiles::{Container, SimplificationOptions, Tile, TileId, Tiles, Tree, UiResponse};
use rigtop_core::config::{ConfigWatcher, HostConfig, OverviewSection, SensorConfig};
use rigtop_core::demo::DemoSource;
use rigtop_core::hosts::{HostKind, HostSpec, host_specs};
use rigtop_core::remote::RemoteSource;
use rigtop_core::update::ReleaseChecker;
use rigtop_core::view::{
    AlertLog, GraphSpan, MetricHistory, ProcessQuery, ProcessRow, Severity, SortKey, process_rows,
    signal_name,
};
use rigtop_core::worker::{Command, Event, Worker};
use rigtop_core::{Config, DataSource, LocalSource, ProcessSignal, Snapshot};

use crate::alert_log;
use crate::hosts_dialog::{self, HostsDialog};
use crate::lhm_setup::{self, LhmSetup};
use crate::notify::{self, Notifier};
use crate::overview;
use crate::panels;
use crate::sensors_dialog::{self, SensorsDialog};
use crate::update_dialog::{self, ReleaseNote, UpdateDialog, UpdateEvent};
use crate::widget_panel;
use crate::widgets::{self, BACKGROUND, BORDER, DIM, TEXT};

/// How long a status message stays visible.
const STATUS_TTL: Duration = Duration::from_secs(5);

/// Allowed UI zoom range (1.0 = 100%).
const MIN_ZOOM: f32 = 0.5;
const MAX_ZOOM: f32 = 3.0;
/// Zoom change per button press or Ctrl +/- (egui's own step).
const ZOOM_STEP: f32 = 0.1;

/// Keys of the values eframe persists between runs.
const ZOOM_KEY: &str = "zoom";
const LAYOUT_KEY: &str = "layout";
const OVERVIEW_KEY: &str = "overview";
const WIDGETS_KEY: &str = "widgets_visible";
/// eframe storage key for the time the graphs cover (seconds, 0 to fit).
const GRAPH_SPAN_KEY: &str = "graph_span";

/// One panel of the layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Pane {
    Cpu,
    Memory,
    Gpu,
    Storage,
    Network,
    Processes,
}

impl Pane {
    /// Every panel, used to validate a restored layout.
    pub const ALL: [Pane; 6] = [
        Pane::Cpu,
        Pane::Memory,
        Pane::Gpu,
        Pane::Storage,
        Pane::Network,
        Pane::Processes,
    ];

    /// Title shown in the panel border.
    pub fn title(self) -> &'static str {
        match self {
            Pane::Cpu => "cpu",
            Pane::Memory => "mem",
            Pane::Gpu => "gpu",
            Pane::Storage => "storage",
            Pane::Network => "net",
            Pane::Processes => "proc",
        }
    }

    /// Title color, as in the TUI.
    pub fn color(self) -> Color32 {
        match self {
            Pane::Cpu => widgets::CPU_TITLE,
            Pane::Memory => widgets::MEM_TITLE,
            Pane::Gpu => widgets::GPU_TITLE,
            Pane::Storage => widgets::STORAGE_TITLE,
            Pane::Network => widgets::NET_TITLE,
            Pane::Processes => widgets::PROC_TITLE,
        }
    }
}

/// A signal waiting for the user's confirmation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmSignal {
    pub pid: u32,
    pub name: String,
    pub signal: ProcessSignal,
}

/// View changes requested from inside the panels, applied after drawing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViewAction {
    ZoomIn,
    ZoomOut,
    ZoomReset,
    ResetLayout,
    /// Open the window for adding and editing hosts.
    EditHosts,
    /// Show or hide the widget column.
    ToggleWidgets,
    /// Switch the graphs to the next time span.
    NextGraphSpan,
    /// Open the window for naming and hiding sensors.
    EditSensors,
    /// Open the history of alerts.
    ShowAlertLog,
    /// Offer to update rigtop on this (remote) host.
    UpdateAgent,
    /// Offer to update this machine's rigtop to the new release.
    SelfUpdate,
    /// Start rigtop again, to run a newly installed release.
    Restart,
}

/// Everything the panels read and modify.
pub struct GuiState {
    pub config: Config,
    pub snapshot: Option<Snapshot>,
    pub history: MetricHistory,
    pub sort_key: SortKey,
    pub sort_descending: bool,
    pub filter: String,
    pub show_kernel_threads: bool,
    /// Processes under their parents.
    pub tree: bool,
    /// Selected process, tracked by pid so it survives re-sorting.
    pub selected_pid: Option<u32>,
    pub confirm: Option<ConfirmSignal>,
    /// Commands queued for the worker during this frame.
    pub commands: Vec<Command>,
    /// View changes queued during this frame.
    pub view_actions: Vec<ViewAction>,
    /// Current UI zoom factor, for display in the panels.
    pub zoom: f32,
    /// Latest collection error, until the next snapshot (connection lost).
    pub connection_error: Option<String>,
    /// When the latest snapshot arrived.
    pub last_update: Option<Instant>,
    /// Whether the CPU panel title shows zoom buttons (single-host mode).
    pub show_zoom: bool,
    /// Whether the widget column is shown, or `None` without widgets (for
    /// the toggle in the CPU panel title in single-host mode).
    pub widgets_visible: Option<bool>,
    /// Unread alerts of every host (count, worst), for the "alerts" button
    /// in the CPU panel title in single-host mode.
    pub alerts_unread: (usize, Option<Severity>),
    /// A new release of rigtop, or one waiting for a restart (title bar).
    pub release: Option<ReleaseNote>,
    /// How much time the graphs cover.
    pub graph_span: GraphSpan,
    /// Collection interval, to turn a time span into samples.
    pub interval: Duration,
    /// Whether this is the machine rigtop runs on (setup offers apply only
    /// to it).
    pub is_local: bool,
    /// Whether this host is reached over SSH (and can be updated from here).
    pub remote: bool,
    /// The LibreHardwareMonitor setup window (Windows).
    pub lhm_setup: LhmSetup,
    status: Option<(String, Instant)>,
}

impl GuiState {
    /// Creates an empty state.
    pub fn new(config: Config) -> Self {
        Self {
            config,
            snapshot: None,
            history: MetricHistory::default(),
            sort_key: SortKey::Cpu,
            sort_descending: true,
            filter: String::new(),
            show_kernel_threads: false,
            tree: false,
            selected_pid: None,
            confirm: None,
            commands: Vec::new(),
            view_actions: Vec::new(),
            zoom: 1.0,
            connection_error: None,
            last_update: None,
            show_zoom: true,
            widgets_visible: None,
            alerts_unread: (0, None),
            release: None,
            graph_span: GraphSpan::default(),
            interval: Duration::from_secs(1),
            is_local: false,
            remote: false,
            lhm_setup: LhmSetup::default(),
            status: None,
        }
    }

    /// Applies a message from the worker.
    pub fn apply(&mut self, event: Event) {
        match event {
            Event::Snapshot(snapshot) => {
                self.history.record(&snapshot);
                self.snapshot = Some(*snapshot);
                self.connection_error = None;
                self.last_update = Some(Instant::now());
            }
            Event::SignalResult {
                pid,
                signal,
                result,
            } => match result {
                Ok(()) => self.set_status(format!("sent {} to {pid}", signal_name(signal))),
                Err(err) => self.set_status(format!("failed: {err}")),
            },
            Event::Error(err) => {
                self.set_status(format!("collection error: {err}"));
                self.connection_error = Some(err);
            }
        }
    }

    /// Processes after filtering and sorting.
    pub fn process_rows(&self) -> Vec<ProcessRow<'_>> {
        let Some(snapshot) = &self.snapshot else {
            return Vec::new();
        };
        process_rows(
            snapshot,
            &ProcessQuery {
                sort_key: self.sort_key,
                descending: self.sort_descending,
                filter: &self.filter,
                show_kernel_threads: self.show_kernel_threads,
                tree: self.tree,
            },
        )
    }

    /// Sorts by `key`, or reverses the order if it already is the sort key.
    pub fn toggle_sort(&mut self, key: SortKey) {
        if self.sort_key == key {
            self.sort_descending = !self.sort_descending;
        } else {
            self.sort_key = key;
            self.sort_descending = key.descending_by_default();
        }
    }

    /// Asks for confirmation before sending `signal` to `pid`.
    pub fn ask_signal(&mut self, pid: u32, name: &str, signal: ProcessSignal) {
        self.confirm = Some(ConfirmSignal {
            pid,
            name: name.to_owned(),
            signal,
        });
    }

    /// Current status message, if still fresh.
    pub fn status(&self) -> Option<&str> {
        self.status
            .as_ref()
            .filter(|(_, at)| at.elapsed() < STATUS_TTL)
            .map(|(msg, _)| msg.as_str())
    }

    /// Shows a status message for a few seconds.
    pub fn set_status(&mut self, message: String) {
        self.status = Some((message, Instant::now()));
    }
}

/// One monitored host: its collector and the state its panels show.
pub struct HostEntry {
    pub spec: HostSpec,
    /// `None` in tests, which feed snapshots directly.
    worker: Option<Worker>,
    pub state: GuiState,
    /// Process limit last sent to the worker (`None` = all processes).
    sent_limit: Option<Option<usize>>,
}

impl HostEntry {
    /// Applies queued events; returns true if a snapshot was among them.
    fn drain(&mut self) -> bool {
        let mut snapshot = false;
        if let Some(worker) = &self.worker {
            while let Some(event) = worker.try_recv() {
                snapshot |= matches!(event, Event::Snapshot(_));
                self.state.apply(event);
            }
        }
        snapshot
    }

    /// Sends queued commands and the wanted process limit to the worker.
    fn flush(&mut self, limit: Option<usize>) {
        let Some(worker) = &self.worker else {
            self.state.commands.clear();
            return;
        };
        for command in self.state.commands.drain(..) {
            worker.send(command);
        }
        if self.sent_limit != Some(limit) {
            worker.send(Command::SetProcessLimit(limit));
            self.sent_limit = Some(limit);
        }
    }

    /// What to show before the first snapshot arrives.
    pub fn waiting_message(&self) -> String {
        if self.spec.is_local() {
            "collecting…".to_owned()
        } else {
            format!("connecting to {}…", self.spec.name)
        }
    }
}

/// What the window shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
    /// All hosts side by side.
    Overview,
    /// The detailed panels of one host (index into the host list).
    Host(usize),
}

/// The eframe application.
pub struct RigtopApp {
    pub hosts: Vec<HostEntry>,
    pub view: View,
    pub overview: OverviewSettings,
    /// The loaded configuration; `hosts` changes when edited in the GUI.
    config: Config,
    /// Where host changes are saved (`None` if there is no config directory).
    /// Made-up hosts instead of real ones (`--demo`).
    demo: bool,
    config_path: Option<PathBuf>,
    /// Notices edits to the configuration file (`None` without one).
    config_watcher: Option<ConfigWatcher>,
    /// Hosts given with `--host`, which are not saved.
    cli_hosts: Vec<String>,
    remote_command: Option<String>,
    interval: Duration,
    /// Context for waking the UI from new workers; `None` in tests, where
    /// hosts get no worker.
    repaint: Option<egui::Context>,
    pub hosts_dialog: HostsDialog,
    pub sensors_dialog: SensorsDialog,
    update_dialog: UpdateDialog,
    /// Looks for new releases (`None` when `[updates] check = false`).
    release_checker: Option<ReleaseChecker>,
    /// A release that replaced this program, waiting for a restart.
    release_installed: Option<String>,
    /// The release last announced by a desktop notification.
    release_announced: Option<String>,
    /// The running program, taken at startup (see `UpdateJob::start_self`).
    exe: Option<PathBuf>,
    /// Alerts of every host as they appeared and cleared.
    alert_log: AlertLog,
    alert_log_open: bool,
    /// Desktop notifications for new alerts.
    notifier: Notifier,
    /// The widget column (`[[widgets]]`), empty without any.
    pub(crate) widgets: Vec<rigtop_core::widget::Widget>,
    /// Whether the widget column is shown (it can be hidden for room).
    show_widgets: bool,
    graph_span: GraphSpan,
    tree: Tree<Pane>,
    /// Processes per overview card (hosts not shown in detail send only these).
    overview_processes: usize,
    /// Whether the theme (and restored zoom) has been applied to the context.
    styled: bool,
    /// Zoom restored from the previous run, applied on the first frame.
    initial_zoom: f32,
    /// Current zoom, saved on exit.
    zoom: f32,
}

impl RigtopApp {
    /// Starts one collector per host (this machine, `[[hosts]]` from the
    /// configuration and `extra_hosts` from the command line), each waking
    /// the UI on new data.
    ///
    /// The zoom factor, panel layout and overview settings of the previous
    /// run are restored from eframe's storage when available.
    pub fn new(
        cc: &eframe::CreationContext<'_>,
        config: Config,
        config_path: Option<PathBuf>,
        interval: Duration,
        extra_hosts: &[String],
        remote_command: Option<&str>,
        demo: bool,
    ) -> Self {
        let storage = cc.storage;
        let initial_zoom = storage
            .and_then(|s| eframe::get_value::<f32>(s, ZOOM_KEY))
            .map_or(1.0, |z| z.clamp(MIN_ZOOM, MAX_ZOOM));
        let tree = storage
            .and_then(|s| eframe::get_value::<Tree<Pane>>(s, LAYOUT_KEY))
            .filter(is_complete_layout)
            .unwrap_or_else(default_tree);
        let overview = storage
            .and_then(|s| eframe::get_value::<OverviewSettings>(s, OVERVIEW_KEY))
            .unwrap_or_else(|| OverviewSettings::from_config(&config));
        let mut app = Self::assemble(config, tree, overview, initial_zoom);
        app.config_watcher = config_path.clone().map(ConfigWatcher::new);
        app.config_path = config_path;
        app.cli_hosts = extra_hosts.to_vec();
        app.remote_command = remote_command.map(str::to_owned);
        app.demo = demo;
        app.interval = interval;
        app.release_checker = app
            .config
            .updates
            .check
            .then(|| ReleaseChecker::new(app.config.updates.check_interval()));
        app.repaint = Some(cc.egui_ctx.clone());
        app.graph_span = storage
            .and_then(|s| eframe::get_value::<u64>(s, GRAPH_SPAN_KEY))
            .map_or(GraphSpan::Fit, GraphSpan::from_secs);
        app.show_widgets = storage
            .and_then(|s| eframe::get_value::<bool>(s, WIDGETS_KEY))
            .unwrap_or(true);
        let repaint = cc.egui_ctx.clone();
        app.widgets = rigtop_core::widget::start_widgets(&app.config.widgets, move || {
            repaint.request_repaint()
        });
        app.update_hosts();
        app
    }

    /// An app without hosts; `update_hosts` (or a test) adds them.
    fn assemble(
        config: Config,
        tree: Tree<Pane>,
        overview: OverviewSettings,
        initial_zoom: f32,
    ) -> Self {
        let notifier = Notifier::new(config.notifications.level);
        Self {
            hosts: Vec::new(),
            view: View::Host(0),
            overview,
            overview_processes: config.overview.processes,
            config,
            config_path: None,
            config_watcher: None,
            demo: false,
            cli_hosts: Vec::new(),
            remote_command: None,
            interval: Duration::from_secs(1),
            repaint: None,
            hosts_dialog: HostsDialog::default(),
            sensors_dialog: SensorsDialog::default(),
            update_dialog: UpdateDialog::default(),
            release_checker: None,
            release_installed: None,
            release_announced: None,
            exe: None,
            alert_log: AlertLog::default(),
            alert_log_open: false,
            notifier,
            widgets: Vec::new(),
            show_widgets: true,
            graph_span: GraphSpan::default(),
            tree,
            styled: false,
            initial_zoom,
            zoom: initial_zoom,
        }
    }

    /// Starts collecting from `spec` (no worker in tests).
    fn start_host(&self, spec: HostSpec) -> HostEntry {
        let worker = self.repaint.clone().map(|repaint| {
            let source_config = self.config.clone();
            let kind = spec.kind.clone();
            Worker::spawn_with_notify(
                move || -> Box<dyn DataSource> {
                    match kind {
                        HostKind::Remote(target) => Box::new(RemoteSource::new(target)),
                        HostKind::Local => Box::new(LocalSource::with_config(&source_config)),
                        HostKind::Demo(host) => Box::new(DemoSource::new(host)),
                    }
                },
                self.interval,
                move || repaint.request_repaint(),
            )
        });
        let mut state = GuiState::new(self.config.clone());
        state.is_local = spec.is_local();
        state.remote = matches!(spec.kind, HostKind::Remote(_));
        HostEntry {
            spec,
            worker,
            state,
            sent_limit: None,
        }
    }

    /// Brings the running hosts in line with the configuration and the
    /// command line: unchanged hosts keep their collector and history, new
    /// ones are started and removed ones stopped.
    fn update_hosts(&mut self) {
        let specs = if self.demo {
            rigtop_core::demo::host_specs(&self.config)
        } else {
            host_specs(
                &self.config,
                &self.cli_hosts,
                self.remote_command.as_deref(),
            )
        };
        let shown = match self.view {
            View::Host(index) => self.hosts.get(index).map(|h| h.spec.name.clone()),
            View::Overview => None,
        };
        let was_multi = self.hosts.len() > 1;
        let mut old = std::mem::take(&mut self.hosts);
        let mut hosts = Vec::with_capacity(specs.len());
        for spec in specs {
            match old
                .iter()
                .position(|h| h.spec.name == spec.name && h.spec.kind == spec.kind)
            {
                Some(position) => {
                    let mut entry = old.swap_remove(position);
                    entry.spec = spec;
                    hosts.push(entry);
                }
                None => hosts.push(self.start_host(spec)),
            }
        }
        // Stopping a worker joins its thread, which can take a while for a
        // host that is still connecting; do not freeze the UI meanwhile.
        let stopped: Vec<Worker> = old.into_iter().filter_map(|h| h.worker).collect();
        if !stopped.is_empty() {
            thread::spawn(move || drop(stopped));
        }
        self.hosts = hosts;
        // Like at startup, the overview opens once there are several hosts
        // and needs at least two; otherwise stay on the same host if it is
        // still there.
        let multi = self.hosts.len() > 1;
        let position = shown.and_then(|name| self.hosts.iter().position(|h| h.spec.name == name));
        self.view = match position {
            Some(index) if was_multi || !multi => View::Host(index),
            _ if multi => View::Overview,
            _ => View::Host(0),
        };
    }

    /// Applies edits to the configuration file, if any (checked at most once
    /// a second; the clock redraws the window that often anyway).
    fn reload_config(&mut self) {
        let Some(result) = self.config_watcher.as_mut().and_then(ConfigWatcher::poll) else {
            return;
        };
        match result {
            Ok(config) => self.apply_config(config),
            Err(err) => {
                // The first line names the file and the problem.
                let reason = err.to_string();
                let reason = reason.lines().next().unwrap_or_default().to_owned();
                for host in &mut self.hosts {
                    host.state
                        .set_status(format!("configuration not applied: {reason}"));
                }
            }
        }
    }

    /// Applies an edited configuration: sensor names, alert thresholds,
    /// notifications and the overview take effect at once; hosts added to
    /// or removed from `[[hosts]]` start or stop (the others keep their
    /// connection and history); widgets and this machine's collector
    /// restart when their settings changed.
    fn apply_config(&mut self, config: Config) {
        let old = std::mem::replace(&mut self.config, config);
        self.update_hosts();
        let mut stopped = Vec::new();
        // This machine's collector reads these settings when it starts.
        if old.smart != self.config.smart
            || old.btrfs != self.config.btrfs
            || old.lhm != self.config.lhm
        {
            for index in 0..self.hosts.len() {
                if self.hosts[index].spec.is_local() {
                    stopped.extend(self.replace_worker(index));
                }
            }
        }
        if !stopped.is_empty() {
            thread::spawn(move || drop(stopped));
        }
        for host in &mut self.hosts {
            host.state.config = self.config.clone();
            host.state.set_status("configuration reloaded".to_owned());
        }
        if old.widgets != self.config.widgets
            && let Some(repaint) = self.repaint.clone()
        {
            self.widgets = rigtop_core::widget::start_widgets(&self.config.widgets, move || {
                repaint.request_repaint()
            });
        }
        if old.updates != self.config.updates {
            self.release_checker = self
                .config
                .updates
                .check
                .then(|| ReleaseChecker::new(self.config.updates.check_interval()));
        }
        if old.notifications.level != self.config.notifications.level {
            self.notifier = Notifier::new(self.config.notifications.level);
        }
        // The GUI's own overview choices stay unless the file changed them.
        if old.overview.include_local != self.config.overview.include_local {
            self.overview.include_local = self.config.overview.include_local;
        }
        self.overview_processes = self.config.overview.processes;
    }

    /// Sets the running program (taken at startup), which a self-update
    /// replaces and a restart starts again.
    pub fn with_exe(mut self, exe: Option<PathBuf>) -> Self {
        self.exe = exe;
        self
    }

    /// What the title bar says about releases of rigtop, if anything.
    fn release_note(&mut self) -> Option<ReleaseNote> {
        if let Some(version) = &self.release_installed {
            return Some(ReleaseNote::Installed(version.clone()));
        }
        let version = self.release_checker.as_mut()?.poll()?;
        Some(ReleaseNote::Available(version.to_owned()))
    }

    /// Announces a new release once with a desktop notification (unless
    /// `[updates] notify = false`).
    fn announce_release(&mut self) {
        let Some(ReleaseNote::Available(version)) = self.release_note() else {
            return;
        };
        if self.release_announced.as_deref() != Some(&version) {
            if self.config.updates.notify && self.repaint.is_some() {
                notify::send_release(&version);
            }
            self.release_announced = Some(version);
        }
    }

    /// Starts this program again (to run a newly installed release) and
    /// closes this window.
    fn restart(&mut self, ctx: &egui::Context) {
        let Some(exe) = &self.exe else {
            return;
        };
        match std::process::Command::new(exe)
            .args(std::env::args_os().skip(1))
            .spawn()
        {
            Ok(_) => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
            Err(err) => {
                let message = format!("cannot restart: {err}");
                for host in &mut self.hosts {
                    host.state.set_status(message.clone());
                }
            }
        }
    }

    /// Gives the host at `index` a new collector (keeping its history) and
    /// returns the old one, which the caller stops.
    fn replace_worker(&mut self, index: usize) -> Option<Worker> {
        let fresh = self.start_host(self.hosts[index].spec.clone());
        let host = &mut self.hosts[index];
        host.sent_limit = None;
        std::mem::replace(&mut host.worker, fresh.worker)
    }

    /// Reconnects the host at `index`, e.g. to run an updated agent.
    fn restart_worker(&mut self, index: usize) {
        if index < self.hosts.len()
            && let Some(old) = self.replace_worker(index)
        {
            // Joining could freeze the UI; see `update_hosts`.
            thread::spawn(move || drop(old));
        }
    }

    /// Writes `hosts` to the configuration file and applies them.
    fn save_hosts(&mut self, hosts: Vec<HostConfig>) {
        let Some(path) = self.config_path.clone() else {
            self.hosts_dialog
                .report("no configuration file to save to".to_owned(), false);
            return;
        };
        match Config::save_hosts(&path, &hosts) {
            Ok(()) => {
                self.config.hosts = hosts;
                self.update_hosts();
                self.hosts_dialog
                    .report(format!("saved to {}", path.display()), true);
            }
            Err(err) => self.hosts_dialog.report(format!("not saved: {err}"), false),
        }
    }

    /// Writes sensor names and hidden sensors to the configuration file and
    /// applies them to every host.
    fn save_sensors(&mut self, sensors: SensorConfig) {
        let Some(path) = self.config_path.clone() else {
            self.sensors_dialog
                .report("no configuration file to save to".to_owned(), false);
            return;
        };
        match Config::save_sensors(&path, &sensors) {
            Ok(()) => {
                for host in &mut self.hosts {
                    host.state.config.sensors = sensors.clone();
                }
                self.config.sensors = sensors;
                self.sensors_dialog
                    .report(format!("saved to {}", path.display()), true);
            }
            Err(err) => self
                .sensors_dialog
                .report(format!("not saved: {err}"), false),
        }
    }

    /// Names that cannot be used for a new host: this machine and hosts
    /// from the command line.
    fn fixed_host_names(&self) -> Vec<String> {
        self.hosts
            .iter()
            .filter(|h| {
                h.spec.is_local() || !self.config.hosts.iter().any(|c| c.name == h.spec.name)
            })
            .map(|h| h.spec.name.clone())
            .collect()
    }

    /// Creates the app for `names` (the first one local) without workers;
    /// snapshots come from `state.apply`.
    #[cfg(test)]
    pub fn for_test(config: Config, names: &[&str]) -> Self {
        let overview = OverviewSettings::from_config(&config);
        let mut app = Self::assemble(config, default_tree(), overview, 1.0);
        app.hosts = names
            .iter()
            .enumerate()
            .map(|(i, name)| {
                app.start_host(HostSpec {
                    name: (*name).to_owned(),
                    kind: if i == 0 {
                        HostKind::Local
                    } else {
                        HostKind::Remote(rigtop_core::remote::RemoteTarget::ssh(
                            name,
                            "rigtop --agent",
                        ))
                    },
                    sections: app.config.overview.sections.clone(),
                })
            })
            .collect();
        // With a single host there is nothing to overview: show it directly.
        if app.hosts.len() > 1 {
            app.view = View::Overview;
        }
        app
    }

    /// A single-host app without a worker (tests).
    #[cfg(test)]
    pub fn without_worker(config: Config) -> Self {
        Self::for_test(config, &["local"])
    }

    /// State of the first host (the only one in single-host tests).
    #[cfg(test)]
    pub fn primary(&self) -> &GuiState {
        &self.hosts[0].state
    }

    /// Mutable state of the first host.
    #[cfg(test)]
    pub fn primary_mut(&mut self) -> &mut GuiState {
        &mut self.hosts[0].state
    }

    /// Applies everything the workers have sent since the last call, and
    /// announces alerts that are new in the fresh snapshots.
    fn drain_events(&mut self) {
        for host in &mut self.hosts {
            if !host.drain() {
                continue;
            }
            let Some(snapshot) = &host.state.snapshot else {
                continue;
            };
            let alerts = rigtop_core::view::alerts_with(snapshot, &host.state.config.alerts);
            // "local" says little in a notification; use the host name.
            let name = if host.spec.is_local() {
                &snapshot.host.hostname
            } else {
                &host.spec.name
            };
            // This machine's clock, which remote hosts' may not agree with.
            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_millis() as u64);
            self.alert_log.update(name, &alerts, now_ms);
            for alert in self.notifier.new_alerts(&host.spec.name, &alerts) {
                // Tests run without workers (and without notifications).
                if self.repaint.is_some() {
                    notify::send(name, &alert);
                }
            }
        }
    }

    /// Draws one frame.
    pub fn show(&mut self, ui: &mut Ui) {
        let ctx = ui.ctx().clone();
        if !self.styled {
            setup_style(&ctx);
            // Context style changes apply from the next frame; this frame's
            // Ui needs the theme too (the default font lacks "▼" etc.).
            ui.set_style(ctx.global_style());
            ctx.set_zoom_factor(self.initial_zoom);
            self.styled = true;
        }
        // Ctrl + mouse wheel (or pinch) zooms the whole UI; egui already
        // handles Ctrl + "+" / "-" / "0" itself.
        let wheel_zoom = ctx.input(|i| i.zoom_delta());
        if wheel_zoom != 1.0 {
            set_zoom(&ctx, ctx.zoom_factor() * wheel_zoom);
        }
        self.zoom = ctx.zoom_factor();
        self.drain_events();
        let release = self.release_note();
        if let View::Host(index) = self.view
            && index >= self.hosts.len()
        {
            self.view = View::Host(0);
        }

        // Cards and panels alike draw their graphs over the same span.
        for host in &mut self.hosts {
            host.state.graph_span = self.graph_span;
            host.state.interval = self.interval;
        }
        let mut actions = Vec::new();
        egui::Frame::new()
            .fill(BACKGROUND)
            .inner_margin(Margin::same(4))
            .show(ui, |ui| {
                // Widgets get a column on the right in every view.
                if !self.widgets.is_empty() && self.show_widgets {
                    egui::Panel::right("widget_panel")
                        .resizable(true)
                        .default_size(widget_panel::DEFAULT_WIDTH)
                        .size_range(160.0..=900.0)
                        .frame(egui::Frame::new().fill(BACKGROUND).inner_margin(Margin {
                            left: 6,
                            ..Margin::ZERO
                        }))
                        .show(ui, |ui| widget_panel::show(ui, &self.widgets));
                }
                if self.hosts.len() > 1 {
                    self.tab_bar(ui, &mut actions);
                }
                match self.view {
                    View::Overview => {
                        if let Some(open) = overview::show(
                            ui,
                            &mut self.hosts,
                            &mut self.overview,
                            self.overview_processes,
                        ) {
                            self.view = View::Host(open);
                        }
                    }
                    View::Host(index) => {
                        let single = self.hosts.len() == 1;
                        let host = &mut self.hosts[index];
                        host.state.zoom = self.zoom;
                        // With several hosts the zoom buttons live in the tab bar.
                        host.state.show_zoom = single;
                        host.state.widgets_visible =
                            (!self.widgets.is_empty()).then_some(self.show_widgets);
                        host.state.alerts_unread = self.alert_log.unread();
                        host.state.release = release.clone();
                        if host.state.snapshot.is_none() {
                            waiting_screen(ui, host);
                        } else {
                            let mut behavior = Behavior {
                                state: &mut host.state,
                            };
                            self.tree.ui(&mut behavior, ui);
                        }
                        actions.append(&mut host.state.view_actions);
                    }
                }
            });
        if let View::Host(index) = self.view {
            panels::confirm_dialog(ui.ctx(), &mut self.hosts[index].state);
            lhm_setup::dialog(ui.ctx(), &mut self.hosts[index].state);
        }

        for action in actions {
            match action {
                ViewAction::ZoomIn => set_zoom(&ctx, ctx.zoom_factor() + ZOOM_STEP),
                ViewAction::ZoomOut => set_zoom(&ctx, ctx.zoom_factor() - ZOOM_STEP),
                ViewAction::ZoomReset => set_zoom(&ctx, 1.0),
                ViewAction::ResetLayout => self.tree = default_tree(),
                ViewAction::EditHosts => self.hosts_dialog.open(),
                ViewAction::ToggleWidgets => self.show_widgets = !self.show_widgets,
                ViewAction::NextGraphSpan => self.graph_span = self.graph_span.next(),
                ViewAction::EditSensors => self.sensors_dialog.open(&self.config.sensors),
                ViewAction::ShowAlertLog => self.alert_log_open = true,
                ViewAction::UpdateAgent => {
                    if let View::Host(index) = self.view {
                        self.update_dialog.ask(index, &self.hosts[index].spec.name);
                    }
                }
                ViewAction::SelfUpdate => {
                    if let Some(ReleaseNote::Available(version)) = self.release_note() {
                        self.update_dialog.ask_self(&version);
                    }
                }
                ViewAction::Restart => self.restart(&ctx),
            }
        }
        let fixed = self.fixed_host_names();
        if let Some(hosts) = hosts_dialog::show(
            &ctx,
            &mut self.hosts_dialog,
            &self.config.hosts,
            &fixed,
            self.config_path.as_deref(),
        ) {
            self.save_hosts(hosts);
        }
        // The sensors of the host shown in detail.
        let sensors = match self.view {
            View::Host(index) => self.hosts[index]
                .state
                .snapshot
                .as_ref()
                .and_then(|snapshot| {
                    sensors_dialog::show(
                        &ctx,
                        &mut self.sensors_dialog,
                        snapshot,
                        self.config_path.as_deref(),
                    )
                }),
            View::Overview => None,
        };
        if let Some(sensors) = sensors {
            self.save_sensors(sensors);
        }
        alert_log::show(&ctx, &mut self.alert_log_open, &mut self.alert_log);
        match self
            .update_dialog
            .show(&ctx, &self.hosts, self.exe.as_deref())
        {
            // The new agent runs from the next connection on.
            Some(UpdateEvent::Reconnect(index)) => self.restart_worker(index),
            Some(UpdateEvent::Installed(version)) => self.release_installed = Some(version),
            Some(UpdateEvent::Restart) => self.restart(&ctx),
            None => {}
        }

        // The host shown in detail sends every process; the others only
        // what an overview card lists.
        for (index, host) in self.hosts.iter_mut().enumerate() {
            let limit = if self.view == View::Host(index) {
                None
            } else {
                Some(self.overview_processes)
            };
            host.flush(limit);
        }
        // Repaint at the next full second so the clock ticks; new data
        // triggers repaints through the workers' notifications.
        let subsec = chrono::Local::now().timestamp_subsec_millis() as u64;
        ui.ctx()
            .request_repaint_after(Duration::from_millis(1000 - subsec.min(999)));
    }

    /// "Overview | local | zefat | ..." with a status dot per host, plus the
    /// zoom controls on the right.
    fn tab_bar(&mut self, ui: &mut Ui, actions: &mut Vec<ViewAction>) {
        let release = self.release_note();
        ui.horizontal(|ui| {
            if ui
                .add(egui::Button::selectable(
                    self.view == View::Overview,
                    RichText::new("Overview").strong(),
                ))
                .clicked()
            {
                self.view = View::Overview;
            }
            ui.add_space(6.0);
            for (index, host) in self.hosts.iter().enumerate() {
                let (color, status) = overview::host_status(host);
                let selected = self.view == View::Host(index);
                let label = overview::dot_label(color, &host.spec.name, selected);
                let response = ui
                    .add(egui::Button::selectable(selected, label))
                    .on_hover_text(status);
                if response.clicked() {
                    self.view = View::Host(index);
                }
            }
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                overview::zoom_controls(ui, self.zoom, actions);
                ui.add_space(8.0);
                overview::hosts_button(ui, actions);
                if !self.widgets.is_empty() {
                    overview::widgets_button(ui, self.show_widgets, actions);
                }
                alert_log::button(ui, self.alert_log.unread(), actions);
                update_dialog::release_button(ui, release.as_ref(), actions);
            });
        });
        ui.add_space(2.0);
    }
}

/// "connecting to zefat…" with the latest connection error under it.
fn waiting_screen(ui: &mut Ui, host: &HostEntry) {
    let error = host.state.connection_error.clone();
    let message = host.waiting_message();
    ui.vertical_centered(|ui| {
        ui.add_space(ui.available_height() / 2.0 - 20.0);
        ui.label(RichText::new(message).color(DIM));
        if let Some(error) = error {
            ui.label(RichText::new(error).color(widgets::WARN));
        }
    });
}

/// Overview choices made in the GUI, persisted between runs.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct OverviewSettings {
    /// Whether the local machine gets a card.
    pub include_local: bool,
    /// Section order chosen in the GUI per host name, overriding the
    /// configuration.
    pub sections: std::collections::BTreeMap<String, Vec<OverviewSection>>,
}

impl OverviewSettings {
    /// Defaults from the configuration file.
    pub fn from_config(config: &Config) -> Self {
        Self {
            include_local: config.overview.include_local,
            sections: Default::default(),
        }
    }

    /// Sections for a host: the GUI choice, else the configured order.
    pub fn sections_for(&self, spec: &HostSpec) -> Vec<OverviewSection> {
        self.sections
            .get(&spec.name)
            .cloned()
            .unwrap_or_else(|| spec.sections.clone())
    }
}

impl eframe::App for RigtopApp {
    /// Runs before every frame and also while the window is hidden
    /// (minimized, screen locked), when `ui` is not called. Draining here
    /// keeps the graphs' history going and the event queues short.
    fn logic(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) {
        self.reload_config();
        self.drain_events();
        self.announce_release();
    }

    fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
        self.show(ui);
    }

    fn save(&mut self, storage: &mut dyn eframe::Storage) {
        eframe::set_value(storage, ZOOM_KEY, &self.zoom);
        eframe::set_value(storage, LAYOUT_KEY, &self.tree);
        eframe::set_value(storage, OVERVIEW_KEY, &self.overview);
        eframe::set_value(storage, WIDGETS_KEY, &self.show_widgets);
        eframe::set_value(storage, GRAPH_SPAN_KEY, &self.graph_span.as_secs());
    }
}

/// Sets the UI zoom, clamped and rounded to whole percents.
fn set_zoom(ctx: &egui::Context, zoom: f32) {
    let zoom = (zoom.clamp(MIN_ZOOM, MAX_ZOOM) * 100.0).round() / 100.0;
    ctx.set_zoom_factor(zoom);
}

/// Whether a restored layout still contains every panel exactly once (a
/// layout saved by another version might not).
fn is_complete_layout(tree: &Tree<Pane>) -> bool {
    let panes: Vec<Pane> = tree
        .tiles
        .iter()
        .filter_map(|(_, tile)| match tile {
            Tile::Pane(pane) => Some(*pane),
            Tile::Container(_) => None,
        })
        .collect();
    panes.len() == Pane::ALL.len() && Pane::ALL.iter().all(|p| panes.contains(p))
}

/// Dark theme with monospace text everywhere, like a terminal monitor.
fn setup_style(ctx: &egui::Context) {
    ctx.set_visuals(Visuals::dark());
    ctx.all_styles_mut(|style| {
        let size = |s: f32| FontId::monospace(s);
        style.text_styles = [
            (TextStyle::Small, size(11.0)),
            (TextStyle::Body, size(13.0)),
            (TextStyle::Button, size(13.0)),
            (TextStyle::Monospace, size(13.0)),
            (TextStyle::Heading, size(15.0)),
        ]
        .into();
        style.visuals.panel_fill = BACKGROUND;
        style.visuals.window_fill = Color32::from_rgb(30, 30, 40);
        style.visuals.override_text_color = Some(TEXT);
        style.visuals.selection.bg_fill = widgets::SELECTION;
        // Dense rows, like a terminal monitor.
        style.spacing.item_spacing = egui::vec2(6.0, 1.0);
        style.spacing.interact_size.y = 16.0;
        // Selectable labels would swallow clicks meant for table rows.
        style.interaction.selectable_labels = false;
    });
}

/// btop-like default arrangement:
///
/// ```text
/// cpu (22%)
/// mem / gpu / storage / net (45%) | proc (55%)
/// ```
fn default_tree() -> Tree<Pane> {
    let mut tiles = Tiles::default();
    let cpu = tiles.insert_pane(Pane::Cpu);
    let mem = tiles.insert_pane(Pane::Memory);
    let gpu = tiles.insert_pane(Pane::Gpu);
    let storage = tiles.insert_pane(Pane::Storage);
    let net = tiles.insert_pane(Pane::Network);
    let procs = tiles.insert_pane(Pane::Processes);
    let left = tiles.insert_vertical_tile(vec![mem, gpu, storage, net]);
    let bottom = tiles.insert_horizontal_tile(vec![left, procs]);
    let root = tiles.insert_vertical_tile(vec![cpu, bottom]);

    set_shares(&mut tiles, root, &[(cpu, 22.0), (bottom, 78.0)]);
    set_shares(&mut tiles, bottom, &[(left, 45.0), (procs, 55.0)]);
    set_shares(
        &mut tiles,
        left,
        &[(mem, 17.0), (gpu, 27.0), (storage, 27.0), (net, 29.0)],
    );
    Tree::new(Id::unique("rigtop_layout"), root, tiles)
}

/// Sets the relative sizes of the children of a linear container.
fn set_shares(tiles: &mut Tiles<Pane>, container: TileId, shares: &[(TileId, f32)]) {
    if let Some(Tile::Container(Container::Linear(linear))) = tiles.get_mut(container) {
        for &(child, share) in shares {
            linear.shares.set_share(child, share);
        }
    }
}

/// Connects egui_tiles to the panels.
struct Behavior<'a> {
    state: &'a mut GuiState,
}

impl egui_tiles::Behavior<Pane> for Behavior<'_> {
    fn pane_ui(&mut self, ui: &mut Ui, _tile_id: TileId, pane: &mut Pane) -> UiResponse {
        let pane = *pane;
        let mut response = UiResponse::None;
        egui::Frame::new()
            .stroke(Stroke::new(1.0, BORDER))
            .corner_radius(CornerRadius::same(6))
            .inner_margin(Margin::symmetric(8, 4))
            .show(ui, |ui| {
                ui.set_min_size(ui.available_size());
                // The title doubles as the drag handle for rearranging panels.
                let title = ui
                    .horizontal(|ui| {
                        let handle = ui
                            .add(
                                egui::Label::new(
                                    RichText::new(pane.title()).color(pane.color()).strong(),
                                )
                                .sense(Sense::drag()),
                            )
                            .on_hover_cursor(egui::CursorIcon::Grab)
                            .on_hover_text("drag to move this panel");
                        panels::title_extras(ui, pane, self.state);
                        handle
                    })
                    .inner;
                if title.drag_started() {
                    response = UiResponse::DragStarted;
                }
                ui.push_id(pane.title(), |ui| {
                    panels::pane_contents(ui, pane, self.state)
                });
            });
        response
    }

    fn tab_title_for_pane(&mut self, pane: &Pane) -> egui::WidgetText {
        pane.title().into()
    }

    fn simplification_options(&self) -> SimplificationOptions {
        SimplificationOptions {
            // Panels carry their own titles; no tab bars unless the user
            // stacks panels into tabs by dragging.
            all_panes_must_have_tabs: false,
            ..Default::default()
        }
    }

    fn gap_width(&self, _style: &egui::Style) -> f32 {
        4.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use egui_kittest::Harness;
    use egui_kittest::kittest::Queryable;
    use rigtop_core::snapshot::{
        BtrfsDeviceStats, BtrfsFilesystem, CpuStats, DiskIo, GpuProcess, GpuStats, HostInfo,
        MemoryStats, NetworkStats, ProcessInfo, RaidStats, SmartDevice,
    };

    fn sample_snapshot() -> Snapshot {
        Snapshot {
            host: HostInfo {
                hostname: "testhost".to_owned(),
                uptime_secs: 3600,
                ..Default::default()
            },
            cpu: CpuStats {
                model: "Test CPU 16-Core".to_owned(),
                total_percent: 23.0,
                per_core_percent: (0..32).map(|i| (i * 3 % 100) as f32).collect(),
                per_core_mhz: vec![4200; 32],
                ..Default::default()
            },
            memory: MemoryStats {
                total_bytes: 96 << 30,
                used_bytes: 12 << 30,
                available_bytes: 84 << 30,
                free_bytes: 20 << 30,
                cached_bytes: Some(60 << 30),
                ..Default::default()
            },
            gpus: vec![GpuStats {
                name: "NVIDIA GeForce RTX 4090".to_owned(),
                utilization_percent: Some(55.0),
                memory_used_bytes: Some(4 << 30),
                memory_total_bytes: Some(24 << 30),
                temperature_c: Some(47.0),
                processes: vec![GpuProcess {
                    pid: 4242,
                    memory_bytes: Some(4 << 30),
                    sm_percent: Some(50.0),
                }],
                ..Default::default()
            }],
            disks: vec![DiskIo {
                name: "nvme0n1".to_owned(),
                temperature_c: Some(57.0),
                ..Default::default()
            }],
            smart: vec![SmartDevice {
                device: "nvme0".to_owned(),
                passed: Some(true),
                percentage_used: Some(3),
                ..Default::default()
            }],
            raid: RaidStats {
                btrfs: vec![BtrfsFilesystem {
                    fsid: "acb63bf0".to_owned(),
                    mount_points: vec!["/".to_owned()],
                    devices: vec!["nvme0n1".to_owned()],
                    device_stats: vec![BtrfsDeviceStats {
                        devid: 1,
                        ..Default::default()
                    }],
                    ..Default::default()
                }],
                md: Vec::new(),
            },
            networks: vec![NetworkStats {
                name: "enp9s0".to_owned(),
                link_speed_mbps: Some(10_000),
                link_up: Some(true),
                ..Default::default()
            }],
            processes: vec![
                ProcessInfo {
                    pid: 4242,
                    name: "python".to_owned(),
                    command: "python train.py".to_owned(),
                    cpu_percent: 99.0,
                    memory_bytes: 2 << 30,
                    ..Default::default()
                },
                ProcessInfo {
                    pid: 1,
                    name: "systemd".to_owned(),
                    ..Default::default()
                },
            ],
            process_count: 2,
            ..Default::default()
        }
    }

    fn harness_with(snapshot: Snapshot) -> Harness<'static, RigtopApp> {
        let mut app = RigtopApp::without_worker(Config::default());
        for _ in 0..30 {
            app.primary_mut()
                .apply(Event::Snapshot(Box::new(snapshot.clone())));
        }
        Harness::builder()
            .with_size([1400.0, 900.0])
            .build_ui_state(|ui, app: &mut RigtopApp| app.show(ui), app)
    }

    #[test]
    fn renders_every_panel() {
        let mut harness = harness_with(sample_snapshot());
        harness.run();
        for label in [
            "cpu",
            "mem",
            "gpu",
            "storage",
            "net",
            "proc",
            "testhost",
            "python",
            "GeForce RTX 4090",
            "errors 0",
            "scrub: no record",
            "wear 3%",
        ] {
            assert!(
                harness.query_all_by_label_contains(label).next().is_some(),
                "missing {label:?}"
            );
        }
    }

    #[test]
    fn header_click_sorts_and_context_menu_asks_before_killing() {
        let mut harness = harness_with(sample_snapshot());
        harness.run();
        harness.get_by_label("Pid").click();
        harness.run();
        assert_eq!(harness.state().primary().sort_key, SortKey::Pid);
        assert!(!harness.state().primary().sort_descending);

        harness.get_by_label("python").click_secondary();
        harness.run();
        harness.get_by_label("Kill (SIGKILL)").click();
        harness.run();
        // Nothing is sent until the dialog is confirmed.
        assert!(harness.state().primary().commands.is_empty());
        let confirm = harness
            .state()
            .primary()
            .confirm
            .clone()
            .expect("confirmation dialog");
        assert_eq!((confirm.pid, confirm.signal), (4242, ProcessSignal::Kill));
        harness.get_by_label("Cancel").click();
        harness.run();
        assert!(harness.state().primary().confirm.is_none());
    }

    #[test]
    fn layout_validation_and_zoom_controls() {
        assert!(is_complete_layout(&default_tree()));
        // A layout missing a panel (e.g. from another version) is rejected.
        let partial = Tree::new_vertical(Id::unique("partial"), vec![Pane::Cpu, Pane::Memory]);
        assert!(!is_complete_layout(&partial));

        let mut harness = harness_with(sample_snapshot());
        harness.run();
        harness.get_by_label("A+").click();
        harness.run();
        assert!((harness.ctx.zoom_factor() - 1.1).abs() < 1e-4);
        harness.get_by_label("A-").click();
        harness.run();
        harness.get_by_label("A-").click();
        harness.run();
        assert!((harness.ctx.zoom_factor() - 0.9).abs() < 1e-4);
        harness.get_by_label("90%").click();
        harness.run();
        assert!((harness.ctx.zoom_factor() - 1.0).abs() < 1e-4);
    }

    fn multi_host_harness() -> Harness<'static, RigtopApp> {
        let mut app = RigtopApp::for_test(Config::default(), &["local", "zefat", "nas"]);
        for host in &mut app.hosts[..2] {
            for _ in 0..5 {
                host.state
                    .apply(Event::Snapshot(Box::new(sample_snapshot())));
            }
        }
        // "nas" never connects: its card shows the error.
        app.hosts[2].state.apply(Event::Error(
            "nas: ssh: Could not resolve hostname nas".to_owned(),
        ));
        Harness::builder()
            .with_size([1400.0, 900.0])
            .build_ui_state(|ui, app: &mut RigtopApp| app.show(ui), app)
    }

    #[test]
    fn overview_is_the_default_with_several_hosts() {
        let mut harness = multi_host_harness();
        harness.run();
        assert_eq!(harness.state().view, View::Overview);
        for label in [
            "Overview",
            "zefat",
            "nas",
            "Could not resolve hostname",
            "CPU",
            "GPU0",
            "Mem",
        ] {
            assert!(
                harness.query_all_by_label_contains(label).next().is_some(),
                "missing {label:?}"
            );
        }
        // Hosts not shown in detail only get the top processes.
        assert_eq!(
            harness.state().hosts[1].sent_limit,
            None,
            "no worker in tests"
        );
    }

    #[test]
    fn clicking_a_tab_opens_the_detail_view() {
        let mut harness = multi_host_harness();
        harness.run();
        // The tab comes first; the card title has the same text.
        harness
            .query_all_by_label_contains("● zefat")
            .next()
            .expect("zefat tab")
            .click();
        harness.run();
        assert_eq!(harness.state().view, View::Host(1));
        // The detail panels of that host are shown.
        assert!(harness.query_all_by_label_contains("proc").next().is_some());
        harness.get_by_label("Overview").click();
        harness.run();
        assert_eq!(harness.state().view, View::Overview);
    }

    #[test]
    fn overview_settings_follow_the_gui() {
        let mut settings = OverviewSettings::from_config(&Config::default());
        let spec = HostSpec {
            name: "nas".to_owned(),
            kind: HostKind::Local,
            sections: vec![OverviewSection::Cpu],
        };
        assert_eq!(settings.sections_for(&spec), vec![OverviewSection::Cpu]);
        settings.sections.insert(
            "nas".to_owned(),
            vec![OverviewSection::Storage, OverviewSection::Cpu],
        );
        assert_eq!(settings.sections_for(&spec)[0], OverviewSection::Storage);

        // Unticking "include this machine" removes the local card.
        let mut harness = multi_host_harness();
        harness.run();
        harness.get_by_label("include this machine").click();
        harness.run();
        assert!(!harness.state().overview.include_local);
    }

    #[test]
    fn laptop_shows_soc_power_and_battery() {
        let mut snapshot = sample_snapshot();
        snapshot.power.cpu_package_w = None;
        snapshot.power.igpu_w = Some(6.0);
        snapshot.power.battery = Some(rigtop_core::snapshot::BatteryStats {
            percent: Some(72.0),
            status: "Charging".to_owned(),
            power_w: Some(20.0),
        });
        let mut harness = harness_with(snapshot);
        harness.run();
        for label in ["Power SoC", "72% +20W"] {
            assert!(
                harness.query_all_by_label_contains(label).next().is_some(),
                "missing {label:?}"
            );
        }
    }

    #[test]
    fn hints_at_librehardwaremonitor_when_unreachable() {
        let mut snapshot = sample_snapshot();
        snapshot.lhm_error = Some("127.0.0.1:8085: connection refused".to_owned());
        let mut harness = harness_with(snapshot);
        harness.run();
        assert!(
            harness
                .query_all_by_label_contains(rigtop_core::view::LHM_HINT)
                .next()
                .is_some()
        );
    }

    #[test]
    fn librehardwaremonitor_setup_window() {
        let mut snapshot = sample_snapshot();
        snapshot.lhm_error = Some("127.0.0.1:8085: connection refused".to_owned());
        let mut harness = harness_with(snapshot.clone());
        harness.run();
        harness.get_by_label("set up…").click();
        harness.run();
        assert!(harness.query_by_label_contains("127.0.0.1:8085").is_some());
        // The steps run in a thread; outside Windows they fail at once. (On
        // Windows they would really install and start LibreHardwareMonitor.)
        #[cfg(not(windows))]
        {
            harness.get_by_label("Set up").click();
            for _ in 0..50 {
                // step, not run: the spinner keeps repainting.
                harness.step();
                if harness.query_by_label_contains("for Windows").is_some() {
                    break;
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            harness.run();
            assert!(harness.query_by_label_contains("for Windows").is_some());
            harness.get_by_label("Close").click();
        }
        #[cfg(windows)]
        harness.get_by_label("Cancel").click();
        harness.run();
        assert!(harness.query_by_label("Set up").is_none());

        // Already running: only where to switch the web server on.
        snapshot.processes.push(rigtop_core::snapshot::ProcessInfo {
            pid: 4242,
            name: "LibreHardwareMonitor.exe".to_owned(),
            ..Default::default()
        });
        let mut harness = harness_with(snapshot);
        harness.run();
        harness.get_by_label("set up…").click();
        harness.run();
        assert!(harness.query_by_label_contains("is running").is_some());
        assert!(harness.query_by_label("Set up").is_none());
    }

    /// A clock and a widget with fixed rows, as a command would print.
    fn sample_widgets() -> Vec<rigtop_core::widget::Widget> {
        use rigtop_core::widget::{Widget, WidgetSource, parse_output};
        let rows = r#"{"rows":[
            {"label":"5h","value":"58% left · 14:30","gauge":0.58,"gauge_style":"level","level":"ok"},
            {"label":"week","value":"22% left · Fri 09:00","gauge":0.22,"gauge_style":"level","level":"warn"},
            {"value":"rigtop","heading":true},
            {"label":"busy","value":"7a · 1 agent","level":"ok"},
            {"label":"  agent","value":"Explore: find the config loader"},
            {"label":"idle","value":"06 · waiting on 1 task · 3m","level":"ok"},
            {"value":"website","heading":true},
            {"label":"idle","value":"d8 · your turn · 12m","level":"normal"}
        ]}"#;
        vec![
            Widget {
                name: "Clock".to_owned(),
                source: WidgetSource::Clock,
            },
            Widget {
                name: "Claude Code".to_owned(),
                source: WidgetSource::Fixed(parse_output(rows)),
            },
        ]
    }

    #[test]
    fn widget_column_shows_clock_and_rows() {
        let mut app = RigtopApp::for_test(Config::default(), &["local", "zefat"]);
        app.widgets = sample_widgets();
        let mut harness = Harness::builder()
            .with_size([1400.0, 900.0])
            .build_ui_state(|ui, app: &mut RigtopApp| app.show(ui), app);
        harness.run();
        for label in [
            "Clock",
            "Claude Code",
            "58% left · 14:30",
            "rigtop",
            "your turn",
        ] {
            assert!(
                harness.query_all_by_label_contains(label).next().is_some(),
                "missing {label:?}"
            );
        }
    }

    #[test]
    fn new_releases_offer_an_update_and_a_restart() {
        let mut harness = harness_with(sample_snapshot());
        harness.state_mut().update_dialog.ask_self("9.9.9");
        harness.run();
        // Windows only gets directions; elsewhere the update is offered.
        let offered = if cfg!(windows) {
            "cannot be updated from here"
        } else {
            "Update rigtop from"
        };
        assert!(
            harness
                .query_all_by_label_contains(offered)
                .next()
                .is_some()
        );
        harness
            .get_by_label(if cfg!(windows) { "close" } else { "cancel" })
            .click();
        harness.run();
        assert!(
            harness
                .query_all_by_label_contains(offered)
                .next()
                .is_none()
        );

        harness.state_mut().release_installed = Some("9.9.9".to_owned());
        harness.run();
        assert!(
            harness
                .query_all_by_label("restart for rigtop 9.9.9")
                .next()
                .is_some()
        );
    }

    #[test]
    fn older_remote_agents_offer_an_update() {
        let mut snapshot = sample_snapshot();
        snapshot.host.rigtop_version = "0.0.1".to_owned();
        let mut harness = harness_with(snapshot);
        harness.state_mut().primary_mut().remote = true;
        harness.run();
        harness.get_by_label("agent 0.0.1 · update…").click();
        harness.run();
        assert!(
            harness
                .query_all_by_label_contains("Update rigtop on")
                .next()
                .is_some()
        );
        harness.get_by_label("cancel").click();
        harness.run();
        assert!(
            harness
                .query_all_by_label_contains("Update rigtop on")
                .next()
                .is_none()
        );
    }

    #[test]
    fn edited_configuration_applies_to_running_hosts() {
        let mut harness = harness_with(sample_snapshot());
        harness.run();
        let mut config = Config::default();
        config.hosts.push(HostConfig {
            name: "nas".to_owned(),
            ssh: None,
            command: None,
            sections: None,
        });
        config.alerts.cpu_warning_celsius = 80.0;
        harness.state_mut().apply_config(config);
        harness.run();
        let app = harness.state();
        let names: Vec<&str> = app.hosts.iter().map(|h| h.spec.name.as_str()).collect();
        assert_eq!(names, vec!["local", "nas"]);
        assert!(
            app.hosts
                .iter()
                .all(|h| h.state.config.alerts.cpu_warning_celsius == 80.0)
        );
        assert_eq!(app.hosts[0].state.status(), Some("configuration reloaded"));
        assert!(
            app.hosts[0].state.snapshot.is_some(),
            "a host that stays keeps its data"
        );
    }

    #[test]
    fn hosts_window_adds_and_removes_hosts() {
        use egui::accesskit::Role;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let mut harness = harness_with(sample_snapshot());
        harness.state_mut().config_path = Some(path.clone());
        harness.run();
        harness.get_by_label("hosts…").click();
        harness.run();
        harness.get_by_label("add host").click();
        harness.run();
        // The first text field is the name; the others are optional.
        // The name field; the process filter is a text field too.
        let name_field = || {
            egui_kittest::kittest::by()
                .role(Role::TextInput)
                .label("Name")
        };
        harness.get(name_field()).click();
        harness.run();
        harness.get(name_field()).type_text("zefat");
        harness.run();
        harness.get_by_label("save").click();
        harness.run();

        let saved = Config::load(&path).unwrap();
        assert_eq!(saved.hosts.len(), 1);
        assert_eq!(saved.hosts[0].name, "zefat");
        assert_eq!(
            saved.hosts[0].ssh, None,
            "the destination defaults to the name"
        );
        let app = harness.state();
        let names: Vec<&str> = app.hosts.iter().map(|h| h.spec.name.as_str()).collect();
        assert_eq!(names, ["local", "zefat"]);
        assert!(
            app.hosts[0].state.snapshot.is_some(),
            "the local host keeps its data"
        );
        assert_eq!(
            app.view,
            View::Overview,
            "several hosts: the overview opens"
        );

        harness.get_by_label("remove").click();
        harness.run();
        assert!(Config::load(&path).unwrap().hosts.is_empty());
        assert_eq!(harness.state().hosts.len(), 1);
        assert_eq!(harness.state().view, View::Host(0));
    }

    #[test]
    fn alert_history_window_lists_alerts_and_marks_them_read() {
        use rigtop_core::view::Alert;
        let mut harness = harness_with(sample_snapshot());
        let full = Alert {
            severity: Severity::Warning,
            text: "/srv 92% full".to_owned(),
        };
        harness
            .state_mut()
            .alert_log
            .update("nas", std::slice::from_ref(&full), 1_000);
        harness.state_mut().alert_log.update("nas", &[], 2_000);
        harness.run();
        harness.get_by_label("alerts 1").click();
        harness.run();
        harness.get_by_label("/srv 92% full");
        harness.get_by_label("cleared: /srv 92% full");
        assert_eq!(harness.state().alert_log.unread(), (0, None));
        harness.get_by_label("alerts…");
    }

    #[test]
    fn sensors_window_names_and_hides_sensors() {
        use egui::accesskit::Role;
        use rigtop_core::snapshot::{Fan, SensorChip, Temperature};

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let mut snapshot = sample_snapshot();
        snapshot.sensors = vec![SensorChip {
            key: "nct6686:nct6683.2592".to_owned(),
            name: "nct6686".to_owned(),
            temperatures: vec![Temperature {
                key: "nct6686:nct6683.2592/temp4".to_owned(),
                label: "temp4".to_owned(),
                celsius: -40.0,
                ..Default::default()
            }],
            fans: vec![Fan {
                key: "nct6686:nct6683.2592/fan2".to_owned(),
                label: "fan2".to_owned(),
                rpm: 1200,
            }],
        }];
        let mut harness = harness_with(snapshot);
        harness.state_mut().config_path = Some(path.clone());
        harness.run();
        harness.get_by_label("sensors…").click();
        harness.run();
        let fan_field = || {
            egui_kittest::kittest::by()
                .role(Role::TextInput)
                .label("fan2")
        };
        harness.get(fan_field()).click();
        harness.run();
        harness.get(fan_field()).type_text("Pump ");
        harness.run();
        // The first channel is the unconnected thermistor: hide it.
        harness.get_all_by_label("show").next().unwrap().click();
        harness.run();
        harness.get_by_label("save").click();
        harness.run();

        let saved = Config::load(&path).unwrap();
        assert_eq!(saved.label_for("nct6686:nct6683.2592/fan2"), Some("Pump"));
        assert!(saved.is_hidden("nct6686:nct6683.2592/temp4"));
        // Applied at once: the fan shows under its new name.
        assert_eq!(harness.state().primary().config.sensors, saved.sensors);
        harness.get_by_label("Pump");
    }

    /// Renders the real machine to a PNG for visual checks:
    /// `RIGTOP_GUI_SCREENSHOT=/tmp/gui.png cargo test -p rigtop-gui -- --ignored screenshot`
    ///
    /// Optional: `RIGTOP_GUI_FILTER` (process filter, e.g. to keep personal
    /// processes out of published images) and `RIGTOP_GUI_SAMPLES` (number of
    /// samples taken 300 ms apart, to fill the graphs; default 20),
    /// `RIGTOP_GUI_SIZE` (window size such as `1000x700`; default 1400x900),
    /// `RIGTOP_GUI_HOSTS` (comma-separated names for an overview) and
    /// `RIGTOP_GUI_CLICK` (comma-separated labels clicked in order, e.g.
    /// `hosts…,add host` to show the hosts window) and `RIGTOP_GUI_DEMO`
    /// (made-up data of `--demo`).
    #[test]
    #[ignore]
    fn screenshot_local_machine() {
        use rigtop_core::{DataSource, LocalSource};
        let path = std::env::var("RIGTOP_GUI_SCREENSHOT").expect("RIGTOP_GUI_SCREENSHOT");
        let samples: usize = std::env::var("RIGTOP_GUI_SAMPLES")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(20);
        // RIGTOP_GUI_HOSTS=local,zefat,nas renders the overview with this
        // machine's data under every name.
        // RIGTOP_GUI_DEMO=1 uses the made-up hosts of `--demo` instead
        // (named workstation, laptop, nas; all three by default), sampled
        // without waiting, and no configuration file.
        let demo = std::env::var("RIGTOP_GUI_DEMO").is_ok();
        let default_names = if demo {
            "workstation,laptop,nas"
        } else {
            "local"
        };
        let names_env =
            std::env::var("RIGTOP_GUI_HOSTS").unwrap_or_else(|_| default_names.to_owned());
        let names: Vec<&str> = names_env.split(',').collect();
        let config = if demo {
            Config::default()
        } else {
            Config::load_default().unwrap_or_default()
        };
        let mut app = RigtopApp::for_test(config, &names);
        if demo {
            use rigtop_core::demo::{DemoHost, DemoSource};
            for host in &mut app.hosts {
                let kind = DemoHost::ALL
                    .into_iter()
                    .find(|d| d.name() == host.spec.name)
                    .unwrap_or(DemoHost::Workstation);
                let mut source = DemoSource::new(kind);
                for _ in 0..samples {
                    let snapshot = source.poll().unwrap();
                    host.state.apply(Event::Snapshot(Box::new(snapshot)));
                }
            }
        } else {
            let mut source = LocalSource::new();
            for _ in 0..samples {
                std::thread::sleep(Duration::from_millis(300));
                let snapshot = source.poll().unwrap();
                for host in &mut app.hosts {
                    host.state
                        .apply(Event::Snapshot(Box::new(snapshot.clone())));
                }
            }
        }
        // The alert history as drain_events would have filled it.
        let found: Vec<(String, Vec<rigtop_core::view::Alert>)> = app
            .hosts
            .iter()
            .filter_map(|h| {
                let snapshot = h.state.snapshot.as_ref()?;
                let alerts = rigtop_core::view::alerts_with(snapshot, &h.state.config.alerts);
                Some((h.spec.name.clone(), alerts))
            })
            .collect();
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_millis() as u64);
        for (name, alerts) in found {
            app.alert_log.update(&name, &alerts, now_ms);
        }
        if std::env::var("RIGTOP_GUI_WIDGETS").is_ok() {
            app.widgets = sample_widgets();
        }
        if let Ok(filter) = std::env::var("RIGTOP_GUI_FILTER") {
            app.primary_mut().filter = filter;
        }
        let size = std::env::var("RIGTOP_GUI_SIZE")
            .ok()
            .and_then(|s| {
                let (w, h) = s.split_once('x')?;
                Some([w.parse::<f32>().ok()?, h.parse::<f32>().ok()?])
            })
            .unwrap_or([1400.0, 900.0]);
        let mut harness = Harness::builder()
            .with_size(size)
            .build_ui_state(|ui, app: &mut RigtopApp| app.show(ui), app);
        harness.run();
        if let Ok(clicks) = std::env::var("RIGTOP_GUI_CLICK") {
            for label in clicks.split(',') {
                harness.get_by_label(label).click();
                harness.run();
            }
            // Otherwise the last click's pointer and hover stay in the picture.
            harness.remove_cursor();
            harness.run();
        }
        harness
            .render()
            .expect("render")
            .save(&path)
            .expect("save PNG");
    }
}