ltop 0.2.3

btop-styled TUI monitoring only local network, LAN neighbours and disk I/O
Documentation
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
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
pub mod graph;

use std::sync::Mutex;

use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Cell, Clear, Paragraph, Row, Table};
use ratatui::Frame;

use crate::app::{
    fmt_dur, fmt_interval, local_time_str, App, BOX_CONNS, BOX_DISKIO, BOX_DISKS, BOX_LAN, BOX_NET,
    BOX_PROCS, IoGraphMode, LayoutMode, MenuState,
};
use crate::collect::conn::{sock_str, Conn, ConnFilter, ConnSort};
use crate::collect::disk::TreeNode;
use crate::collect::lan::Neighbor;
use crate::config::{Config, Lang};
use crate::theme::*;

use graph::{braille_bar, braille_graph};
pub use graph::GraphMode;

const GRAPH_FLOOR: f64 = 64.0 * 1024.0; // keep idle graphs from being pure noise
pub(crate) const THEME_VISIBLE: usize = 14;

/// Screen rects of the visible boxes this frame, for mouse-wheel scrolling
static BOX_AREAS: Mutex<Vec<(usize, Rect)>> = Mutex::new(Vec::new());

/// Box index under the given terminal position, if any
pub fn hit_box(col: u16, row: u16) -> Option<usize> {
    BOX_AREAS
        .lock()
        .unwrap()
        .iter()
        .find(|(_, r)| col >= r.x && col < r.x + r.width && row >= r.y && row < r.y + r.height)
        .map(|(i, _)| *i)
}

/// Full rect of a box, for mouse hit-testing of list rows
pub fn box_rect(idx: usize) -> Option<Rect> {
    BOX_AREAS
        .lock()
        .unwrap()
        .iter()
        .find(|(i, _)| *i == idx)
        .map(|(_, r)| *r)
}

pub fn draw(f: &mut Frame, app: &App) {
    let area = f.area();
    if let Some(bg) = bg() {
        f.render_widget(Block::new().style(Style::new().bg(bg)), area);
    }
    BOX_AREAS.lock().unwrap().clear();

    let outer = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(area);

    let zoom_active = app
        .zoom
        .is_some_and(|b| {
            matches!(b, crate::app::BOX_LAN | crate::app::BOX_CONNS | crate::app::BOX_PROCS)
                && app.visible[b]
        });

    if zoom_active {
        // zoom:焦点盒独占主区;footer 与 popup(MenuState 分派)照常渲染
        if let Some(b) = app.zoom {
            draw_box(f, outer[0], app, b);
        }
    } else {
    let graph_ids: Vec<usize> = [BOX_NET, BOX_DISKIO]
        .into_iter()
        .filter(|&i| app.visible[i])
        .collect();
    let table_ids: Vec<usize> = [BOX_LAN, BOX_CONNS, BOX_PROCS, BOX_DISKS]
        .into_iter()
        .filter(|&i| app.visible[i])
        .collect();

    match (graph_ids.is_empty(), table_ids.is_empty()) {
        (false, false) => match app.layout {
            LayoutMode::Classic => {
                // tables first: they need ~76 columns for full rates/addresses;
                // the graphs give up width down to 40 columns
                let (graphs_w, _) = split_horizontal(outer[0].width, 76, 40);
                let main = Layout::horizontal([
                    Constraint::Length(graphs_w),
                    Constraint::Fill(1),
                ])
                .split(outer[0]);
                draw_stack(f, main[0], app, &graph_ids, true);
                // 右列在中线分组:LAN+CONNS 的底边与左列 NET|DISK 分界对齐
                draw_list_stack(f, main[1], app, &table_ids, true);
            }
            LayoutMode::Wide | LayoutMode::Tall => {
                // lists keep their ideal height; graphs absorb the remainder
                // and only shrink to GRAPH_MIN_ROWS (each) before lists scroll
                let stacked_graphs = app.layout == LayoutMode::Tall;
                let graph_min = GRAPH_MIN_ROWS * if stacked_graphs { graph_ids.len() as u16 } else { 1 };
                let ideal = tables_ideal_h(app, &table_ids, outer[0].width);
                let (g_desired, t_desired) = split_vertical(outer[0].height, graph_min, ideal);
                let hs = VERT_ALLOC.lock().unwrap().update(
                    vec![g_desired, t_desired],
                    outer[0].height,
                    std::time::Instant::now(),
                );
                let graphs_h = hs.first().copied().unwrap_or(g_desired);
                let main = Layout::vertical([
                    Constraint::Length(graphs_h),
                    Constraint::Fill(1),
                ])
                .split(outer[0]);
                if stacked_graphs {
                    draw_stack(f, main[0], app, &graph_ids, true);
                } else {
                    draw_row(f, main[0], app, &graph_ids);
                }
                draw_table_grid(f, main[1], app, &table_ids);
            }
        },
        (false, true) => draw_stack(f, outer[0], app, &graph_ids, app.layout == LayoutMode::Tall),
        (true, false) => draw_table_grid(f, outer[0], app, &table_ids),
        (true, true) => {}
    }

    }

    match app.menu {
        MenuState::None if app.zoom.is_some() => {
            // zoom 态 footer:该状态下可用的键(与正常态不同)
            let lang = app.lang;
            let key = |k: &str, label: &str| footer_key(k, label);
            let mut spans: Vec<Span> = vec![Span::styled(" ", dim())];
            spans.extend(key("z / esc", "exit zoom"));
            spans.extend(key("enter", lang.tr("detail_desc")));
            spans.extend(key("space", lang.tr("pause")));
            spans.extend(key("/", lang.tr("search")));
            f.render_widget(Paragraph::new(Line::from(spans)), outer[1]);
        }
        MenuState::None => draw_footer(f, outer[1], app),
        MenuState::Search => {
            // 搜索模式:footer 左侧变输入行,实时回显缓冲
            let cols =
                Layout::horizontal([Constraint::Min(0), Constraint::Length(9)]).split(outer[1]);
            let target = if app.search_box == BOX_PROCS {
                "procs"
            } else {
                "conns"
            };
            let q = &app.search_buf;
            let mut spans = vec![
                Span::styled("[/] ", Style::new().fg(hi())),
                Span::styled(
                    format!("{q}▏ "),
                    Style::new().fg(if q.is_empty() {
                        palette().dim
                    } else {
                        palette().text
                    }),
                ),
            ];
            // 与主页按键同款 [键] 标签 样式;[tab] 的标签即当前目标盒
            spans.extend(footer_key("tab", target));
            spans.extend(footer_key("enter", app.lang.tr("filter")));
            spans.extend(footer_key("esc", app.lang.tr("clear")));
            f.render_widget(Paragraph::new(Line::from(spans)), cols[0]);
            f.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    format!("{} ", local_time_str()),
                    Style::new().fg(accent()),
                ))),
                cols[1],
            );
        }
        MenuState::Main(sel) => draw_menu_footer(f, outer[1], sel, app.lang),
        MenuState::Theme(sel, scroll) => {
            draw_menu_footer(f, outer[1], 0, app.lang);
            draw_theme_popup(f, outer[0], sel, scroll);
        }
        MenuState::Settings(sel) => {
            draw_menu_footer(f, outer[1], 1, app.lang);
            draw_settings_popup(f, outer[0], app, sel);
        }
        MenuState::Reset(sel) => {
            draw_menu_footer(f, outer[1], 2, app.lang);
            draw_reset_popup(f, outer[0], sel, app.lang);
        }
        MenuState::Graphs(sel) => {
            draw_menu_footer(f, outer[1], 3, app.lang);
            draw_graphs_popup(f, outer[0], app, sel);
        }
        MenuState::Help => {
            draw_menu_footer(f, outer[1], 4, app.lang);
            draw_help_popup(f, outer[0], app);
        }
        MenuState::Detail(b, id) => {
            draw_menu_footer(f, outer[1], 0, app.lang);
            draw_detail_popup(f, outer[0], app, b, id);
        }
        MenuState::ConfirmKill(pid) => {
            draw_menu_footer(f, outer[1], 0, app.lang);
            draw_confirm_popup(f, outer[0], app, pid, false);
        }
        MenuState::ConfirmRestart(pid) => {
            draw_menu_footer(f, outer[1], 0, app.lang);
            draw_confirm_popup(f, outer[0], app, pid, true);
        }
    }
}

fn draw_stack(f: &mut Frame, area: Rect, app: &App, ids: &[usize], fill: bool) {
    if ids.is_empty() {
        return;
    }
    let cons: Vec<Constraint> = if fill {
        vec![Constraint::Fill(1); ids.len()]
    } else {
        // graph boxes keep a natural ratio when stacked in a half
        ids.iter()
            .map(|&i| {
                if i == BOX_NET {
                    Constraint::Percentage(58)
                } else {
                    Constraint::Percentage(42)
                }
            })
            .collect()
    };
    let parts = Layout::vertical(cons).split(area);
    for (&i, r) in ids.iter().zip(parts.iter()) {
        draw_box(f, *r, app, i);
    }
}

fn draw_row(f: &mut Frame, area: Rect, app: &App, ids: &[usize]) {
    if ids.is_empty() {
        return;
    }
    let cons = vec![Constraint::Fill(1); ids.len()];
    let parts = Layout::horizontal(cons).split(area);
    for (&i, r) in ids.iter().zip(parts.iter()) {
        draw_box(f, *r, app, i);
    }
}

fn draw_box(f: &mut Frame, area: Rect, app: &App, idx: usize) {
    match idx {
        BOX_NET => draw_net(f, area, app, app.focus[BOX_NET]),
        BOX_LAN => draw_lan(f, area, app, app.focus[BOX_LAN]),
        BOX_DISKIO => draw_diskio(f, area, app, app.focus[BOX_DISKIO]),
        BOX_DISKS => draw_disks(f, area, app, app.focus[BOX_DISKS]),
        BOX_CONNS => draw_conns(f, area, app, app.focus[BOX_CONNS]),
        BOX_PROCS => draw_procs(f, area, app, app.focus[BOX_PROCS]),
        _ => {}
    }
}

/// btop-style box frame: `┤ N word ├ rest` title with the box number just
/// left of the word and the function letter highlighted inside it.
fn boxed(
    f: &mut Frame,
    area: Rect,
    title: Line<'static>,
    border: Color,
    badge: usize,
    focused: bool,
) -> Rect {
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(if focused { hi() } else { border }))
        .title(title);
    let inner = block.inner(area);
    f.render_widget(block, area);
    BOX_AREAS.lock().unwrap().push((badge - 1, area));
    inner
}

/// Minimum rows a graph box can usefully show: one section header + a 3-row
/// braille plot.
const GRAPH_MIN_ROWS: u16 = 4;
/// A list box never asks for more than this before the others get their share.
const LIST_MAX_ROWS: u16 = 12;
/// Below this width a table row of four boxes squeezes each box past useful
/// column widths, so tables stack instead of forming a grid.
const TABLE_GRID_MIN_W: u16 = 100;

/// Applied-heights memory with hysteresis. Live row counts change every tick
/// (a connection opens, a process shows activity), and recomputing the split
/// from them moves every box by a row or two. A new allocation is only
/// adopted when it differs by `MIN_DELTA` rows and has persisted for
/// `SETTLE`, so genuine changes land while transient blips are ignored.
/// A terminal resize always re-applies immediately.
struct StableAlloc {
    applied: Vec<u16>,
    total: u16,
    last: Option<std::time::Instant>,
}

impl StableAlloc {
    const fn new() -> Self {
        Self {
            applied: Vec::new(),
            total: 0,
            last: None,
        }
    }

    fn update(&mut self, desired: Vec<u16>, total: u16, now: std::time::Instant) -> Vec<u16> {
        const MIN_DELTA: i32 = 4;
        const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
        let reset = self.applied.len() != desired.len() || self.total != total;
        if reset || self.last.is_none() {
            self.applied = desired;
            self.total = total;
            self.last = Some(now);
            return self.applied.clone();
        }
        // Adopt the whole allocation or none of it: taking only the boxes
        // that grew would break the invariant that the heights sum to the
        // available space, and the overflow would clip the last box.
        if now.duration_since(self.last.unwrap_or(now)) >= SETTLE {
            let moved = desired
                .iter()
                .zip(&self.applied)
                .any(|(d, a)| (*d as i32 - *a as i32).abs() >= MIN_DELTA);
            if moved && desired.iter().sum::<u16>() == total {
                self.applied = desired;
                self.last = Some(now);
            }
        }
        self.applied.clone()
    }
}

static LIST_ALLOC: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());
static VERT_ALLOC: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());
// classic 右列按中线分组后,上(LAN+CONNS)/下(PROCS+DISKS)各自平滑
static LIST_ALLOC_TOP: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());
/// classic 里 LAN 盒的高度上限:它可滚动,不必随设备数膨胀挤占 CONNS
const LAN_BOX_MAX_ROWS: u16 = 6;
static LIST_ALLOC_BOTTOM: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());

/// Split `total` rows among `ideals`: everyone gets their ideal while there is
/// room, but the spare height goes only to the boxes listed in `spare_to`
/// (process tables) so short lan/disks lists don't waste rows. When space is
/// short everything shrinks proportionally down to 3 rows each (border + one
/// content line).
fn alloc_heights(ideals: &[u16], total: u16, spare_to: &[usize]) -> Vec<u16> {
    let n = ideals.len();
    if n == 0 {
        return Vec::new();
    }
    let sum: u16 = ideals.iter().sum();
    let mut out = ideals.to_vec();
    if total >= sum {
        let spare = total - sum;
        let targets: Vec<usize> = if spare_to.is_empty() {
            (0..n).collect()
        } else {
            spare_to.iter().copied().filter(|&i| i < n).collect()
        };
        if !targets.is_empty() {
            let base = spare / targets.len() as u16;
            let rem = spare % targets.len() as u16;
            for (k, &i) in targets.iter().enumerate() {
                out[i] += base + u16::from((k as u16) < rem);
            }
        }
        let used: u16 = out.iter().sum();
        if let Some(last) = out.last_mut() {
            *last += total.saturating_sub(used);
        }
        return out;
    }
    let min_each = 3u16;
    if total <= min_each * n as u16 {
        // pathological terminal: equal shares, borders win
        return vec![(total / n as u16).max(1); n];
    }
    let usable = total - min_each * n as u16;
    let flex: u32 = ideals.iter().map(|h| h.saturating_sub(min_each) as u32).sum();
    let mut out = vec![min_each; n];
    if flex > 0 {
        let mut assigned = 0u16;
        for (i, &h) in ideals.iter().enumerate() {
            let share = (h.saturating_sub(min_each) as u32)
                .saturating_mul(usable as u32)
                .saturating_div(flex) as u16;
            out[i] += share;
            assigned += share;
        }
        // rounding remainder goes to the box that wanted the most
        let rem = usable - assigned;
        let biggest = ideals
            .iter()
            .enumerate()
            .max_by_key(|(_, &h)| h)
            .map(|(i, _)| i)
            .unwrap_or(0);
        out[biggest] += rem;
    }
    out
}

/// Classic layout width split (graphs_w, tables_w). Lists are the priority:
/// they keep at least half the width and take up to `need` columns, while the
/// graphs shrink down to `graph_min` before losing anything else.
fn split_horizontal(w: u16, need: u16, graph_min: u16) -> (u16, u16) {
    let tables = (w / 2).max(need.min(w.saturating_sub(graph_min)));
    (w.saturating_sub(tables), tables)
}

/// Vertical split for wide/tall (graphs_h, tables_h). Lists get their ideal
/// height first; the graphs absorb the surplus but are capped at half the
/// height — on full-screen terminals the surplus flows back to the lists
/// instead of letting the two charts balloon to 4/5 of the screen. Only when
/// the lists themselves shrink below ideal do graphs give way down to
/// `graph_min`, after which the lists start scrolling.
fn split_vertical(h: u16, graph_min: u16, tables_ideal: u16) -> (u16, u16) {
    let graph_cap = h / 2;
    let tables = if h.saturating_sub(tables_ideal) > graph_cap {
        h - graph_cap
    } else {
        tables_ideal.clamp(3, h.saturating_sub(graph_min).max(3))
    };
    (h.saturating_sub(tables), tables)
}

/// Rows a list box would like (content + border + table header), capped and
/// rounded up to an even number: a connection opening/closing then changes the
/// requested height only every other row, so the graph/list split does not
/// breathe on every tick.
fn list_ideal_rows(rows: usize) -> u16 {
    let h = ((rows as u16).saturating_add(3)).clamp(4, LIST_MAX_ROWS);
    (h + 1) & !1
}

fn box_ideal_rows(app: &App, idx: usize) -> u16 {
    match idx {
        BOX_LAN => list_ideal_rows(app.lan.neighbors.len()),
        BOX_CONNS => list_ideal_rows(app.conn.conns.len()),
        BOX_PROCS => list_ideal_rows(app.proc.procs.len()),
        BOX_DISKS => list_ideal_rows(app.disk.tree.len() * 2),
        _ => GRAPH_MIN_ROWS,
    }
}

/// Rows the table area needs: side by side (grid) the two boxes of a row share
/// a height, stacked they add up.
fn tables_ideal_h(app: &App, ids: &[usize], width: u16) -> u16 {
    if ids.is_empty() {
        return 0;
    }
    if width < TABLE_GRID_MIN_W {
        return ids.iter().map(|&i| box_ideal_rows(app, i)).sum();
    }
    ids.chunks(2)
        .map(|pair| pair.iter().map(|&i| box_ideal_rows(app, i)).max().unwrap_or(0))
        .sum()
}

/// Column widths from a fixed width vocabulary — never from live content.
/// A rate flipping between "999B/s" and "1.0KiB/s" must not resize the table
/// every tick, so the bases are constants per table; spare width is spread
/// evenly with a per-column growth cap. The result depends only on the box
/// width, which makes the layout completely stable between frames.
fn fit_columns(
    base: &[usize],
    flex: usize,
    flex_min: usize,
    flex_max: usize,
    total: u16,
    spacing: usize,
) -> Vec<Constraint> {
    let n = base.len();
    if n == 0 {
        return Vec::new();
    }
    let avail = (total as usize).saturating_sub(spacing * n.saturating_sub(1));
    let fixed: usize = base
        .iter()
        .enumerate()
        .filter(|(i, _)| *i != flex)
        .map(|(_, w)| *w)
        .sum();
    let room = avail.saturating_sub(fixed);
    let mut want = base.to_vec();
    // keep the flexible column visible even when the fixed ones already
    // overflow; the right edge clips, which is the least bad option
    want[flex] = if room >= flex_min {
        room.min(flex_max.max(flex_min))
    } else {
        flex_min
    };

    let base_sum: usize = want.iter().sum();
    if base_sum > avail {
        // even the fixed vocabulary does not fit: keep every column and let
        // the right edge clip, rather than hiding the name column entirely
        return want.iter().map(|&w| Constraint::Length(w as u16)).collect();
    }
    let max_grow: Vec<usize> = want.iter().map(|&w| (w / 2).max(2)).collect();
    let mut grow = vec![0usize; n];
    let mut slack = avail - base_sum;
    let mut progressed = true;
    while slack > 0 && progressed {
        progressed = false;
        for i in 0..n {
            if slack == 0 {
                break;
            }
            if grow[i] < max_grow[i] {
                grow[i] += 1;
                slack -= 1;
                progressed = true;
            }
        }
    }
    want.iter()
        .zip(&grow)
        .map(|(&w, &g)| Constraint::Length((w + g) as u16))
        .collect()
}

/// Table area: a grid of two columns where width allows, otherwise a stack.
/// Heights follow the boxes' ideal row counts so a short list is not padded
/// with blank space while a long one scrolls.
fn draw_table_grid(f: &mut Frame, area: Rect, app: &App, ids: &[usize]) {
    if ids.is_empty() {
        return;
    }
    let grid = area.width >= TABLE_GRID_MIN_W && ids.len() > 1;
    if !grid {
        // 非经典布局的列表栈无需中线对齐
        draw_list_stack(f, area, app, ids, false);
        return;
    }
    let row_ideals: Vec<u16> = ids
        .chunks(2)
        .map(|pair| pair.iter().map(|&i| box_ideal_rows(app, i)).max().unwrap_or(4))
        .collect();
    // in each grid row the process table (conns/procs) gets the spare height
    let spare_rows: Vec<usize> = row_ideals
        .iter()
        .enumerate()
        .map(|(r, _)| {
            ids[r * 2..(r * 2 + 2).min(ids.len())]
                .iter()
                .position(|&i| matches!(i, BOX_CONNS | BOX_PROCS))
                .unwrap_or(0)
        })
        .collect();
    let desired = alloc_heights(&row_ideals, area.height, &spare_rows);
    let hs = LIST_ALLOC
        .lock()
        .unwrap()
        .update(desired, area.height, std::time::Instant::now());
    let cons: Vec<Constraint> = hs.iter().map(|&h| Constraint::Length(h)).collect();
    let rows = Layout::vertical(cons).split(area);
    for (pair, r) in ids.chunks(2).zip(rows.iter()) {
        if pair.len() == 1 {
            draw_box(f, *r, app, pair[0]);
        } else {
            let cols =
                Layout::horizontal([Constraint::Fill(1), Constraint::Fill(1)]).split(*r);
            draw_box(f, cols[0], app, pair[0]);
            draw_box(f, cols[1], app, pair[1]);
        }
    }
}

/// Stack list boxes by their ideal heights; spare space is spread evenly and
/// when short they shrink proportionally (each keeps at least 3 rows).
fn draw_list_stack(f: &mut Frame, area: Rect, app: &App, ids: &[usize], snap_mid: bool) {
    // classic:LAN+CONNS 组钉在列的上半,底边与左列 NET|DISK 分界(中线)对齐;
    // PROCS+DISKS 在下半。组的开拆点是第一个非 LAN/CONNS 的盒子。
    if snap_mid {
        let bi = ids
            .iter()
            .position(|&i| !matches!(i, BOX_LAN | BOX_CONNS))
            .unwrap_or(ids.len());
        if bi > 0 && bi < ids.len() {
            // 与左列 NET|DISK 相同的 Fill(1)+Fill(1) 分法,奇数高度时余行
            // 给上半,两侧分界线逐行重合
            let parts =
                Layout::vertical([Constraint::Fill(1), Constraint::Fill(1)]).split(area);
            // 上半组里 LAN 单独算:钉一个矮个头上限(滚动可见全量),
            // 剩余全部让给信息量最大的 CONNS
            // LAN 钉矮个头的前提是 CONNS 可见(矮个头是为给 CONNS 让位);
            // CONNS hide 后上组只剩 LAN,应占满上半而非留空
            if ids[0] == BOX_LAN && ids.contains(&BOX_CONNS) && ids.len() > 2 {
                // 内层 clamp 的上界恒 ≥ 下界(1≤6),迷你终端不会 panic
                let lan_h = box_ideal_rows(app, BOX_LAN)
                    .min(LAN_BOX_MAX_ROWS)
                    .clamp(
                        1,
                        (parts[0].height.saturating_sub(3)).clamp(1, LAN_BOX_MAX_ROWS),
                    );
                let sub = Layout::vertical([Constraint::Length(lan_h), Constraint::Fill(1)])
                    .split(parts[0]);
                draw_box(f, sub[0], app, ids[0]);
                draw_table_group(f, sub[1], app, &ids[1..bi], &LIST_ALLOC_TOP);
            } else {
                draw_table_group(f, parts[0], app, &ids[..bi], &LIST_ALLOC_TOP);
            }
            draw_table_group(f, parts[1], app, &ids[bi..], &LIST_ALLOC_BOTTOM);
            return;
        }
    }
    draw_table_group(f, area, app, ids, &LIST_ALLOC);
}

fn draw_table_group(
    f: &mut Frame,
    area: Rect,
    app: &App,
    ids: &[usize],
    alloc: &Mutex<StableAlloc>,
) {
    if ids.is_empty() || area.height == 0 {
        return;
    }
    let ideals: Vec<u16> = ids.iter().map(|&i| box_ideal_rows(app, i)).collect();
    let spare_to: Vec<usize> = ids
        .iter()
        .enumerate()
        .filter(|&(_, id)| matches!(*id, BOX_CONNS | BOX_PROCS))
        .map(|(i, _)| i)
        .collect();
    let desired = alloc_heights(&ideals, area.height, &spare_to);
    let hs = alloc
        .lock()
        .unwrap()
        .update(desired, area.height, std::time::Instant::now());
    let cons: Vec<Constraint> = hs.iter().map(|&h| Constraint::Length(h)).collect();
    let parts = Layout::vertical(cons).split(area);
    for (&id, r) in ids.iter().zip(parts.iter()) {
        draw_box(f, *r, app, id);
    }
}

/// btop-style title: the box word framed as `─┐¹word┌`, then every info
/// segment framed in its own `┐…┌` pair (btop menu-button style), all in
/// border color. Superscript digit + function letters highlighted.
fn title_line(
    badge: usize,
    word: &str,
    key: char,
    pieces: Vec<Vec<Span<'static>>>,
    border: Color,
    focused: bool,
) -> Line<'static> {
    let frame = if focused { hi() } else { border };
    let b = Style::new().fg(frame);
    let mut spans: Vec<Span> = vec![Span::styled("─", b), Span::styled("┐", b)];
    if badge > 0 {
        spans.push(Span::styled(superscript(badge), bold(hi())));
    }
    match word.find(key) {
        Some(pos) => {
            let (head, tail) = word.split_at(pos);
            let (k, tail) = tail.split_at(1);
            spans.push(Span::styled(head.to_string(), bold(palette().title)));
            spans.push(Span::styled(k.to_string(), bold(hi())));
            spans.push(Span::styled(tail.to_string(), bold(palette().title)));
        }
        None => spans.push(Span::styled(word.to_string(), bold(palette().title))),
    }
    spans.push(Span::styled("┌", b));
    for p in pieces {
        // frames chained together by the border line, btop menu style
        spans.push(Span::styled("─", b));
        spans.push(Span::styled("┐", b));
        spans.extend(p);
        spans.push(Span::styled("┌", b));
    }
    Line::from(spans)
}

fn text_s(s: String) -> Span<'static> {
    Span::styled(s, text())
}

fn key_span(k: &str) -> Span<'static> {
    Span::styled(k.to_string(), bold(hi()))
}

/// A function word with its key letter highlighted: `[f]ilter: all`
fn fword(key: char, word: &str, value: &str) -> Vec<Span<'static>> {
    let mut v = Vec::new();
    match word.find(key) {
        Some(pos) => {
            let (head, tail) = word.split_at(pos);
            let (k, tail) = tail.split_at(1);
            v.push(Span::styled(head.to_string(), Style::new().fg(palette().title)));
            v.push(Span::styled(k.to_string(), bold(hi())));
            v.push(Span::styled(tail.to_string(), Style::new().fg(palette().title)));
        }
        None => v.push(Span::styled(word.to_string(), Style::new().fg(palette().title))),
    }
    if !value.is_empty() {
        v.push(Span::styled(format!(": {value}"), Style::new().fg(palette().title)));
    }
    v
}

/// Append a "+N more rows" hint to a title rest string when a list scrolls
fn scroll_hint(list_len: usize, off: usize, area: Rect) -> String {
    let visible = area.height.saturating_sub(3); // borders + table header
    let hidden = list_len.saturating_sub(off + visible as usize);
    if hidden > 0 {
        format!("+{hidden}")
    } else {
        String::new()
    }
}

/// Unicode superscript digits — the btop-style corner badge look
fn superscript(n: usize) -> String {
    const SUP: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];
    n.to_string()
        .chars()
        .map(|c| SUP[c.to_digit(10).unwrap_or(0) as usize])
        .collect()
}

/// stable id for list items that survive reordering
/// readable text colour for a coloured row background
fn contrast_fg(c: Color) -> Color {
    match c {
        Color::Rgb(r, g, b) => {
            let l = 0.2126 * r as f32 + 0.7152 * g as f32 + 0.0722 * b as f32;
            if l > 140.0 {
                Color::Rgb(0, 0, 0)
            } else {
                Color::Rgb(255, 255, 255)
            }
        }
        _ => Color::Black,
    }
}

/// alternating track colours: two distinct theme accents
fn track_bg(slot: usize) -> Color {
    if slot.is_multiple_of(2) {
        download().at(1.0)
    } else {
        upload().at(1.0)
    }
}

fn track_fg(slot: usize) -> Color {
    contrast_fg(track_bg(slot))
}

/// Rows of a box's current list, for selection clamping
/// 滚动偏移的统一封顶:最后一页(与 draw_procs/draw_conns/鼠标点击同源),
/// 旧版各自手写 min(len-1) 导致滚到底后点击错位、只剩单行
pub fn clamped_offset(app: &App, idx: usize, visible: usize) -> usize {
    app.scroll[idx].min(list_len(app, idx).saturating_sub(visible.max(1)))
}

/// 跳到列表顶/底(Home/End/g/G):有选中模型的盒移动选中,DISKS 盒只滚
pub fn jump_selection(app: &mut App, idx: usize, top: bool) {
    if idx == crate::app::BOX_DISKS {
        app.scroll[idx] = if top { 0 } else { usize::MAX };
        return;
    }
    let len = list_len(app, idx);
    if len == 0 {
        return;
    }
    let target = if top { 0 } else { len - 1 };
    app.sel[idx] = Some(target);
    // 窗口跟随,与 move_selection 同语义
    let cap = box_capacity(idx);
    let off = &mut app.scroll[idx];
    if target < *off {
        *off = target;
    } else if target + 1 >= *off + cap {
        *off = target + 1 - cap;
    }
}

pub fn list_len(app: &App, idx: usize) -> usize {
    match idx {
        BOX_LAN => app.lan.neighbors.len(),
        BOX_CONNS => conn_items(app).len(),
        BOX_PROCS => procs_display(app).len(),
        BOX_DISKS => {
            let mut flat: Vec<(&TreeNode, String)> = Vec::new();
            emit_tree_rows(&app.disk.tree, "", 0, &mut flat);
            flat.len()
        }
        _ => 0,
    }
}

/// Process list in display order: tracked rows pinned at the top in the
/// order they were activated, the rest following the active sort.
/// `/` 搜索:名字子串过滤(大小写不敏感);空串不过滤
fn name_matches(name: &str, q: &str) -> bool {
    q.is_empty() || name.to_lowercase().contains(&q.to_lowercase())
}

/// proc 分组的聚合信息(可见行、聚合行与详情共用)
#[derive(Clone, Copy, Default)]
pub struct GroupInfo {
    pub n: usize,
    pub rx: u64,
    pub tx: u64,
    pub rr: f64,
    pub rs: f64,
}

/// CONNS proc 排序下的可见行:聚合父行或单条连接
pub enum ConnItem<'a> {
    Agg {
        key: String,
        name: String,
        rep: &'a Conn,
        info: GroupInfo,
    },
    /// `child`:展开组的子行(渲染时树形缩进)
    Row {
        c: &'a Conn,
        child: bool,
    },
}

impl ConnItem<'_> {
    /// 稳定 id:连接行 = inode;聚合行 = 归属键哈希,最高位置 1
    /// (真实 socket inode 远小于 2^63,不会相撞)
    pub fn id(&self) -> u64 {
        match self {
            Self::Row { c, .. } => c.inode,
            Self::Agg { key, .. } => {
                use std::hash::{Hash, Hasher};
                let mut h = std::collections::hash_map::DefaultHasher::new();
                key.hash(&mut h);
                0x8000_0000_0000_0000 | (h.finish() & 0x7fff_ffff_ffff_ffff)
            }
        }
    }

    pub fn is_agg(&self) -> bool {
        matches!(self, Self::Agg { .. })
    }

    pub fn conn(&self) -> Option<&Conn> {
        match self {
            Self::Row { c, .. } => Some(c),
            _ => None,
        }
    }
}

/// CONNS 的可见行序列(默认折叠 proc 分组;搜索时全部展开)
pub fn conn_items(app: &App) -> Vec<ConnItem<'_>> {
    let list = conns_display(app);
    if app.conn.sort != ConnSort::Proc {
        return list
            .into_iter()
            .map(|c| ConnItem::Row { c, child: false })
            .collect();
    }
    // 搜索时全部展开:命中不可见的折叠组等于没搜到
    let expand_all = !app.search.is_empty();
    let group_open = |key: &str| -> bool {
        app.proc_expand_default != app.expanded.contains(key)
    };
    let mut out: Vec<ConnItem> = Vec::new();
    let mut i = 0;
    while i < list.len() {
        let key = crate::collect::conn::owner_key(list[i]);
        let n = list[i..]
            .iter()
            .take_while(|c| crate::collect::conn::owner_key(c) == key)
            .count();
        if n == 1 {
            out.push(ConnItem::Row {
                c: list[i],
                child: false,
            });
            i += 1;
            continue;
        }
        let group = &list[i..i + n];
        let info = GroupInfo {
            n,
            rx: group.iter().map(|c| c.bytes_recv).sum(),
            tx: group.iter().map(|c| c.bytes_sent).sum(),
            rr: group.iter().map(|c| c.rate_recv).sum(),
            rs: group.iter().map(|c| c.rate_sent).sum(),
        };
        let expanded = expand_all || group_open(&key);
        out.push(ConnItem::Agg {
            key: key.clone(),
            name: key.clone(),
            rep: group[0],
            info,
        });
        if expanded {
            out.extend(group.iter().map(|c| ConnItem::Row {
                c,
                child: true,
            }));
        }
        i += n;
    }
    out
}

/// 选中聚合行时的归属键(展开/折叠用)
pub fn selected_agg_key(app: &App, idx: usize) -> Option<String> {
    match conn_items(app).get(app.sel[idx]?) {
        Some(ConnItem::Agg { key, .. }) => Some(key.clone()),
        _ => None,
    }
}

/// 选中行是否为聚合父行
pub fn selected_is_agg(app: &App, idx: usize) -> bool {
    idx == BOX_CONNS
        && app.sel[idx].is_some()
        && conn_items(app)
            .get(app.sel[idx].unwrap())
            .is_some_and(|i| i.is_agg())
}


/// 组当前是否展开
pub fn group_is_open(app: &App, key: &str) -> bool {
    app.proc_expand_default != app.expanded.contains(key)
}

/// 设定组开/合(相对默认态反转)
pub fn set_group_open(app: &mut App, key: &str, open: bool) {
    if open != app.proc_expand_default {
        app.expanded.insert(key.to_string());
    } else {
        app.expanded.remove(key);
    }
}

/// 切换组开/合
pub fn toggle_group(app: &mut App, key: &str) {
    let open = group_is_open(app, key);
    set_group_open(app, key, !open);
}


pub fn procs_display(app: &App) -> Vec<&crate::collect::proc::ProcRow> {
    let mut out = Vec::new();
    for pid in &app.tracked.procs {
        if let Some(p) = app.proc.procs.iter().find(|p| p.pid == *pid) {
            out.push(p);
        }
    }
    for p in app.proc.procs.iter() {
        if !app.tracked.procs.contains(&p.pid)
            && (app.search_box != BOX_PROCS || name_matches(&p.name, &app.search))
        {
            out.push(p);
        }
    }
    out
}
/// Connection list in display order: tracked pinned first, then the rest.
pub fn conns_display(app: &App) -> Vec<&Conn> {
    let mut out = Vec::new();
    for ino in &app.tracked.conns {
        if let Some(c) = app.conn.conns.iter().find(|c| c.inode == *ino) {
            out.push(c);
        }
    }
    for c in app.conn.conns.iter() {
        if !app.tracked.conns.contains(&c.inode) {
            out.push(c);
        }
    }
    let mut out = match app.conn.filter {
        ConnFilter::All => out,
        ConnFilter::Lan => out
            .into_iter()
            .filter(|c| matches!(c.remote.0, std::net::IpAddr::V4(v4) if v4.is_private()))
            .collect(),
        ConnFilter::Tcp => out.into_iter().filter(|c| c.is_tcp()).collect(),
        ConnFilter::Udp => out.into_iter().filter(|c| !c.is_tcp()).collect(),
    };
    // LAN 联动的对端过滤(enter from lan row)
    if let Some(ip) = app.conn.peer_filter {
        out.retain(|c| c.remote.0 == std::net::IpAddr::V4(ip));
    }
    // `/` 搜索:仅作用于目标盒(非目标盒直通显示)
    if app.search_box == BOX_CONNS && !app.search.is_empty() {
        let q = app.search.to_lowercase();
        out.retain(|c| {
            c.proc
                .as_deref()
                .unwrap_or("")
                .to_lowercase()
                .contains(&q)
        });
    }
    out
}

/// the connection list after the active filter, in display order
pub fn conn_list(app: &App) -> Vec<&Conn> {
    conns_display(app)
}

/// stable id of the selected row of a list box
pub fn selected_id(app: &App, idx: usize) -> Option<u64> {
    match idx {
        BOX_PROCS => procs_display(app).get(app.sel[BOX_PROCS]?).map(|p| p.pid as u64),
        BOX_LAN => app
            .lan
            .sorted_neighbors()
            .get(app.sel[BOX_LAN]?)
            .map(|n| u32::from(n.ip) as u64),
        BOX_CONNS => conn_items(app)
            .get(app.sel[BOX_CONNS]?)
            .map(|i| i.id()),
        _ => None,
    }
}

/// pid behind the selected row, when there is one
pub fn selected_pid(app: &App, idx: usize) -> Option<u32> {
    match idx {
        BOX_PROCS => procs_display(app).get(app.sel[BOX_PROCS]?).map(|p| p.pid),
        BOX_CONNS => conn_items(app)
            .get(app.sel[BOX_CONNS]?)
            .and_then(|i| i.conn())
            .and_then(|c| c.pid),
        _ => None,
    }
}

/// toggle tracking of the item shown in the detail panel
pub fn toggle_track(app: &mut App, idx: usize, id: u64) {
    match idx {
        BOX_PROCS => app.tracked.toggle_proc(id as u32),
        BOX_CONNS => app.tracked.toggle_conn(id),
        _ => {}
    }
}

/// rows that fit in a list box (border + header + the selected row's 2nd line)
pub fn box_capacity(idx: usize) -> usize {
    BOX_AREAS
        .lock()
        .unwrap()
        .iter()
        .find(|(i, _)| *i == idx)
        .map(|(_, r)| (r.height.saturating_sub(3)).max(1) as usize)
        .unwrap_or(10)
}

/// Re-anchor a box's selection onto the entity it names (pid for procs,
/// inode for conns) after the list re-sorted underneath it, and keep the row
/// inside the viewport. An entity that left the list clears the selection.
pub fn reselect(app: &mut App, idx: usize, id: u64) {
    let pos = match idx {
        BOX_PROCS => procs_display(app).iter().position(|p| p.pid as u64 == id),
        BOX_LAN => app
            .lan
            .sorted_neighbors()
            .iter()
            .position(|n| u32::from(n.ip) as u64 == id),
        BOX_CONNS => conn_items(app).iter().position(|i| i.id() == id),
        _ => None,
    };
    app.sel[idx] = pos;
    if let Some(n) = pos {
        let cap = box_capacity(idx);
        let off = &mut app.scroll[idx];
        if n < *off {
            *off = n;
        } else if n + 1 >= *off + cap {
            *off = (n + 1).saturating_sub(cap);
        }
    }
}

/// Move the cursor of a list box, keeping it inside the visible window
pub fn move_selection(app: &mut App, idx: usize, delta: i32) {
    let len = list_len(app, idx);
    if len == 0 {
        return;
    }
    let cap = box_capacity(idx);
    let next = match app.sel[idx] {
        None => Some(if delta < 0 { len - 1 } else { 0 }),
        Some(cur) => Some((cur as i32 + delta).clamp(0, len as i32 - 1) as usize),
    };
    app.sel[idx] = next;
    // keep the selected row (which is 2 lines tall) inside the viewport
    if let Some(n) = next {
        let off = &mut app.scroll[idx];
        if n < *off {
            *off = n;
        } else if n + 1 >= *off + cap {
            *off = (n + 1).saturating_sub(cap);
        }
    }
}

fn draw_net(f: &mut Frame, area: Rect, app: &App, focused: bool) {
    let name = app
        .net
        .selected
        .clone()
        .unwrap_or_else(|| "-".to_string());
    // hostname and refresh interval live in the title (no separate top bar)
    let rest = vec![
        vec![text_s(app.hostname.clone())],
        vec![text_s(name.clone())],
        vec![
            key_span("-"),
            text_s("refresh ".to_string()),
            text_s(fmt_interval(app.tick)),
            key_span("+"),
        ],
    ];
    let inner = boxed(
        f,
        area,
        title_line(BOX_NET + 1, "net", 'n', rest, border_net(), focused),
        border_net(),
        BOX_NET + 1,
        focused,
    );
    if inner.width < 10 || inner.height < 4 {
        return;
    }

    let chunks = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Min(3),
        Constraint::Length(1),
        Constraint::Min(3),
    ])
    .split(inner);

    // interface info line
    let mut info: Vec<Span> = vec![Span::styled(" ", dim())];
    if let Some(i) = app.net.ifaces.get(&name) {
        let (mark, col) = if i.operstate == "up" {
            ("▲ up", hi())
        } else {
            ("▼ down", alert_end())
        };
        info.push(Span::styled(format!("{mark} "), Style::new().fg(col)));
        if let Some(s) = i.speed_mbps {
            info.push(Span::styled(format!("{s}Mb/s "), Style::new().fg(accent())));
        }
        if let Some(d) = &i.duplex {
            info.push(Span::styled(
                format!("{} ", if d == "full" { "FD" } else { "HD" }),
                dim(),
            ));
        }
        if let Some(m) = i.mtu {
            info.push(Span::styled(format!("mtu {m} "), dim()));
        }
        if let Some(a) = i.addrs.first() {
            info.push(Span::styled(a.clone(), Style::new().fg(accent())));
        }
        if i.addrs.len() > 1 {
            info.push(Span::styled(format!(" +{}", i.addrs.len() - 1), dim()));
        }
    }
    f.render_widget(Paragraph::new(Line::from(info)), chunks[0]);

    let rates = app.net.selected_rates();
    let (hrx, htx) = app.net.selected_hist();

    // 头行标签随列宽分级:≥52 全称,≥40 缩写,更窄只留 session
    let head_w = chunks[1].width as usize;
    let sess_lbl = if head_w >= 52 { "  session Σ " } else { " Σs " };
    let (alive_lbl, _show_alive) = if head_w >= 52 {
        ("  alive Σ ", true)
    } else if head_w >= 40 {
        (" Σa ", true)
    } else {
        ("", false)
    };

    let alive = app.net.selected_alive();

    let rx_head = Line::from(vec![
        Span::styled(" ▼ RX ", bold(download().at(0.5))),
        Span::styled(
            rates.map(|r| fmt_speed(r.rx)).unwrap_or_else(|| "…".into()),
            bold(download().at(0.5)),
        ),
        Span::styled(sess_lbl, dim()),
        Span::styled(
            rates.map(|r| fmt_bytes(r.rx_total as f64)).unwrap_or_default(),
            text(),
        ),
        Span::styled(alive_lbl, dim()),
        Span::styled(
            if alive_lbl.is_empty() {
                String::new()
            } else {
                alive.map(|(a, _)| fmt_bytes(a as f64)).unwrap_or_default()
            },
            dim(),
        ),
    ]);
    let tx_head = Line::from(vec![
        Span::styled(" ▲ TX ", bold(upload().at(0.5))),
        Span::styled(
            rates.map(|r| fmt_speed(r.tx)).unwrap_or_else(|| "…".into()),
            bold(upload().at(0.5)),
        ),
        Span::styled(sess_lbl, dim()),
        Span::styled(
            rates.map(|r| fmt_bytes(r.tx_total as f64)).unwrap_or_default(),
            text(),
        ),
        Span::styled(alive_lbl, dim()),
        Span::styled(
            if alive_lbl.is_empty() {
                String::new()
            } else {
                alive.map(|(_, a)| fmt_bytes(a as f64)).unwrap_or_default()
            },
            dim(),
        ),
    ]);
    f.render_widget(Paragraph::new(rx_head), chunks[1]);
    f.render_widget(
        Paragraph::new(braille_graph(
            &hrx,
            chunks[2].width as usize,
            chunks[2].height as usize,
            GRAPH_FLOOR,
            download(),
            app.graph_net,
        )),
        chunks[2],
    );
    f.render_widget(Paragraph::new(tx_head), chunks[3]);
    f.render_widget(
        Paragraph::new(braille_graph(
            &htx,
            chunks[4].width as usize,
            chunks[4].height as usize,
            GRAPH_FLOOR,
            upload(),
            app.graph_net,
        )),
        chunks[4],
    );
}

fn draw_lan(f: &mut Frame, area: Rect, app: &App, focused: bool) {
    let list = app.lan.sorted_neighbors();
    let subnets = app
        .lan
        .subnets
        .iter()
        .map(|(_, n, p)| format!("{n}/{p}"))
        .collect::<Vec<_>>()
        .join(" ");
    let sweep = if app.lan.sweeping {
        "scanning…"
    } else if app.lan.sweep_enabled {
        "on"
    } else {
        "off"
    };
    let per_remote = app.conn.per_remote_v4();
    let visible = area.height.saturating_sub(3).max(1) as usize;
    let off = clamped_offset(app, BOX_LAN, visible);
    let sel = if focused { app.sel[BOX_LAN] } else { None };
    let mut rest = vec![
        vec![text_s(subnets)],
        vec![text_s(format!("{} hosts", list.len()))],
        fword('s', "sweep", sweep),
        fword('e', "order", app.lan.sort.label()),
    ];
    let sh = scroll_hint(list.len(), off, area);
    if !sh.is_empty() {
        rest.push(vec![text_s(sh)]);
    }
    let inner = boxed(
        f,
        area,
        title_line(BOX_LAN + 1, "lan", 'l', rest, border_lan(), focused),
        border_lan(),
        BOX_LAN + 1,
        focused,
    );
    if inner.width < 10 || inner.height < 2 {
        return;
    }

    let headers = ["IP", "MAC", "HOSTNAME", "IF"];
    // 滚动窗口:一页 = 表头之下的全部行(inner 已不含边框,只减表头 1 行;
    // 旧写法 -2 把表头算两次,6 行高的盒子只渲染出 2 台设备)
    let visible = inner.height.saturating_sub(1) as usize;
    if list.is_empty() && app.lan.arp_blocked {
        let tip = if app.lang == Lang::Zh {
            "macOS 隐私限制:邻居 MAC 不可见(签名限制);本行扫描仅覆盖当前子网"
        } else {
            "macOS privacy: neighbour MACs are hidden (code-signing gate); scan covers the current subnet only"
        };
        f.render_widget(Paragraph::new(vec![Line::from(vec![Span::styled(tip, dim())])]), inner);
        return;
    }
    let rows: Vec<Row> = list
        .iter()
        .enumerate()
        .skip(off)
        .take(visible)
        .map(|(i, nb)| {
            let pinned = app.lan.tracked.contains(&nb.ip);
            let selected = sel == Some(i);
            let alt = (i - off) % 2 == 1;
            neighbor_row(
                nb,
                &app.lan.resolve_failures,
                per_remote.get(&nb.ip),
                pinned,
                selected,
                alt,
            )
        })
        .collect();
    let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
    // IP/MAC/IF have fixed formats; the hostname column takes the spare width
    let cols = fit_columns(&[16, 17, 0, 8], 2, 8, 30, inner.width, 1);
    let table = Table::new(rows, cols).header(header).column_spacing(1);
    f.render_widget(table, inner);
}

fn neighbor_row(
    nb: &Neighbor,
    resolve_failures: &std::collections::HashSet<std::net::Ipv4Addr>,
    conns: Option<&(usize, f64, f64, u64, u64)>,
    pinned: bool,
    selected: bool,
    alt: bool,
) -> Row<'static> {
    let (marker, color) = if nb.is_gateway {
        ("✦", hi())
    } else if nb.is_self {
        ("·", accent())
    } else {
        (" ", palette().text)
    };
    let host = match &nb.hostname {
        Some(h) => (h.clone(), palette().text),
        None if resolve_failures.contains(&nb.ip) => ("—".to_string(), palette().dim),
        None => ("resolving…".to_string(), palette().dim),
    };
    let host_text = host.0.clone();
    // 置顶行:高亮主色底(红);选中行:复色高亮(隔行双底色)。
    // 底色铺在 row 级 style 上,整行(含列间空隙)一体化,而非分散到列
    let (bg, base_fg) = if pinned {
        (Some(track_bg(0)), contrast_fg(track_bg(0)))
    } else if selected {
        (Some(track_bg(alt as usize)), contrast_fg(track_bg(alt as usize)))
    } else {
        (None, palette().text)
    };
    let fg = |col: Color| if bg.is_some() { base_fg } else { col };
    let mut host_cell = Line::from(Span::styled(host_text.clone(), fg(host.1)));
    if let Some((n, r, _, tr, _)) = conns {
        if *n > 0 {
            let extra = format!(" ·{n}conn {}", fmt_speed(*r));
            let sum = if *tr > 0 {
                format!(" Σ{}", fmt_bytes(*tr as f64))
            } else {
                String::new()
            };
            host_cell = Line::from(vec![
                Span::styled(host_text, fg(host.1)),
                Span::styled(extra, fg(hi())),
                Span::styled(sum, fg(hi())),
            ]);
        }
    }
    // 普通行不设 bg:保留主题 main_bg(Reset 会盖掉主题底色,与 conn_row 同规)
    let style = match bg {
        Some(c) => Style::new().fg(base_fg).bg(c),
        None => Style::new().fg(base_fg),
    };
    let mac_plain = if nb.mac_hidden {
        "—".to_string()
    } else {
        nb.mac.clone().unwrap_or_else(|| "expired".into())
    };
    Row::new([
        Cell::from(Line::from(vec![
            Span::styled(marker.to_string(), fg(color)),
            Span::styled(nb.ip.to_string(), fg(color)),
        ])),
        Cell::from(Span::styled(mac_plain, fg(palette().text))),
        Cell::from(host_cell),
        Cell::from(Span::styled(nb.iface.clone(), fg(palette().text))),
    ])
    .style(style)
}

fn draw_diskio(f: &mut Frame, area: Rect, app: &App, focused: bool) {
    let (tr, tw, ti, sr, sw) = app.disk.totals();
    // r/w rates already live in the READ/WRITE section headers; the title
    // keeps only what is not shown inside
    let rest = vec![
        vec![text_s(format!("{:.0} iop/s", ti))],
        vec![text_s(format!("mode {}", app.io_graph.label()))],
    ];
    let inner = boxed(
        f,
        area,
        title_line(BOX_DISKIO + 1, "disk i/o", 'i', rest, border_disk(), focused),
        border_disk(),
        BOX_DISKIO + 1,
        focused,
    );
    if inner.width < 16 || inner.height < 4 {
        return;
    }
    let (hr, hw) = app.disk.hist();
    match app.io_graph {
        IoGraphMode::Both => {
            let g = Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)])
                .split(inner);
            graph_section(f, g[0], " ▼ READ ", download(), &hr, tr, sr, app.graph_disk);
            graph_section(f, g[1], " ▲ WRITE ", upload(), &hw, tw, sw, app.graph_disk);
        }
        IoGraphMode::Read => graph_section(f, inner, " ▼ READ ", download(), &hr, tr, sr, app.graph_disk),
        IoGraphMode::Write => graph_section(f, inner, " ▲ WRITE ", upload(), &hw, tw, sw, app.graph_disk),
    }
}

#[allow(clippy::too_many_arguments)]
fn graph_section(
    f: &mut Frame,
    area: Rect,
    label: &str,
    grad: Gradient,
    data: &[f64],
    total: f64,
    sum: u64,
    mode: GraphMode,
) {
    let g = Layout::vertical([Constraint::Length(1), Constraint::Min(2)]).split(area);
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(label, bold(grad.at(0.5))),
            Span::styled(fmt_speed(total), bold(grad.at(0.5))),
            Span::styled("  Σ ", dim()),
            Span::styled(fmt_bytes(sum as f64), text()),
        ])),
        g[0],
    );
    f.render_widget(
        Paragraph::new(braille_graph(
            data,
            g[1].width as usize,
            g[1].height as usize,
            GRAPH_FLOOR,
            grad,
            mode,
        )),
        g[1],
    );
}

fn draw_disks(f: &mut Frame, area: Rect, app: &App, focused: bool) {
    let mut flat: Vec<(&TreeNode, String)> = Vec::new();
    emit_tree_rows(&app.disk.tree, "", 0, &mut flat);
    let off = app.scroll[BOX_DISKS].min(flat.len().saturating_sub(1));
    let mut rest = vec![
        vec![text_s(format!("{} dev", app.disk.devices.len()))],
        vec![text_s(format!(
            "mounts: {}",
            if app.disks_expanded { "all" } else { "first" }
        ))],
    ];
    let sh = scroll_hint(flat.len(), off, area);
    if !sh.is_empty() {
        rest.push(vec![text_s(sh)]);
    }
    let inner = boxed(
        f,
        area,
        title_line(BOX_DISKS + 1, "disks", 'd', rest, border_disk(), focused),
        border_disk(),
        BOX_DISKS + 1,
        focused,
    );
    if inner.width < 16 || inner.height < 2 {
        return;
    }
    // 表头之下的可视行数封顶:旧写法 min(len-1) 滚到底后从最后一行起渲染
    // (只剩单行/空白),与 LAN/CONNS/PROCS 的 clamped_offset 同语义
    let off = off.min(flat.len().saturating_sub((inner.height - 1).max(1) as usize));

    let rows: Vec<Row> = flat
        .into_iter()
        .skip(off)
        .map(|(node, label)| disk_row(app, node, label))
        .collect();
    let headers = ["DEV", "USED", "R/S", "W/S"];
    let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
    // DEV absorbs slack; the bar and both rates are exact-width
    let cols = fit_columns(&[0, 16, 9, 9], 0, 10, 40, inner.width, 1);
    let table = Table::new(rows, cols).header(header).column_spacing(1);
    f.render_widget(table, inner);
}

fn disk_row(app: &App, node: &TreeNode, mut label: String) -> Row<'static> {
    let dev = app.disk.dev_by_name(&node.name);
    match dev {
        Some(d) => {
            if let Some(p) = &d.pretty {
                label.push_str(&format!(" ({p})"));
            }
            if let Some(m) = d.mounts.first() {
                if app.disks_expanded {
                    label.push_str(&format!(" {}", d.mounts.join(" ")));
                } else {
                    label.push_str(&format!(" {m}"));
                    if d.mounts.len() > 1 {
                        label.push_str(&format!(" +{}", d.mounts.len() - 1));
                    }
                }
            }
        }
        // mapper alias is still useful for unmounted devices (e.g. closed LUKS)
        None => {
            if let Some(p) = &node.pretty {
                label.push_str(&format!(" ({p})"));
            }
        }
    }
    // usage bars only for rows backed by a filesystem (one per dev);
    // structural nodes (whole disks, carrier partitions) show their size
    let usage = if let Some(d) = dev {
        let frac = if d.total > 0 {
            d.used as f64 / d.total as f64
        } else {
            0.0
        };
        Line::from(vec![
            braille_bar(frac, 10, palette().used.at(frac as f32)),
            Span::styled(format!(" {:>3.0}%", frac * 100.0), text()),
        ])
    } else if let Some(sz) = node.size {
        Line::from(Span::styled(fmt_bytes(sz as f64), text()))
    } else {
        Line::from(Span::styled("", dim()))
    };
    let rate_r = dev.map(|d| fmt_speed(d.rate_r)).unwrap_or_default();
    let rate_w = dev.map(|d| fmt_speed(d.rate_w)).unwrap_or_default();
    Row::new([
        Cell::from(Span::styled(label, text())),
        Cell::from(usage),
        Cell::from(Span::styled(rate_r, Style::new().fg(download().at(0.5)))),
        Cell::from(Span::styled(rate_w, Style::new().fg(upload().at(0.5)))),
    ])
}

/// 选中聚合行时的详情:组 Σ/速率 + 成员连接清单(最多 3 条,余者计数)
/// 选中聚合行时的详情:单行组摘要(Σ 与速率小计;子行细节展开后自见)
fn proc_group_detail(name: &str, info: GroupInfo) -> Vec<Line<'static>> {
    let k = dim();
    let line1 = vec![
        Span::styled(format!(" {} ×{} ", name, info.n), bold(accent())),
        Span::styled("  Σ ", k),
        Span::styled(
            format!(
                "{}{} {}{} ",
                '\u{2193}',
                fmt_bytes(info.rx as f64),
                '\u{2191}',
                fmt_bytes(info.tx as f64)
            ),
            text(),
        ),
        Span::styled("rate ", k),
        Span::styled(
            format!(
                "{}{}/s {}{}/s",
                '\u{2193}',
                fmt_speed(info.rr),
                '\u{2191}',
                fmt_speed(info.rs)
            ),
            text(),
        ),
    ];
    vec![Line::from(line1)]
}

/// proc 分组的聚合父行:进程级 Σ 与连接数(M1,无折叠——子行全部展开)
fn conn_row_aggregate(
    name: &str,
    n: usize,
    open: bool,
    rx: u64,
    tx: u64,
    slot: Option<usize>,
) -> Row<'static> {
    if open {
        // 展开态:高亮底色(主题下载渐变顶;追踪行保留隔行底色),整行正文色
        let bg = match slot {
            Some(sl) => track_bg(sl % 2),
            None => track_bg(0),
        };
        let cell = |s: String| {
            Cell::from(Span::styled(s, Style::new().fg(palette().text).bg(bg)))
        };
        Row::new([
            cell(format!("\u{25be}{name} ×{n} Σ")),
            cell("-".into()),
            cell("-".into()),
            cell(format!("{n} conns")),
            cell(fmt_bytes(rx as f64)),
            cell(fmt_bytes(tx as f64)),
        ])
        .style(Style::new().bg(bg))
    } else {
        // 折叠态:无底色,常规配色(名字强调色 + Σ 标签 dim + 数值渐变色)
        let paint = |col: Color| slot.map(track_fg).unwrap_or(col);
        Row::new([
            Cell::from(Line::from(vec![
                Span::styled(
                    format!("\u{25b8}{name} ×{n}"),
                    Style::new().fg(paint(accent())),
                ),
                Span::styled(" Σ", Style::new().fg(paint(palette().dim))),
            ])),
            Cell::from(Span::styled(
                "-",
                Style::new().fg(paint(palette().dim)),
            )),
            Cell::from(Span::styled(
                "-",
                Style::new().fg(paint(palette().dim)),
            )),
            Cell::from(Span::styled(
                format!("{n} conns"),
                Style::new().fg(paint(accent())),
            )),
            Cell::from(Span::styled(
                fmt_bytes(rx as f64),
                Style::new().fg(paint(download().at(0.5))),
            )),
            Cell::from(Span::styled(
                fmt_bytes(tx as f64),
                Style::new().fg(paint(upload().at(0.5))),
            )),
        ])
    }
}

fn draw_conns(f: &mut Frame, area: Rect, app: &App, focused: bool) {
    let filter = app.conn.filter;
    let items = conn_items(app);
    // 滚动封顶 = 最后一页,而非最后一行(旧写法滚到底只剩 1 行且卡死)
    let visible = area.height.saturating_sub(3).max(1) as usize;
    let off = clamped_offset(app, BOX_CONNS, visible);
    // same as procs: the selection overlay follows focus, not persistence
    let sel = if focused { app.sel[BOX_CONNS] } else { None };
    let mut rest = vec![
        vec![text_s(format!("{}", items.len()))],
        fword('f', "filter", filter.label()),
        fword('o', "order", app.conn.sort.label()),
    ];
    let sh = scroll_hint(items.len(), off, area);
    if !sh.is_empty() {
        rest.push(vec![text_s(sh)]);
    }
    let inner = boxed(
        f,
        area,
        title_line(BOX_CONNS + 1, "conns", 'c', rest, border_lan(), focused),
        border_lan(),
        BOX_CONNS + 1,
        focused,
    );
    if inner.width < 16 || inner.height < 2 {
        return;
    }

    // sum/proc 排序下这两列显示的都是合计量,表头如实标注
    let total_mode = matches!(app.conn.sort, ConnSort::Sum | ConnSort::Proc);
    let headers = if total_mode {
        ["NAME", "PID", "LOCAL", "REMOTE", "\u{3a3} RX", "\u{3a3} TX"]
    } else {
        ["NAME", "PID", "LOCAL", "REMOTE", "RX/S", "TX/S"]
    };
    let mut rows: Vec<Row> = Vec::new();
    let mut sel_y = None;
    for (i, item) in items.iter().enumerate().skip(off).take(visible) {
        let id = item.id();
        let slot = app.tracked.conn_slot(id);
        let mut row = match item {
            ConnItem::Agg { name, info, .. } => {
                // 展开态的聚合行 = 打开状态
                conn_row_aggregate(
                    name,
                    info.n,
                    group_is_open(app, name),
                    info.rx,
                    info.tx,
                    slot,
                )
            }
            ConnItem::Row { c, child } => conn_row(c, app, slot, *child),
        };
        if sel == Some(i) {
            row = row.height(2);
            sel_y = Some(inner.y + 1 + (i - off) as u16);
        }
        rows.push(row);
    }
    let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
    // squeeze the address columns first when the box is narrow; rates stay exact
    // name column min 12: it now carries the 3-4 char protocol label
    let cols = fit_columns(&[0, 7, 18, 18, 9, 9], 0, 12, 24, inner.width, 1);
    let table = Table::new(rows, cols).header(header).column_spacing(1);
    f.render_widget(table, inner);
    if let (Some(y), Some(si)) = (sel_y, sel) {
        if let Some(item) = items.get(si) {
            if let Some(rect) = overlay_rect(inner, y) {
                // 选中聚合父行:详情显示进程组摘要(Σ + 速率小计),
                // 子行细节展开后自见;选中普通行仍是该连接详情
                let lines = match item {
                    ConnItem::Agg { name, info, .. } => {
                        proc_group_detail(name, *info)
                    }
                    ConnItem::Row { c, .. } => conn_detail(c, app),
                };
                draw_selected(f, rect, lines);
            }
        }
    }
}

/// Two-line selected-row overlay starting at `y`, clipped to the box interior.
/// The selected row can sit on the frame's bottom edge (bottom-most box, last
/// visible row); unclipped, the overlay's second line would land outside the
/// buffer and panic inside ratatui (observed as "index … (126, 67)" on a
/// 249x67 terminal).
fn overlay_rect(inner: Rect, y: u16) -> Option<Rect> {
    if y < inner.y || y >= inner.bottom() {
        return None; // row not on screen
    }
    Some(Rect {
        x: inner.x,
        y,
        width: inner.width,
        height: 2.min(inner.bottom() - y),
    })
}

/// two-line detail drawn over the selected row
fn draw_selected(f: &mut Frame, rect: Rect, lines: Vec<Line<'static>>) {
    // 弱着色深底(渐变暗端):overlay 内容的语义色(accent/dim/红绿流量)
    // 按深底设计——旧实现用 hi 亮底 + 单色 contrast,两行色彩层次全灭。
    // Paragraph 只铺 bg 不铺 fg,span 各自的显式色全部保留。
    let bgc = download().at(0.12);
    // wipe the underlying table text first — Paragraph.style only recolors
    // cells, it does not erase the symbols underneath
    f.render_widget(Clear, rect);
    let mut ls: Vec<Line> = lines.into_iter().take(2).collect();
    while ls.len() < 2 {
        ls.push(Line::from(""));
    }
    // 左缘竖条:弱底色后的选中锚点
    let bar_w = 1.min(rect.width);
    f.render_widget(
        Paragraph::new(vec![Line::from("▌"), Line::from("▌")])
            .style(Style::new().fg(accent()).bg(bgc)),
        Rect { x: rect.x, y: rect.y, width: bar_w, height: rect.height },
    );
    let rest = Rect {
        x: rect.x + bar_w,
        y: rect.y,
        width: rect.width.saturating_sub(bar_w),
        height: rect.height,
    };
    f.render_widget(Paragraph::new(ls).style(Style::new().bg(bgc)), rest);
}

/// two overlay lines for a selected connection
fn conn_detail(c: &Conn, app: &App) -> Vec<Line<'static>> {
    let name = c.proc.clone().unwrap_or_else(|| app.conn.user_name(c.uid));
    let pid = c.pid.map(|p| p.to_string()).unwrap_or_else(|| "-".into());
    // UDP has no LISTEN/ESTAB states; the plain label says everything
    let mut state = if c.is_listen() {
        "tcp LISTEN".to_string()
    } else if c.is_tcp() {
        "tcp ESTAB".to_string()
    } else {
        "udp".to_string()
    };
    if c.dead {
        state.push_str(" closed");
    }
    let k = Style::new().fg(palette().dim);
    let dl = download().at(0.5);
    let up = upload().at(0.5);
    let (local_s, remote_s) = if c.is_listen() {
        (sock_str(&c.local), "—".to_string())
    } else {
        (sock_str(&c.local), sock_str(&c.remote))
    };
    vec![
        Line::from(vec![
            Span::styled(format!(" {} ", name), bold(accent())),
            Span::styled(format!("(pid {})   ", pid), dim()),
            Span::styled(format!("{state}   ",), text()),
            Span::styled("inode ", k),
            Span::styled(c.inode.to_string(), text()),
            Span::styled(
                match c.first_seen {
                    Some(fs) => {
                        let end = c.dead_at.unwrap_or_else(std::time::Instant::now);
                        format!(
                            "   {} {}",
                            app.lang.tr("lifetime"),
                            fmt_dur(end.duration_since(fs).as_secs())
                        )
                    }
                    _ => String::new(),
                },
                dim(),
            ),
        ]),
        Line::from(vec![
            Span::styled(format!("{}  ", local_s), text()),
            Span::styled("→ ".to_string(), k),
            Span::styled(format!("{}   ", remote_s), text()),
            Span::styled("↓ ", Style::new().fg(dl)),
            Span::styled(format!("{} ", fmt_bytes(c.bytes_recv as f64)), Style::new().fg(dl)),
            Span::styled(format!("({})   ", fmt_speed(c.rate_recv)), dim()),
            Span::styled("↑ ", Style::new().fg(up)),
            Span::styled(format!("{} ", fmt_bytes(c.bytes_sent as f64)), Style::new().fg(up)),
            Span::styled(format!("({})", fmt_speed(c.rate_sent)), dim()),
        ]),
    ]
}

fn conn_row(
    c: &Conn,
    app: &App,
    slot: Option<usize>,
    child: bool,
) -> Row<'static> {
    // 墓碑行整体压暗(协议标签/远端一并),语义是"已关闭的余像"
    let dim_all = c.dead;
    let paint = |col: Color| {
        if dim_all {
            palette().dim
        } else {
            slot.map(track_fg).unwrap_or(col)
        }
    };
    // proc 档与 sum 同为合计口径:表头 Σ 对应的单元格显示字节数
    let sum_mode = matches!(app.conn.sort, ConnSort::Sum | ConnSort::Proc);
    let proc_str = match &c.proc {
        Some(n) => n.clone(),
        None => app.conn.user_name(c.uid),
    };
    let pid_str = c.pid.map(|p| p.to_string()).unwrap_or_else(|| "-".into());
    let proc_color = if c.proc.is_some() {
        accent()
    } else {
        palette().dim
    };
    // protocol label replaces the old ▸/⋄ glyphs: explicit text needs no
    // legend. The ◦ listen marker merges into the label and survives the
    // narrow name column (the old "tcp listen" wording truncated there).
    let label = if c.is_listen() {
        "\u{25e6}tcp"
    } else if c.is_tcp() {
        "tcp"
    } else {
        "udp"
    };
    let (local_s, remote_s) = if c.is_listen() {
        (sock_str(&c.local), "—".to_string())
    } else {
        (sock_str(&c.local), sock_str(&c.remote))
    };
    let mark = "";
    let (r_cell, w_cell) = if sum_mode {
        (
            fmt_bytes(c.bytes_recv as f64),
            fmt_bytes(c.bytes_sent as f64),
        )
    } else {
        (fmt_speed(c.rate_recv), fmt_speed(c.rate_sent))
    };
    let rx = format!("{mark}{r_cell}");
    let tx = format!("{mark}{w_cell}");
    // 展开组的子行树形缩进两级,层次一眼分明
    let indent = if child { "  " } else { "" };
    Row::new([
        Cell::from(Line::from(vec![
            Span::styled(format!("{indent}{proc_str}"), Style::new().fg(paint(proc_color))),
            Span::styled(
                format!(" {label}"),
                Style::new().fg(paint(palette().dim)),
            ),
        ])),
        Cell::from(Span::styled(pid_str, Style::new().fg(paint(palette().dim)))),
        Cell::from(Span::styled(local_s, Style::new().fg(paint(palette().text)))),
        Cell::from(Span::styled(remote_s, Style::new().fg(paint(palette().text)))),
        Cell::from(Span::styled(rx, Style::new().fg(paint(download().at(0.5))))),
        Cell::from(Span::styled(tx, Style::new().fg(paint(upload().at(0.5))))),
    ])
    .style(match slot {
        Some(sl) => Style::new().bg(track_bg(sl)),
        None => Style::new(),
    })
}

fn draw_procs(f: &mut Frame, area: Rect, app: &App, focused: bool) {
    let list = procs_display(app);
    let visible = area.height.saturating_sub(3).max(1) as usize;
    let off = clamped_offset(app, BOX_PROCS, visible);
    // the two-line selection overlay only makes sense while the box holds
    // focus — otherwise it lingers after p/c unfocus and reads as a stuck
    // highlight
    let sel = if focused { app.sel[BOX_PROCS] } else { None };
    let mut rest = vec![
        vec![text_s(format!("{} procs", app.proc.procs.len()))],
        fword('r', "order", app.proc.sort.label()),
    ];
    if app.proc.is_root {
        rest.push(vec![text_s("root".to_string())]);
    }
    if app.log.enabled {
        rest.push(vec![Span::styled("● rec", bold(hi()))]);
    }
    // eBPF UDP accounting is live: the ltop-bpf daemon snapshot is fresh
    if app.udp.fresh {
        rest.push(vec![Span::styled("udp", bold(hi()))]);
    }
    let sh = scroll_hint(list.len(), off, area);
    if !sh.is_empty() {
        rest.push(vec![text_s(sh)]);
    }
    let inner = boxed(
        f,
        area,
        title_line(BOX_PROCS + 1, "procs", 'p', rest, border_lan(), focused),
        border_lan(),
        BOX_PROCS + 1,
        focused,
    );
    if inner.width < 16 || inner.height < 2 {
        return;
    }

    let headers = [
        "NAME", "PID", "Σ NET↓", "Σ NET↑", "↓/s", "↑/s", "DISK ΣR", "DISK ΣW",
    ];
    let mut rows: Vec<Row> = Vec::new();
    let mut sel_y = None;
    // rows AND the selection overlay must read the same list: procs_display
    // is reordered (tracked first), so indexing into the raw procs vec shows
    // the overlay of whichever process sat at that position before pinning
    let list = procs_display(app);
    for (i, p) in list.iter().enumerate().skip(off).take(visible) {
        let slot = app.tracked.proc_slot(p.pid);
        let paint = |col: Color| slot.map(track_fg).unwrap_or(col);
        let cells = [p.name.clone(),
            p.pid.to_string(),
            fmt_bytes(p.net_recv as f64),
            fmt_bytes(p.net_sent as f64),
            fmt_speed(p.net_rr),
            fmt_speed(p.net_sr),
            fmt_bytes(p.disk_r as f64),
            fmt_bytes(p.disk_w as f64)];
        let mut row = Row::new([
            Cell::from(Span::styled(
                cells[0].clone(),
                Style::new().fg(paint(if p.alive {
                    palette().text
                } else {
                    palette().dim
                })),
            )),
            Cell::from(Span::styled(cells[1].clone(), Style::new().fg(paint(palette().text)))),
            Cell::from(Span::styled(cells[2].clone(), Style::new().fg(paint(download().at(0.5))))),
            Cell::from(Span::styled(cells[3].clone(), Style::new().fg(paint(upload().at(0.5))))),
            Cell::from(Span::styled(cells[4].clone(), Style::new().fg(paint(download().at(0.5))))),
            Cell::from(Span::styled(cells[5].clone(), Style::new().fg(paint(upload().at(0.5))))),
            Cell::from(Span::styled(cells[6].clone(), Style::new().fg(paint(download().at(1.0))))),
            Cell::from(Span::styled(cells[7].clone(), Style::new().fg(paint(upload().at(1.0))))),
        ])
        .style(match slot {
            Some(sl) => Style::new().bg(track_bg(sl)),
            None => Style::new(),
        });
        if sel == Some(i) {
            row = row.height(2);
            sel_y = Some(inner.y + 1 + (i - off) as u16);
        }
        rows.push(row);
    }
    let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
    // every numeric column is exact; only the process name stretches
    let cols = fit_columns(&[0, 7, 7, 7, 9, 9, 7, 7], 0, 8, 24, inner.width, 1);
    let table = Table::new(rows, cols).header(header).column_spacing(1);
    f.render_widget(table, inner);
    if let (Some(y), Some(si)) = (sel_y, sel) {
        if let Some(p) = list.get(si) {
            if let Some(rect) = overlay_rect(inner, y) {
                draw_selected(f, rect, proc_detail(p, app.lang));
            }
        }
    }
}

/// two overlay lines for a selected process
fn proc_detail(
    p: &crate::collect::proc::ProcRow,
    lang: crate::config::Lang,
) -> Vec<Line<'static>> {
    let cmd = std::fs::read(format!("/proc/{}/cmdline", p.pid))
        .ok()
        .map(|b| {
            let s: String = b
                .split(|&c| c == 0)
                .filter(|s| !s.is_empty())
                .map(|s| String::from_utf8_lossy(s).into_owned())
                .collect::<Vec<_>>()
                .join(" ");
            s
        })
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "-".to_string());
    let k = Style::new().fg(palette().dim);
    let dl = download().at(0.5);
    let up = upload().at(0.5);
    let arrows = ['\u{2193}', '\u{2191}'];
    vec![
        Line::from(vec![
            Span::styled(format!(" {} ", p.name), bold(accent())),
            Span::styled(format!("(pid {})   ", p.pid), dim()),
            Span::styled(
                match p.uptime_s {
                    Some(s) => format!("{} {}   ", lang.tr("uptime"), fmt_dur(s)),
                    None => String::new(),
                },
                dim(),
            ),
            Span::styled("net ", k),
            Span::styled(
                format!("{}{}  ", arrows[0], fmt_bytes(p.net_recv as f64)),
                Style::new().fg(dl),
            ),
            Span::styled(
                format!("{}{}   ", arrows[1], fmt_bytes(p.net_sent as f64)),
                Style::new().fg(up),
            ),
            Span::styled("rate ", k),
            Span::styled(
                format!("{}{} ", arrows[0], fmt_speed(p.net_rr)),
                Style::new().fg(dl),
            ),
            Span::styled(
                format!("{}{}", arrows[1], fmt_speed(p.net_sr)),
                Style::new().fg(up),
            ),
            Span::styled("  udp ", k),
            Span::styled(
                format!(
                    "{}Σ{} {}{} ",
                    arrows[0],
                    fmt_bytes(p.udp_recv as f64),
                    arrows[1],
                    fmt_bytes(p.udp_sent as f64)
                ),
                Style::new().fg(dl),
            ),
            Span::styled(
                format!(
                    "{}{}/s {}{}/s",
                    arrows[0],
                    fmt_speed(p.udp_rr),
                    arrows[1],
                    fmt_speed(p.udp_sr)
                ),
                Style::new().fg(up),
            ),
        ]),
        Line::from(vec![
            Span::styled("disk ", k),
            Span::styled(
                format!("\u{3a3}R{} ", fmt_bytes(p.disk_r as f64)),
                Style::new().fg(dl),
            ),
            Span::styled(
                format!("\u{3a3}W{}   ", fmt_bytes(p.disk_w as f64)),
                Style::new().fg(up),
            ),
            Span::styled("rate ", k),
            Span::styled(
                format!("R{} ", fmt_speed(p.disk_rr)),
                Style::new().fg(dl),
            ),
            Span::styled(
                format!("W{}", fmt_speed(p.disk_wr)),
                Style::new().fg(up),
            ),
            Span::styled("   cmd ", k),
            Span::styled(cmd, text()),
        ]),
    ]
}

fn emit_tree_rows<'a>(
    nodes: &'a [TreeNode],
    prefix: &str,
    depth: usize,
    out: &mut Vec<(&'a TreeNode, String)>,
) {
    let n = nodes.len();
    for (i, node) in nodes.iter().enumerate() {
        let last = i + 1 == n;
        let glyph = if depth == 0 {
            String::new()
        } else if last {
            "└ ".to_string()
        } else {
            "├ ".to_string()
        };
        out.push((node, format!("{prefix}{glyph}{}", node.name)));
        let branch = if last { "  " } else { "│ " };
        let child_prefix = if depth == 0 {
            String::new()
        } else {
            format!("{prefix}{branch}")
        };
        emit_tree_rows(&node.children, &child_prefix, depth + 1, out);
    }
}

/// footer 按键统一样式:[键] hi_fg + 标签 dim,主页与搜索栏共用
fn footer_key(k: &str, label: &str) -> Vec<Span<'static>> {
    vec![
        Span::styled(format!("[{k}]"), Style::new().fg(hi())),
        Span::styled(format!(" {label}  "), dim()),
    ]
}

fn draw_footer(f: &mut Frame, area: Rect, app: &App) {
    let cols = Layout::horizontal([Constraint::Min(0), Constraint::Length(9)]).split(area);
    let key = |k: &str, label: &str| footer_key(k, label);
    let lang = app.lang;
    let mut spans: Vec<Span> = vec![Span::styled(" ", dim())];
    if app.paused {
        spans.push(Span::styled(
            format!(" ⏸ {} ", app.lang.tr("paused")),
            Style::new()
                .fg(bg().unwrap_or(Color::Reset))
                .bg(hi())
                .add_modifier(Modifier::BOLD),
        ));
    }
    spans.extend(key("q", "quit"));
    spans.extend(key("m", "menu"));
    spans.extend(key("space", lang.tr("pause")));
    spans.extend(key("/", lang.tr("search")));
    spans.extend(key("Tab", &format!("{}:{}", lang.tr("layout"), app.layout.label())));
    spans.extend(key("1-6", "boxes"));
    spans.extend(key("z", "zoom"));
    if app.allow_global_kill {
        spans.extend(key("k", "kill"));
    }
    f.render_widget(Paragraph::new(Line::from(spans)), cols[0]);
    f.render_widget(
        Paragraph::new(Line::from(Span::styled(
            format!("{} ", local_time_str()),
            Style::new().fg(accent()),
        ))),
        cols[1],
    );
}

/// btop-style bottom menu bar: [ themes ] [ reset ] [ graphs ] [ about ] [ quit ] [ close ]
fn draw_menu_footer(f: &mut Frame, area: Rect, sel: usize, lang: Lang) {
    let labels = ["themes", "settings", "reset", "graphs", "help", "quit", "close"];
    let mut spans: Vec<Span> = vec![Span::styled(" ", dim())];
    for (i, l) in labels.iter().enumerate() {
        let style = if i == sel {
            Style::new()
                .fg(bg().unwrap_or(Color::Reset))
                .bg(hi())
                .add_modifier(Modifier::BOLD)
        } else {
            Style::new().fg(palette().text)
        };
        spans.push(Span::styled(format!(" {} ", lang.tr(l)), style));
        spans.push(Span::styled("  ", dim()));
    }
    spans.push(Span::styled(lang.tr("hint"), dim()));
    f.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// graphs 面板:与 settings 同款风格(居中弹窗、label: value 行列表)
fn draw_graphs_popup(f: &mut Frame, area: Rect, app: &App, sel: usize) {
    let lang = app.lang;
    let rows: [(&str, &str, String); 3] = [
        ("n", "net", app.graph_net.label().to_string()),
        ("d", "disk i/o", app.graph_disk.label().to_string()),
        ("a", "all", lang.tr("set_both").to_string()),
    ];
    let (w, h) = (60.min(area.width), 7.min(area.height));
    let popup = centered(area, w, h);
    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(hi()))
        .title(title_line(0, "graphs", '\0', vec![], hi(), false));
    let inner = block.inner(popup);
    f.render_widget(block, popup);
    let mut lines: Vec<Line> = rows
        .iter()
        .enumerate()
        .map(|(i, (k, word, value))| {
            let sel_style =
                Style::new().fg(bg().unwrap_or(Color::Reset)).bg(hi()).add_modifier(Modifier::BOLD);
            let (ks, ls, vs) = if i == sel {
                (sel_style, sel_style, sel_style)
            } else {
                (
                    Style::new().fg(palette().title),
                    text(),
                    Style::new().fg(palette().dim),
                )
            };
            Line::from(vec![
                Span::styled(" [", dim()),
                Span::styled(k.to_string(), ks),
                Span::styled(format!("] {word}"), ls),
                Span::styled(format!("  {value}"), vs),
            ])
        })
        .collect();
    lines.push(Line::from(Span::styled(lang.tr("letters_hint"), dim())));
    f.render_widget(Paragraph::new(lines), inner);
}

fn draw_reset_popup(f: &mut Frame, area: Rect, sel: usize, lang: Lang) {
    let items = [
        ("n", "net", lang.tr("reset_net")),
        ("d", "disk", lang.tr("reset_disk")),
        ("a", "all", lang.tr("reset_all")),
    ];
    let (w, h) = (34.min(area.width), 5.min(area.height));
    let popup = centered(area, w, h);
    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(hi()))
        .title(title_line(0, "reset", '\0', vec![], hi(), false));
    let inner = block.inner(popup);
    f.render_widget(block, popup);
    let lines = items
        .iter()
        .enumerate()
        .map(|(i, (k, word, desc))| {
            let style = if i == sel {
                Style::new()
                    .fg(bg().unwrap_or(Color::Reset))
                    .bg(hi())
                    .add_modifier(Modifier::BOLD)
            } else {
                text()
            };
            Line::from(vec![
                Span::styled(" [", dim()),
                Span::styled(k.to_string(), Style::new().fg(if i == sel { bg().unwrap_or(Color::Reset) } else { hi() })),
                Span::styled(format!("] {word}"), style),
                Span::styled(format!("  {desc}"), dim()),
            ])
        })
        .collect::<Vec<_>>();
    f.render_widget(Paragraph::new(lines), inner);
}

fn draw_settings_popup(f: &mut Frame, area: Rect, app: &App, sel: usize) {
    let lang = app.lang;
    let retention = if app.log.retention_days == 0 {
        lang.tr("never").to_string()
    } else {
        format!("{}d", app.log.retention_days)
    };
    let rows: [(&str, String); 13] = [
        (lang.tr("language"), lang.label().to_string()),
        (lang.tr("refresh"), fmt_interval(app.tick)),
        (lang.tr("layout"), app.layout.label().to_string()),
        (lang.tr("net"), app.graph_net.label().to_string()),
        (lang.tr("disk"), app.graph_disk.label().to_string()),
        (lang.tr("log_interval"), fmt_interval(app.log.interval)),
        (lang.tr("log_retention"), retention),
        (lang.tr("sweep_interval"), fmt_interval(app.lan.sweep_interval)),
        (
            lang.tr("sweep"),
            lang.tr(if app.lan.sweep_enabled { "on" } else { "off" }).to_string(),
        ),
        (
            lang.tr("tracked_only"),
            lang.tr(if app.log_tracked_only { "on" } else { "off" }).to_string(),
        ),
        (
            lang.tr("global_kill"),
            lang.tr(if app.allow_global_kill { "on" } else { "off" }).to_string(),
        ),
        (
            lang.tr("tombstone"),
            if app.conn.tombstone_ttl.is_zero() {
                lang.tr("off").to_string()
            } else {
                fmt_interval(app.conn.tombstone_ttl)
            },
        ),
        (
            lang.tr("proc_groups"),
            lang
                .tr(if app.proc_expand_default {
                    "expanded"
                } else {
                    "collapsed"
                })
                .to_string(),
        ),
    ];
    let (w, h) = (60.min(area.width), 19.min(area.height));
    let popup = centered(area, w, h);
    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(hi()))
        .title(title_line(0, "settings", '\0', vec![], hi(), false));
    let inner = block.inner(popup);
    f.render_widget(block, popup);
    let mut lines: Vec<Line> = rows
        .iter()
        .enumerate()
        .map(|(i, (label, value))| {
            let (ls, vs) = if i == sel {
                (
                    Style::new()
                        .fg(bg().unwrap_or(Color::Reset))
                        .bg(hi())
                        .add_modifier(Modifier::BOLD),
                    Style::new()
                        .fg(bg().unwrap_or(Color::Reset))
                        .bg(hi())
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                (Style::new().fg(palette().title), text())
            };
            Line::from(vec![
                Span::styled(format!(" {label}: "), ls),
                Span::styled(value.clone(), vs),
            ])
        })
        .collect();
    lines.push(Line::from(Span::styled(lang.tr("hint"), dim())));
    if let Some(p) = Config::path() {
        let mut path = p.display().to_string();
        let prefix = format!(" {}: ", lang.tr("config_path"));
        let room = inner.width.saturating_sub(prefix.chars().count() as u16) as usize;
        if path.chars().count() > room {
            path = format!("…{}", path.chars().skip(path.chars().count() - room.saturating_sub(1)).collect::<String>());
        }
        lines.push(Line::from(Span::styled(format!("{prefix}{path}"), dim())));
    }
    f.render_widget(Paragraph::new(lines), inner);
}

/// extra /proc fields for the detail panel
/// structured field for the detail popup: (label, value)
type Field = (&'static str, String);

/// detail 弹窗字段值的配色层级:Text=正文,Dl/Up=收发色(与 NET 盒图表
/// 同色彩语言),Accent=名字,Hi=状态徽章
#[derive(Clone, Copy, PartialEq)]
enum ValStyle {
    Text,
    Dl,
    Up,
    Accent,
    Hi,
}

/// detail 弹窗的字段分组:(组标题, 字段组);空标题 = 首组(无标题行)
type FieldGroup = (&'static str, Vec<(Field, ValStyle)>);

fn val_style(s: ValStyle) -> Style {
    match s {
        ValStyle::Text => text(),
        ValStyle::Dl => Style::new().fg(download().at(0.5)),
        ValStyle::Up => Style::new().fg(upload().at(0.5)),
        ValStyle::Accent => Style::new().fg(accent()),
        ValStyle::Hi => Style::new().fg(hi()),
    }
}

fn proc_status_fields(p: &crate::collect::proc::ProcRow) -> Vec<Field> {
    let mut out: Vec<Field> = Vec::new();
    let pid = p.pid;
    // explicit running/exited banner first — the whole point of the field
    out.push((
        "state",
        if p.alive { "running".into() } else { "exited".into() },
    ));
    if !p.alive {
        // the ledger keeps exited processes; say so instead of showing empty
        // live fields
        if let Some(cmd) = &p.cmdline {
            out.push(("cmd", cmd.join(" ")));
            out.push(("start", format!("s restarts `{}`", cmd[0])));
        }
        return out;
    }
    if let Ok(st) = std::fs::read_to_string(format!("/proc/{pid}/status")) {
        let pick = |key: &str, label: &'static str| -> Option<Field> {
            st.lines()
                .find(|l| l.starts_with(key))
                .and_then(|l| l.split_whitespace().nth(1))
                .map(|v| (label, v.to_string()))
        };
        if let Some(f) = pick("Uid:", "uid") {
            out.push(f);
        }
        if let Some(f) = pick("State:", "kstate") {
            out.push(f);
        }
        if let Some(f) = pick("Threads:", "threads") {
            out.push(f);
        }
        if let Some(f) = pick("VmRSS:", "rss") {
            out.push((f.0, format!("{} kB", f.1)));
        }
    }
    // exe/cwd:linux 读 /proc 符号链接;mac 走 libproc(proc_pidpath 即
    // exe 路径,cwd 经 PROC_PIDVNODEPATHINFO)
    #[cfg(target_os = "linux")]
    let exe = std::fs::read_link(format!("/proc/{pid}/exe"))
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| "-".into());
    #[cfg(target_os = "macos")]
    let exe = crate::collect::macproc::cmdline(pid)
        .and_then(|v| v.into_iter().next())
        .unwrap_or_else(|| "-".into());
    out.push(("exe", exe));
    #[cfg(target_os = "linux")]
    let cwd = std::fs::read_link(format!("/proc/{pid}/cwd"))
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| "-".into());
    #[cfg(target_os = "macos")]
    let cwd = crate::collect::macproc::proc_cwd(pid).unwrap_or_else(|| "-".into());
    out.push(("cwd", cwd));
    if let Ok(cmd) = std::fs::read(format!("/proc/{pid}/cmdline")) {
        let s: String = cmd
            .split(|&c| c == 0)
            .filter(|s| !s.is_empty())
            .map(|s| String::from_utf8_lossy(s).into_owned())
            .collect::<Vec<_>>()
            .join(" ");
        if !s.is_empty() {
            out.push(("cmd", s));
        }
    }
    out
}

/// detail 弹窗的字段数据(渲染、游标计数、复制取值三处同源)
struct DetailData {
    groups: Vec<FieldGroup>,
    pid: Option<u32>,
    tracked: bool,
    gone: String,
    start_hint: bool,
}

fn detail_data(app: &App, box_idx: usize, id: u64) -> DetailData {
    let mut pid: Option<u32> = None;
    let mut tracked = false;
    let mut groups: Vec<FieldGroup> = Vec::new();
    let mut gone = String::new();
    let mut start_hint = false;
    match box_idx {
        BOX_PROCS => {
            if let Some(p) = app.proc.procs.iter().find(|p| p.pid as u64 == id) {
                pid = Some(p.pid);
                tracked = app.tracked.proc_slot(p.pid).is_some();
                // resident hint: s starts an exited process, restarts a live one
                start_hint = p.cmdline.is_some();
                let mut identity: Vec<(Field, ValStyle)> =
                    vec![(("name", p.name.clone()), ValStyle::Accent), (("pid", p.pid.to_string()), ValStyle::Text)];
                identity.extend(proc_status_fields(p).into_iter().map(|f| (f, ValStyle::Text)));
                let traffic = vec![
                    (("net \u{3a3}\u{2193}", fmt_bytes(p.net_recv as f64)), ValStyle::Dl),
                    (("net \u{3a3}\u{2191}", fmt_bytes(p.net_sent as f64)), ValStyle::Up),
                    (("net \u{2193}/s", fmt_speed(p.net_rr)), ValStyle::Dl),
                    (("net \u{2191}/s", fmt_speed(p.net_sr)), ValStyle::Up),
                ];
                let disk = vec![
                    (("disk \u{3a3}R", fmt_bytes(p.disk_r as f64)), ValStyle::Text),
                    (("disk \u{3a3}W", fmt_bytes(p.disk_w as f64)), ValStyle::Text),
                    (("disk R/s", fmt_speed(p.disk_rr)), ValStyle::Text),
                    (("disk W/s", fmt_speed(p.disk_wr)), ValStyle::Text),
                ];
                groups = vec![("", identity), ("traffic", traffic), ("disk", disk)];
            } else {
                gone = format!("process {id} is gone");
            }
        }
        BOX_CONNS => {
            if let Some(c) = app.conn.conns.iter().find(|c| c.inode == id) {
                pid = c.pid;
                tracked = app.tracked.conn_slot(c.inode).is_some();
                let (state, state_st) = if c.is_listen() {
                    ("LISTEN", ValStyle::Hi)
                } else if c.is_tcp() {
                    ("ESTAB", ValStyle::Dl)
                } else {
                    ("UDP", ValStyle::Accent)
                };
                let proto = if c.is_tcp() { "tcp" } else { "udp" };
                let mut identity: Vec<(Field, ValStyle)> = vec![(
                    ("name", c.proc.clone().unwrap_or_else(|| app.conn.user_name(c.uid))),
                    ValStyle::Accent,
                )];
                if let Some(p) = c.pid {
                    identity.push((("pid", p.to_string()), ValStyle::Text));
                }
                identity.push((("user", app.conn.user_name(c.uid)), ValStyle::Text));
                let conn = vec![
                    (("proto", proto.to_string()), ValStyle::Text),
                    (("state", state.to_string()), state_st),
                    (("local", sock_str(&c.local)), ValStyle::Text),
                    (("remote", sock_str(&c.remote)), ValStyle::Text),
                    (("inode", c.inode.to_string()), ValStyle::Text),
                ];
                let traffic = vec![
                    (("net \u{2193}", fmt_bytes(c.bytes_recv as f64)), ValStyle::Dl),
                    (("net \u{2191}", fmt_bytes(c.bytes_sent as f64)), ValStyle::Up),
                    (("net \u{2193}/s", fmt_speed(c.rate_recv)), ValStyle::Dl),
                    (("net \u{2191}/s", fmt_speed(c.rate_sent)), ValStyle::Up),
                ];
                groups = vec![("", identity), ("connection", conn), ("traffic", traffic)];
            } else {
                gone = format!("connection {id} is gone");
            }
        }
        _ => {}
    }
    DetailData {
        groups,
        pid,
        tracked,
        gone,
        start_hint,
    }
}

/// detail 弹窗的字段总数(游标上界)
pub fn detail_field_count(app: &App, box_idx: usize, id: u64) -> usize {
    detail_data(app, box_idx, id)
        .groups
        .iter()
        .map(|(_, fs)| fs.len())
        .sum()
}

/// 第 detail_sel 个字段的值(y 复制的内容)
pub fn detail_selected_value(app: &App, box_idx: usize, id: u64) -> Option<String> {
    let d = detail_data(app, box_idx, id);
    let mut flat = d
        .groups
        .iter()
        .flat_map(|(_, fs)| fs.iter())
        .map(|((_, v), _)| v.clone());
    flat.nth(app.detail_sel)
}

fn draw_detail_popup(f: &mut Frame, area: Rect, app: &App, box_idx: usize, id: u64) {
    let DetailData {
        groups,
        pid,
        tracked,
        gone,
        start_hint,
    } = detail_data(app, box_idx, id);
    let track_hint = if tracked {
        "[space] [x] tracked"
    } else {
        "[space] [ ] track"
    };
    let mut hints = vec![track_hint.to_string(), "[y] copy".to_string(), "[esc] close".to_string()];
    if let Some(p) = pid {
        hints.insert(2, format!("[k] kill pid {p}"));
    }
    if start_hint {
        hints.insert(2, "[s] start/restart".to_string());
    }

    let w = 92.min(area.width);
    let lbl_w = groups
        .iter()
        .flat_map(|(_, fs)| fs.iter())
        .map(|((l, _), _)| l.chars().count())
        .max()
        .unwrap_or(0);
    // values longer than the column wrap onto continuation lines
    let inner_w = w.saturating_sub(2) as usize;
    let chunk_w = inner_w.saturating_sub(lbl_w + 4).max(10);
    let n_lines: usize = gone.len().min(1)
        + groups
            .iter()
            .map(|(title, fs)| {
                let head = if title.is_empty() { 0 } else { 2 };
                head + fs.iter().map(|((_, v), _)| wrap_chunks(v, chunk_w).len()).sum::<usize>()
            })
            .sum::<usize>();
    // +2 borders +1 blank +1 hint row; the hint row is pinned to the bottom
    // line of the box so the key bindings stay visible even when the fields
    // overflow a small terminal
    let h = (n_lines as u16 + 4).min(area.height);
    let popup = centered(area, w, h);
    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(hi()))
        .title(title_line(0, "detail", '\0', vec![], hi(), true));
    let inner = block.inner(popup);
    f.render_widget(block, popup);

    let mut all: Vec<Line> = Vec::new();
    // 每个字段的行区间(游标定位与滚动推导;组标题/空行不计入字段游标)
    let mut field_rows: Vec<(usize, usize)> = Vec::new();
    if !gone.is_empty() {
        all.push(Line::from(Span::styled(format!(" {gone}"), dim())));
    }
    for (title, fields) in &groups {
        if !title.is_empty() {
            all.push(Line::from(""));
            all.push(Line::from(Span::styled(
                format!(" \u{2500}\u{2500} {title} \u{2500}\u{2500}"),
                bold(hi()),
            )));
        }
        for ((label, value), st) in fields {
            let start = all.len();
            for (i, chunk) in wrap_chunks(value, chunk_w).into_iter().enumerate() {
                let indent = if i == 0 {
                    format!(" {:<lbl_w$}  ", label)
                } else {
                    format!(" {:<lbl_w$}  ", "")
                };
                let vspan = if *st == ValStyle::Accent {
                    Span::styled(chunk, bold(accent()))
                } else {
                    Span::styled(chunk, val_style(*st))
                };
                all.push(Line::from(vec![Span::styled(indent, dim()), vspan]));
            }
            field_rows.push((start, all.len() - start));
        }
    }
    // pin the hint row(s) to the bottom line of the box so the key bindings
    // stay visible even when the fields overflow a small terminal; on narrow
    // popups the segments repack onto extra rows instead of being cut
    let hint_lines = pack_rows(&hints, inner.width.saturating_sub(1) as usize);
    let hints_h = hint_lines.len() as u16;
    let hints_y = inner.bottom().saturating_sub(hints_h);
    let fields_h = hints_y.saturating_sub(inner.y);
    // 字段游标:高亮选中字段行(行首 ▸ + 弱底)并推导滚动保证其可见
    let sel = app.detail_sel.min(field_rows.len().saturating_sub(1));
    let (s0, n0) = field_rows.get(sel).copied().unwrap_or((0, 1));
    let vis = fields_h as usize;
    // 无状态滚动推导:选中行不可见时,让其贴可见区底部(上方留 3 行)
    let scroll = (s0 + n0).saturating_sub(vis);
    let hl_bg = download().at(0.12);
    let lines_with_cursor: Vec<Line> = all
        .into_iter()
        .enumerate()
        .map(|(li, line)| {
            let in_field = field_rows
                .get(sel)
                .is_some_and(|(start, count)| li >= *start && li < start + count);
            if !in_field {
                return line;
            }
            let bar = if li == s0 { "▸" } else { " " };
            let mut spans = vec![Span::styled(bar, Style::new().fg(accent()).bg(hl_bg))];
            spans.extend(line.spans.into_iter().map(|mut sp| {
                sp.style = sp.style.bg(hl_bg);
                sp
            }));
            Line::from(spans)
        })
        .collect();
    let skipped: Vec<Line> = lines_with_cursor
        .iter()
        .skip(scroll)
        .take(fields_h as usize)
        .cloned()
        .collect();
    f.render_widget(
        Paragraph::new(skipped),
        Rect { x: inner.x, y: inner.y, width: inner.width, height: fields_h },
    );
    f.render_widget(
        Paragraph::new(
            hint_lines
                .into_iter()
                .map(|l| Line::from(Span::styled(l, bold(hi()))))
                .collect::<Vec<_>>(),
        ),
        Rect { x: inner.x, y: hints_y, width: inner.width, height: hints_h },
    );
}

/// greedy line packing: join `items` with three spaces, breaking to a new
/// row only between items when the width would overflow
fn pack_rows(items: &[String], w: usize) -> Vec<String> {
    let mut rows: Vec<String> = Vec::new();
    let mut cur = String::new();
    for it in items {
        let sep = if cur.is_empty() { "" } else { "   " };
        if !cur.is_empty() && cur.chars().count() + sep.len() + it.chars().count() > w {
            rows.push(std::mem::take(&mut cur));
        } else {
            cur.push_str(sep);
        }
        cur.push_str(it);
    }
    if !cur.is_empty() {
        rows.push(cur);
    }
    rows.into_iter().map(|r| format!(" {r}")).collect()
}

/// split `s` into display chunks of at most `w` characters (char-aware)
fn wrap_chunks(s: &str, w: usize) -> Vec<String> {
    if w == 0 {
        return vec![s.to_string()];
    }
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= w {
        return vec![s.to_string()];
    }
    chars
        .chunks(w)
        .map(|c| c.iter().collect())
        .collect()
}

fn draw_confirm_popup(f: &mut Frame, area: Rect, app: &App, pid: u32, restart: bool) {
    let name = app
        .proc
        .procs
        .iter()
        .find(|p| p.pid == pid)
        .map(|p| p.name.clone())
        .unwrap_or_else(|| "?".into());
    let (w, h) = (52.min(area.width), 7.min(area.height));
    let popup = centered(area, w, h);
    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(alert_end()))
        .title(title_line(0, if restart { "restart" } else { "kill" }, '\0', vec![], alert_end(), true));
    let inner = block.inner(popup);
    f.render_widget(block, popup);
    let question = if restart {
        format!(" Restart {name} (pid {pid})? SIGTERM, then relaunch its command line.")
    } else {
        format!(" Send SIGTERM to {name} (pid {pid})?")
    };
    let lines = vec![
        Line::from(question),
        Line::from(""),
        Line::from(vec![
            Span::styled(" [y] ", bold(hi())),
            Span::styled("yes    ", text()),
            Span::styled("[n] ", bold(hi())),
            Span::styled("no", text()),
        ]),
    ];
    f.render_widget(Paragraph::new(lines), inner);
}

/// (key, description) rows for the help panel
fn help_rows(lang: Lang) -> Vec<(String, String)> {
    let t = |k: &str| lang.tr(k);
    vec![
        ("1-6".into(), format!("{} / {}", t("boxes"), t("hint_close_short"))),
        ("Tab".into(), t("layout").to_string()),
        ("enter".into(), t("detail_desc").to_string()),
        ("p / c / l".into(), t("focus_desc").to_string()),
        ("r".into(), t("order_desc").to_string()),
        ("d".into(), t("expand_desc").to_string()),
        ("f".into(), t("filter_desc").to_string()),
        ("o".into(), t("conn_order_desc").to_string()),
        ("e".into(), t("lan_order_desc").to_string()),
        ("n / i".into(), t("net_io_desc").to_string()),
        ("space".into(), t("track_desc").to_string()),
        ("k".into(), t("kill_desc").to_string()),
        ("L".into(), t("log_desc").to_string()),
        ("s".into(), t("sweep_desc").to_string()),
        ("+ / -".into(), t("refresh_desc").to_string()),
        ("\u{2191}\u{2193} / wheel".into(), t("sel_scroll_desc").to_string()),
        ("z".into(), t("zoom_desc").to_string()),
        ("q / esc / m".into(), t("quit_menu_desc").to_string()),
    ]
}

/// merged help + about panel
fn draw_help_popup(f: &mut Frame, area: Rect, app: &App) {
    let rows = help_rows(app.lang);
    // 双列键位把总高从 ~33 行压到 ~23 行:旧版 h 估算 (+8) 低估头部开销
    // 且撞终端高度封顶后无滚动,底部(数据口径段/press any)固定被裁。
    // 宽度按内容精确计算:双列放不下(横向截断)自动回退单列
    let kw = rows.iter().map(|(k, _)| k.chars().count()).max().unwrap_or(0);
    let desc_w = |rs: &[(String, String)]| {
        rs.iter().map(|(_, d)| d.chars().count()).max().unwrap_or(0)
    };
    let dw_all = desc_w(&rows);
    let col_w = 3 + kw + 2 + dw_all + 3;
    let w_two = (2 + 2 * col_w) as u16;
    let w_one = (2 + 3 + kw + 2 + dw_all + 4) as u16;
    let two_col = area.width >= w_two;
    let half = rows.len().div_ceil(2);
    let mut lines: Vec<Line> = Vec::new();
    lines.push(Line::from(vec![
        Span::styled(format!(" ltop v{}", env!("CARGO_PKG_VERSION")), bold(accent())),
        Span::styled("  by uMaj35ty", dim()),
    ]));
    lines.push(Line::from(Span::styled(
        " local list monitor: net / lan / disk io / conns / procs",
        dim(),
    )));
    lines.push(Line::from(Span::styled(
        format!(
            " theme: {} \u{b7} {}",
            theme_name(),
            app.lang.tr(if app.udp.fresh { "udp_on" } else { "udp_off" })
        ),
        dim(),
    )));
    lines.push(Line::from(Span::styled(
        format!(" {}", app.lang.tr("caliber_head")),
        bold(hi()),
    )));
    for k in ["caliber_procs", "caliber_conns", "caliber_keys"] {
        lines.push(Line::from(Span::styled(app.lang.tr(k), dim())));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        " \u{2500}\u{2500} keys \u{2500}\u{2500}",
        bold(hi()),
    )));
    let col_spans =
        |(k, d): &(String, String), dw: usize| -> Vec<Span<'static>> {
            vec![
                Span::styled(format!(" {:<kw$}  ", k), bold(hi())),
                Span::styled(format!("{:<dw$}   ", d), text()),
            ]
        };
    if two_col {
        let (left, right) = rows.split_at(half);
        let dw_l = desc_w(left);
        let dw_r = desc_w(right);
        for i in 0..half {
            let mut spans = match left.get(i) {
                Some(e) => col_spans(e, dw_l),
                None => vec![Span::raw(" ".repeat(6 + kw + dw_l))],
            };
            spans.push(Span::raw("  "));
            if let Some(e) = right.get(i) {
                spans.extend(col_spans(e, dw_r));
            }
            lines.push(Line::from(spans));
        }
    } else {
        let dw = desc_w(&rows);
        for e in &rows {
            lines.push(Line::from(col_spans(e, dw)));
        }
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(app.lang.tr("press_any"), dim())));
    let w = if two_col { w_two } else { w_one.min(area.width) };
    let h = (lines.len() as u16 + 2).min(area.height);
    let popup = centered(area, w, h);
    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(hi()))
        .title(title_line(0, "help", '\0', vec![], hi(), false));
    let inner = block.inner(popup);
    f.render_widget(block, popup);

    f.render_widget(Paragraph::new(lines), inner);
}

fn centered(area: Rect, w: u16, h: u16) -> Rect {
    Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    }
}

fn draw_theme_popup(f: &mut Frame, area: Rect, sel: usize, scroll: usize) {
    let count = builtin_count() + 1; // + omarchy
    // popup hugs its content: at most THEME_VISIBLE rows, never a half-empty box
    let visible = THEME_VISIBLE.min(area.height.saturating_sub(4).max(1) as usize);
    let height = visible as u16 + 2;
    let width = 30.min(area.width);
    let popup = Rect {
        x: area.x + 1,
        y: area.bottom().saturating_sub(height),
        width,
        height,
    };

    let current = theme_name();
    // clamp the window so the selection stays visible even on short terminals
    let mut lo = scroll.min(count.saturating_sub(visible));
    if sel < lo {
        lo = sel;
    }
    if sel >= lo + visible {
        lo = sel + 1 - visible;
    }
    let mut lines: Vec<Line> = Vec::new();
    for i in lo..count.min(lo + visible) {
        let name = if i == 0 {
            "omarchy (current)".to_string()
        } else {
            builtin_name(i - 1).to_string()
        };
        let is_current = current == if i == 0 { "omarchy" } else { builtin_name(i - 1) };
        let style = if i == sel {
            Style::new()
                .fg(bg().unwrap_or(Color::Reset))
                .bg(hi())
                .add_modifier(Modifier::BOLD)
        } else if is_current {
            Style::new().fg(hi())
        } else {
            text()
        };
        let marker = if is_current { "● " } else { "  " };
        lines.push(Line::from(Span::styled(format!("{marker}{name}"), style)));
    }

    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .style(Style::new().bg(bg().unwrap_or(Color::Reset)))
        .border_style(Style::new().fg(hi()))
        .title(title_line(0, "theme", '\0', vec![], hi(), false));
    let inner = block.inner(popup);
    f.render_widget(block, popup);
    f.render_widget(Paragraph::new(lines), inner);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::BOX_COUNT;
    use ratatui::layout::Constraint;

    fn lens(cs: &[Constraint]) -> Vec<Option<u16>> {
        cs.iter()
            .map(|c| match c {
                Constraint::Length(n) => Some(*n),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn fit_columns_uses_fixed_vocabulary_widths() {
        // LAN: bases [IP16, MAC17, flex, IF8]; the hostname column takes the
        // room up to its cap, then the small remaining slack is spread
        let cs = fit_columns(&[16, 17, 0, 8], 2, 8, 30, 80, 1);
        assert_eq!(lens(&cs), vec![Some(18), Some(19), Some(31), Some(9)]);
        // identical call -> identical layout (widths never sample live data)
        let again = fit_columns(&[16, 17, 0, 8], 2, 8, 30, 80, 1);
        assert_eq!(lens(&cs), lens(&again));
        // cramped: the fixed columns stay intact and the right edge clips
        let narrow = fit_columns(&[16, 17, 0, 8], 2, 8, 30, 40, 1);
        assert_eq!(lens(&narrow), vec![Some(16), Some(17), Some(8), Some(8)]);
    }

    #[test]
    fn process_table_width_is_stable_and_capped() {
        let base = [0, 7, 7, 7, 9, 9, 7, 7];
        // 73 wide: no slack, name gets exactly the remainder
        assert_eq!(
            lens(&fit_columns(&base, 0, 8, 24, 73, 1)),
            vec![Some(13), Some(7), Some(7), Some(7), Some(9), Some(9), Some(7), Some(7)]
        );
        // very wide: the name column is capped at 24, growth is capped too,
        // and the rest stays as trailing blank
        let wide = lens(&fit_columns(&base, 0, 8, 24, 160, 1));
        assert_eq!(wide[0], Some(36));
        assert_eq!(wide.iter().map(|w| w.unwrap()).sum::<u16>(), 112);
    }

    #[test]
    fn rendered_table_keeps_one_space_between_columns() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let headers = ["NAME", "PID", "Σ NET↓", "Σ NET↑", "↓/s", "↑/s", "DISK ΣR", "DISK ΣW"];
        let data = [vec![
            "zcode-host-local".to_string(),
            "546829".to_string(),
            "0B".to_string(),
            "0B".to_string(),
            "0B/s".to_string(),
            "0B/s".to_string(),
            "20.0KiB".to_string(),
            "0B".to_string(),
        ]];
        let cols = fit_columns(&[0, 7, 7, 7, 9, 9, 7, 7], 0, 8, 24, 73, 1);
        let mut term = Terminal::new(TestBackend::new(73, 4)).unwrap();
        let rows: Vec<Row> = data
            .iter()
            .map(|r| Row::new(r.iter().map(|c| Cell::from(c.clone())).collect::<Vec<_>>()))
            .collect();
        let header = Row::new(headers);
        term.draw(|f| {
            let t = Table::new(rows, cols).header(header).column_spacing(1);
            f.render_widget(t, f.area());
        })
        .unwrap();
        let buf = term.backend().buffer();
        let line: String = (0..73)
            .map(|x| buf[(x, 1)].symbol().to_string())
            .collect::<String>();
        // columns are separated by blanks (never glued), and spare width is
        // spread evenly across them rather than dumped into one column
        let fields: Vec<&str> = line.split_whitespace().collect();
        // the name is clipped to its fixed 13 columns; every numeric column
        // stays intact because its width came from the vocabulary, not from
        // this particular row
        assert_eq!(
            fields,
            vec!["zcode-host-lo", "546829", "0B", "0B", "0B/s", "0B/s", "20.0KiB", "0B"]
        );
    }

    /// Regression: a real 249x67 terminal panicked with "index outside of
    /// buffer … index is (126, 67)" on the first frame — some box drew one
    /// row past its area. Every draw call must stay inside the buffer.
    #[test]
    fn full_frame_stays_inside_the_terminal() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        app.update();
        std::thread::sleep(std::time::Duration::from_millis(700));
        app.update();
        for (w, h) in [(249u16, 67u16), (80, 24), (120, 30), (200, 50), (60, 20)] {
            let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
            term.draw(|f| draw(f, &app))
                .unwrap_or_else(|e| panic!("{w}x{h}: {e}"));
        }
    }

    /// Regression: selecting the last visible row of the bottom-most list box
    /// drew the 2-line overlay one row past the buffer ("index … (126, 67)" on
    /// a 249x67 terminal). The overlay must be clipped to the box interior.
    #[test]
    fn selected_row_overlay_never_leaves_the_buffer() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        app.update();
        // PROCS bottom-most: hide every other table box. The live ledger only
        // lists processes with I/O in the sampling window, so inject rows.
        for i in [BOX_LAN, BOX_CONNS, BOX_DISKS] {
            app.visible[i] = false;
        }
        app.focus[BOX_PROCS] = true;
        for k in 0..40u32 {
            app.proc.procs.push(crate::collect::proc::ProcRow {
                pid: 1000 + k,
                name: format!("proc{k}"),
                net_recv: 10,
                net_sent: 5,
                net_rr: 1.0,
                net_sr: 0.5,
                udp_recv: 0,
                udp_sent: 0,
                udp_rr: 0.0,
                udp_sr: 0.0,
                disk_r: 0,
                disk_w: 0,
                disk_rr: 0.0,
                disk_wr: 0.0,
                uptime_s: None,                alive: true,
                cmdline: None,
            });
        }
        let n = crate::ui::procs_display(&app).len();
        // sel sweeps every row plus two past the end: the boundary cases are
        // the last visible row and the first invisible one
        for (w, h) in [(249u16, 67u16), (80, 24), (100, 30), (60, 18)] {
            for sel in 0..n + 2 {
                app.sel[BOX_PROCS] = (sel < n).then_some(sel);
                let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
                term.draw(|f| draw(f, &app))
                    .unwrap_or_else(|e| panic!("{w}x{h} sel {sel}: {e}"));
            }
        }
    }

    /// Regression: the detail popup shows the explicit running/exited status —
    /// "running" for a live row, "exited" + captured cmdline + start hint for a
    /// dead one — and must not try to read /proc for a dead pid.
    #[test]
    fn detail_popup_renders_exited_process() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        app.update();
        let mut row = crate::collect::proc::ProcRow {
            pid: 4242,
            name: "deadproc".into(),
            net_recv: 100,
            net_sent: 50,
            net_rr: 0.0,
            net_sr: 0.0,
            udp_recv: 0,
            udp_sent: 0,
            udp_rr: 0.0,
            udp_sr: 0.0,
            disk_r: 0,
            disk_w: 0,
            disk_rr: 0.0,
            disk_wr: 0.0,
            uptime_s: None,            alive: false,
            cmdline: Some(vec!["/usr/bin/deadproc".into(), "--flag".into()]),
        };
        app.proc.procs.push(row.clone());
        let buf_text = |term: &Terminal<TestBackend>| {
            let buf = term.backend().buffer();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol().to_string())
                        .collect::<String>()
                })
                .collect::<String>()
        };
        app.menu = crate::app::MenuState::Detail(BOX_PROCS, 4242);
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text = buf_text(&term);
        assert!(text.contains("exited"), "status shown");
        assert!(text.contains("/usr/bin/deadproc"), "captured cmdline shown");
        assert!(text.contains("[s] start/restart"), "start hint shown");

        // the same row while alive reads live /proc fields and says running
        row.alive = true;
        row.pid = std::process::id();
        app.proc.procs.push(row);
        app.menu = crate::app::MenuState::Detail(BOX_PROCS, u64::from(std::process::id()));
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text = buf_text(&term);
        assert!(text.contains("running"), "alive row shows running");
        assert!(!text.contains("exited"), "no exited banner for a live row");
        // the s hint is resident for any process with a captured cmdline
        assert!(text.contains("[s] start/restart"), "resident start hint");
    }

    /// Long command lines wrap onto continuation lines, and the key-binding
    /// hint row stays visible (pinned to the popup's bottom line) even when
    /// the fields overflow a small terminal.
    #[test]
    fn detail_panel_wraps_cmd_and_pins_the_hint_row() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        app.update();
        let tail = "and-a-long-tail-marker".to_string();
        let long_cmd = format!("/usr/bin/deadproc --very-long-option={} {}", "x".repeat(120), tail);
        app.proc.procs.push(crate::collect::proc::ProcRow {
            pid: 4242,
            name: "deadproc".into(),
            net_recv: 100,
            net_sent: 50,
            net_rr: 0.0,
            net_sr: 0.0,
            udp_recv: 0,
            udp_sent: 0,
            udp_rr: 0.0,
            udp_sr: 0.0,
            disk_r: 0,
            disk_w: 0,
            disk_rr: 0.0,
            disk_wr: 0.0,
            uptime_s: None,            alive: false,
            cmdline: Some(vec![long_cmd]),
        });
        app.menu = crate::app::MenuState::Detail(BOX_PROCS, 4242);
        let buf_text = |term: &Terminal<TestBackend>| {
            let buf = term.backend().buffer();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol().to_string())
                        .collect::<String>()
                })
                .collect::<String>()
        };
        // roomy terminal: the whole command is readable across wrapped lines
        let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text = buf_text(&term);
        assert!(text.contains(&tail), "wrapped cmd tail is rendered");
        assert!(text.contains("[esc] close"), "hints complete");

        // tiny terminal: fields overflow but the hint row must survive
        let mut term = Terminal::new(TestBackend::new(60, 10)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let text = buf_text(&term);
        assert!(text.contains("[esc] close"), "hints pinned to the bottom");
        assert!(text.contains("[s] start/restart"), "s hint visible");
        assert!(text.contains("[k] kill pid 4242"), "k hint visible");
    }

    /// Regression: with a tracked (pinned-to-top) process, the selection
    /// overlay must follow the *display* order. It used to index the raw
    /// ledger, showing the detail of whichever process sat at that position
    /// before pinning (enter's detail popup was right, the overlay wrong).
    #[test]
    fn procs_overlay_follows_the_pinned_order() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        app.update();
        for (pid, name) in [(100u32, "aaa"), (200u32, "bbb")] {
            app.proc.procs.push(crate::collect::proc::ProcRow {
                pid,
                name: name.into(),
                net_recv: 10,
                net_sent: 0,
                net_rr: 0.0,
                net_sr: 0.0,
                udp_recv: 0,
                udp_sent: 0,
                udp_rr: 0.0,
                udp_sr: 0.0,
                disk_r: 0,
                disk_w: 0,
                disk_rr: 0.0,
                disk_wr: 0.0,
                uptime_s: None,                alive: true,
                cmdline: None,
            });
        }
        app.tracked.toggle_proc(200); // bbb pinned → display [bbb, aaa]
        // PROCS alone in the table column: parallel tests share the global
        // height allocator, so a stacked layout could squeeze this box until
        // the selected row falls outside the viewport and renders no overlay
        for i in [BOX_LAN, BOX_CONNS, BOX_DISKS] {
            app.visible[i] = false;
        }
        app.focus[BOX_PROCS] = true;
        app.sel[BOX_PROCS] = Some(1); // display row 1 = aaa (pid 100)
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let buf = term.backend().buffer();
        let text: String = (0..buf.area().height)
            .map(|y| {
                (0..buf.area().width)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect();
        assert!(text.contains("(pid 100"), "overlay shows the selected row's process");
        assert!(!text.contains("(pid 200"), "overlay must not show the pre-pin occupant");
    }

    /// The selection follows the entity it names (pid / inode) through
    /// re-sorts; an entity that left the list clears the selection instead of
    /// silently moving onto whatever took its list position.
    #[test]
    fn selection_follows_the_entity_through_resorts() {
        let mut app = crate::app::App::new(None);
        app.update();
        for (pid, name, recv) in [(100u32, "aaa", 10u64), (200u32, "bbb", 1000u64)] {
            app.proc.procs.push(crate::collect::proc::ProcRow {
                pid,
                name: name.into(),
                net_recv: recv,
                net_sent: 0,
                net_rr: 0.0,
                net_sr: 0.0,
                udp_recv: 0,
                udp_sent: 0,
                udp_rr: 0.0,
                udp_sr: 0.0,
                disk_r: 0,
                disk_w: 0,
                disk_rr: 0.0,
                disk_wr: 0.0,
                uptime_s: None,                alive: true,
                cmdline: None,
            });
        }
        app.sel[BOX_PROCS] = Some(0); // aaa
        let anchor = selected_id(&app, BOX_PROCS);
        assert_eq!(anchor, Some(100));
        // a re-sort puts bbb first; the selection must stay on aaa
        app.proc.procs.swap(0, 1);
        reselect(&mut app, BOX_PROCS, anchor.unwrap());
        assert_eq!(app.sel[BOX_PROCS], Some(1));

        // the entity leaving the list clears the selection
        app.proc.procs.retain(|p| p.pid != 100);
        reselect(&mut app, BOX_PROCS, anchor.unwrap());
        assert_eq!(app.sel[BOX_PROCS], None);

        // conns follow their inode the same way
        let mk = |inode: u64| crate::collect::conn::Conn {
            proto: 6,
            local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
            remote: ("127.0.0.1".parse().unwrap(), 80),
            state: 1,
            uid: 0,
            inode,
            bytes_recv: 0,
            bytes_sent: 0,
            rate_recv: 0.0,
            rate_sent: 0.0,
            pid: None,
            proc: None,
            dead: false,
            first_seen: None,
            dead_at: None,
        };
        app.conn.sort = crate::collect::conn::ConnSort::Name; // 平面行的 inode 跟随
        app.conn.conns = vec![mk(11), mk(22)];
        app.sel[BOX_CONNS] = Some(1); // inode 22
        let anchor = selected_id(&app, BOX_CONNS);
        assert_eq!(anchor, Some(22));
        app.conn.conns.swap(0, 1); // inode 22 moved to position 0
        reselect(&mut app, BOX_CONNS, anchor.unwrap());
        assert_eq!(app.sel[BOX_CONNS], Some(0), "selection follows the inode");
    }

    /// classic 右列中线分组:CONNS 底边与左列 NET 图表底边对齐,
    /// LAN+CONNS 恰好占上半,PROCS 从中线开始。
    /// 断言走 buffer 文本而非 BOX_AREAS——后者是全局态,并行测试会互踩。
    /// 回归:CONNS 超百行时滚到底曾"只剩 1 行且卡死"——off 封顶应是
    /// 最后一页而非最后一行,且渲染裁剪 take(visible) 防止越界半行
    #[test]
    fn conns_bottom_scroll_shows_full_last_page() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        for i in 0..BOX_COUNT {
            app.visible[i] = i == BOX_CONNS;
        }
        let n = 200usize;
        for k in 0..n {
            app.conn.conns.push(crate::collect::conn::Conn {
                proto: crate::collect::conn::IPPROTO_TCP,
                local: ("127.0.0.1".parse().unwrap(), 1000 + k as u16),
                remote: ("127.0.0.1".parse().unwrap(), 443),
                state: 1,
                uid: 0,
                inode: k as u64,
                bytes_recv: 0,
                bytes_sent: 0,
                rate_recv: 0.0,
                rate_sent: 0.0,
                pid: Some(1),
                proc: Some(format!("c{k:04}")),
                dead: false,
                first_seen: None,
                dead_at: None,
            });
        }
        // 滚动值严重越界(旧版会 clamp 到 len-1 只剩最后一行)
        app.scroll[BOX_CONNS] = 5000;
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let buf = term.backend().buffer();
        let rows: Vec<String> = (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect()
            })
            .collect();
        let shown: Vec<&String> = rows.iter().filter(|r| r.contains("c019")).collect();
        assert!(!shown.is_empty(), "最后一页应包含尾段连接");
        // 尾页应是多行(旧 bug 只渲染 1 行)
        assert!(shown.len() >= 5, "尾页行数 {} < 5,像是只剩单行", shown.len());
        // 首屏的行不应再出现
        assert!(!rows.iter().any(|r| r.contains("c0000")), "越界滚动后仍显示首行");
    }

    /// DISKS 滚到底:off 封顶应是最后一页(可视行数)而非最后一行。
    /// 回归:DISKS 曾手写 min(len-1)(LAN/CONNS/PROCS 用 clamped_offset,
    /// 唯它漏网),滚到底后整盒只剩 1 行或空白
    #[test]
    fn disks_bottom_scroll_shows_full_last_page() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        for i in 0..BOX_COUNT {
            app.visible[i] = i == BOX_DISKS;
        }
        // 5 个盘 × 每盘 12 个分区 = 60+ 行树,远超一屏
        for d in 0..5 {
            let root = crate::collect::disk::TreeNode {
                name: format!("sd{d}"),
                pretty: None,
                size: None,
                children: (0..12)
                    .map(|p| crate::collect::disk::TreeNode {
                        name: format!("sd{d}p{}", p + 1),
                        pretty: None,
                        size: None,
                        children: Vec::new(),
                    })
                    .collect(),
            };
            app.disk.tree.push(root);
        }
        app.scroll[BOX_DISKS] = 5000;
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let buf = term.backend().buffer();
        let rows: Vec<String> = (0..buf.area.height)
            .map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect())
            .collect();
        // 尾段分区(sd4p8..p12)应可见
        assert!(
            rows.iter().any(|r| r.contains("sd4p11")),
            "最后一页应包含尾部节点"
        );
        // 尾页应是多行(旧 bug 只渲染 1 行)
        let tail_rows = rows
            .iter()
            .filter(|r| ["sd4p", "sd4"].iter().any(|t| r.contains(t)))
            .count();
        assert!(tail_rows >= 5, "尾页行数 {tail_rows} < 5,像是只剩单行");
        assert!(!rows.iter().any(|r| r.contains("sd0p1")), "越界滚动后仍显示首行");
    }

    /// proc 排序:同名进程成组,组首行带 ×N 标识
    /// 选中聚合父行:覆盖层显示组摘要(Σ/成员清单),而非被聚合的单条连接
    #[test]
    fn aggregate_selection_shows_group_summary() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        for i in [BOX_NET, BOX_DISKIO, BOX_DISKS, BOX_LAN, BOX_PROCS] {
            app.visible[i] = false;
        }
        let mk = |inode: u64, recv: u64| crate::collect::conn::Conn {
            proto: crate::collect::conn::IPPROTO_TCP,
            local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
            remote: ("127.0.0.1".parse().unwrap(), 443),
            state: 1,
            uid: 0,
            inode,
            bytes_recv: recv,
            bytes_sent: 0,
            rate_recv: 0.0,
            rate_sent: 0.0,
            pid: Some(1000 + inode as u32),
            proc: Some("firefox".into()),
            dead: false,
            first_seen: None,
            dead_at: None,
        };
        app.conn.conns = vec![mk(1, 100), mk(2, 900), mk(3, 50)];
        app.conn.sort = crate::collect::conn::ConnSort::Proc;
        app.sel[BOX_CONNS] = Some(0); // 聚合父行
        app.focus[BOX_CONNS] = true;
        fn rows_containing(buf: &str, needle: &str, cap: usize) -> bool {
            buf.matches(needle).count() >= cap
        }
        let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let buf: String = term
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(buf.contains("firefox ×3"), "组摘要缺失");
        assert!(buf.contains("1.0KiB"), "组 Σ 缺失");
        // 单行摘要:不再罗列成员 IP(子行本身就在聚合行下方展开)
        assert!(!rows_containing(&buf, "127.0.0.1:1001", 3), "成员 IP 不应出现在摘要里");
    }

    #[test]
    fn proc_sort_groups_same_name_with_marker() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        for i in [BOX_NET, BOX_DISKIO, BOX_DISKS, BOX_LAN, BOX_PROCS] {
            app.visible[i] = false;
        }
        let mk = |inode: u64, recv: u64| crate::collect::conn::Conn {
            proto: crate::collect::conn::IPPROTO_TCP,
            local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
            remote: ("127.0.0.1".parse().unwrap(), 443),
            state: 1,
            uid: 0,
            inode,
            bytes_recv: recv,
            bytes_sent: 0,
            rate_recv: 0.0,
            rate_sent: 0.0,
            pid: Some(1000 + inode as u32),
            proc: Some("firefox".into()),
            dead: false,
            first_seen: None,
            dead_at: None,
        };
        app.conn.conns = vec![mk(1, 100), mk(2, 900), mk(3, 50)];
        app.conn.sort = crate::collect::conn::ConnSort::Proc;
        let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let buf: String = term
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        eprintln!("BUF:\n{}", {
            let b = term.backend().buffer();
            (0..b.area.height)
                .map(|y| (0..b.area.width).map(|x| b[(x, y)].symbol()).collect::<String>())
                .collect::<Vec<_>>()
                .join("\n")
        });
        assert!(buf.contains("firefox ×3"), "组首 ×N 标识缺失");
        // 默认折叠:聚合行显示组 Σ(1050B → 1.0KiB),子行隐藏
        assert!(buf.contains("1.0KiB"), "聚合 Σ 缺失");
        assert!(!buf.contains("900B"), "折叠时子行不应显示");
        // 展开后子行可见(各自字节)
        app.expanded.insert("firefox".into());
        term.draw(|f| draw(f, &app)).unwrap();
        let buf: String = term
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(buf.contains("900B") && buf.contains("100B") && buf.contains("50B"), "展开后子行缺失");
        // 组按合计降序:最大字节连接(900)是组首且排最前
        assert!(buf.contains("c"), "应有连接行");
    }

    #[test]
    fn classic_right_column_snaps_to_midline() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        app.layout = crate::app::LayoutMode::Classic;
        for i in 0..BOX_COUNT {
            app.visible[i] = true;
        }
        // LAN 盒高被钉 6 行:标题+表头+3 行设备+边框——3 台应全部可见
        for k in 0..5u32 {
            app.lan.neighbors.insert(
                format!("10.0.0.{}", k + 1).parse().unwrap(),
                crate::collect::lan::Neighbor {
                    ip: format!("10.0.0.{}", k + 1).parse().unwrap(),
                    mac: None,
mac_hidden: false,
                    iface: "eth0".into(),
                    complete: true,
                    hostname: None,
                    is_gateway: false,
                    is_self: false,
                    last_seen: std::time::Instant::now(),
                },
            );
        }
        let mut term = Terminal::new(TestBackend::new(140, 40)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let buf = term.backend().buffer();
        let rows: Vec<String> = (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect()
            })
            .collect();

        // 盒标题自带唯一的上标编号(btop 角标样式),按它定位最稳:
        // 标题行 = 盒子顶边框行;底边框行 = 下一盒标题行 - 1
        let title_row = |tag: &str| -> usize {
            rows.iter()
                .enumerate()
                .find(|(_, r)| r.contains(tag))
                .map(|(y, _)| y)
                .unwrap_or_else(|| panic!("找不到标题 {tag}"))
        };

        let _y_net = title_row("\u{b9}net"); // ¹
        let y_diskio = title_row("\u{b3}disk i/o"); // ³
        let y_lan = title_row("\u{b2}lan"); // ²
        let y_conns = title_row("\u{2075}conns"); // ⁵
        let y_procs = title_row("\u{2076}procs"); // ⁶
        let net_bottom = y_diskio - 1; // NET 底边框 = DISK I/O 标题行的上一行
        let conns_bottom = y_procs - 1;
        assert_eq!(
            conns_bottom, net_bottom,
            "CONNS 底边框(行 {conns_bottom})未对齐 NET 底边框(行 {net_bottom})"
        );
        // 上组相邻:LAN 底边框 = CONNS 顶边框 - 1,且 LAN 至少有标题+一行内容
        assert!(y_conns - 1 > y_lan + 1, "LAN 与 CONNS 应相邻且 LAN 有内容区");
        // 盒高 6 → 内容 3 行:设备 1-3 可见,4-5 不见(曾因表头重复扣行只剩 2 台)
        assert!(rows.iter().any(|r| r.contains("10.0.0.3")), "第 3 台设备应可见");
        assert!(!rows.iter().any(|r| r.contains("10.0.0.4")), "第 4 台设备应被滚动窗口裁掉");
    }

    #[test]
    fn search_filters_procs_and_conns_by_name() {
        use crate::collect::conn::IPPROTO_TCP;
        let mut app = crate::app::App::new(None);
        app.proc.procs.push(crate::collect::proc::ProcRow {
            pid: 1,
            name: "firefox".into(),
            net_recv: 10,
            net_sent: 5,
            net_rr: 0.0,
            net_sr: 0.0,
            udp_recv: 0,
            udp_sent: 0,
            udp_rr: 0.0,
            udp_sr: 0.0,
            disk_r: 0,
            disk_w: 0,
            disk_rr: 0.0,
            disk_wr: 0.0,
            uptime_s: None,            alive: true,
            cmdline: None,
        });
        app.proc.procs.push(crate::collect::proc::ProcRow {
            pid: 2,
            name: "chrome".into(),
            ..app.proc.procs[0].clone()
        });
        app.conn.conns.push(crate::collect::conn::Conn {
            proto: IPPROTO_TCP,
            local: ("127.0.0.1".parse().unwrap(), 1000),
            remote: ("127.0.0.1".parse().unwrap(), 443),
            state: 1,
            uid: 0,
            inode: 9,
            bytes_recv: 0,
            bytes_sent: 0,
            rate_recv: 0.0,
            rate_sent: 0.0,
            pid: Some(1),
            proc: Some("firefox".into()),
            dead: false,
            first_seen: None,
            dead_at: None,
        });
        app.search = "FIRE".into(); // 大小写不敏感
        app.search_box = BOX_CONNS; // 默认目标:conns
        let names: Vec<_> = procs_display(&app).iter().map(|p| p.name.clone()).collect();
        assert_eq!(names.len(), 2, "目标 conns 时 procs 不过滤");
        let conns = conns_display(&app);
        assert_eq!(conns.len(), 1, "目标 conns 应过滤连接归属");
        app.search_box = BOX_PROCS;
        let names: Vec<_> = procs_display(&app).iter().map(|p| p.name.clone()).collect();
        assert_eq!(names, vec!["firefox"], "目标 procs 应过滤进程");
        assert_eq!(conns_display(&app).len(), 1, "非目标盒 conns 应直通不清空");
        app.search.clear();
        assert_eq!(procs_display(&app).len(), 2, "清空搜索应恢复全部");
    }

    #[test]
    fn conn_filter_cycles_all_lan_tcp_udp() {
        use crate::collect::conn::{ConnFilter, IPPROTO_TCP, IPPROTO_UDP};
        let mut app = crate::app::App::new(None);
        let mk = |inode: u64, proto: u8, remote: std::net::IpAddr| {
            crate::collect::conn::Conn {
                proto,
                local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
                remote: (remote, 443),
                state: 1,
                uid: 0,
                inode,
                bytes_recv: 0,
                bytes_sent: 0,
                rate_recv: 0.0,
                rate_sent: 0.0,
                pid: None,
                proc: None,
                dead: false,
                first_seen: None,
                dead_at: None,
            }
        };
        let lan = std::net::IpAddr::V4("192.168.1.9".parse().unwrap());
        app.conn.conns = vec![
            mk(1, IPPROTO_TCP, "93.184.216.34".parse().unwrap()), // 外网 tcp
            mk(2, IPPROTO_TCP, lan),                              // 局域网 tcp
            mk(3, IPPROTO_UDP, lan),                              // 局域网 udp
        ];
        app.conn.filter = ConnFilter::All;
        assert_eq!(conns_display(&app).len(), 3);
        app.conn.filter = ConnFilter::Lan;
        assert_eq!(conns_display(&app).len(), 2, "lan 应滤掉外网");
        app.conn.filter = ConnFilter::Tcp;
        assert_eq!(conns_display(&app).len(), 2, "tcp 应只剩两条 tcp");
        assert!(conns_display(&app).iter().all(|c| c.is_tcp()));
        app.conn.filter = ConnFilter::Udp;
        assert_eq!(conns_display(&app).len(), 1, "udp 应只剩一条 udp");
        // 循环闭合
        assert_eq!(ConnFilter::Udp.next(), ConnFilter::All);
    }

    /// LAN 列表滚动:off 推进后可见行随之移动,列表不再"超面板高度不可滚"
    #[test]
    fn lan_list_scrolls_with_offset() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        // 盒子开关来自真实 config,测试必须显式设定目标盒
        for i in 0..BOX_COUNT {
            app.visible[i] = i == BOX_LAN;
        }
        for k in 0..30u32 {
            app.lan.neighbors.insert(
                format!("10.0.0.{}", k + 1).parse().unwrap(),
                crate::collect::lan::Neighbor {
                    ip: format!("10.0.0.{}", k + 1).parse().unwrap(),
                    mac: None,
mac_hidden: false,
                    iface: "eth0".into(),
                    complete: true,
                    hostname: None,
                    is_gateway: false,
                    is_self: false,
                    last_seen: std::time::Instant::now(),
                },
            );
        }
        let render_buf = |app: &crate::app::App| {
            let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
            term.draw(|f| draw(f, app)).unwrap();
            term.backend()
                .buffer()
                .content
                .iter()
                .map(|c| c.symbol())
                .collect::<String>()
        };
        let render_first_ip = |app: &crate::app::App| {
            let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
            term.draw(|f| draw(f, app)).unwrap();
            let buf: String = term
                .backend()
                .buffer()
                .content
                .iter()
                .map(|c| c.symbol())
                .collect();
            // 匹配带尾随空格的完整 IP:"10.0.0.1 " 不会被 "10.0.0.19" 满足
            (0..30u32)
                .filter(|k| buf.contains(&format!("10.0.0.{} ", k + 1)))
                .collect::<Vec<_>>()
        };
        app.scroll[BOX_LAN] = 0;
        let at0 = render_first_ip(&app);
        assert!(at0.contains(&0), "首屏应含第 1 台");
        assert!(!at0.contains(&20), "首屏不应含第 21 台");
        // 滚动提示与真实剩余一致(30 台 − 可见 12 行 = +18)
        assert!(at0.contains(&0), "占位");
        let buf0 = render_buf(&app);
        assert!(buf0.contains("+18"), "+N 提示缺失或错误");
        app.scroll[BOX_LAN] = 20;
        let at20 = render_first_ip(&app);
        assert!(at20.contains(&20), "滚动后应见第 21 台");
        assert!(!at20.contains(&0), "滚动后首屏不应再含第 1 台");
    }

    #[test]
    fn conn_rows_carry_protocol_labels_without_glyphs() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        // 过滤/排序/语言来自真实 config:断言前显式钉住
        app.conn.filter = crate::collect::conn::ConnFilter::All;
        for i in [BOX_NET, BOX_DISKIO, BOX_DISKS, BOX_LAN] {
            app.visible[i] = false;
        }
        let mk = |inode: u64, name: &str, proto: u8, state: u8| {
            crate::collect::conn::Conn {
                proto,
                local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
                remote: ("127.0.0.1".parse().unwrap(), 443),
                state,
                uid: 0,
                inode,
                bytes_recv: 0,
                bytes_sent: 0,
                rate_recv: 0.0,
                rate_sent: 0.0,
                pid: Some(7),
                proc: Some(name.to_string()),
                dead: false,
                first_seen: None,
                dead_at: None,
            }
        };
        // 三个不同名字:proc 排序下各自成组(×1),不触发 ×N 标记
        app.conn.conns = vec![
            mk(1, "demo", crate::collect::conn::IPPROTO_TCP, crate::collect::conn::TCP_ESTABLISHED),
            mk(2, "demo2", crate::collect::conn::IPPROTO_UDP, 7),
            mk(3, "demo3", crate::collect::conn::IPPROTO_TCP, crate::collect::conn::TCP_LISTEN),
        ];
        let mut term = Terminal::new(TestBackend::new(160, 30)).unwrap();
        // 表头随排序模式切换:sum 显示 Σ 合计量,rate 显示速率
        app.conn.sort = crate::collect::conn::ConnSort::Rate;
        term.draw(|f| draw(f, &app)).unwrap();
        let buf: String = term
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(buf.contains("RX/S"), "rate 表头缺失");
        assert!(!buf.contains("Σ RX"), "rate 模式不应出现 Σ 表头");
        app.conn.sort = crate::collect::conn::ConnSort::Sum;
        term.draw(|f| draw(f, &app)).unwrap();
        let buf: String = term
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(buf.contains("Σ RX") && buf.contains("Σ TX"), "sum 表头缺失");
        assert!(!buf.contains("RX/S"), "sum 模式不应残留速率表头");
        // proc 档同为合计口径
        app.conn.sort = crate::collect::conn::ConnSort::Proc;
        term.draw(|f| draw(f, &app)).unwrap();
        let buf: String = term
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(buf.contains("Σ RX"), "proc 档应显示合计表头");
        eprintln!("DEMO-HITS: {}", ["demo tcp","demo2 udp","◦demo3 tcp","demo","demo2","demo3"].iter().map(|t| format!("{t}={}", buf.contains(t))).collect::<Vec<_>>().join(" "));
        eprintln!("FULL: {}", buf.replace("\n", "|"));
        assert!(buf.contains("demo tcp"), "tcp 标签缺失");
        assert!(buf.contains("demo2 udp"), "udp 标签缺失");
        assert!(buf.contains("demo3 \u{25e6}tcp"), "监听标签缺失");
        for gone in ["\u{25b8}", "\u{22c4}"] {
            assert!(!buf.contains(gone), "旧符号 {gone} 仍在");
        }
    }

    #[test]
    fn layout_priority_favours_lists() {
        // classic: lists keep at least half, the graphs give up width first
        assert_eq!(split_horizontal(150, 76, 40), (74, 76));
        assert_eq!(split_horizontal(100, 76, 40), (40, 60)); // graphs at their floor
        assert_eq!(split_horizontal(60, 76, 40), (30, 30)); // both cramped, split evenly
        // wide/tall: lists take their ideal height, graphs absorb the surplus
        // but are capped at half the height — full-screen surplus goes to lists
        assert_eq!(split_vertical(100, 4, 30), (50, 50));
        assert_eq!(split_vertical(40, 4, 30), (10, 30));
        // when short, graphs hit graph_min before the lists shrink
        assert_eq!(split_vertical(20, 8, 30), (8, 12));
        assert_eq!(split_vertical(12, 8, 30), (8, 4));
    }

    /// 全高回归(用户实机截图发现):wide/tall 下两个图表曾吃到 4/5 屏高。
    /// 复现场景 = 列表内容少(ideal 小)时余量全被图表吞掉。渲染级钉住:
    /// 只留 PROCS 一个列表盒,tall 全高时 ⁶procs 标题必须起自下半屏
    #[test]
    fn tall_layout_caps_graphs_at_half_height() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = crate::app::App::new(None);
        app.layout = crate::app::LayoutMode::Tall;
        for i in [BOX_LAN, BOX_CONNS, BOX_DISKS] {
            app.visible[i] = false;
        }
        app.update();
        let mut term = Terminal::new(TestBackend::new(200, 60)).unwrap();
        term.draw(|f| crate::ui::draw(f, &app)).unwrap();
        let buf = term.backend().buffer();
        let rows: Vec<String> = (0..buf.area().height)
            .map(|y| {
                (0..buf.area().width)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect()
            })
            .collect();
        let title_row = |tag: &str| {
            rows.iter()
                .position(|r| r.contains(tag))
                .unwrap_or_else(|| panic!("找不到标题 {tag}"))
        };
        let y_net = title_row("\u{b9}net"); // ¹net 图表区顶
        let y_procs = title_row("\u{2076}procs"); // ⁶procs 表格区起
        assert!(
            y_procs - y_net <= 32,
            "图表区应 ≤ 半屏:net@{y_net} procs@{y_procs}(总高 60)"
        );
    }

    #[test]
    fn stable_alloc_ignores_blips_and_adopts_real_changes() {
        use std::time::{Duration, Instant};
        let t0 = Instant::now();
        let mut m = StableAlloc::new();
        // first call always applies
        assert_eq!(m.update(vec![10, 20], 30, t0), vec![10, 20]);
        // 2 rows of drift is a blip: ignored even after the settle window
        assert_eq!(
            m.update(vec![12, 18], 30, t0 + Duration::from_secs(5)),
            vec![10, 20]
        );
        // a 4-row change that persists is adopted as a whole
        assert_eq!(
            m.update(vec![14, 16], 30, t0 + Duration::from_secs(10)),
            vec![14, 16]
        );
        // a terminal resize re-applies immediately
        assert_eq!(
            m.update(vec![20, 30], 50, t0 + Duration::from_secs(10)),
            vec![20, 30]
        );
        // an allocation whose sum does not match the space is rejected
        assert_eq!(
            m.update(vec![20, 40], 50, t0 + Duration::from_secs(20)),
            vec![20, 30]
        );
    }

    #[test]
    fn alloc_heights_gives_spare_to_priority_boxes() {
        // ideals [6,12,4,10] (lan,conns,procs,disks), 40 total: spare 8 goes
        // to the process tables (positions 1,2) split evenly
        assert_eq!(
            alloc_heights(&[6, 12, 4, 10], 40, &[1, 2]),
            vec![6, 16, 8, 10]
        );
        // spare smaller than the target count still lands on priority boxes
        assert_eq!(
            alloc_heights(&[6, 12, 4, 10], 39, &[1, 2]),
            vec![6, 16, 7, 10]
        );
        // no spare_to: even spread (old behaviour)
        assert_eq!(alloc_heights(&[6, 8, 4, 5], 40, &[]), vec![11, 12, 8, 9]);
    }

    #[test]
    fn alloc_heights_shrinks_proportionally_when_cramped() {
        // cramped: proportional shrink, every box keeps >= 3 rows
        assert_eq!(alloc_heights(&[10, 10], 10, &[]), vec![5, 5]);
        assert_eq!(alloc_heights(&[10, 10], 6, &[1]), vec![3, 3]);
        // degenerate terminal still yields usable rows
        assert!(alloc_heights(&[8, 8, 8], 5, &[]).iter().all(|&h| h >= 1));
    }

}