egui-elegance 0.4.0

Elegant, opinionated widgets for egui: buttons, inputs, selects, cards, tabs and more. Paired dark/light themes.
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
//! Multi-pane terminal widget with per-pane broadcast toggles.
//!
//! [`MultiTerminal`] renders a responsive grid of [`TerminalPane`]s with a
//! shared keyboard input surface: whatever the user types is broadcast to
//! every pane whose "broadcast" pill is on. Think tmux's synchronized panes
//! or MobaXterm's multi-exec, rendered in the elegance design language.
//!
//! The widget is purely presentational: it captures keystrokes, maintains a
//! pending input buffer, and emits [`TerminalEvent::Command`] when the user
//! presses Enter. The caller is responsible for running the command on each
//! target and pushing response lines back into the corresponding pane via
//! [`MultiTerminal::push_line`].
//!
//! # Interaction
//!
//! * Click a pane header or body to move keyboard focus onto that pane.
//! * Click a pane's broadcast pill to toggle it in or out of the broadcast
//!   set. Every pane with broadcast on will receive input; offline panes
//!   are skipped. An empty broadcast set is a real state: Enter is a no-op
//!   until at least one pane is toggled on.
//! * Each pane has a **Solo** target button next to its broadcast pill:
//!   clicking solos that pane (broadcast = `{this}`); clicking again
//!   restores the previously stashed set.
//! * The gridbar has an **All on** toggle: clicking turns broadcast on
//!   for every connected pane, and clicking again turns all of them off.
//! * Keyboard: `Enter` sends, `Backspace` / `Delete` edit, `Esc` clears.
//!   `Left` / `Right` move the editing caret one character; `Home` / `End`
//!   jump to the start / end of the input (`Ctrl + E` is also bound to
//!   end-of-line; the readline `Ctrl + A` is reserved for the All-on
//!   toggle). `Up` / `Down` walk a shared command history (replacing the
//!   pending buffer with the selected entry). `Ctrl + C` cancels the
//!   current input line (SIGINT-style, distinct from `Cmd + C` which
//!   copies a text selection on macOS). `Ctrl + L` (Unix `clear`) and
//!   `Cmd + K` (macOS Terminal) clear scrollback in every receiving pane.
//!   `Cmd`/`Ctrl` + `A` toggles All on/off; `Cmd`/`Ctrl` + `D` solos the
//!   focused pane.
//!
//! # Example
//!
//! ```no_run
//! use elegance::{LineKind, MultiTerminal, TerminalEvent, TerminalLine,
//!                TerminalPane, TerminalStatus};
//!
//! struct App {
//!     terms: MultiTerminal,
//! }
//!
//! impl Default for App {
//!     fn default() -> Self {
//!         let terms = MultiTerminal::new("ssh-multi")
//!             .with_pane(
//!                 TerminalPane::new("api-east", "api-east-01")
//!                     .user("root")
//!                     .cwd("/var/log")
//!                     .status(TerminalStatus::Connected),
//!             )
//!             .with_pane(
//!                 TerminalPane::new("edge", "edge-proxy-01")
//!                     .user("root")
//!                     .status(TerminalStatus::Connected),
//!             );
//!         Self { terms }
//!     }
//! }
//!
//! # impl App {
//! fn ui(&mut self, ui: &mut egui::Ui) {
//!     self.terms.show(ui);
//!     for ev in self.terms.take_events() {
//!         match ev {
//!             TerminalEvent::Command { targets, command } => {
//!                 for id in targets {
//!                     self.terms.push_line(
//!                         &id,
//!                         TerminalLine::new(LineKind::Out, format!("ran: {command}")),
//!                     );
//!                 }
//!             }
//!         }
//!     }
//! }
//! # }
//! ```

use std::collections::HashSet;
use std::hash::Hash;

use egui::epaint::text::{LayoutJob, TextFormat};
use egui::text::CCursor;
use egui::{
    Align2, Color32, CornerRadius, Event, FontFamily, FontId, Id, Key, Modifiers, Pos2, Rect,
    Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, WidgetType,
};

use crate::theme::{Palette, Theme, Typography};

/// Connection status for a [`TerminalPane`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TerminalStatus {
    /// The pane is live and will receive broadcast input.
    Connected,
    /// The pane is temporarily unavailable; shown in amber and excluded
    /// from broadcasts.
    Reconnecting,
    /// The pane is offline; shown in red and excluded from broadcasts.
    Offline,
}

impl TerminalStatus {
    /// Map to the corresponding [`IndicatorState`](crate::IndicatorState) so
    /// the pane header can reuse the library's status-light glyph.
    pub fn indicator_state(self) -> crate::IndicatorState {
        match self {
            Self::Connected => crate::IndicatorState::On,
            Self::Reconnecting => crate::IndicatorState::Connecting,
            Self::Offline => crate::IndicatorState::Off,
        }
    }
}

/// How a [`TerminalLine`] is coloured when rendered.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LineKind {
    /// Plain output, rendered in the primary text colour.
    Out,
    /// Informational text, rendered faint and italic.
    Info,
    /// Successful output, rendered in the success green.
    Ok,
    /// Warning, rendered in amber.
    Warn,
    /// Error, rendered in danger red.
    Err,
    /// Dimmed secondary output, rendered in muted grey.
    Dim,
    /// A command echo with a full prompt prefix (`user@host:cwd$ cmd`).
    ///
    /// When this variant is used, the `text` field of [`TerminalLine`] is
    /// ignored; the command text is stored inline.
    Command {
        /// Username shown in the prompt.
        user: String,
        /// Hostname shown in the prompt.
        host: String,
        /// Working directory shown in the prompt.
        cwd: String,
        /// The command text the user typed.
        cmd: String,
    },
}

/// A single line in a [`TerminalPane`]'s scrollback buffer.
#[derive(Clone, Debug)]
pub struct TerminalLine {
    /// Colour/style of the line.
    pub kind: LineKind,
    /// The text content. Unused when `kind` is [`LineKind::Command`].
    pub text: String,
}

impl TerminalLine {
    /// Create a line with the given kind and text.
    pub fn new(kind: LineKind, text: impl Into<String>) -> Self {
        Self {
            kind,
            text: text.into(),
        }
    }

    /// Plain-output shortcut.
    pub fn out(text: impl Into<String>) -> Self {
        Self::new(LineKind::Out, text)
    }
    /// Informational shortcut.
    pub fn info(text: impl Into<String>) -> Self {
        Self::new(LineKind::Info, text)
    }
    /// Success shortcut.
    pub fn ok(text: impl Into<String>) -> Self {
        Self::new(LineKind::Ok, text)
    }
    /// Warning shortcut.
    pub fn warn(text: impl Into<String>) -> Self {
        Self::new(LineKind::Warn, text)
    }
    /// Error shortcut.
    pub fn err(text: impl Into<String>) -> Self {
        Self::new(LineKind::Err, text)
    }
    /// Dimmed shortcut.
    pub fn dim(text: impl Into<String>) -> Self {
        Self::new(LineKind::Dim, text)
    }

    /// Build a command echo line. Rendered as `user@host:cwd$ cmd` with
    /// elegance's prompt colouring.
    pub fn command(
        user: impl Into<String>,
        host: impl Into<String>,
        cwd: impl Into<String>,
        cmd: impl Into<String>,
    ) -> Self {
        Self {
            kind: LineKind::Command {
                user: user.into(),
                host: host.into(),
                cwd: cwd.into(),
                cmd: cmd.into(),
            },
            text: String::new(),
        }
    }
}

/// A single pane rendered by [`MultiTerminal`].
#[derive(Clone, Debug)]
pub struct TerminalPane {
    /// Stable identifier used as the key in the broadcast set and event
    /// target list. Must be unique across panes in a single `MultiTerminal`.
    pub id: String,
    /// Hostname shown in the header and prompt.
    pub host: String,
    /// Username shown in the prompt. Default: `"user"`.
    pub user: String,
    /// Working directory shown in the prompt. Default: `"~"`.
    pub cwd: String,
    /// Connection status. Default: [`TerminalStatus::Connected`].
    pub status: TerminalStatus,
    /// Scrollback buffer. Oldest line at index 0, newest at the end.
    pub lines: Vec<TerminalLine>,
}

impl TerminalPane {
    /// Create a pane with the given id and hostname. Defaults: user `"user"`,
    /// cwd `"~"`, status [`TerminalStatus::Connected`], no lines.
    pub fn new(id: impl Into<String>, host: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            host: host.into(),
            user: "user".into(),
            cwd: "~".into(),
            status: TerminalStatus::Connected,
            lines: Vec::new(),
        }
    }

    /// Set the username shown in the prompt.
    #[inline]
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = user.into();
        self
    }

    /// Set the working directory shown in the prompt.
    #[inline]
    pub fn cwd(mut self, cwd: impl Into<String>) -> Self {
        self.cwd = cwd.into();
        self
    }

    /// Set the connection status.
    #[inline]
    pub fn status(mut self, status: TerminalStatus) -> Self {
        self.status = status;
        self
    }

    /// Append a line to the scrollback buffer (builder form).
    #[inline]
    pub fn push(mut self, line: TerminalLine) -> Self {
        self.lines.push(line);
        self
    }

    /// Append a line at runtime.
    pub fn push_line(&mut self, line: TerminalLine) {
        self.lines.push(line);
    }

    /// Replace the connection status at runtime.
    pub fn set_status(&mut self, status: TerminalStatus) {
        self.status = status;
    }

    /// Build a command echo line targeting this pane. Convenience helper:
    /// the prompt pieces are filled from the pane's own user/host/cwd.
    pub fn command_line(&self, cmd: impl Into<String>) -> TerminalLine {
        TerminalLine::command(self.user.clone(), self.host.clone(), self.cwd.clone(), cmd)
    }
}

/// Events emitted by [`MultiTerminal`] that the caller must react to.
#[derive(Clone, Debug)]
pub enum TerminalEvent {
    /// The user pressed Enter with a non-empty buffer. Run `command` on
    /// each pane whose id is in `targets` and push the response lines back
    /// via [`MultiTerminal::push_line`].
    ///
    /// The widget has already echoed the command into each target pane
    /// (as a [`LineKind::Command`] line) before this event is emitted, so
    /// the caller only needs to append the reply.
    Command {
        /// Pane ids that should run this command, in grid order.
        targets: Vec<String>,
        /// The command text as typed by the user.
        command: String,
    },
}

/// Multi-pane terminal with per-pane broadcast toggles.
///
/// See the module-level documentation for the full interaction model.
#[must_use = "Call `.show(ui)` to render the widget."]
pub struct MultiTerminal {
    id_salt: Id,
    panes: Vec<TerminalPane>,
    broadcast: HashSet<String>,
    collapsed: HashSet<String>,
    stashed: Option<HashSet<String>>,
    focused_id: Option<String>,
    pending: String,
    /// Byte offset into `pending` where the editing caret sits. Always
    /// aligned to a UTF-8 char boundary; updated by every editing path
    /// (insert / backspace / delete / arrow keys / paste / history).
    pending_cursor: usize,
    /// Submitted commands, oldest first. Up / Down navigate this list,
    /// replacing `pending` with the selected entry.
    history: Vec<String>,
    /// `Some(i)` while the user is browsing history; `None` when editing
    /// a fresh buffer. Reset on Enter and Esc.
    history_cursor: Option<usize>,
    history_cap: usize,
    columns_mode: ColumnsMode,
    pane_min_height: f32,
    scrollback_cap: usize,
    /// When true (default), the widget claims keyboard focus whenever no
    /// other widget owns it. Apps with multiple non-text surfaces may want
    /// to disable this to avoid swallowing global Tab / Esc navigation.
    auto_focus: bool,
    events: Vec<TerminalEvent>,
}

/// How [`MultiTerminal`] decides the grid's column count.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ColumnsMode {
    /// Always render exactly `n` columns, regardless of available width.
    Fixed(usize),
    /// Pick the column count each frame from the available width, ensuring
    /// every column is at least `min_col_width` points wide. Scales well
    /// from a narrow sidebar (1 column) up to a wide monitor (3-4+ columns).
    Auto {
        /// Minimum column width before the grid drops a column.
        min_col_width: f32,
    },
}

impl std::fmt::Debug for MultiTerminal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MultiTerminal")
            .field("id_salt", &self.id_salt)
            .field("panes", &self.panes.len())
            .field("broadcast", &self.broadcast)
            .field("collapsed", &self.collapsed)
            .field("focused_id", &self.focused_id)
            .field("pending", &self.pending)
            .field("history", &self.history.len())
            .field("columns_mode", &self.columns_mode)
            .field("events", &self.events.len())
            .finish()
    }
}

impl MultiTerminal {
    /// Create an empty widget. `id_salt` scopes the widget's memory state;
    /// two `MultiTerminal`s on the same page need distinct salts.
    pub fn new(id_salt: impl Hash) -> Self {
        Self {
            id_salt: Id::new(("elegance_multi_terminal", id_salt)),
            panes: Vec::new(),
            broadcast: HashSet::new(),
            collapsed: HashSet::new(),
            stashed: None,
            focused_id: None,
            pending: String::new(),
            pending_cursor: 0,
            history: Vec::new(),
            history_cursor: None,
            history_cap: 200,
            columns_mode: ColumnsMode::Fixed(2),
            pane_min_height: 220.0,
            scrollback_cap: 500,
            auto_focus: true,
            events: Vec::new(),
        }
    }

    /// Add a pane at construction time (builder form).
    #[inline]
    pub fn with_pane(mut self, pane: TerminalPane) -> Self {
        self.add_pane(pane);
        self
    }

    /// Render with a fixed number of columns in the pane grid. Panes
    /// wrap after `columns` per row. Default: 2.
    ///
    /// See also [`columns_auto`](Self::columns_auto) for a width-responsive
    /// mode that's better suited to large pane counts.
    #[inline]
    pub fn columns(mut self, columns: usize) -> Self {
        self.columns_mode = ColumnsMode::Fixed(columns.max(1));
        self
    }

    /// Render with a width-responsive column count. Each frame the grid
    /// picks the largest column count such that every column is at least
    /// `min_col_width` points wide, clamped between 1 and the number of
    /// panes. With 16 panes, this naturally produces 3–4 columns on a
    /// wide monitor and 1–2 on a narrow sidebar.
    ///
    /// `min_col_width` is clamped to a minimum of 240 pt so the pane
    /// header always has room for the chevron, hostname, solo button,
    /// broadcast pill and status indicator.
    #[inline]
    pub fn columns_auto(mut self, min_col_width: f32) -> Self {
        self.columns_mode = ColumnsMode::Auto {
            min_col_width: min_col_width.max(240.0),
        };
        self
    }

    /// Minimum height of a single pane, in points. Default: `220.0`.
    #[inline]
    pub fn pane_min_height(mut self, h: f32) -> Self {
        self.pane_min_height = h.max(80.0);
        self
    }

    /// Cap on the number of lines retained per pane. Older lines are
    /// dropped when the buffer exceeds this count. Default: 500.
    #[inline]
    pub fn scrollback_cap(mut self, n: usize) -> Self {
        self.scrollback_cap = n.max(1);
        self
    }

    /// Cap on the shared command history (Up / Down navigation). Older
    /// entries are dropped when the buffer exceeds this count. Default: 200.
    #[inline]
    pub fn history_cap(mut self, n: usize) -> Self {
        self.history_cap = n.max(1);
        // Trim if we just shrank past the current length.
        if self.history.len() > self.history_cap {
            let drop = self.history.len() - self.history_cap;
            self.history.drain(0..drop);
        }
        self
    }

    /// Whether the widget should auto-claim keyboard focus when no other
    /// widget owns it. Default: `true`. Disable in apps where global Tab /
    /// Esc navigation would otherwise be swallowed.
    #[inline]
    pub fn auto_focus(mut self, enabled: bool) -> Self {
        self.auto_focus = enabled;
        self
    }

    /// Append a pane at runtime.
    pub fn add_pane(&mut self, pane: TerminalPane) {
        // If this is the first pane, focus it by default.
        if self.focused_id.is_none() {
            self.focused_id = Some(pane.id.clone());
        }
        // Auto-broadcast only the very first pane added: gives single-pane
        // setups a sensible default target without silently broadcasting
        // every newly-added pane in bulk-add flows (where the user can
        // accidentally fan a command out to a dozen brand-new targets).
        if pane.status == TerminalStatus::Connected && self.panes.is_empty() {
            self.broadcast.insert(pane.id.clone());
        }
        self.panes.push(pane);
    }

    /// Remove a pane by id.
    pub fn remove_pane(&mut self, id: &str) {
        self.panes.retain(|p| p.id != id);
        self.broadcast.remove(id);
        if let Some(stash) = self.stashed.as_mut() {
            stash.remove(id);
        }
        if self.focused_id.as_deref() == Some(id) {
            self.focused_id = self.panes.first().map(|p| p.id.clone());
        }
    }

    /// Borrow a pane by id.
    pub fn pane(&self, id: &str) -> Option<&TerminalPane> {
        self.panes.iter().find(|p| p.id == id)
    }

    /// Borrow a pane mutably by id.
    pub fn pane_mut(&mut self, id: &str) -> Option<&mut TerminalPane> {
        self.panes.iter_mut().find(|p| p.id == id)
    }

    /// All panes, in grid order.
    pub fn panes(&self) -> &[TerminalPane] {
        &self.panes
    }

    /// Append a line to the pane with the given id. No-op if not found.
    /// Applies the scrollback cap.
    pub fn push_line(&mut self, id: &str, line: TerminalLine) {
        let cap = self.scrollback_cap;
        if let Some(p) = self.panes.iter_mut().find(|p| p.id == id) {
            p.lines.push(line);
            if p.lines.len() > cap {
                let drop = p.lines.len() - cap;
                p.lines.drain(0..drop);
            }
        }
    }

    /// Change a pane's status at runtime. If the pane leaves the connected
    /// state, it's removed from the broadcast set.
    pub fn set_status(&mut self, id: &str, status: TerminalStatus) {
        if let Some(p) = self.pane_mut(id) {
            p.status = status;
        }
        if status != TerminalStatus::Connected {
            self.broadcast.remove(id);
        }
    }

    /// Id of the currently focused pane, if any.
    pub fn focused(&self) -> Option<&str> {
        self.focused_id.as_deref()
    }

    /// Programmatically set the focused pane.
    pub fn set_focused(&mut self, id: Option<String>) {
        self.focused_id = id;
    }

    /// Current broadcast set (pane ids that will receive input). Does not
    /// include offline panes.
    pub fn broadcast(&self) -> &HashSet<String> {
        &self.broadcast
    }

    /// Replace the broadcast set wholesale. Invalidates the stash used by
    /// the Solo / All-on toggles.
    pub fn set_broadcast(&mut self, set: HashSet<String>) {
        self.broadcast = set;
        self.stashed = None;
    }

    /// Whether a pane is currently collapsed (rendered as a header-only
    /// strip with its scrollback hidden).
    pub fn is_collapsed(&self, id: &str) -> bool {
        self.collapsed.contains(id)
    }

    /// Collapse or expand a pane by id.
    pub fn set_collapsed(&mut self, id: &str, collapsed: bool) {
        if collapsed {
            self.collapsed.insert(id.to_string());
        } else {
            self.collapsed.remove(id);
        }
    }

    /// Flip the collapsed state of a pane.
    pub fn toggle_collapsed(&mut self, id: &str) {
        if self.collapsed.contains(id) {
            self.collapsed.remove(id);
        } else {
            self.collapsed.insert(id.to_string());
        }
    }

    /// Collapse every pane to its header strip.
    pub fn collapse_all(&mut self) {
        for p in &self.panes {
            self.collapsed.insert(p.id.clone());
        }
    }

    /// Expand every pane back to full height.
    pub fn expand_all(&mut self) {
        self.collapsed.clear();
    }

    /// Toggle whether `id` is in the broadcast set. Connected panes only.
    pub fn toggle_broadcast(&mut self, id: &str) {
        if self
            .pane(id)
            .is_some_and(|p| p.status == TerminalStatus::Connected)
        {
            self.stashed = None;
            if self.broadcast.contains(id) {
                self.broadcast.remove(id);
            } else {
                self.broadcast.insert(id.to_string());
            }
        }
    }

    /// Collapse the broadcast set to just the pane with the given id, and
    /// focus that pane. Calling solo on a pane that's already the sole
    /// receiver restores the previously-stashed set (so the button toggles).
    ///
    /// No-op if the id doesn't match a connected pane.
    pub fn solo(&mut self, id: &str) {
        if !self
            .panes
            .iter()
            .any(|p| p.id == id && p.status == TerminalStatus::Connected)
        {
            return;
        }
        let is_solo = self.broadcast.len() == 1 && self.broadcast.contains(id);
        if is_solo {
            self.restore_or_fallback();
        } else {
            self.stashed = Some(self.broadcast.clone());
            self.broadcast.clear();
            self.broadcast.insert(id.to_string());
        }
        self.focused_id = Some(id.to_string());
    }

    /// Solo the currently-focused pane. See [`solo`](Self::solo) for the
    /// toggle semantics. Bound to the `Cmd/Ctrl+D` shortcut.
    pub fn solo_focused(&mut self) {
        if let Some(fid) = self.focused_id.clone() {
            self.solo(&fid);
        }
    }

    /// Toggle broadcast on every connected pane. If every connected pane
    /// is already in the broadcast set, clears it; otherwise fills it with
    /// every connected pane. When the set ends up empty, Enter is a no-op
    /// until the user opts panes back in.
    pub fn broadcast_all(&mut self) {
        let connected: Vec<String> = self
            .panes
            .iter()
            .filter(|p| p.status == TerminalStatus::Connected)
            .map(|p| p.id.clone())
            .collect();
        let all_on =
            !connected.is_empty() && connected.iter().all(|id| self.broadcast.contains(id));
        // All-on is now a plain on/off toggle rather than a stash-and-restore
        // mechanism: an explicit "turn everything off" is cleaner for users
        // than having the button sometimes restore a prior set.
        self.stashed = None;
        if all_on {
            self.broadcast.clear();
        } else {
            self.broadcast = connected.into_iter().collect();
        }
    }

    /// Flip the broadcast state on every connected pane (off becomes on
    /// and vice versa). Clears the stash.
    pub fn invert_broadcast(&mut self) {
        self.stashed = None;
        let mut next = HashSet::new();
        for p in &self.panes {
            if p.status != TerminalStatus::Connected {
                continue;
            }
            if !self.broadcast.contains(&p.id) {
                next.insert(p.id.clone());
            }
        }
        self.broadcast = next;
    }

    /// Current pending input (what the user is typing).
    pub fn pending(&self) -> &str {
        &self.pending
    }

    /// Clear the pending input buffer (and reset the editing cursor).
    pub fn clear_pending(&mut self) {
        self.pending.clear();
        self.pending_cursor = 0;
    }

    /// Drain and return the events accumulated since the previous call.
    /// Call this once per frame after [`show`](Self::show) to react to
    /// user-submitted commands.
    pub fn take_events(&mut self) -> Vec<TerminalEvent> {
        std::mem::take(&mut self.events)
    }

    /// Render the widget. Call once per frame inside a `CentralPanel` or
    /// similar container.
    pub fn show(&mut self, ui: &mut Ui) -> Response {
        let theme = Theme::current(ui.ctx());
        let focus_id = self.id_salt;

        // Reserve the whole widget region first so we have a rect to make
        // keyboard-focusable. The closure renders the actual content.
        let inner = ui
            .vertical(|ui| {
                self.ui_gridbar(ui, &theme);
                ui.add_space(0.0);
                self.ui_grid(ui, &theme);
            })
            .response;

        // Register the full region as keyboard-focusable *without* claiming
        // pointer clicks. An interactive `Sense::click()` here would sit on
        // top of the children in egui's z-order and swallow their clicks
        // (broadcast pill, quick actions, pane headers). Children call
        // `request_focus(focus_id)` explicitly when clicked.
        let bg = ui.interact(inner.rect, focus_id, Sense::focusable_noninteractive());

        // Auto-claim focus whenever nothing else has it: the widget is a
        // REPL-style typing surface, so keystrokes should land in the panes
        // as soon as the widget is visible, without requiring an initial
        // click. We only take focus when the app isn't focused on something
        // else (a TextEdit elsewhere, for instance). Disabled via
        // `auto_focus(false)` for apps where this would swallow global Tab /
        // Esc navigation.
        if self.auto_focus {
            let someone_else_has_focus = ui
                .ctx()
                .memory(|m| m.focused().is_some_and(|f| f != focus_id));
            if !someone_else_has_focus {
                ui.ctx().memory_mut(|m| m.request_focus(focus_id));
            }
        }

        if ui.ctx().memory(|m| m.has_focus(focus_id)) {
            // Capture arrow keys: vertical for history (Up / Down) and
            // horizontal for cursor positioning (Left / Right). Without
            // this, egui's default focus-navigation eats them and they
            // never reach `handle_keys`.
            ui.ctx().memory_mut(|m| {
                m.set_focus_lock_filter(
                    focus_id,
                    egui::EventFilter {
                        tab: false,
                        horizontal_arrows: true,
                        vertical_arrows: true,
                        escape: false,
                    },
                );
            });
            self.handle_keys(ui);
        }

        bg.widget_info(|| {
            WidgetInfo::labeled(
                WidgetType::Other,
                true,
                format!(
                    "Multi-terminal, {} pane{}, {} receiving",
                    self.panes.len(),
                    if self.panes.len() == 1 { "" } else { "s" },
                    self.target_ids().len()
                ),
            )
        });
        bg
    }

    // ---- Internal helpers ------------------------------------------------

    /// Restore from the stashed broadcast set or fall back to the focused
    /// pane if nothing is stashed.
    fn restore_or_fallback(&mut self) {
        if let Some(stash) = self.stashed.take() {
            // Honor the stash, including an explicitly-empty one: if the
            // user had no panes broadcasting before solo, un-solo returns
            // to no panes broadcasting. Filter to currently-connected
            // panes so a stash referencing a since-disconnected pane
            // doesn't leave a dangling id behind.
            self.broadcast = stash
                .into_iter()
                .filter(|id| {
                    self.panes
                        .iter()
                        .any(|p| p.id == *id && p.status == TerminalStatus::Connected)
                })
                .collect();
        } else {
            // No stash to restore (the soloed pane was the only initial
            // broadcaster). Clear the set so un-solo is a meaningful
            // toggle without forcing an "all panes" default the user
            // didn't ask for; they can opt back in via pane pills or
            // the gridbar's All-on button.
            self.broadcast.clear();
        }
    }

    /// The set of pane ids that should actually receive input right now.
    /// Empty when the broadcast set is empty (or every member is offline);
    /// in that case Enter is a no-op and the gridbar mode pill shows
    /// "NO TARGET".
    fn target_ids(&self) -> Vec<String> {
        self.panes
            .iter()
            .filter(|p| self.broadcast.contains(&p.id) && p.status == TerminalStatus::Connected)
            .map(|p| p.id.clone())
            .collect()
    }

    fn connected_count(&self) -> usize {
        self.panes
            .iter()
            .filter(|p| p.status == TerminalStatus::Connected)
            .count()
    }

    /// Clear scrollback in every pane that would currently receive input
    /// (the broadcast targets, with the same focused-pane fallback as
    /// [`run_pending`](Self::run_pending)). Bound to `Ctrl+L` and `Cmd+K`.
    fn clear_targets(&mut self) {
        let targets = self.target_ids();
        for id in targets {
            if let Some(pane) = self.panes.iter_mut().find(|p| p.id == id) {
                pane.lines.clear();
            }
        }
    }

    fn run_pending(&mut self) {
        let cmd = self.pending.clone();
        if self.send_command(&cmd) {
            self.clear_pending();
            self.history_cursor = None;
        }
    }

    /// Run `cmd` against the current broadcast targets exactly as if the
    /// user had typed it and pressed Enter: trims the command, echoes it
    /// into each target pane, appends to the shared history (deduped
    /// against the previous entry), and emits a [`TerminalEvent::Command`].
    /// The pending input buffer is left untouched.
    ///
    /// Returns `true` if the command was dispatched, `false` if it was
    /// empty after trimming or no panes are reachable.
    pub fn send_command(&mut self, cmd: &str) -> bool {
        let cmd = cmd.trim().to_string();
        if cmd.is_empty() {
            return false;
        }
        let targets = self.target_ids();
        if targets.is_empty() {
            return false;
        }
        // Echo the command into each target pane before emitting the event,
        // so the caller just appends the response.
        let cap = self.scrollback_cap;
        for id in &targets {
            if let Some(pane) = self.panes.iter_mut().find(|p| p.id == *id) {
                let line = pane.command_line(&cmd);
                pane.lines.push(line);
                if pane.lines.len() > cap {
                    let drop = pane.lines.len() - cap;
                    pane.lines.drain(0..drop);
                }
            }
        }
        // Push the submitted command onto the shared history, deduped
        // against the immediately previous entry so repeated Enter doesn't
        // bloat the buffer.
        if self.history.last().map(String::as_str) != Some(cmd.as_str()) {
            self.history.push(cmd.clone());
            if self.history.len() > self.history_cap {
                let drop = self.history.len() - self.history_cap;
                self.history.drain(0..drop);
            }
        }
        self.events.push(TerminalEvent::Command {
            targets,
            command: cmd,
        });
        true
    }

    // ---- Pending-buffer editing helpers --------------------------------
    //
    // All edits flow through these so the cursor stays in sync with the
    // buffer. `pending_cursor` is a byte offset that always sits on a
    // UTF-8 char boundary.

    fn pending_set(&mut self, text: String) {
        self.pending = text;
        self.pending_cursor = self.pending.len();
    }

    fn pending_insert(&mut self, s: &str) {
        self.pending.insert_str(self.pending_cursor, s);
        self.pending_cursor += s.len();
    }

    fn pending_backspace(&mut self) {
        if self.pending_cursor == 0 {
            return;
        }
        let prev = self.pending_prev_boundary(self.pending_cursor);
        self.pending.replace_range(prev..self.pending_cursor, "");
        self.pending_cursor = prev;
    }

    fn pending_delete(&mut self) {
        if self.pending_cursor >= self.pending.len() {
            return;
        }
        let next = self.pending_next_boundary(self.pending_cursor);
        self.pending.replace_range(self.pending_cursor..next, "");
    }

    fn pending_cursor_left(&mut self) {
        self.pending_cursor = self.pending_prev_boundary(self.pending_cursor);
    }

    fn pending_cursor_right(&mut self) {
        self.pending_cursor = self.pending_next_boundary(self.pending_cursor);
    }

    fn pending_cursor_home(&mut self) {
        self.pending_cursor = 0;
    }

    fn pending_cursor_end(&mut self) {
        self.pending_cursor = self.pending.len();
    }

    fn pending_prev_boundary(&self, idx: usize) -> usize {
        if idx == 0 {
            return 0;
        }
        let mut i = idx - 1;
        while i > 0 && !self.pending.is_char_boundary(i) {
            i -= 1;
        }
        i
    }

    fn pending_next_boundary(&self, idx: usize) -> usize {
        let len = self.pending.len();
        if idx >= len {
            return len;
        }
        let mut i = idx + 1;
        while i < len && !self.pending.is_char_boundary(i) {
            i += 1;
        }
        i
    }

    /// Move the history cursor by `delta` (negative = older, positive =
    /// newer) and replace `pending` with the selected entry. Stepping past
    /// the newest entry exits history mode and clears the buffer.
    fn step_history(&mut self, delta: isize) {
        if self.history.is_empty() {
            return;
        }
        let last = self.history.len() - 1;
        let next = match self.history_cursor {
            None => {
                if delta < 0 {
                    Some(last)
                } else {
                    return;
                }
            }
            Some(i) => {
                let i = i as isize + delta;
                if i < 0 {
                    Some(0)
                } else if i as usize > last {
                    None
                } else {
                    Some(i as usize)
                }
            }
        };
        match next {
            Some(i) => {
                self.pending_set(self.history[i].clone());
                self.history_cursor = Some(i);
            }
            None => {
                self.clear_pending();
                self.history_cursor = None;
            }
        }
    }

    fn handle_keys(&mut self, ui: &mut Ui) {
        // Collect events first to release the input borrow; many handlers
        // want `&mut self` which the input closure can't hold.
        let events: Vec<Event> = ui.ctx().input(|i| i.events.clone());
        for event in events {
            match event {
                Event::Key {
                    key,
                    pressed: true,
                    modifiers,
                    ..
                } => {
                    // Ctrl-only (distinct from Cmd on macOS, where Cmd+C
                    // is reserved for copy via egui's selectable labels).
                    if modifiers.matches_exact(Modifiers::CTRL) {
                        match key {
                            Key::C => {
                                // SIGINT-style: cancel the current input line.
                                self.clear_pending();
                                self.history_cursor = None;
                                continue;
                            }
                            // readline `end-of-line`. The complementary
                            // `Ctrl+A` (start-of-line) clashes with the
                            // existing All-on toggle; `Home` covers it.
                            Key::E => {
                                self.pending_cursor_end();
                                continue;
                            }
                            _ => {}
                        }
                    }
                    if modifiers.matches_exact(Modifiers::COMMAND)
                        || modifiers.matches_exact(Modifiers::CTRL)
                    {
                        match key {
                            Key::A => self.broadcast_all(),
                            Key::D => self.solo_focused(),
                            // Clear scrollback. `L` is the Unix `clear`
                            // convention; `K` is the macOS Terminal.app
                            // convention (Cmd+K).
                            Key::L | Key::K => self.clear_targets(),
                            _ => {}
                        }
                        continue;
                    }
                    if modifiers.any() {
                        // Let other shortcuts fall through untouched.
                        continue;
                    }
                    match key {
                        Key::Enter => self.run_pending(),
                        Key::Escape => {
                            self.clear_pending();
                            self.history_cursor = None;
                        }
                        Key::Backspace => self.pending_backspace(),
                        Key::Delete => self.pending_delete(),
                        Key::ArrowLeft => self.pending_cursor_left(),
                        Key::ArrowRight => self.pending_cursor_right(),
                        Key::Home => self.pending_cursor_home(),
                        Key::End => self.pending_cursor_end(),
                        Key::ArrowUp => self.step_history(-1),
                        Key::ArrowDown => self.step_history(1),
                        _ => {}
                    }
                }
                Event::Text(text) => {
                    let cleaned: String = text.chars().filter(|c| !c.is_control()).collect();
                    if !cleaned.is_empty() {
                        self.pending_insert(&cleaned);
                    }
                }
                Event::Paste(text) => {
                    // Insert pasted text at the cursor. Strip control
                    // characters (including newlines) so a multi-line
                    // paste collapses into a single command; auto-submitting
                    // on `\n` would silently broadcast every line to every
                    // receiving pane.
                    let cleaned: String = text.chars().filter(|c| !c.is_control()).collect();
                    if !cleaned.is_empty() {
                        self.pending_insert(&cleaned);
                    }
                }
                _ => {}
            }
        }
    }

    // ---- Painting ------------------------------------------------------

    fn ui_gridbar(&mut self, ui: &mut Ui, theme: &Theme) {
        let palette = &theme.palette;
        let typo = &theme.typography;
        let connected = self.connected_count();
        let targets = self.target_ids();
        let targets_len = targets.len();

        let height = 36.0;
        let (rect, _resp) =
            ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover());
        let painter = ui.painter_at(rect);

        // Fill + top-of-grid rounded corners.
        painter.rect(
            rect,
            CornerRadius {
                nw: theme.card_radius as u8,
                ne: theme.card_radius as u8,
                sw: 0,
                se: 0,
            },
            palette.card,
            Stroke::new(1.0, palette.border),
            StrokeKind::Inside,
        );

        // Broadcast-fraction underline on the bottom edge of the gridbar.
        // Widens with how many panes are receiving; gives a felt sense of
        // reach at a glance.
        if connected > 0 {
            let frac = (targets_len as f32 / connected as f32).clamp(0.0, 1.0);
            let bar_top = rect.bottom() - 1.5;
            let bar_rect = Rect::from_min_max(
                Pos2::new(rect.left(), bar_top),
                Pos2::new(rect.left() + rect.width() * frac, rect.bottom()),
            );
            painter.rect_filled(bar_rect, CornerRadius::ZERO, palette.sky);
        }

        // Mode pill.
        let (mode_label, mode_style) = self.derive_mode(targets_len, connected);
        let mut cursor_x = rect.left() + 14.0;
        let y_mid = rect.center().y;

        cursor_x += self.paint_mode_pill(
            &painter,
            Pos2::new(cursor_x, y_mid),
            mode_label,
            mode_style,
            palette,
            typo,
        );
        cursor_x += 10.0;

        // Target summary (truncated if too many hosts).
        let summary = self.target_summary(&targets, targets_len, connected);
        let summary_color = if targets_len == 0 {
            palette.warning
        } else {
            palette.text_muted
        };
        // Reserve space on the right for buttons so the summary can be
        // clipped without overlapping them.
        let right_reserve = 280.0;
        let max_text_right = (rect.right() - right_reserve).max(cursor_x + 40.0);
        let summary_job = summary_layout(
            &summary,
            palette,
            typo.label,
            summary_color,
            max_text_right - cursor_x,
        );
        let galley = painter.layout_job(summary_job);
        painter.galley(
            Pos2::new(cursor_x, y_mid - galley.size().y * 0.5),
            galley,
            palette.text_muted,
        );

        // Right-aligned "All on" toggle. Solo lives on each pane's header;
        // manual per-pane broadcast toggles cover every other case.
        let mut x = rect.right() - 10.0;
        let all_on = connected > 0 && targets_len == connected;

        let all_w = qa_button(
            ui,
            rect,
            &mut x,
            self.id_salt.with("qa-all"),
            "All on",
            Some("\u{2318}A"),
            all_on,
            theme,
        );
        if all_w.clicked {
            self.broadcast_all();
            // Clicking the button grabs egui's focus; hand it back to the
            // widget so the next keystroke still lands in the panes.
            ui.ctx().memory_mut(|m| m.request_focus(self.id_salt));
        }
    }

    fn target_summary(&self, targets: &[String], n: usize, connected: usize) -> String {
        if n == 0 {
            return "No reachable terminals".into();
        }
        let phrase = if n == 1 {
            "Sending to"
        } else if n == connected {
            "Broadcasting to ALL"
        } else {
            "Broadcasting to"
        };
        let hosts: Vec<&str> = targets
            .iter()
            .filter_map(|id| self.pane(id).map(|p| p.host.as_str()))
            .collect();
        let shown = if hosts.len() <= 3 {
            hosts.join(", ")
        } else {
            format!("{}, +{} more", hosts[..2].join(", "), hosts.len() - 2)
        };
        format!("{phrase} {n} \u{00b7} {shown}")
    }

    fn paint_mode_pill(
        &self,
        painter: &egui::Painter,
        left_center: Pos2,
        label: &str,
        style: ModePillStyle,
        palette: &Palette,
        typo: &Typography,
    ) -> f32 {
        let text_color = match style {
            ModePillStyle::Single => palette.text_muted,
            ModePillStyle::Selected => palette.sky,
            ModePillStyle::All => Color32::from_rgb(0x0f, 0x17, 0x2a),
        };
        let (fill, border) = match style {
            ModePillStyle::Single => (palette.input_bg, palette.border),
            ModePillStyle::Selected => (with_alpha(palette.sky, 22), with_alpha(palette.sky, 90)),
            ModePillStyle::All => (palette.sky, palette.sky),
        };

        let galley = painter.layout_no_wrap(
            label.to_string(),
            FontId::new(typo.small - 1.5, FontFamily::Proportional),
            text_color,
        );
        let pad_x = 7.0;
        let pill_h = galley.size().y + 4.0;
        let pill_w = galley.size().x + pad_x * 2.0;
        let pill_rect = Rect::from_center_size(
            Pos2::new(left_center.x + pill_w * 0.5, left_center.y),
            Vec2::new(pill_w, pill_h),
        );
        painter.rect(
            pill_rect,
            CornerRadius::same((pill_h * 0.5) as u8),
            fill,
            Stroke::new(1.0, border),
            StrokeKind::Inside,
        );
        painter.galley(
            Pos2::new(
                pill_rect.left() + pad_x,
                pill_rect.center().y - galley.size().y * 0.5,
            ),
            galley,
            text_color,
        );
        pill_w
    }

    fn derive_mode(&self, targets: usize, connected: usize) -> (&'static str, ModePillStyle) {
        if targets == 0 {
            ("NO TARGET", ModePillStyle::Single)
        } else if targets == 1 {
            ("SINGLE", ModePillStyle::Single)
        } else if targets == connected {
            ("ALL", ModePillStyle::All)
        } else {
            ("SELECTED", ModePillStyle::Selected)
        }
    }

    fn ui_grid(&mut self, ui: &mut Ui, theme: &Theme) {
        let palette = &theme.palette;
        let full_w = ui.available_width();
        ui.spacing_mut().item_spacing.y = 0.0;

        // Panes tile edge-to-edge separated by 1px lines: the container is
        // filled with `palette.border`, and a 1px gap (`inner_pad` around the
        // outside, `gap` between cells) lets that fill show through as thin
        // separators.
        let inner_pad = 1.0;
        let gap = 1.0;

        // Resolve the column count from the configured mode. Auto picks
        // the largest column count that keeps every column at least
        // `min_col_width` wide.
        let inner_w_for_cols = (full_w - inner_pad * 2.0).max(0.0);
        // Column count: Fixed modes use the caller's number; Auto first
        // finds the cap allowed by the available width, then balances rows
        // by using the *smallest* column count that still fits in that cap.
        // For 4 panes on a 3-col-capable screen this gives 2+2, not 3+1.
        let max_cols_from_width = |min_col_width: f32| -> usize {
            ((inner_w_for_cols + gap) / (min_col_width + gap))
                .floor()
                .max(1.0) as usize
        };
        let pane_count = self.panes.len().max(1);
        let cols_raw = match self.columns_mode {
            ColumnsMode::Fixed(n) => n,
            ColumnsMode::Auto { min_col_width } => {
                let max_cols = max_cols_from_width(min_col_width).min(pane_count);
                let rows = pane_count.div_ceil(max_cols);
                pane_count.div_ceil(rows)
            }
        };
        let cols = cols_raw.max(1).min(pane_count);
        let n_rows = self.panes.len().div_ceil(cols);

        // Per-row heights: a row where every pane is collapsed shrinks
        // to the header height so 16 idle panes don't hog the viewport.
        let header_only_h = PANE_HEADER_HEIGHT;
        let row_heights: Vec<f32> = (0..n_rows)
            .map(|row| {
                let any_expanded = (0..cols).any(|col| {
                    let idx = row * cols + col;
                    idx < self.panes.len() && !self.collapsed.contains(&self.panes[idx].id)
                });
                if any_expanded {
                    self.pane_min_height
                } else {
                    header_only_h
                }
            })
            .collect();
        let total_h = if self.panes.is_empty() {
            60.0
        } else {
            inner_pad * 2.0
                + row_heights.iter().sum::<f32>()
                + (n_rows.saturating_sub(1)) as f32 * gap
        };

        let (outer_rect, _resp) =
            ui.allocate_exact_size(Vec2::new(full_w, total_h), Sense::hover());

        ui.painter().rect(
            outer_rect,
            CornerRadius {
                nw: 0,
                ne: 0,
                sw: theme.card_radius as u8,
                se: theme.card_radius as u8,
            },
            palette.border,
            Stroke::NONE,
            StrokeKind::Inside,
        );

        if self.panes.is_empty() {
            // Repaint with the card colour: with no panes to overlay, the
            // border-coloured base would look like a solid block.
            ui.painter().rect(
                outer_rect,
                CornerRadius {
                    nw: 0,
                    ne: 0,
                    sw: theme.card_radius as u8,
                    se: theme.card_radius as u8,
                },
                palette.card,
                Stroke::new(1.0, palette.border),
                StrokeKind::Inside,
            );
            ui.painter().text(
                outer_rect.center(),
                Align2::CENTER_CENTER,
                "No terminals",
                FontId::proportional(theme.typography.body),
                palette.text_faint,
            );
            return;
        }

        let inner = outer_rect.shrink(inner_pad);
        // Width per cell, parameterised by row pane count so a partial last
        // row (e.g. 2 panes in a 3-col grid) stretches its panes to fill the
        // full inner width rather than leaving an empty column. Panes within
        // any single row always share width equally.
        let cell_w_for = |panes_in_row: usize| -> f32 {
            let n = panes_in_row.max(1) as f32;
            (inner.width() - gap * (n - 1.0)) / n
        };

        // Collect click intents across panes so we can apply mutations
        // after the read-only iteration.
        let mut intent_focus: Option<String> = None;
        let mut intent_toggle: Option<String> = None;
        let mut intent_solo: Option<String> = None;
        let mut intent_collapse: Option<String> = None;

        // Rolling vertical cursor so variable-height rows stack tidily.
        let mut y_cursor = inner.top();
        let mut row_top_for = vec![0.0_f32; n_rows];
        for (row, h) in row_heights.iter().enumerate() {
            row_top_for[row] = y_cursor;
            y_cursor += h + gap;
        }

        // Outermost panes touching the container's rounded sw/se corners
        // need matching rounded corners on the pane, otherwise their square
        // corners would protrude past the container's curve. Inset by 1px
        // (the inner_pad) so the pane's curve runs parallel to the container's.
        let pane_corner = (theme.card_radius - inner_pad).max(0.0) as u8;
        let last_idx = self.panes.len() - 1;
        let last_row = n_rows - 1;
        let panes_in_last_row = self.panes.len() - last_row * cols;
        for (idx, pane) in self.panes.iter().enumerate() {
            let row = idx / cols;
            let col = idx % cols;
            let row_pane_count = if row == last_row {
                panes_in_last_row
            } else {
                cols
            };
            let row_cell_w = cell_w_for(row_pane_count);
            let cell_top = row_top_for[row];
            let cell_left = inner.left() + col as f32 * (row_cell_w + gap);
            // Collapsed panes render as just the header row at the top of
            // their row-slot — the space below stays empty and shows the
            // container's border-colour fill, blending with the gap lines.
            let is_collapsed = self.collapsed.contains(&pane.id);
            let cell_h = if is_collapsed {
                header_only_h
            } else {
                row_heights[row]
            };
            let cell_rect = Rect::from_min_size(
                Pos2::new(cell_left, cell_top),
                Vec2::new(row_cell_w, cell_h),
            );

            let is_focused = self.focused_id.as_deref() == Some(pane.id.as_str());
            let is_receiving =
                self.broadcast.contains(&pane.id) && pane.status == TerminalStatus::Connected;
            let is_solo = self.broadcast.len() == 1 && self.broadcast.contains(&pane.id);

            let corner_radius = CornerRadius {
                nw: 0,
                ne: 0,
                sw: if row == last_row && col == 0 {
                    pane_corner
                } else {
                    0
                },
                se: if idx == last_idx { pane_corner } else { 0 },
            };

            let ctx = PaneCtx {
                rect: cell_rect,
                pane,
                is_focused,
                is_receiving,
                is_solo,
                is_collapsed,
                corner_radius,
                pending: if is_receiving { &self.pending } else { "" },
                pending_cursor: if is_receiving { self.pending_cursor } else { 0 },
                theme,
                id_salt: self.id_salt.with(("pane", idx)),
            };
            let actions = draw_pane(ui, &ctx);

            if actions.header_clicked || actions.body_clicked {
                intent_focus = Some(pane.id.clone());
            }
            if actions.toggle_clicked {
                intent_toggle = Some(pane.id.clone());
            }
            if actions.solo_clicked {
                intent_solo = Some(pane.id.clone());
            }
            // Clicking anywhere on the header strip (outside the chevron,
            // solo, broadcast and indicator child widgets, which consume
            // their own clicks) toggles collapse. The chevron remains a
            // precise target for the same action.
            if actions.collapse_clicked || actions.header_clicked {
                intent_collapse = Some(pane.id.clone());
            }
        }

        if let Some(id) = intent_focus {
            self.focused_id = Some(id);
            ui.ctx().memory_mut(|m| m.request_focus(self.id_salt));
        }
        if let Some(id) = intent_toggle {
            self.toggle_broadcast(&id);
            ui.ctx().memory_mut(|m| m.request_focus(self.id_salt));
        }
        if let Some(id) = intent_solo {
            self.solo(&id);
            ui.ctx().memory_mut(|m| m.request_focus(self.id_salt));
        }
        if let Some(id) = intent_collapse {
            self.toggle_collapsed(&id);
            ui.ctx().memory_mut(|m| m.request_focus(self.id_salt));
        }
    }
}

/// Fixed header height used by pane rendering and by collapsed-row layout.
const PANE_HEADER_HEIGHT: f32 = 34.0;

// ---------------------------------------------------------------------------
// Rendering helpers (free functions, not methods, so the borrow checker
// doesn't get tangled with `&self.panes`).
// ---------------------------------------------------------------------------

struct PaneCtx<'a> {
    rect: Rect,
    pane: &'a TerminalPane,
    is_focused: bool,
    is_receiving: bool,
    /// This pane is the only member of the broadcast set.
    is_solo: bool,
    /// This pane is collapsed to a header-only strip.
    is_collapsed: bool,
    /// Per-pane corner rounding: square in the interior of the grid; the
    /// outermost panes touching the container's rounded corners get those
    /// corners rounded so they don't protrude past the container's curve.
    corner_radius: CornerRadius,
    pending: &'a str,
    /// Byte offset of the editing caret within `pending` for receiving
    /// panes; `0` for non-receiving panes (their `pending` is empty).
    pending_cursor: usize,
    theme: &'a Theme,
    id_salt: Id,
}

struct PaneActions {
    header_clicked: bool,
    body_clicked: bool,
    toggle_clicked: bool,
    solo_clicked: bool,
    collapse_clicked: bool,
}

fn draw_pane(ui: &mut Ui, ctx: &PaneCtx<'_>) -> PaneActions {
    let palette = &ctx.theme.palette;
    let p = ctx.rect;

    // Panes tile edge-to-edge with 1px gaps; the gap lines come from the
    // grid container's border-coloured fill showing through. The default
    // pane has no border of its own. Focused / receiving panes draw an
    // inset accent stroke (`StrokeKind::Inside`) so it stays inside the
    // pane and doesn't bleed into the gap.
    let stroke = if ctx.is_focused {
        Stroke::new(1.5, palette.sky)
    } else if ctx.is_receiving {
        Stroke::new(1.0, with_alpha(palette.sky, 115))
    } else {
        Stroke::NONE
    };
    ui.painter().rect(
        p,
        ctx.corner_radius,
        palette.card,
        stroke,
        StrokeKind::Inside,
    );

    // Header + (optional) body layout. Collapsed panes don't render a
    // body — the rect is sized to just the header height by the caller.
    let header_rect = Rect::from_min_size(p.min, Vec2::new(p.width(), PANE_HEADER_HEIGHT));
    let (header_clicked, toggle_clicked, solo_clicked, collapse_clicked) =
        draw_pane_header(ui, header_rect, ctx);

    let body_clicked = if ctx.is_collapsed {
        false
    } else {
        let body_rect = Rect::from_min_max(Pos2::new(p.left(), header_rect.bottom()), p.max);
        draw_pane_body(ui, body_rect, ctx)
    };

    PaneActions {
        header_clicked,
        body_clicked,
        toggle_clicked,
        solo_clicked,
        collapse_clicked,
    }
}

fn draw_pane_header(ui: &mut Ui, rect: Rect, ctx: &PaneCtx<'_>) -> (bool, bool, bool, bool) {
    let palette = &ctx.theme.palette;
    let typo = &ctx.theme.typography;

    // Bottom separator under the header — only drawn when the pane is
    // expanded (and therefore has a body below the separator).
    if !ctx.is_collapsed {
        ui.painter().line_segment(
            [
                Pos2::new(rect.left() + 1.0, rect.bottom() - 0.5),
                Pos2::new(rect.right() - 1.0, rect.bottom() - 0.5),
            ],
            Stroke::new(1.0, palette.border),
        );
    }

    // Background click area. Child widgets (chevron, solo, broadcast pill)
    // are drawn afterwards so their clicks take priority via egui's z-order.
    let header_resp = ui.interact(rect, ctx.id_salt.with("header"), Sense::click());

    // Chevron at the far left. Click to collapse / expand this pane.
    let edge_pad = 6.0;
    let (collapse_clicked, chev_w) = draw_chevron_button(ui, ctx, rect, edge_pad);

    // Right cluster: status indicator, broadcast pill, solo button. Drawn
    // before the hostname so we know the leftmost X of the cluster and can
    // clip the hostname to fit the available space (long hostnames would
    // otherwise overrun the pill / solo button on narrow panes).
    let pad_x = 13.0;
    let ind_size = 10.0;
    let ind_center = Pos2::new(rect.right() - pad_x - ind_size * 0.5, rect.center().y);
    paint_status_indicator(ui.painter(), ind_center, ctx.pane.status, palette, ind_size);

    let bc_rect_right = ind_center.x - ind_size * 0.5 - 8.0;
    let (toggle_clicked, bc_w) = draw_broadcast_pill(ui, ctx, bc_rect_right, rect.center().y);

    let solo_right = bc_rect_right - bc_w - 6.0;
    let (solo_clicked, solo_w) = draw_solo_button(ui, ctx, solo_right, rect.center().y);
    let solo_left = solo_right - solo_w;

    // Hostname, clipped to fit between the chevron and the right cluster.
    let host_x = rect.left() + edge_pad + chev_w + 6.0;
    let host_max_w = (solo_left - host_x - 6.0).max(0.0);
    let mut job = LayoutJob::default();
    job.wrap.max_width = host_max_w;
    job.wrap.max_rows = 1;
    job.wrap.break_anywhere = true;
    job.wrap.overflow_character = Some('\u{2026}');
    job.append(
        &ctx.pane.host,
        0.0,
        TextFormat {
            font_id: FontId::monospace(typo.small + 0.5),
            color: palette.text,
            ..Default::default()
        },
    );
    job.append(
        &format!("@{}", ctx.pane.user),
        0.0,
        TextFormat {
            font_id: FontId::monospace(typo.small + 0.5),
            color: palette.text_faint,
            ..Default::default()
        },
    );
    let galley = ui.painter().layout_job(job);
    ui.painter().galley(
        Pos2::new(host_x, rect.center().y - galley.size().y * 0.5),
        galley,
        palette.text,
    );

    (
        header_resp.clicked(),
        toggle_clicked,
        solo_clicked,
        collapse_clicked,
    )
}

/// Chevron button at the left edge of a pane header. Triangle pointing
/// down when the pane is expanded, right when it's collapsed.
///
/// Returns `(clicked, width)`.
fn draw_chevron_button(ui: &mut Ui, ctx: &PaneCtx<'_>, header: Rect, edge_pad: f32) -> (bool, f32) {
    let palette = &ctx.theme.palette;
    let size = 18.0;
    let rect = Rect::from_center_size(
        Pos2::new(header.left() + edge_pad + size * 0.5, header.center().y),
        Vec2::splat(size),
    );
    let resp = ui.interact(rect, ctx.id_salt.with("chev"), Sense::click());
    let color = if resp.hovered() {
        palette.text
    } else {
        palette.text_muted
    };

    // Small triangle centred in the button.
    let c = rect.center();
    let h = 3.5; // half-size of the triangle
    let pts = if ctx.is_collapsed {
        // Pointing right: â–¸
        vec![
            Pos2::new(c.x - h * 0.7, c.y - h),
            Pos2::new(c.x - h * 0.7, c.y + h),
            Pos2::new(c.x + h, c.y),
        ]
    } else {
        // Pointing down: â–¾
        vec![
            Pos2::new(c.x - h, c.y - h * 0.7),
            Pos2::new(c.x + h, c.y - h * 0.7),
            Pos2::new(c.x, c.y + h),
        ]
    };
    ui.painter()
        .add(egui::Shape::convex_polygon(pts, color, Stroke::NONE));

    (resp.clicked(), size)
}

/// Paint the connection indicator glyph at `center`. Mirrors the library's
/// [`Indicator`](crate::Indicator) widget so the pane header shares the
/// same visual vocabulary.
fn paint_status_indicator(
    painter: &egui::Painter,
    center: Pos2,
    status: TerminalStatus,
    palette: &Palette,
    size: f32,
) {
    let r = size * 0.5;
    match status {
        TerminalStatus::Connected => {
            painter.circle_filled(center, r + 1.5, with_alpha(palette.success, 70));
            painter.circle_filled(center, r, palette.success);
        }
        TerminalStatus::Reconnecting => {
            painter.circle_stroke(center, r - 0.5, Stroke::new(1.8, palette.warning));
        }
        TerminalStatus::Offline => {
            painter.circle_stroke(center, r - 0.5, Stroke::new(1.0, palette.danger));
            let bar_w = size * 0.7;
            let bar_h = 2.0;
            let bar = Rect::from_center_size(center, Vec2::new(bar_w, bar_h));
            painter.rect_filled(bar, CornerRadius::same(1), palette.danger);
        }
    }
}

fn draw_broadcast_pill(ui: &mut Ui, ctx: &PaneCtx<'_>, right_edge: f32, y_mid: f32) -> (bool, f32) {
    let palette = &ctx.theme.palette;
    let dim = ctx.pane.status != TerminalStatus::Connected;

    // Compact icon-only toggle: a broadcast-waves glyph (dot with arcs
    // flanking it on both sides) inside a rounded pill.
    let pill_w = 34.0;
    let pill_h = 22.0;
    let rect = Rect::from_min_size(
        Pos2::new(right_edge - pill_w, y_mid - pill_h * 0.5),
        Vec2::new(pill_w, pill_h),
    );

    let resp = ui.interact(rect, ctx.id_salt.with("bcast"), Sense::click());
    let hovered = resp.hovered() && !dim;

    let (fill, border, icon_color) = if ctx.is_receiving {
        // On: sky fill; hover slightly lifts it so the press is felt.
        let fill = if hovered {
            palette.depth_tint(palette.sky, 0.12)
        } else {
            palette.sky
        };
        (fill, palette.sky, Color32::from_rgb(0x0f, 0x17, 0x2a))
    } else if hovered {
        // Off + hovered: preview the "on" state with a faint sky tint so
        // the affordance is obvious — clicking will turn it sky.
        (
            with_alpha(palette.sky, 26),
            with_alpha(palette.sky, 130),
            palette.sky,
        )
    } else {
        (Color32::TRANSPARENT, palette.border, palette.text_faint)
    };

    ui.painter().rect(
        rect,
        CornerRadius::same((pill_h * 0.5) as u8),
        fill,
        Stroke::new(1.0, border),
        StrokeKind::Inside,
    );

    // Pulse halo behind the centre dot while receiving.
    let center = rect.center();
    if ctx.is_receiving {
        let t = ui.input(|i| i.time);
        let phase = (t.rem_euclid(1.2) / 1.2) as f32;
        let halo_r = 2.0 + phase.min(1.0) * 4.5;
        let halo_a = (70.0 * (1.0 - phase)).clamp(0.0, 255.0) as u8;
        ui.painter()
            .circle_filled(center, halo_r, with_alpha(icon_color, halo_a));
    }

    paint_broadcast_glyph(ui.painter(), center, icon_color);

    (if dim { false } else { resp.clicked() }, pill_w)
}

/// Broadcast-waves glyph: centre dot with two symmetric arcs emanating
/// outward on both sides. Rendered at `center`, roughly 18 pt wide and
/// 8 pt tall so it fits comfortably inside a pill.
fn paint_broadcast_glyph(painter: &egui::Painter, center: Pos2, color: Color32) {
    // Centre source dot.
    painter.circle_filled(center, 1.8, color);

    let stroke = Stroke::new(1.2, color);
    // Inner arcs (radius ~4.5) and outer arcs (radius ~7.5) on each side.
    // Angles are measured in radians; 0 points right, so "right arc" spans
    // roughly [-span, +span] around 0 and "left arc" spans [PI - span, PI + span].
    use std::f32::consts::PI;
    paint_arc(painter, center, 4.5, -0.45, 0.45, stroke);
    paint_arc(painter, center, 4.5, PI - 0.45, PI + 0.45, stroke);
    paint_arc(painter, center, 7.5, -0.32, 0.32, stroke);
    paint_arc(painter, center, 7.5, PI - 0.32, PI + 0.32, stroke);
}

/// Approximate an arc with a short line-segment polyline.
fn paint_arc(
    painter: &egui::Painter,
    center: Pos2,
    radius: f32,
    start: f32,
    end: f32,
    stroke: Stroke,
) {
    const STEPS: usize = 8;
    let mut pts = Vec::with_capacity(STEPS + 1);
    for i in 0..=STEPS {
        let t = i as f32 / STEPS as f32;
        let a = start + (end - start) * t;
        pts.push(Pos2::new(
            center.x + radius * a.cos(),
            center.y + radius * a.sin(),
        ));
    }
    painter.add(egui::Shape::line(pts, stroke));
}

/// Per-pane solo button: a small round target-icon button. Clicking makes
/// this pane the only member of the broadcast set; clicking again (while
/// already solo) restores the prior set.
///
/// Returns `(clicked, width)`.
fn draw_solo_button(ui: &mut Ui, ctx: &PaneCtx<'_>, right_edge: f32, y_mid: f32) -> (bool, f32) {
    let palette = &ctx.theme.palette;
    let dim = ctx.pane.status != TerminalStatus::Connected;

    let size = 22.0;
    let rect = Rect::from_min_size(
        Pos2::new(right_edge - size, y_mid - size * 0.5),
        Vec2::splat(size),
    );

    let resp = ui.interact(rect, ctx.id_salt.with("solo"), Sense::click());
    let hovered = resp.hovered() && !dim;

    let (fill, border, icon_color) = if ctx.is_solo {
        (with_alpha(palette.sky, 28), palette.sky, palette.sky)
    } else if hovered {
        (Color32::TRANSPARENT, palette.text_muted, palette.text)
    } else {
        (Color32::TRANSPARENT, palette.border, palette.text_faint)
    };

    ui.painter().rect(
        rect,
        CornerRadius::same((size * 0.5) as u8),
        fill,
        Stroke::new(1.0, border),
        StrokeKind::Inside,
    );

    // Solo glyph: 2x2 grid with only the top-left cell filled. Pairs
    // visually with the All-on button's four-cell grid and reads as
    // "just this one of the many".
    paint_solo_icon(ui.painter(), rect.center(), icon_color);

    (if dim { false } else { resp.clicked() }, size)
}

fn paint_solo_icon(painter: &egui::Painter, center: Pos2, color: Color32) {
    let pad = 1.0;
    let cell = 5.5;
    let cells = [
        (-cell - pad, -cell - pad, true),
        (pad, -cell - pad, false),
        (-cell - pad, pad, false),
        (pad, pad, false),
    ];
    for (dx, dy, filled) in cells {
        let r = Rect::from_min_size(Pos2::new(center.x + dx, center.y + dy), Vec2::splat(cell));
        if filled {
            painter.rect_filled(r, CornerRadius::same(1), color);
        } else {
            painter.rect_stroke(
                r,
                CornerRadius::same(1),
                Stroke::new(1.2, color),
                StrokeKind::Inside,
            );
        }
    }
}

/// Returns true if the body area was clicked.
fn draw_pane_body(ui: &mut Ui, rect: Rect, ctx: &PaneCtx<'_>) -> bool {
    let palette = &ctx.theme.palette;
    let typo = &ctx.theme.typography;

    // Terminal-bg fill (darker than the card, like a screen).
    let term_bg = palette.depth_tint(palette.input_bg, 0.015);
    ui.painter().rect_filled(
        rect.shrink2(Vec2::new(1.0, 1.0)),
        CornerRadius {
            nw: 0,
            ne: 0,
            sw: (ctx.theme.control_radius + 1.0) as u8,
            se: (ctx.theme.control_radius + 1.0) as u8,
        },
        term_bg,
    );

    let body_resp = ui.interact(rect, ctx.id_salt.with("body"), Sense::click());

    // Render the lines inside a child UI so we can use ScrollArea.
    let mut child = ui.new_child(
        egui::UiBuilder::new()
            .max_rect(rect.shrink(8.0))
            .layout(egui::Layout::top_down(egui::Align::Min)),
    );
    child.spacing_mut().item_spacing.y = 2.0;

    // Scrollback labels are always selectable so drag-to-select works on
    // any pane, focused or not. To preserve click-to-focus on text (since
    // selectable labels consume clicks), we treat any label interaction
    // as a focus signal alongside the body's click.
    let mut label_interacted = false;
    egui::ScrollArea::vertical()
        .id_salt(ctx.id_salt.with("scroll"))
        .auto_shrink([false, false])
        .stick_to_bottom(true)
        .show(&mut child, |ui| {
            for line in &ctx.pane.lines {
                if paint_line(ui, line, palette, typo) {
                    label_interacted = true;
                }
            }
            if paint_live_prompt(ui, ctx, palette, typo) {
                label_interacted = true;
            }
        });

    body_resp.clicked() || label_interacted
}

/// Returns `true` if the rendered label was clicked or dragged (used by
/// the caller to focus the pane on any text interaction, since selectable
/// labels consume clicks that would otherwise reach the body).
fn paint_line(ui: &mut Ui, line: &TerminalLine, palette: &Palette, typo: &Typography) -> bool {
    let size = typo.small + 0.5;
    let font = FontId::monospace(size);
    let wrap_width = ui.available_width();

    match &line.kind {
        LineKind::Command {
            user,
            host,
            cwd,
            cmd,
        } => {
            let mut job = LayoutJob::default();
            // `LayoutJob`s don't wrap by default; constrain them to the
            // pane's current content width so long commands wrap like
            // output lines do. `break_anywhere` lets unbroken tokens
            // (URLs, paths, pasted blobs) wrap mid-character.
            job.wrap.max_width = wrap_width;
            job.wrap.break_anywhere = true;
            job.append(
                &format!("{user}@{host}"),
                0.0,
                TextFormat {
                    font_id: font.clone(),
                    color: palette.success,
                    ..Default::default()
                },
            );
            job.append(
                ":",
                0.0,
                TextFormat {
                    font_id: font.clone(),
                    color: palette.text_muted,
                    ..Default::default()
                },
            );
            job.append(
                cwd,
                0.0,
                TextFormat {
                    font_id: font.clone(),
                    color: palette.purple,
                    ..Default::default()
                },
            );
            job.append(
                "$ ",
                0.0,
                TextFormat {
                    font_id: font.clone(),
                    color: palette.text_muted,
                    ..Default::default()
                },
            );
            job.append(
                cmd,
                0.0,
                TextFormat {
                    font_id: font,
                    color: palette.text,
                    ..Default::default()
                },
            );
            let resp = ui.add(egui::Label::new(job).selectable(true));
            resp.clicked() || resp.dragged()
        }
        other => {
            let color = color_for_kind(other, palette);
            let italic = matches!(other, LineKind::Info);
            let rich = egui::RichText::new(&line.text).font(font).color(color);
            let rich = if italic { rich.italics() } else { rich };
            let resp = ui.add(egui::Label::new(rich).wrap().selectable(true));
            resp.clicked() || resp.dragged()
        }
    }
}

/// Returns `true` if the prompt's label was clicked or dragged (treated
/// like a scrollback-line interaction by the caller, so dragging on the
/// in-progress prompt selects text and focuses the pane).
fn paint_live_prompt(ui: &mut Ui, ctx: &PaneCtx<'_>, palette: &Palette, typo: &Typography) -> bool {
    let size = typo.small + 0.5;
    let font = FontId::monospace(size);
    let pane = ctx.pane;

    let mut job = LayoutJob::default();
    // Reserve space for the caret block at the end so the prompt wraps
    // before the caret falls off the right edge.
    job.wrap.max_width = (ui.available_width() - 10.0).max(40.0);
    // Typed text in a terminal is usually one unbroken token (no spaces),
    // so `break_anywhere` is required to wrap it mid-character. Without
    // this the pending buffer overflows past the pane's right edge.
    job.wrap.break_anywhere = true;
    job.append(
        &format!("{}@{}", pane.user, pane.host),
        0.0,
        TextFormat {
            font_id: font.clone(),
            color: palette.success,
            ..Default::default()
        },
    );
    job.append(
        ":",
        0.0,
        TextFormat {
            font_id: font.clone(),
            color: palette.text_muted,
            ..Default::default()
        },
    );
    job.append(
        &pane.cwd,
        0.0,
        TextFormat {
            font_id: font.clone(),
            color: palette.purple,
            ..Default::default()
        },
    );
    job.append(
        "$ ",
        0.0,
        TextFormat {
            font_id: font.clone(),
            color: palette.text_muted,
            ..Default::default()
        },
    );
    if !ctx.pending.is_empty() {
        job.append(
            ctx.pending,
            0.0,
            TextFormat {
                font_id: font.clone(),
                color: palette.sky,
                ..Default::default()
            },
        );
    }

    // Lay out the wrapped prompt (without a horizontal wrapper, whose
    // effectively-unbounded available width can override the job's wrap
    // cap) so we can ask the galley where the caret sits.
    let galley = ui.painter().layout_job(job);
    let caret_h = size + 2.0;
    let block_caret_w = 7.0;
    let total_size = Vec2::new(
        galley.size().x + block_caret_w + 2.0,
        galley.size().y.max(caret_h),
    );

    // Locate the caret. Galley positions are in character offsets, not
    // bytes, so convert the byte cursor through `chars().count()`. The
    // prefix is everything before the (possibly empty) pending insert.
    let prefix_chars = pane.user.chars().count()
        + 1 // '@'
        + pane.host.chars().count()
        + 1 // ':'
        + pane.cwd.chars().count()
        + 2; // '$ '
    let cursor_byte = ctx.pending_cursor.min(ctx.pending.len());
    let pending_chars_before = ctx.pending[..cursor_byte].chars().count();
    let caret_local = galley.pos_from_cursor(CCursor::new(prefix_chars + pending_chars_before));
    let cursor_at_end = ctx.pending_cursor >= ctx.pending.len();
    let caret_w = if cursor_at_end { block_caret_w } else { 2.0 };

    let galley_size = galley.size();

    // Reserve the full galley + caret-padding area in the parent layout,
    // then place a selectable label using the pre-laid-out galley so the
    // pending buffer is drag-selectable just like submitted scrollback.
    let (rect, _resp) = ui.allocate_exact_size(total_size, Sense::hover());
    let galley_origin = rect.min;
    let label_rect = Rect::from_min_size(galley_origin, galley_size);
    let resp = ui.put(label_rect, egui::Label::new(galley).selectable(true));

    let row_top = galley_origin.y + caret_local.top();
    let row_bottom = galley_origin.y + caret_local.bottom();
    let caret_y_center = (row_top + row_bottom) * 0.5;
    let caret_rect = Rect::from_min_size(
        Pos2::new(
            galley_origin.x + caret_local.left(),
            caret_y_center - caret_h * 0.5,
        ),
        Vec2::new(caret_w, caret_h),
    );
    let caret_color = if ctx.is_receiving {
        palette.sky
    } else {
        with_alpha(palette.text_faint, 80)
    };
    ui.painter()
        .rect_filled(caret_rect, CornerRadius::ZERO, caret_color);

    resp.clicked() || resp.dragged()
}

fn color_for_kind(kind: &LineKind, palette: &Palette) -> Color32 {
    match kind {
        LineKind::Out => palette.text,
        LineKind::Info => palette.text_faint,
        LineKind::Ok => palette.success,
        LineKind::Warn => palette.warning,
        LineKind::Err => palette.danger,
        LineKind::Dim => palette.text_muted,
        LineKind::Command { .. } => palette.text,
    }
}

fn summary_layout(
    text: &str,
    palette: &Palette,
    size: f32,
    color: Color32,
    max_width: f32,
) -> LayoutJob {
    let mut job = LayoutJob::default();
    job.wrap.max_width = max_width;
    job.wrap.max_rows = 1;
    job.wrap.break_anywhere = true;
    job.wrap.overflow_character = Some('\u{2026}');
    job.append(
        text,
        0.0,
        TextFormat {
            font_id: FontId::new(size, FontFamily::Proportional),
            color,
            ..Default::default()
        },
    );
    let _ = palette;
    job
}

// ---------------------------------------------------------------------------
// "All on" toggle button in the gridbar.
// ---------------------------------------------------------------------------

struct QaResult {
    clicked: bool,
}

#[allow(clippy::too_many_arguments)]
fn qa_button(
    ui: &mut Ui,
    bar_rect: Rect,
    x_right: &mut f32,
    id: Id,
    label: &str,
    shortcut: Option<&str>,
    active: bool,
    theme: &Theme,
) -> QaResult {
    let palette = &theme.palette;
    let typo = &theme.typography;
    let font = FontId::new(typo.small, FontFamily::Proportional);
    let label_galley = ui
        .painter()
        .layout_no_wrap(label.to_string(), font.clone(), palette.text);

    let kbd_font = FontId::monospace(typo.small - 1.5);
    let kbd_galley = shortcut.map(|s| {
        ui.painter()
            .layout_no_wrap(s.to_string(), kbd_font.clone(), palette.text_faint)
    });

    let icon_w = 16.0;
    let pad_x = 8.0;
    let label_w = label_galley.size().x;
    let kbd_w = kbd_galley.as_ref().map(|g| g.size().x + 8.0).unwrap_or(0.0);
    let btn_w = icon_w + 6.0 + label_w + kbd_w + pad_x * 2.0;
    let btn_h = bar_rect.height() - 10.0;
    let btn_rect = Rect::from_min_size(
        Pos2::new(*x_right - btn_w, bar_rect.center().y - btn_h * 0.5),
        Vec2::new(btn_w, btn_h),
    );
    *x_right = btn_rect.left() - 4.0;

    let resp = ui.interact(btn_rect, id, Sense::click());
    let hover = resp.hovered();

    let (fg, border, fill) = if active {
        (
            palette.sky,
            with_alpha(palette.sky, 110),
            with_alpha(palette.sky, 22),
        )
    } else if hover {
        (palette.text, palette.text_muted, Color32::TRANSPARENT)
    } else {
        (palette.text_muted, palette.border, Color32::TRANSPARENT)
    };

    ui.painter().rect(
        btn_rect,
        CornerRadius::same(theme.control_radius as u8),
        fill,
        Stroke::new(1.0, border),
        StrokeKind::Inside,
    );

    // Icon: 2x2 grid of small squares matching the pane-grid metaphor.
    let icon_center = Pos2::new(btn_rect.left() + pad_x + icon_w * 0.5, btn_rect.center().y);
    paint_grid_icon(ui.painter(), icon_center, fg);

    // Label.
    let label_x = btn_rect.left() + pad_x + icon_w + 6.0;
    let label_galley2 = ui
        .painter()
        .layout_no_wrap(label.to_string(), font.clone(), fg);
    ui.painter().galley(
        Pos2::new(label_x, btn_rect.center().y - label_galley2.size().y * 0.5),
        label_galley2,
        fg,
    );

    // Shortcut pill (right-aligned).
    if let Some(kbd) = shortcut {
        let kbd_galley2 =
            ui.painter()
                .layout_no_wrap(kbd.to_string(), kbd_font.clone(), palette.text_faint);
        let kbd_rect = Rect::from_min_size(
            Pos2::new(
                btn_rect.right() - pad_x - kbd_galley2.size().x - 8.0,
                btn_rect.center().y - (kbd_galley2.size().y + 2.0) * 0.5,
            ),
            Vec2::new(kbd_galley2.size().x + 8.0, kbd_galley2.size().y + 2.0),
        );
        ui.painter().rect(
            kbd_rect,
            CornerRadius::same(3),
            palette.input_bg,
            Stroke::new(1.0, palette.border),
            StrokeKind::Inside,
        );
        ui.painter().galley(
            Pos2::new(
                kbd_rect.left() + 4.0,
                kbd_rect.center().y - kbd_galley2.size().y * 0.5,
            ),
            kbd_galley2,
            palette.text_faint,
        );
    }

    QaResult {
        clicked: resp.clicked(),
    }
}

/// 2x2 grid glyph drawn at `center`. Used as the "All on" button's icon.
fn paint_grid_icon(painter: &egui::Painter, center: Pos2, color: Color32) {
    let pad = 1.0;
    let size = 5.5;
    for (dx, dy) in &[
        (-size - pad, -size - pad),
        (pad, -size - pad),
        (-size - pad, pad),
        (pad, pad),
    ] {
        let r = Rect::from_min_size(Pos2::new(center.x + dx, center.y + dy), Vec2::splat(size));
        painter.rect_stroke(
            r,
            CornerRadius::same(1),
            Stroke::new(1.2, color),
            StrokeKind::Inside,
        );
    }
}

#[derive(Clone, Copy)]
enum ModePillStyle {
    Single,
    Selected,
    All,
}

fn with_alpha(c: Color32, a: u8) -> Color32 {
    Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), a)
}