superlighttui 0.22.0

Super Light TUI - A lightweight, ergonomic terminal UI library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
//! SuperLightTUI — an immediate-mode flexbox-layout terminal UI library.
//!
//! Build a TUI as easily as a web page: write a closure, SLT calls it
//! every frame. State lives in your code; layout is described every
//! frame; styling uses Tailwind-inspired shorthand; focus and events are
//! threaded through a single [`Context`] parameter.
//!
//! See `docs/QUICK_START.md` for a 5-minute introduction and
//! `docs/DESIGN_PRINCIPLES.md` for the principles every public API
//! follows.
//!
//! # Example
//!
//! ```no_run
//! fn main() -> std::io::Result<()> {
//!     slt::run(|ui| {
//!         ui.text("hello, world");
//!     })
//! }
//! ```

// Safety: the shipping library is 100% safe. Unit tests are excused only
// because edition 2024 made `std::env::set_var`/`remove_var` `unsafe`, and a
// few `#[cfg(test)]` terminal-detection helpers must mutate process env (they
// serialize via a mutex). `forbid` stays on for every non-test build.
#![cfg_attr(not(test), forbid(unsafe_code))]
#![cfg_attr(test, deny(unsafe_code))]
// Cross-target lints (rustdoc links, rust-2018-idioms) are configured
// centrally in [workspace.lints] and applied via `[lints] workspace = true` in
// Cargo.toml. The lints below stay here as lib-only inner attributes on
// purpose: `[lints]` is package-scoped and would otherwise fire on the
// package's example binaries and integration tests, which legitimately expose
// undocumented `pub` helpers, print to stdout, and unwrap. The cfg-conditional
// unsafe_code policy above likewise can't live in workspace.lints.
#![warn(missing_docs)]
#![warn(unreachable_pub)]
#![deny(clippy::unwrap_in_result)]
#![warn(clippy::unwrap_used)]
#![warn(clippy::dbg_macro)]
#![warn(clippy::print_stdout)]
#![warn(clippy::print_stderr)]
#![cfg_attr(docsrs, feature(doc_cfg))]

//! # SLT — Super Light TUI
//!
//! Immediate-mode terminal UI for Rust. Small core. Zero `unsafe`.
//!
//! SLT gives you an egui-style API for terminals: your closure runs each frame,
//! you describe your UI, and SLT handles layout, diffing, and rendering.
//!
//! ## Quick Start
//!
//! ```no_run
//! fn main() -> std::io::Result<()> {
//!     slt::run(|ui| {
//!         ui.text("hello, world");
//!     })
//! }
//! ```
//!
//! ## Features
//!
//! - **Flexbox layout** — `row()`, `col()`, `gap()`, `grow()`
//! - **50+ built-in widgets** — input, textarea, table, list, tabs, button, checkbox, toggle, spinner, progress, toast, slider, separator, help bar, scrollable, chart, bar chart, stacked bar chart, sparkline, histogram, heatmap, treemap, candlestick, canvas, grid, select, radio, multi-select, tree, virtual list, command palette, markdown, alert, badge, stat, breadcrumb, accordion, code block, big text, image, modal, tooltip, form, calendar, file picker, qr code
//! - **Styling** — bold, italic, dim, underline, 256 colors, RGB
//! - **Mouse** — click, hover, drag-to-scroll
//! - **Focus** — automatic Tab/Shift+Tab cycling
//! - **Theming** — 10 presets, semantic tokens (`ThemeColor`), spacing scale, contrast helpers
//! - **Animation** — tween and spring primitives with 9 easing functions
//! - **Inline mode** — render below your prompt, no alternate screen
//! - **Async** — optional tokio integration via `async` feature
//! - **Layout debugger** — F12 to visualize container bounds
//!
//! ## Feature Flags
//!
//! | Flag | Description |
//! |------|-------------|
//! | `crossterm` | Built-in terminal runtime (`run`, `run_inline`, clipboard query helpers). Enabled by default. |
//! | `bidi` | Reorder right-to-left text (Hebrew, Arabic, …) to visual order per UAX #9 before rendering. Enabled by default; pure-LTR text takes a zero-cost fast path. Since 0.21.0. |
//! | `async` | Enable `run_async()` with tokio channel-based message passing |
//! | `serde` | Enable Serialize/Deserialize for Style, Color, Theme, and layout types |
//! | `image` | Enable image-loading helpers for terminal image widgets |
//! | `qrcode` | Enable `ui.qr_code(...)` |
//! | `syntax` / `syntax-*` | Enable tree-sitter syntax highlighting |
//!
//! ## Learn More
//!
//! - Guides index: <https://github.com/subinium/SuperLightTUI/blob/main/docs/README.md>
//! - Quick start: <https://github.com/subinium/SuperLightTUI/blob/main/docs/QUICK_START.md>
//! - Backends and run loops: <https://github.com/subinium/SuperLightTUI/blob/main/docs/BACKENDS.md>
//! - Testing: <https://github.com/subinium/SuperLightTUI/blob/main/docs/TESTING.md>
//! - Debugging: <https://github.com/subinium/SuperLightTUI/blob/main/docs/DEBUGGING.md>

/// Animation primitives: tween, spring, keyframes, sequence, stagger.
pub mod anim;
/// Double-buffered cell grid with clip stack and diff tracking.
pub mod buffer;
/// Terminal cell representation.
pub mod cell;
/// Chart and data visualization widgets.
pub mod chart;
/// UI context, container builder, and widget rendering.
pub mod context;
/// Input events (keyboard, mouse, resize, paste).
pub mod event;
/// Half-block image rendering.
pub mod halfblock;
#[cfg(feature = "crossterm")]
mod iterm;
/// Keyboard shortcut mapping.
pub mod keymap;
/// Flexbox layout engine and command tree.
pub mod layout;
/// Color palettes (Tailwind-style).
pub mod palette;
/// Rectangular region type used throughout SLT layout.
pub mod rect;
#[cfg(feature = "crossterm")]
mod sixel;
/// Styling: colors, borders, padding, margins, themes, constraints.
pub mod style;
/// Tree-sitter syntax highlighting integration.
pub mod syntax;
#[cfg(feature = "crossterm")]
mod terminal;
/// Headless test utilities for unit-testing TUI closures.
pub mod test_utils;
/// Widget state types (list, table, input, select, etc.).
pub mod widgets;

use std::io;
#[cfg(feature = "crossterm")]
use std::io::IsTerminal;
#[cfg(feature = "crossterm")]
use std::io::Write;
#[cfg(feature = "crossterm")]
use std::sync::Once;
use std::time::{Duration, Instant};

#[doc(hidden)]
pub use layout::__bench_dim_buffer_around;
#[doc(hidden)]
pub use layout::__bench_wrap_segments;
#[cfg(feature = "crossterm")]
#[doc(hidden)]
pub use terminal::__bench_flush_buffer_diff;
#[cfg(feature = "crossterm")]
#[doc(hidden)]
pub use terminal::__bench_flush_buffer_diff_mut;
#[cfg(feature = "crossterm")]
#[doc(hidden)]
pub use terminal::__bench_flush_buffer_diff_mut_with_buf;
#[cfg(feature = "crossterm")]
#[doc(hidden)]
pub use terminal::__bench_flush_kitty;
#[cfg(feature = "crossterm")]
#[doc(hidden)]
pub use terminal::{__BenchKittyFixture, __bench_new_kitty_fixture};
#[cfg(feature = "crossterm")]
#[doc(hidden)]
pub use terminal::{__BenchSprixelFixture, __bench_flush_sprixels, __bench_new_sprixel_fixture};
/// Runtime terminal capability probe (issue #264): read-only [`Capabilities`]
/// snapshot plus the [`Blitter`] ladder it drives. Diagnostics-only — image
/// rendering routes through the ladder automatically.
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub use terminal::{Blitter, BlitterSupport, Capabilities, capabilities};
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub use terminal::{ColorScheme, detect_color_scheme, read_clipboard};
#[cfg(feature = "crossterm")]
use terminal::{InlineTerminal, Terminal};

pub use crate::test_utils::{EventBuilder, FrameRecord, TestBackend, TestSequence};
/// PTY/sink test harness for end-to-end escape-byte assertions (issue #274).
/// Gated behind the dev-only `pty-test` feature; absent from default builds.
#[cfg(feature = "pty-test")]
#[cfg_attr(docsrs, doc(cfg(feature = "pty-test")))]
pub use crate::test_utils::{PtyBackend, PtyFrame};
// Animation primitives (builder types) are re-exported at crate root for
// ergonomic `use slt::{Tween, Spring, ...}`. The easing functions and `lerp`
// live under `slt::anim::*` — they are rarely imported in isolation and
// keeping them out of the root shrinks the top-level surface.
pub use anim::{Keyframes, LoopMode, Sequence, Spring, Stagger, Tween};
pub use buffer::Buffer;
pub use cell::Cell;
// Chart user-facing types at crate root; internals (`ChartRenderer`,
// `RenderedLine`, `ColorSpan`, `DatasetEntry`, `HistogramBuilder`,
// `GraphType`, `Axis`) live under `slt::chart::*`.
pub use chart::{Candle, ChartBuilder, ChartConfig, Dataset, LegendPosition, Marker};
pub use context::{
    Anchor, Bar, BarChartConfig, BarDirection, BarGroup, Breadcrumb, CanvasContext, CodeBlock,
    ContainerBuilder, Context, Gauge, GutterOpts, LineGauge, Memo, Response, State, TreemapItem,
    Widget,
};
// Issue #234: opaque handle from `Context::spawn`, gated behind `async`.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use context::TaskHandle;
pub use event::{
    Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, ModifierKey, MouseButton, MouseEvent,
    MouseKind,
};
pub use halfblock::HalfBlockImage;
pub use keymap::{Binding, KeyMap, PublishedKeymap, WidgetKeyHelp};
pub use layout::Direction;
pub use palette::Palette;
pub use rect::Rect;
#[cfg(feature = "theme-watch")]
#[cfg_attr(docsrs, doc(cfg(feature = "theme-watch")))]
pub use style::ThemeWatcher;
pub use style::{
    Align, Border, BorderSides, Breakpoint, Color, ColorDepth, ColorParseError, Constraints,
    ContainerStyle, HeightSpec, Justify, Margin, Modifiers, Padding, Spacing, Style, SyntaxPalette,
    Theme, ThemeBuilder, ThemeColor, UnderlineStyle, WidgetColors, WidgetTheme, WidthSpec,
};
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub use style::{ThemeFile, ThemeLoadError};
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use widgets::AsyncValidation;
pub use widgets::validators;
pub use widgets::{
    AlertLevel, ApprovalAction, BreadcrumbResponse, ButtonVariant, CalDate, CalendarSelect,
    CalendarState, ChordState, ColorPickerState, CommandPaletteState, ContextItem,
    DEFAULT_CHORD_TIMEOUT_TICKS, DirectoryTreeState, FileEntry, FilePickerState, FormField,
    FormState, GaugeResponse, GridColumn, GutterResponse, HighlightRange, ListResponse, ListState,
    ModeState, MultiSelectState, NumberInputState, PaginatorState, PaginatorStyle, PaletteCommand,
    PickerMode, RadioState, RichLogEntry, RichLogState, SchedulerState, ScreenState, ScrollState,
    SelectState, SpinnerPreset, SpinnerState, SplitPaneResponse, SplitPaneState, StaticOutput,
    StreamingMarkdownState, StreamingTextState, TableColumn, TableState, TabsState, TextInputState,
    TextareaState, ToastLevel, ToastMessage, ToastState, ToolApprovalState, TreeNode, TreeState,
    Trend, ValidateTrigger, Validator,
};

/// Rendering backend for SLT.
///
/// Implement this trait to render SLT UIs to custom targets — alternative
/// terminals, GUI embeds, test harnesses, WASM canvas, etc.
///
/// The built-in terminal backend ([`run()`], [`run_with()`]) handles setup,
/// teardown, and event polling automatically. For custom backends, pair this
/// trait with [`AppState`] and [`frame()`] to drive the render loop yourself.
///
/// # Example
///
/// ```ignore
/// use slt::{Backend, AppState, Buffer, Rect, RunConfig, Context, Event};
///
/// struct MyBackend {
///     buffer: Buffer,
/// }
///
/// impl Backend for MyBackend {
///     fn size(&self) -> (u32, u32) {
///         (self.buffer.area.width, self.buffer.area.height)
///     }
///     fn buffer_mut(&mut self) -> &mut Buffer {
///         &mut self.buffer
///     }
///     fn flush(&mut self) -> std::io::Result<()> {
///         // Render self.buffer to your target
///         Ok(())
///     }
/// }
///
/// fn main() -> std::io::Result<()> {
///     let mut backend = MyBackend {
///         buffer: Buffer::empty(Rect::new(0, 0, 80, 24)),
///     };
///     let mut state = AppState::new();
///     let config = RunConfig::default();
///
///     loop {
///         let events: Vec<Event> = vec![]; // Collect your own events
///         if !slt::frame(&mut backend, &mut state, &config, &events, &mut |ui| {
///             ui.text("Hello from custom backend!");
///         })? {
///             break;
///         }
///     }
///     Ok(())
/// }
/// ```
pub trait Backend {
    /// Returns the current display size as `(width, height)` in cells.
    fn size(&self) -> (u32, u32);

    /// Returns a mutable reference to the display buffer.
    ///
    /// SLT writes the UI into this buffer each frame. After [`frame()`]
    /// returns, call [`flush()`](Backend::flush) to present the result.
    fn buffer_mut(&mut self) -> &mut Buffer;

    /// Flush the buffer contents to the display.
    ///
    /// Called automatically at the end of each [`frame()`] call. Implementations
    /// should present the current buffer to the user — by writing ANSI escapes,
    /// drawing to a canvas, updating a texture, etc.
    fn flush(&mut self) -> io::Result<()>;
}

/// Opaque per-session state that persists between frames.
///
/// Tracks focus, scroll positions, hook state, and other frame-to-frame data.
/// Create with [`AppState::new()`] and pass to [`frame()`] each iteration.
///
/// # Example
///
/// ```ignore
/// let mut state = slt::AppState::new();
/// // state is passed to slt::frame() in your render loop
/// ```
pub struct AppState {
    pub(crate) inner: FrameState,
}

impl AppState {
    /// Create a new empty application state.
    pub fn new() -> Self {
        Self {
            inner: FrameState::default(),
        }
    }

    /// Returns the current frame tick count (increments each frame).
    pub fn tick(&self) -> u64 {
        self.inner.diagnostics.tick
    }

    /// Returns the smoothed FPS estimate (exponential moving average).
    pub fn fps(&self) -> f32 {
        self.inner.diagnostics.fps_ema
    }

    /// Toggle the debug overlay (same as pressing F12).
    pub fn set_debug(&mut self, enabled: bool) {
        self.inner.diagnostics.debug_mode = enabled;
    }
}

impl Default for AppState {
    fn default() -> Self {
        Self::new()
    }
}

/// Process a single UI frame with a custom [`Backend`].
///
/// This is the low-level entry point for custom backends. For standard terminal
/// usage, prefer [`run()`] or [`run_with()`] which handle the event loop,
/// terminal setup, and teardown automatically.
///
/// Returns `Ok(true)` to continue, `Ok(false)` when [`Context::quit()`] was
/// called.
///
/// # Arguments
///
/// * `backend` — Your [`Backend`] implementation
/// * `state` — Persistent [`AppState`] (reuse across frames)
/// * `config` — [`RunConfig`] (theme, tick rate, etc.)
/// * `events` — Input events for this frame (keyboard, mouse, resize)
/// * `f` — Your UI closure, called once per frame
///
/// Build a fresh event slice each frame in your outer loop, then pass it here.
/// `frame()` reads from that slice but does not own your event source.
/// Reuse the same [`AppState`] for the lifetime of the session.
///
/// # Example
///
/// ```ignore
/// let keep_going = slt::frame(
///     &mut my_backend,
///     &mut state,
///     &config,
///     &events,
///     &mut |ui| { ui.text("hello"); },
/// )?;
/// ```
pub fn frame(
    backend: &mut impl Backend,
    state: &mut AppState,
    config: &RunConfig,
    events: &[Event],
    f: &mut impl FnMut(&mut Context),
) -> io::Result<bool> {
    frame_owned(backend, state, config, events.to_vec(), f)
}

/// Process a single UI frame, taking ownership of the events `Vec` (zero-copy).
///
/// Like [`frame`], but accepts an owned `Vec<Event>` to avoid the `to_vec()`
/// copy `frame` performs internally. Prefer this in high-frequency custom
/// render loops where you already own the event buffer.
///
/// # Example
///
/// ```ignore
/// let events: Vec<slt::Event> = collect_events();
/// let keep_going = slt::frame_owned(
///     &mut my_backend,
///     &mut state,
///     &config,
///     events,
///     &mut |ui| { ui.text("hello"); },
/// )?;
/// ```
pub fn frame_owned(
    backend: &mut impl Backend,
    state: &mut AppState,
    config: &RunConfig,
    events: Vec<Event>,
    f: &mut impl FnMut(&mut Context),
) -> io::Result<bool> {
    run_frame(backend, &mut state.inner, config, events, f)
}

#[cfg(feature = "crossterm")]
static PANIC_HOOK_ONCE: Once = Once::new();

#[allow(clippy::print_stderr)]
#[cfg(feature = "crossterm")]
fn install_panic_hook() {
    PANIC_HOOK_ONCE.call_once(|| {
        let original = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |panic_info| {
            let _ = crossterm::terminal::disable_raw_mode();
            let mut stdout = io::stdout();
            let _ = crossterm::execute!(
                stdout,
                crossterm::terminal::LeaveAlternateScreen,
                crossterm::cursor::Show,
                crossterm::event::DisableMouseCapture,
                crossterm::event::DisableBracketedPaste,
                crossterm::style::ResetColor,
                crossterm::style::SetAttribute(crossterm::style::Attribute::Reset)
            );

            // Print friendly panic header
            eprintln!("\n\x1b[1;31m━━━ SLT Panic ━━━\x1b[0m\n");

            // Print location if available
            if let Some(location) = panic_info.location() {
                eprintln!(
                    "\x1b[90m{}:{}:{}\x1b[0m",
                    location.file(),
                    location.line(),
                    location.column()
                );
            }

            // Print message
            if let Some(msg) = panic_info.payload().downcast_ref::<&str>() {
                eprintln!("\x1b[1m{}\x1b[0m", msg);
            } else if let Some(msg) = panic_info.payload().downcast_ref::<String>() {
                eprintln!("\x1b[1m{}\x1b[0m", msg);
            }

            eprintln!(
                "\n\x1b[90mTerminal state restored. Report bugs at https://github.com/subinium/SuperLightTUI/issues\x1b[0m\n"
            );

            original(panic_info);
        }));
    });
}

/// RAII guard owning the unix suspend/resume (`SIGTSTP`/`SIGCONT`) handler
/// thread for the duration of a run loop (issue #263).
///
/// Dropping the guard closes the `signal-hook` registration so the background
/// thread breaks out of `Signals::forever()` and is joined, leaving no signal
/// handlers installed after the loop exits.
#[cfg(all(feature = "crossterm", unix))]
struct SuspendGuard {
    handle: signal_hook::iterator::Handle,
    thread: Option<std::thread::JoinHandle<()>>,
}

#[cfg(all(feature = "crossterm", unix))]
impl Drop for SuspendGuard {
    fn drop(&mut self) {
        // Closing the handle wakes `Signals::forever()` so the thread returns.
        self.handle.close();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

/// Install the unix job-control suspend/resume handler for one run loop.
///
/// Spawns a `signal-hook` background thread that, on `SIGTSTP`, restores the
/// terminal and re-raises the default-disposition stop, and on `SIGCONT`
/// re-enters the session and flags a full redraw. Uses only signal-hook's safe
/// API, preserving `#![forbid(unsafe_code)]`. Returns the guard that owns the
/// thread; dropping it uninstalls the handler.
#[cfg(all(feature = "crossterm", unix))]
fn install_suspend_handler(snapshot: terminal::SessionSnapshot) -> io::Result<SuspendGuard> {
    use signal_hook::consts::{SIGCONT, SIGTSTP};
    use signal_hook::iterator::Signals;

    let mut signals = Signals::new([SIGTSTP, SIGCONT])?;
    let handle = signals.handle();
    let thread = std::thread::Builder::new()
        .name("slt-suspend".to_string())
        .spawn(move || {
            // `has_terminal` tracks whether the TUI session is currently
            // entered, so a stray SIGCONT (no prior SIGTSTP) or a repeated
            // SIGTSTP cannot double-leave / double-enter (idempotency).
            let mut has_terminal = true;
            for signal in &mut signals {
                match signal {
                    SIGTSTP if has_terminal => {
                        terminal::suspend_to_shell(&snapshot);
                        has_terminal = false;
                        // Genuinely stop the process now that the terminal is
                        // restored; control returns to the shell.
                        let _ = signal_hook::low_level::emulate_default_handler(SIGTSTP);
                    }
                    SIGCONT if !has_terminal => {
                        terminal::resume_from_shell(&snapshot);
                        has_terminal = true;
                    }
                    // Repeated SIGTSTP/SIGCONT or out-of-order delivery is a
                    // no-op — the `has_terminal` guard keeps enter/leave
                    // balanced (idempotency, issue #263).
                    _ => {}
                }
            }
        })?;

    Ok(SuspendGuard {
        handle,
        thread: Some(thread),
    })
}

/// Consume the pending full-redraw request raised by a `SIGCONT` resume and, if
/// set, clear + repaint the whole frame (issue #263).
///
/// Called at the top of each run-loop iteration. No-op on non-unix builds.
#[cfg(all(feature = "crossterm", unix))]
fn drain_resume_redraw(handle_resize: &mut impl FnMut() -> io::Result<()>) -> io::Result<()> {
    use std::sync::atomic::Ordering;
    if terminal::NEEDS_FULL_REDRAW.swap(false, Ordering::SeqCst) {
        handle_resize()?;
    }
    Ok(())
}

/// Configuration for a TUI run loop.
///
/// Pass to [`run_with`] or [`run_inline_with`] to customize behavior.
/// Use [`Default::default()`] for sensible defaults (16ms tick / 60fps, no mouse, dark theme).
/// This type is `#[non_exhaustive]`, so prefer builder methods instead of struct literals.
///
/// # Example
///
/// ```no_run
/// use slt::{RunConfig, Theme};
/// use std::time::Duration;
///
/// let config = RunConfig::default()
///     .tick_rate(Duration::from_millis(50))
///     .mouse(true)
///     .theme(Theme::light())
///     .max_fps(60);
/// ```
#[non_exhaustive]
#[must_use = "configure loop behavior before passing to run_with or run_inline_with"]
pub struct RunConfig {
    /// How long to wait for input before triggering a tick with no events.
    ///
    /// Lower values give smoother animations at the cost of more CPU usage.
    /// Defaults to 16ms (60fps).
    pub tick_rate: Duration,
    /// Whether to enable mouse event reporting.
    ///
    /// When `true`, the terminal captures mouse clicks, scrolls, and movement.
    /// Defaults to `false`.
    pub mouse: bool,
    /// Whether to enable the Kitty keyboard protocol for enhanced input.
    ///
    /// When `true`, enables disambiguated key events, key release events,
    /// and modifier-only key reporting on supporting terminals (kitty, Ghostty, WezTerm).
    /// Terminals that don't support it silently ignore the request.
    /// Defaults to `false`.
    pub kitty_keyboard: bool,
    /// Whether to request modifier-only key events (bare Ctrl/Shift/Alt/Super
    /// presses and releases, with no accompanying character).
    ///
    /// Has **no effect** unless [`kitty_keyboard`](Self::kitty_keyboard) is also
    /// `true`: it OR-es the Kitty `REPORT_ALL_KEYS_AS_ESCAPE_CODES`
    /// progressive-enhancement flag into the pushed flag set. On supporting
    /// terminals (kitty, Ghostty, WezTerm) this makes bare modifier presses
    /// arrive as [`KeyCode::Modifier`] events; other terminals never emit them.
    ///
    /// Kept opt-in to avoid flooding apps with modifier events they don't want.
    /// Defaults to `false`.
    ///
    /// Since 0.21.0.
    pub report_all_keys: bool,
    /// The color theme applied to all widgets automatically.
    ///
    /// Defaults to [`Theme::dark()`].
    pub theme: Theme,
    /// Color depth override.
    ///
    /// `None` means auto-detect from `$COLORTERM` and `$TERM` environment
    /// variables. Set explicitly to force a specific color depth regardless
    /// of terminal capabilities.
    pub color_depth: Option<ColorDepth>,
    /// Optional maximum frame rate.
    ///
    /// `None` means unlimited frame rate. `Some(fps)` sleeps at the end of each
    /// loop iteration to target that frame time.
    pub max_fps: Option<u32>,
    /// Lines scrolled per mouse scroll event. Defaults to 1.
    pub scroll_speed: u32,
    /// Optional terminal window title (set via OSC 2).
    pub title: Option<String>,
    /// Default colors applied to all instances of each widget type.
    ///
    /// Per-callsite `_colored()` overrides still take precedence.
    /// Defaults to all-`None` (use theme colors).
    pub widget_theme: style::WidgetTheme,
    /// Whether the runtime intercepts Ctrl+C and exits the loop cleanly.
    ///
    /// When `true` (the default), Ctrl+C is treated as a quit signal —
    /// matching the v0.19 behavior. When `false`, the Ctrl+C key event flows
    /// through to the frame closure as a regular [`Event::Key`], matching
    /// RataTUI's raw-mode semantics. The user is then responsible for
    /// deciding whether to call [`Context::quit`] or treat it as any other
    /// shortcut (e.g. clear input, cancel current operation).
    ///
    /// Set this to `false` when migrating code from RataTUI that already
    /// handles Ctrl+C explicitly, or when implementing a graceful-shutdown
    /// prompt (e.g. "save unsaved changes?").
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use slt::{KeyCode, KeyModifiers, RunConfig};
    /// slt::run_with(RunConfig::default().handle_ctrl_c(false), |ui| {
    ///     // Ctrl+C now reaches your closure as a normal key event.
    ///     if ui.key_mod('c', KeyModifiers::CONTROL) {
    ///         // Decide what to do — clear input, prompt to save, quit, etc.
    ///         ui.quit();
    ///     }
    /// }).unwrap();
    /// ```
    pub handle_ctrl_c: bool,
    /// Whether the runtime restores the terminal on Ctrl+Z (`SIGTSTP`) and
    /// re-enters it on resume (`SIGCONT`).
    ///
    /// When `true` (the default) on Unix, pressing Ctrl+Z runs the full
    /// session teardown — leave the alternate screen (fullscreen only), show
    /// the cursor, disable raw mode / bracketed paste / focus / mouse / kitty
    /// — *before* the process is suspended, so the shell prompt returns to a
    /// clean terminal. Resuming with `fg` re-enters the same session and forces
    /// a full redraw. This matches helix/zellij/bubbletea job-control behavior.
    ///
    /// When `false`, no signal handler is installed and Ctrl+Z falls through to
    /// crossterm as a regular key event in raw mode (the pre-0.21 behavior).
    ///
    /// Unix only; ignored on Windows, WASM, and non-`crossterm` builds where
    /// there is no `SIGTSTP`. Defaults to `true`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use slt::RunConfig;
    /// // Opt out: let Ctrl+Z reach the frame closure as a key event.
    /// let cfg = RunConfig::default().handle_suspend(false);
    /// assert!(!cfg.handle_suspend);
    /// ```
    pub handle_suspend: bool,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            tick_rate: Duration::from_millis(16),
            mouse: false,
            kitty_keyboard: false,
            report_all_keys: false,
            theme: Theme::dark(),
            color_depth: None,
            max_fps: Some(60),
            scroll_speed: 1,
            title: None,
            widget_theme: style::WidgetTheme::new(),
            handle_ctrl_c: true,
            handle_suspend: true,
        }
    }
}

impl RunConfig {
    /// Set the tick rate (input polling interval).
    pub fn tick_rate(mut self, rate: Duration) -> Self {
        self.tick_rate = rate;
        self
    }

    /// Enable or disable mouse event reporting.
    pub fn mouse(mut self, enabled: bool) -> Self {
        self.mouse = enabled;
        self
    }

    /// Enable or disable Kitty keyboard protocol.
    pub fn kitty_keyboard(mut self, enabled: bool) -> Self {
        self.kitty_keyboard = enabled;
        self
    }

    /// Enable or disable modifier-only key reporting (Kitty
    /// `REPORT_ALL_KEYS_AS_ESCAPE_CODES`).
    ///
    /// Requires [`kitty_keyboard(true)`](Self::kitty_keyboard) to have any
    /// effect. When enabled on a supporting terminal, bare modifier presses
    /// and releases arrive as [`KeyCode::Modifier`] events. Defaults to
    /// `false`.
    ///
    /// Since 0.21.0.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use slt::RunConfig;
    /// let cfg = RunConfig::default().kitty_keyboard(true).report_all_keys(true);
    /// assert!(cfg.report_all_keys);
    /// ```
    pub fn report_all_keys(mut self, enabled: bool) -> Self {
        self.report_all_keys = enabled;
        self
    }

    /// Set the color theme.
    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = theme;
        self
    }

    /// Override the color depth.
    pub fn color_depth(mut self, depth: ColorDepth) -> Self {
        self.color_depth = Some(depth);
        self
    }

    /// Set the maximum frame rate.
    pub fn max_fps(mut self, fps: u32) -> Self {
        self.max_fps = Some(fps);
        self
    }

    /// Disable the frame rate cap (unlimited FPS).
    ///
    /// By default, [`RunConfig`] caps rendering at 60 fps. Call this to remove
    /// the cap entirely — useful when controlling external sleep/vsync.
    ///
    /// # Example
    ///
    /// ```no_run
    /// slt::run_with(
    ///     slt::RunConfig::default().no_fps_cap(),
    ///     |ui| { ui.text("uncapped"); },
    /// ).unwrap();
    /// ```
    pub fn no_fps_cap(mut self) -> Self {
        self.max_fps = None;
        self
    }

    /// Set the scroll speed (lines per scroll event).
    pub fn scroll_speed(mut self, lines: u32) -> Self {
        self.scroll_speed = lines.max(1);
        self
    }

    /// Set the terminal window title.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set default widget colors for all widget types.
    pub fn widget_theme(mut self, widget_theme: style::WidgetTheme) -> Self {
        self.widget_theme = widget_theme;
        self
    }

    /// Configure whether the runtime auto-exits on Ctrl+C.
    ///
    /// Defaults to `true` (current v0.19 behavior). Set to `false` to
    /// receive Ctrl+C as a regular [`Event::Key`] inside the frame closure
    /// — see [`RunConfig::handle_ctrl_c`] for the full migration story.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use slt::RunConfig;
    /// let cfg = RunConfig::default().handle_ctrl_c(false);
    /// assert!(!cfg.handle_ctrl_c);
    /// ```
    pub fn handle_ctrl_c(mut self, enabled: bool) -> Self {
        self.handle_ctrl_c = enabled;
        self
    }

    /// Configure whether the runtime restores the terminal on Ctrl+Z
    /// (`SIGTSTP`) and re-enters it on resume (`SIGCONT`).
    ///
    /// Defaults to `true`. Set to `false` to disable the suspend handler so
    /// Ctrl+Z falls through to crossterm as a regular key event — see
    /// [`RunConfig::handle_suspend`] for the full behavior. Unix only; ignored
    /// elsewhere.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use slt::RunConfig;
    /// let cfg = RunConfig::default().handle_suspend(false);
    /// assert!(!cfg.handle_suspend);
    /// ```
    pub fn handle_suspend(mut self, enabled: bool) -> Self {
        self.handle_suspend = enabled;
        self
    }
}

#[derive(Default)]
pub(crate) struct FocusState {
    pub focus_index: usize,
    pub prev_focus_count: usize,
    pub prev_modal_active: bool,
    pub prev_modal_focus_start: usize,
    pub prev_modal_focus_count: usize,
    /// Issue #208: focus index at the end of the previous frame. `None` on
    /// the first frame so widgets do not falsely report `gained_focus`.
    pub prev_focus_index: Option<usize>,
    /// Issue #217: persisted `name → focus_index` map from the most recent
    /// completed frame. Used at frame start to resolve a pending
    /// `focus_by_name(...)` against the previous render's registrations.
    pub focus_name_map_prev: std::collections::HashMap<String, usize>,
    /// Issue #217: a name passed to `focus_by_name(...)` that has not yet
    /// been resolved. Consumed once the matching registration is found in
    /// `focus_name_map_prev`.
    pub pending_focus_name: Option<String>,
}

/// v0.21.1: maximum gap between two same-cell left clicks for them to count as
/// a double-click. Tuned to the common desktop default (~400ms).
pub(crate) const DOUBLE_CLICK_WINDOW: std::time::Duration = std::time::Duration::from_millis(400);

#[derive(Default)]
pub(crate) struct LayoutFeedbackState {
    /// `(content_extent, viewport_extent, is_horizontal)` per scrollable last
    /// frame (#247). `is_horizontal` selects which `ScrollState` axis the
    /// `scrollable` binding updates.
    pub prev_scroll_infos: Vec<(u32, u32, bool)>,
    pub prev_scroll_rects: Vec<rect::Rect>,
    pub prev_hit_map: Vec<rect::Rect>,
    pub prev_group_rects: Vec<(std::sync::Arc<str>, rect::Rect)>,
    pub prev_content_map: Vec<(rect::Rect, rect::Rect)>,
    pub prev_focus_rects: Vec<(usize, rect::Rect)>,
    pub prev_focus_groups: Vec<Option<std::sync::Arc<str>>>,
    pub last_mouse_pos: Option<(u32, u32)>,
    /// v0.21.1: wall-clock time of the previous left-click `Down`, used to
    /// detect a double-click (a second click on the same cell within
    /// `DOUBLE_CLICK_WINDOW`, ~400ms). `None` after a double-click fires (so a
    /// triple click is not double-counted) or when no click has occurred.
    pub last_click_at: Option<std::time::Instant>,
    /// v0.21.1: cell position of the previous left-click `Down`, paired with
    /// `last_click_at` for same-cell double-click detection.
    pub last_click_pos: Option<(u32, u32)>,
}

#[derive(Default)]
pub(crate) struct DiagnosticsState {
    pub tick: u64,
    pub notification_queue: Vec<(String, ToastLevel, u64)>,
    pub debug_mode: bool,
    pub debug_layer: DebugLayer,
    /// Issue #268: whether the devtools inspector panel (Ctrl+F12) is active.
    /// Independent of `debug_mode`/`debug_layer`. Round-trips through
    /// `Context::inspector_mode` like `debug_layer` so `set_inspector` persists.
    pub inspector_mode: bool,
    pub fps_ema: f32,
}

/// Which layers the F12 debug overlay should outline (issue #201).
///
/// `All` (the default) outlines both the base layer and any active
/// overlays/modals — matching the user's expectation for "show everything
/// the renderer is producing this frame." `TopMost` only outlines the
/// topmost overlay (or the base if no overlay is active), and `BaseOnly`
/// keeps the legacy pre-fix behavior of skipping overlays entirely.
///
/// At runtime, **Shift+F12** cycles `All → TopMost → BaseOnly → All` so a
/// developer debugging a stacked modal can shrink the visible outlines to
/// just the layer they care about without leaving the keyboard. Plain
/// **F12** independently toggles the overlay on/off.
///
/// # Example
///
/// ```no_run
/// use slt::{Context, DebugLayer};
///
/// slt::run(|ui: &mut Context| {
///     // Match on the current layer to drive bespoke debug UI.
///     let label = match ui.debug_layer() {
///         DebugLayer::All => "showing base + overlays",
///         DebugLayer::TopMost => "showing topmost overlay only",
///         DebugLayer::BaseOnly => "showing base layer only",
///     };
///     ui.text(label);
/// })
/// .unwrap();
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DebugLayer {
    /// Outline both the base tree and every active overlay/modal.
    ///
    /// Default. Matches the reporter expectation that F12 reflects
    /// everything the renderer is producing this frame. Each layer family
    /// gets its own hue so a glance distinguishes base, overlay, and modal
    /// containers.
    #[default]
    All,
    /// Outline only the topmost overlay (or the base if no overlay is
    /// active).
    ///
    /// Useful when modals or popovers stack and you only care about the
    /// active dialog — base-tree outlines become noise underneath an open
    /// modal.
    TopMost,
    /// Outline only the base layer (legacy v0.19.x behavior).
    ///
    /// Skips overlays and modals entirely. Use when an overlay is
    /// confirmed correct and you want to inspect the base layout
    /// underneath it.
    BaseOnly,
}

/// Type alias matching `context::core::RawDrawCallback` (private over there);
/// used inside `FrameState` for the recycled-Vec field for issue #204. Kept
/// in lib.rs to avoid leaking a public type alias.
pub(crate) type FrameDeferredDrawSlot =
    Option<Box<dyn FnOnce(&mut crate::buffer::Buffer, crate::rect::Rect)>>;

#[derive(Default)]
pub(crate) struct FrameState {
    pub hook_states: Vec<Box<dyn std::any::Any>>,
    pub named_states: std::collections::HashMap<&'static str, Box<dyn std::any::Any>>,
    /// Issue #215: runtime-string-keyed parallel of `named_states`. Persisted
    /// across frames; survives panics inside `error_boundary` (matching the
    /// `named_states` policy).
    pub keyed_states: std::collections::HashMap<String, Box<dyn std::any::Any>>,
    /// Issue #262: cross-frame partial-chord buffer for [`Context::key_chord`].
    /// Round-trips across frames using the same `std::mem::take` out/in policy
    /// as `keyed_states` (moved out in `Context::new`, restored at frame end in
    /// `run_frame_kernel`).
    pub chord_states: widgets::ChordState,
    /// Issue #248: persistent frame-clock timer table. Round-tripped through
    /// `Context` exactly like `named_states` — moved out at frame start, moved
    /// back at frame end where untouched slots are garbage-collected.
    pub scheduler: widgets::SchedulerState,
    /// Issue #234: persistent async task registry backing `Context::spawn` /
    /// `Context::poll`. Round-tripped through `Context` exactly like
    /// `scheduler` — moved out at frame start, moved back at frame end. Gated
    /// behind `async`; absent (zero overhead) when the feature is off.
    #[cfg(feature = "async")]
    pub async_tasks: context::AsyncTasks,
    pub screen_hook_map: std::collections::HashMap<String, (usize, usize)>,
    pub focus: FocusState,
    pub layout_feedback: LayoutFeedbackState,
    pub diagnostics: DiagnosticsState,
    /// Recycled command Vec (issue #150). `Context::new` swaps this into the
    /// new context (capacity preserved, len reset to 0). After `build_tree`
    /// drains the commands, the now-empty Vec is reclaimed back here.
    pub commands_buf: Vec<crate::layout::Command>,
    /// Recycled per-frame layout collection scratch (issue #155). Same
    /// pattern as `commands_buf`: clear before use, restore after.
    pub frame_data: crate::layout::FrameData,
    /// Recycled `Context::context_stack` Vec (issue #204). Empty/cleared at
    /// frame end (same pattern as `commands_buf`).
    pub context_stack_buf: Vec<Box<dyn std::any::Any>>,
    /// Recycled `Context::deferred_draws` Vec (issue #204). Slots are emptied
    /// (set to `None`) when callbacks fire; we clear before reuse.
    pub deferred_draws_buf: Vec<FrameDeferredDrawSlot>,
    /// Recycled `rollback.group_stack` Vec (issue #204). Asserted empty at
    /// frame end before reclamation.
    pub group_stack_buf: Vec<std::sync::Arc<str>>,
    /// Recycled `rollback.text_color_stack` Vec (issue #204). Asserted empty
    /// at frame end before reclamation.
    pub text_color_stack_buf: Vec<Option<crate::style::Color>>,
    /// Recycled `Context::pending_tooltips` Vec (issue #204). Asserted empty
    /// at frame end before reclamation.
    pub pending_tooltips_buf: Vec<context::PendingTooltip>,
    /// Recycled `Context::hovered_groups` set (issue #204). Cleared at the
    /// start of each frame by `build_hovered_groups`.
    pub hovered_groups_buf: std::collections::HashSet<std::sync::Arc<str>>,
    /// Issue #273: per-call-site version keys recorded by
    /// [`ContainerBuilder::cached`](crate::ContainerBuilder::cached) on the
    /// previous frame, indexed by the order `cached` regions were declared.
    /// Compared against this frame's keys to classify each cached region as a
    /// hit (key unchanged) or miss (key changed / new slot / first frame).
    /// Cleared on resize by [`clear_frame_layout_cache`] so every cached
    /// region misses after a geometry change. Round-trips through `Context`
    /// exactly like `commands_buf` (moved out at frame start, moved back at
    /// frame end). Empty (zero overhead) for apps that never call `cached`.
    pub region_versions: Vec<u64>,
    /// Issue #273: recycled scratch Vec for the CURRENT frame's `cached`
    /// region keys (same alloc-reuse discipline as `commands_buf`). Cleared
    /// before reuse; swapped into `region_versions` at frame end so the keys
    /// recorded this frame become next frame's comparison baseline.
    pub region_versions_buf: Vec<u64>,
    #[cfg(feature = "crossterm")]
    pub selection: terminal::SelectionState,
}

/// Run the TUI loop with default configuration.
///
/// Enters alternate screen mode, runs `f` each frame, and exits cleanly on
/// Ctrl+C or when [`Context::quit`] is called.
///
/// # Raw mode is handled for you
///
/// SLT enters raw mode automatically inside [`run`] / [`run_with`] /
/// [`run_inline`] / [`run_async`]. Wrapping these with manual
/// `crossterm::terminal::enable_raw_mode()` and `disable_raw_mode()` is
/// **redundant** — the calls are idempotent so no harm comes of it, but it
/// suggests a misunderstood lifecycle. Drop the wrapper calls:
///
/// ```no_run
/// // Don't do this — it's already handled internally:
/// // crossterm::terminal::enable_raw_mode()?;
/// slt::run(|ui| { ui.text("hi"); })?;
/// // crossterm::terminal::disable_raw_mode()?;
/// # Ok::<_, std::io::Error>(())
/// ```
///
/// # Ctrl+C opt-out (issue #238)
///
/// By default, Ctrl+C exits the loop cleanly — matching the v0.19 contract
/// and the convention most TUIs follow. To match RataTUI's raw-mode
/// semantics (Ctrl+C delivered as a regular `Event::Key`), set
/// [`RunConfig::handle_ctrl_c(false)`](RunConfig::handle_ctrl_c) and decide
/// inside the frame closure whether to call [`Context::quit`]:
///
/// ```no_run
/// use slt::{KeyModifiers, RunConfig};
///
/// slt::run_with(RunConfig::default().handle_ctrl_c(false), |ui| {
///     if ui.key_mod('c', KeyModifiers::CONTROL) {
///         // e.g. clear input, prompt to save, then quit:
///         ui.quit();
///     }
/// })?;
/// # Ok::<_, std::io::Error>(())
/// ```
///
/// # Example
///
/// ```no_run
/// fn main() -> std::io::Result<()> {
///     slt::run(|ui| {
///         ui.text("Press Ctrl+C to exit");
///     })
/// }
/// ```
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn run(f: impl FnMut(&mut Context)) -> io::Result<()> {
    run_with(RunConfig::default(), f)
}

#[cfg(feature = "crossterm")]
fn set_terminal_title(title: &Option<String>) {
    if let Some(title) = title {
        use std::io::Write;
        let mut stdout = io::stdout();
        let _ = write!(stdout, "\x1b]2;{title}\x07");
        let _ = stdout.flush();
    }
}

/// Run the TUI loop with custom configuration.
///
/// Like [`run`], but accepts a [`RunConfig`] to control tick rate, mouse
/// support, and theming.
///
/// # Example
///
/// ```no_run
/// use slt::{RunConfig, Theme};
///
/// fn main() -> std::io::Result<()> {
///     slt::run_with(
///         RunConfig::default().theme(Theme::light()),
///         |ui| {
///             ui.text("Light theme!");
///         },
///     )
/// }
/// ```
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn run_with(config: RunConfig, mut f: impl FnMut(&mut Context)) -> io::Result<()> {
    if !io::stdout().is_terminal() {
        return Ok(());
    }

    install_panic_hook();
    let color_depth = config.color_depth.unwrap_or_else(ColorDepth::detect);
    let mut term = Terminal::new(
        config.mouse,
        config.kitty_keyboard,
        config.report_all_keys,
        color_depth,
    )?;
    set_terminal_title(&config.title);
    if config.theme.bg != Color::Reset {
        term.theme_bg = Some(config.theme.bg);
    }
    // Issue #263: install the unix Ctrl+Z / `fg` suspend handler for the loop.
    #[cfg(unix)]
    let _suspend_guard = if config.handle_suspend {
        Some(install_suspend_handler(term.session_snapshot())?)
    } else {
        None
    };
    let mut events: Vec<Event> = Vec::new();
    let mut state = FrameState::default();

    loop {
        let frame_start = Instant::now();
        // Issue #263: after a SIGCONT resume, repaint the whole frame.
        #[cfg(unix)]
        drain_resume_redraw(&mut || term.handle_resize())?;
        let (w, h) = term.size();
        if w == 0 || h == 0 {
            sleep_for_fps_cap(config.max_fps, frame_start.elapsed());
            continue;
        }

        if !run_frame(
            &mut term,
            &mut state,
            &config,
            std::mem::take(&mut events),
            &mut f,
        )? {
            break;
        }
        // Issue #233: full-screen mode has no scrollback channel — warn and
        // drop any `ui.static_log(...)` lines so they do not leak into the
        // next frame's named_states.
        discard_static_log(&mut state, "full-screen run()");
        let render_elapsed = frame_start.elapsed();

        if !poll_events(
            &mut events,
            &mut state,
            config.tick_rate,
            &mut || term.handle_resize(),
            config.handle_ctrl_c,
        )? {
            break;
        }

        sleep_for_fps_cap(config.max_fps, render_elapsed);
    }

    Ok(())
}

/// Run the TUI loop asynchronously with default configuration.
///
/// Requires the `async` feature. Spawns the render loop in a blocking thread
/// and returns a [`tokio::sync::mpsc::Sender`] you can use to push messages
/// from async tasks into the UI closure.
///
/// # Example
///
/// ```no_run
/// # #[cfg(feature = "async")]
/// # async fn example() -> std::io::Result<()> {
/// let tx = slt::run_async::<String>(|ui, messages| {
///     for msg in messages.drain(..) {
///         ui.text(msg);
///     }
/// })?;
/// tx.send("hello from async".to_string()).await.ok();
/// # Ok(())
/// # }
/// ```
#[cfg(all(feature = "crossterm", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "crossterm", feature = "async"))))]
pub fn run_async<M: Send + 'static>(
    f: impl FnMut(&mut Context, &mut Vec<M>) + Send + 'static,
) -> io::Result<tokio::sync::mpsc::Sender<M>> {
    run_async_with(RunConfig::default(), f)
}

/// Run the TUI loop asynchronously with custom configuration.
///
/// Requires the `async` feature. Like [`run_async`], but accepts a
/// [`RunConfig`] to control tick rate, mouse support, and theming.
///
/// Returns a [`tokio::sync::mpsc::Sender`] for pushing messages into the UI.
#[cfg(all(feature = "crossterm", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "crossterm", feature = "async"))))]
pub fn run_async_with<M: Send + 'static>(
    config: RunConfig,
    f: impl FnMut(&mut Context, &mut Vec<M>) + Send + 'static,
) -> io::Result<tokio::sync::mpsc::Sender<M>> {
    let (tx, rx) = tokio::sync::mpsc::channel(100);
    let handle =
        tokio::runtime::Handle::try_current().map_err(|err| io::Error::other(err.to_string()))?;

    // Issue #234: clone the runtime handle into the render loop so
    // `Context::spawn` has a runtime to launch tasks onto. The render loop runs
    // on `spawn_blocking` (no ambient runtime), so the handle must be passed
    // explicitly rather than recovered via `Handle::try_current()` inside.
    let loop_handle = handle.clone();
    handle.spawn_blocking(move || {
        let _ = run_async_loop(config, f, rx, loop_handle);
    });

    Ok(tx)
}

#[cfg(all(feature = "crossterm", feature = "async"))]
fn run_async_loop<M: Send + 'static>(
    config: RunConfig,
    mut f: impl FnMut(&mut Context, &mut Vec<M>) + Send,
    mut rx: tokio::sync::mpsc::Receiver<M>,
    runtime: tokio::runtime::Handle,
) -> io::Result<()> {
    if !io::stdout().is_terminal() {
        return Ok(());
    }

    install_panic_hook();
    let color_depth = config.color_depth.unwrap_or_else(ColorDepth::detect);
    let mut term = Terminal::new(
        config.mouse,
        config.kitty_keyboard,
        config.report_all_keys,
        color_depth,
    )?;
    set_terminal_title(&config.title);
    if config.theme.bg != Color::Reset {
        term.theme_bg = Some(config.theme.bg);
    }
    // Issue #263: install the unix Ctrl+Z / `fg` suspend handler for the loop.
    #[cfg(unix)]
    let _suspend_guard = if config.handle_suspend {
        Some(install_suspend_handler(term.session_snapshot())?)
    } else {
        None
    };
    let mut events: Vec<Event> = Vec::new();
    let mut messages: Vec<M> = Vec::new();
    let mut state = FrameState::default();
    // Issue #234: inject the ambient runtime so `Context::spawn` works inside
    // the frame closure. Set once before the loop; round-tripped through
    // `Context` from here on (see `run_frame_kernel`).
    state.async_tasks.set_runtime(runtime);

    loop {
        let frame_start = Instant::now();
        // Issue #263: after a SIGCONT resume, repaint the whole frame.
        #[cfg(unix)]
        drain_resume_redraw(&mut || term.handle_resize())?;
        messages.clear();
        while let Ok(message) = rx.try_recv() {
            messages.push(message);
        }

        let (w, h) = term.size();
        if w == 0 || h == 0 {
            sleep_for_fps_cap(config.max_fps, frame_start.elapsed());
            continue;
        }

        let mut render = |ctx: &mut Context| {
            f(ctx, &mut messages);
        };
        if !run_frame(
            &mut term,
            &mut state,
            &config,
            std::mem::take(&mut events),
            &mut render,
        )? {
            break;
        }
        // Issue #233: full-screen async mode has no scrollback channel — warn
        // and drop any pending static_log lines.
        discard_static_log(&mut state, "run_async()");
        let render_elapsed = frame_start.elapsed();

        if !poll_events(
            &mut events,
            &mut state,
            config.tick_rate,
            &mut || term.handle_resize(),
            config.handle_ctrl_c,
        )? {
            break;
        }

        sleep_for_fps_cap(config.max_fps, render_elapsed);
    }

    Ok(())
}

/// Run the TUI in inline mode with default configuration.
///
/// Renders `height` rows directly below the current cursor position without
/// entering alternate screen mode. Useful for CLI tools that want a small
/// interactive widget below the prompt.
///
/// `height` is the reserved inline render area in terminal rows.
/// The rest of the terminal stays in normal scrollback mode.
///
/// # Example
///
/// ```no_run
/// fn main() -> std::io::Result<()> {
///     slt::run_inline(3, |ui| {
///         ui.text("Inline TUI — no alternate screen");
///     })
/// }
/// ```
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn run_inline(height: u32, f: impl FnMut(&mut Context)) -> io::Result<()> {
    run_inline_with(height, RunConfig::default(), f)
}

/// Run the TUI in inline mode with custom configuration.
///
/// Like [`run_inline`], but accepts a [`RunConfig`] to control tick rate,
/// mouse support, and theming.
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn run_inline_with(
    height: u32,
    config: RunConfig,
    mut f: impl FnMut(&mut Context),
) -> io::Result<()> {
    if !io::stdout().is_terminal() {
        return Ok(());
    }

    install_panic_hook();
    let color_depth = config.color_depth.unwrap_or_else(ColorDepth::detect);
    let mut term = InlineTerminal::new(
        height,
        config.mouse,
        config.kitty_keyboard,
        config.report_all_keys,
        color_depth,
    )?;
    set_terminal_title(&config.title);
    if config.theme.bg != Color::Reset {
        term.theme_bg = Some(config.theme.bg);
    }
    // Issue #263: install the unix Ctrl+Z / `fg` suspend handler for the loop.
    #[cfg(unix)]
    let _suspend_guard = if config.handle_suspend {
        Some(install_suspend_handler(term.session_snapshot())?)
    } else {
        None
    };
    let mut events: Vec<Event> = Vec::new();
    let mut state = FrameState::default();

    loop {
        let frame_start = Instant::now();
        // Issue #263: after a SIGCONT resume, repaint the whole frame.
        #[cfg(unix)]
        drain_resume_redraw(&mut || term.handle_resize())?;
        let (w, h) = term.size();
        if w == 0 || h == 0 {
            sleep_for_fps_cap(config.max_fps, frame_start.elapsed());
            continue;
        }

        if !run_frame(
            &mut term,
            &mut state,
            &config,
            std::mem::take(&mut events),
            &mut f,
        )? {
            break;
        }
        // Issue #233: inline mode without `StaticOutput` has no scrollback
        // channel either — warn and drop any pending lines.
        discard_static_log(&mut state, "run_inline()");
        let render_elapsed = frame_start.elapsed();

        if !poll_events(
            &mut events,
            &mut state,
            config.tick_rate,
            &mut || term.handle_resize(),
            config.handle_ctrl_c,
        )? {
            break;
        }

        sleep_for_fps_cap(config.max_fps, render_elapsed);
    }

    Ok(())
}

/// Run the TUI in static-output mode.
///
/// Static lines written through [`StaticOutput`] are printed into terminal
/// scrollback, while the interactive UI stays rendered in a fixed-height inline
/// area at the bottom.
///
/// Use this when you want a log-style output stream above a live inline UI.
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn run_static(
    output: &mut StaticOutput,
    dynamic_height: u32,
    f: impl FnMut(&mut Context),
) -> io::Result<()> {
    run_static_with(output, dynamic_height, RunConfig::default(), f)
}

/// Run the TUI in static-output mode with custom configuration.
///
/// Like [`run_static`] but accepts a [`RunConfig`] for theme, mouse, tick rate,
/// and other settings.
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn run_static_with(
    output: &mut StaticOutput,
    dynamic_height: u32,
    config: RunConfig,
    mut f: impl FnMut(&mut Context),
) -> io::Result<()> {
    if !io::stdout().is_terminal() {
        return Ok(());
    }

    install_panic_hook();

    let initial_lines = output.drain_new();
    write_static_lines(&initial_lines)?;

    let color_depth = config.color_depth.unwrap_or_else(ColorDepth::detect);
    let mut term = InlineTerminal::new(
        dynamic_height,
        config.mouse,
        config.kitty_keyboard,
        config.report_all_keys,
        color_depth,
    )?;
    set_terminal_title(&config.title);
    if config.theme.bg != Color::Reset {
        term.theme_bg = Some(config.theme.bg);
    }
    // Issue #263: install the unix Ctrl+Z / `fg` suspend handler for the loop.
    #[cfg(unix)]
    let _suspend_guard = if config.handle_suspend {
        Some(install_suspend_handler(term.session_snapshot())?)
    } else {
        None
    };

    let mut events: Vec<Event> = Vec::new();
    let mut state = FrameState::default();

    loop {
        let frame_start = Instant::now();
        // Issue #263: after a SIGCONT resume, repaint the whole frame.
        #[cfg(unix)]
        drain_resume_redraw(&mut || term.handle_resize())?;
        let (w, h) = term.size();
        if w == 0 || h == 0 {
            sleep_for_fps_cap(config.max_fps, frame_start.elapsed());
            continue;
        }

        let new_lines = output.drain_new();
        write_static_lines(&new_lines)?;

        if !run_frame(
            &mut term,
            &mut state,
            &config,
            std::mem::take(&mut events),
            &mut f,
        )? {
            break;
        }
        // Issue #233: drain any `ui.static_log(...)` lines queued during the
        // frame closure into `output`; the next loop iteration flushes them
        // above the inline area via `write_static_lines`.
        for line in drain_static_log(&mut state) {
            output.println(line);
        }
        let render_elapsed = frame_start.elapsed();

        if !poll_events(
            &mut events,
            &mut state,
            config.tick_rate,
            &mut || term.handle_resize(),
            config.handle_ctrl_c,
        )? {
            break;
        }

        sleep_for_fps_cap(config.max_fps, render_elapsed);
    }

    Ok(())
}

#[cfg(feature = "crossterm")]
fn write_static_lines(lines: &[String]) -> io::Result<()> {
    if lines.is_empty() {
        return Ok(());
    }

    let mut stdout = io::stdout();
    for line in lines {
        stdout.write_all(line.as_bytes())?;
        stdout.write_all(b"\r\n")?;
    }
    stdout.flush()
}

/// Reserved sentinel key used by [`Context::static_log`] (issue #233).
/// Re-exported into `context::runtime` so reads/writes never drift.
pub(crate) const STATIC_LOG_NAMED_STATE_KEY: &str = "__slt_static_log_pending";

/// Reserved sentinel key used by [`Context::publish_keymap`] (issue #236).
/// Re-exported into `context::runtime` so reads/writes never drift.
pub(crate) const KEYMAP_REGISTRY_NAMED_STATE_KEY: &str = "__slt_keymap_registry";

/// Clear the per-frame keymap registry stored in [`FrameState::named_states`]
/// (issue #236). Called at the start of every kernel iteration so that
/// `Context::publish_keymap` always sees a fresh empty buffer. Capacity is
/// preserved by clearing the inner `Vec` rather than removing the entry.
pub(crate) fn clear_keymap_registry(state: &mut FrameState) {
    if let Some(boxed) = state.named_states.get_mut(KEYMAP_REGISTRY_NAMED_STATE_KEY)
        && let Some(vec) = boxed.downcast_mut::<Vec<crate::keymap::PublishedKeymap>>()
    {
        vec.clear();
    }
}

/// Drain any [`Context::static_log`] lines accumulated during the most recent
/// frame from the persisted [`FrameState`] (issue #233).
///
/// After [`run_frame_kernel`] returns, `state.named_states` owns the buffer.
/// This helper drains it back to a `Vec<String>` so the runtime can flush
/// the lines through whichever scrollback mechanism is appropriate
/// (`run_static_with` writes them above the inline region; other run modes
/// drop them with a debug warning).
#[cfg(feature = "crossterm")]
pub(crate) fn drain_static_log(state: &mut FrameState) -> Vec<String> {
    if let Some(boxed) = state.named_states.get_mut(STATIC_LOG_NAMED_STATE_KEY)
        && let Some(buf) = boxed.downcast_mut::<Vec<String>>()
    {
        return std::mem::take(buf);
    }
    Vec::new()
}

/// Discard any [`Context::static_log`] lines that accumulated during the
/// most recent frame and emit a debug warning (issue #233).
///
/// Used by run modes that have no scrollback channel (full-screen,
/// inline-without-static, async). Release builds silently drop the buffer.
#[cfg(feature = "crossterm")]
fn discard_static_log(state: &mut FrameState, mode: &str) {
    let drained = drain_static_log(state);
    #[cfg(debug_assertions)]
    if !drained.is_empty() {
        #[allow(clippy::print_stderr)]
        {
            eprintln!(
                "[slt] {} static_log lines were dropped: {} runtime has no scrollback channel; use slt::run_static for streaming output",
                drained.len(),
                mode
            );
        }
    }
    #[cfg(not(debug_assertions))]
    {
        let _ = (drained, mode);
    }
}

/// Apply a single terminal event to `FrameState`, mutating tracked
/// diagnostics fields (debug overlay toggle, mouse position cache,
/// resize flag) accordingly.
///
/// Issue #201: handles **F12** (toggle overlay on/off) and **Shift+F12**
/// (cycle [`DebugLayer`] across `All → TopMost → BaseOnly`). The two
/// keybindings are independent — toggling the overlay does not change
/// the active layer.
///
/// Extracted from `poll_events` so the keybinding behavior can be
/// exercised by unit tests without standing up a real crossterm event
/// stream.
#[cfg(feature = "crossterm")]
pub(crate) fn process_run_loop_event(ev: &Event, state: &mut FrameState, has_resize: &mut bool) {
    match ev {
        Event::Mouse(m) => {
            state.layout_feedback.last_mouse_pos = Some((m.x, m.y));
        }
        Event::FocusLost => {
            state.layout_feedback.last_mouse_pos = None;
        }
        // Issue #268: Ctrl+F12 toggles the devtools inspector panel
        // independently of the F12 outline overlay and the Shift+F12 layer
        // cycle. Match before the Shift/NONE arms so the Control branch wins.
        Event::Key(event::KeyEvent {
            code: KeyCode::F(12),
            kind: event::KeyEventKind::Press,
            modifiers,
        }) if modifiers.contains(event::KeyModifiers::CONTROL) => {
            state.diagnostics.inspector_mode = !state.diagnostics.inspector_mode;
        }
        // Issue #201: Shift+F12 cycles the active `DebugLayer`. Match
        // before the plain-F12 arm so the modifier branch wins. Plain
        // F12 keeps its legacy on/off toggle when no modifiers are
        // held; we explicitly require `KeyModifiers::NONE` so the two
        // arms do not double-fire on the same press.
        Event::Key(event::KeyEvent {
            code: KeyCode::F(12),
            kind: event::KeyEventKind::Press,
            modifiers,
        }) if modifiers.contains(event::KeyModifiers::SHIFT) => {
            state.diagnostics.debug_layer = match state.diagnostics.debug_layer {
                DebugLayer::All => DebugLayer::TopMost,
                DebugLayer::TopMost => DebugLayer::BaseOnly,
                DebugLayer::BaseOnly => DebugLayer::All,
            };
        }
        Event::Key(event::KeyEvent {
            code: KeyCode::F(12),
            kind: event::KeyEventKind::Press,
            modifiers,
        }) if *modifiers == event::KeyModifiers::NONE => {
            state.diagnostics.debug_mode = !state.diagnostics.debug_mode;
        }
        Event::Resize(_, _) => {
            *has_resize = true;
        }
        _ => {}
    }
}

/// Number of `on_resize` invocations a batch of events should trigger.
///
/// v0.21.1 resize coalescing: a single poll batch may deliver a burst of
/// `Event::Resize` events while a user drags the window edge. Each
/// [`Terminal::handle_resize`](crate::terminal::Terminal::handle_resize) does a
/// `terminal::size()` syscall, two buffer reallocations, and a `Clear(All)`, so
/// firing it per-event is pure waste — only the *final* geometry matters and
/// `handle_resize` always reads the live terminal size, not the per-event
/// payload. This helper returns `1` if the batch contains any resize and `0`
/// otherwise, so the caller can collapse the burst into one end-of-batch call.
///
/// Kept as a pure function (no I/O) so the coalescing rule is unit-testable
/// without a real crossterm event source.
#[cfg(feature = "crossterm")]
#[inline]
fn resize_invocations_for_batch(events: &[Event]) -> usize {
    usize::from(events.iter().any(|e| matches!(e, Event::Resize(_, _))))
}

/// Poll for terminal events, handling resize, Ctrl-C, F12 debug toggle,
/// and layout cache invalidation. Returns `Ok(false)` when the loop should exit.
///
/// `handle_ctrl_c` controls whether Ctrl+C exits the loop (`true`, default
/// v0.19 behavior) or is delivered to the frame closure as a regular key
/// event (`false`, RataTUI parity, issue #238).
///
/// v0.21.1: resize events within one poll batch are *coalesced* — `on_resize`
/// is invoked at most once, after the whole batch is drained, using the final
/// terminal size (`handle_resize` re-reads `terminal::size()`). Dragging a
/// window edge can emit dozens of `Event::Resize` per poll; firing the
/// `Clear(All)` + double realloc + `size()` syscall for each is wasted work
/// when only the last geometry survives. The SIGCONT/resume redraw path in
/// [`run_with`] is unaffected — it calls `handle_resize` directly, outside this
/// function.
#[cfg(feature = "crossterm")]
fn poll_events(
    events: &mut Vec<Event>,
    state: &mut FrameState,
    tick_rate: Duration,
    on_resize: &mut impl FnMut() -> io::Result<()>,
    handle_ctrl_c: bool,
) -> io::Result<bool> {
    let mut has_resize = false;

    fn process_ev(ev: &Event, state: &mut FrameState, has_resize: &mut bool) {
        process_run_loop_event(ev, state, has_resize);
    }

    if crossterm::event::poll(tick_rate)? {
        let raw = crossterm::event::read()?;
        if let Some(ev) = event::from_crossterm(raw) {
            if handle_ctrl_c && is_ctrl_c(&ev) {
                return Ok(false);
            }
            // Resize is recorded (via `has_resize`) but not yet acted on — the
            // single `on_resize` call is deferred to end-of-batch so a burst
            // collapses into one geometry sync.
            process_ev(&ev, state, &mut has_resize);
            events.push(ev);
        }

        while crossterm::event::poll(Duration::ZERO)? {
            let raw = crossterm::event::read()?;
            if let Some(ev) = event::from_crossterm(raw) {
                if handle_ctrl_c && is_ctrl_c(&ev) {
                    return Ok(false);
                }
                process_ev(&ev, state, &mut has_resize);
                events.push(ev);
            }
        }
    }

    // Coalesced resize: fire `on_resize` exactly once for the whole batch,
    // after every event has been read, so it picks up the final terminal size.
    // `has_resize` is the per-batch "saw a resize" flag set by `process_ev`.
    debug_assert_eq!(
        usize::from(has_resize),
        resize_invocations_for_batch(events),
        "has_resize must agree with the coalescing helper"
    );
    if has_resize {
        on_resize()?;
    }

    // #90: clear cache first (which also resets last_mouse_pos to None),
    // then re-apply latest mouse pos so Resize+Mouse frames keep coords.
    if has_resize {
        clear_frame_layout_cache(state);
        // After clearing, re-walk events to restore the latest mouse pos
        // (process_ev already set it during collection, but
        // clear_frame_layout_cache wiped it).
        for ev in events.iter() {
            match ev {
                Event::Mouse(m) => {
                    state.layout_feedback.last_mouse_pos = Some((m.x, m.y));
                }
                Event::FocusLost => {
                    state.layout_feedback.last_mouse_pos = None;
                }
                _ => {}
            }
        }
    }

    Ok(true)
}

struct FrameKernelResult {
    should_quit: bool,
    #[cfg(feature = "crossterm")]
    clipboard_text: Option<String>,
    #[cfg(feature = "crossterm")]
    should_copy_selection: bool,
}

pub(crate) fn run_frame_kernel(
    buffer: &mut Buffer,
    state: &mut FrameState,
    config: &RunConfig,
    size: (u32, u32),
    events: Vec<event::Event>,
    is_real_terminal: bool,
    f: &mut impl FnMut(&mut context::Context),
) -> FrameKernelResult {
    let frame_start = Instant::now();
    let (w, h) = size;
    // Issue #236: reset the per-frame keymap registry before constructing
    // `Context`. Widgets that call `publish_keymap` accumulate fresh
    // entries; entries from the previous frame must not leak through
    // `named_states` persistence.
    clear_keymap_registry(state);
    // Issue #273: invalidate every `cached` region's persisted version key on a
    // resize. The real run loop also clears region keys via
    // `clear_frame_layout_cache` (driven by its `has_resize` flag), but the
    // headless `TestBackend` / `frame_owned` paths feed the kernel directly
    // and never run that flag, so we detect the resize event here too. This
    // keeps the "resize forces a cache miss for all cached regions" invariant
    // path-independent: a geometry change cannot be silently treated as a hit.
    // Cheap when unused — `region_versions` is empty for apps without `cached`.
    if !state.region_versions.is_empty() && events.iter().any(|e| matches!(e, Event::Resize(_, _)))
    {
        state.region_versions.clear();
    }
    let mut ctx = Context::new(events, w, h, state, config.theme);
    ctx.is_real_terminal = is_real_terminal;
    // Issue #264: surface the negotiated capability snapshot read-only. The
    // probe ran once at session enter (cached in a `OnceLock`); on a headless
    // backend it never ran, so we keep the conservative default rather than
    // forcing a probe that would block on stdin.
    #[cfg(feature = "crossterm")]
    if is_real_terminal {
        ctx.capabilities = terminal::capabilities();
    }
    ctx.set_scroll_speed(config.scroll_speed);
    ctx.widget_theme = config.widget_theme;

    f(&mut ctx);
    ctx.process_focus_keys();
    ctx.render_notifications();
    ctx.emit_pending_tooltips();

    debug_assert_eq!(
        ctx.rollback.overlay_depth, 0,
        "overlay depth must settle back to zero before layout"
    );
    debug_assert_eq!(
        ctx.rollback.group_count, 0,
        "group count must settle back to zero before layout"
    );
    debug_assert!(
        ctx.rollback.group_stack.is_empty(),
        "group stack must be empty before layout"
    );
    debug_assert!(
        ctx.rollback.text_color_stack.is_empty(),
        "text color stack must be empty before layout"
    );
    debug_assert!(
        ctx.pending_tooltips.is_empty(),
        "pending tooltips must be emitted before layout"
    );

    if ctx.should_quit {
        state.hook_states = ctx.hook_states;
        state.named_states = ctx.named_states;
        state.keyed_states = ctx.keyed_states;
        // Issue #262: persist the partial-chord buffer on quit too (TestBackend
        // reuses `FrameState` across `render()` calls — same rationale as the
        // keyed-state reclaim).
        state.chord_states = ctx.chord;
        // Issue #248: hand the scheduler table back and GC abandoned timers.
        let mut scheduler = ctx.scheduler;
        scheduler.gc_untouched();
        state.scheduler = scheduler;
        // Issue #234: hand the async task registry back so in-flight tasks and
        // pending results survive to the next frame (TestBackend reuses
        // `FrameState` across `render()` calls — same rationale as the
        // scheduler reclaim).
        #[cfg(feature = "async")]
        {
            // Pump the registry every frame so a handle dropped on a frame that
            // calls neither spawn nor poll still has its cancellation processed
            // (and completed results moved in) before the round-trip.
            ctx.async_tasks.maintain();
            state.async_tasks = ctx.async_tasks;
        }
        state.screen_hook_map = ctx.screen_hook_map;
        state.diagnostics.notification_queue = ctx.rollback.notification_queue;
        state.diagnostics.debug_layer = ctx.debug_layer;
        // Issue #268: persist any in-frame `set_inspector` change on quit too.
        state.diagnostics.inspector_mode = ctx.inspector_mode;
        // Issue #208 / #217: persist focus tracking state on quit so a later
        // resumed run starts in a sensible place. (Real TUI exits before
        // resuming, but tests reuse `FrameState` across calls.)
        state.focus.prev_focus_index = Some(ctx.focus_index);
        state.focus.focus_name_map_prev = ctx.focus_name_map;
        state.focus.pending_focus_name = ctx.pending_focus_name;
        // Issue #204: reclaim the 6 alloc-reuse buffers on the quit path
        // too. Real TUI exits ignore this, but TestBackend reuses the same
        // FrameState across `render()` calls — without the reclaim the next
        // frame's `Context::new` `mem::take`s an empty Vec and silently
        // reverts to v0.19 per-frame allocation.
        ctx.deferred_draws.clear();
        state.context_stack_buf = std::mem::take(&mut ctx.context_stack);
        state.deferred_draws_buf = std::mem::take(&mut ctx.deferred_draws);
        state.group_stack_buf = std::mem::take(&mut ctx.rollback.group_stack);
        state.text_color_stack_buf = std::mem::take(&mut ctx.rollback.text_color_stack);
        state.pending_tooltips_buf = std::mem::take(&mut ctx.pending_tooltips);
        state.hovered_groups_buf = std::mem::take(&mut ctx.hovered_groups);
        // Issue #273: reclaim the region-cache key buffers on quit too
        // (TestBackend reuses `FrameState` across `render()` calls — same
        // rationale as #204). The quit path skips `build_tree`, but the keys
        // recorded by any `cached` regions before `quit()` are still valid as
        // next frame's baseline.
        state.region_versions = std::mem::take(&mut ctx.region_versions_cur);
        state.region_versions_buf = std::mem::take(&mut ctx.region_versions_prev);
        // Issue #150: reclaim `commands` on quit too (TestBackend reuses
        // `FrameState` across `render()` calls — same rationale as #204).
        // The Vec was never `build_tree`'d on the quit path so it may still
        // hold the recorded commands; clearing here drops them and keeps
        // capacity for the next frame.
        ctx.commands.clear();
        state.commands_buf = std::mem::take(&mut ctx.commands);
        #[cfg(feature = "crossterm")]
        let clipboard_text = ctx.clipboard_text.take();
        #[cfg(feature = "crossterm")]
        let should_copy_selection = false;
        return FrameKernelResult {
            should_quit: true,
            #[cfg(feature = "crossterm")]
            clipboard_text,
            #[cfg(feature = "crossterm")]
            should_copy_selection,
        };
    }
    state.focus.prev_modal_active = ctx.rollback.modal_active;
    state.focus.prev_modal_focus_start = ctx.rollback.modal_focus_start;
    state.focus.prev_modal_focus_count = ctx.rollback.modal_focus_count;
    #[cfg(feature = "crossterm")]
    let clipboard_text = ctx.clipboard_text.take();
    #[cfg(not(feature = "crossterm"))]
    let _clipboard_text = ctx.clipboard_text.take();

    #[cfg(feature = "crossterm")]
    let mut should_copy_selection = false;
    #[cfg(feature = "crossterm")]
    for ev in &ctx.events {
        if let Event::Mouse(mouse) = ev {
            match mouse.kind {
                event::MouseKind::Down(event::MouseButton::Left) => {
                    state.selection.mouse_down(
                        mouse.x,
                        mouse.y,
                        &state.layout_feedback.prev_content_map,
                    );
                }
                event::MouseKind::Drag(event::MouseButton::Left) => {
                    state.selection.mouse_drag(
                        mouse.x,
                        mouse.y,
                        &state.layout_feedback.prev_content_map,
                    );
                }
                event::MouseKind::Up(event::MouseButton::Left) => {
                    should_copy_selection = state.selection.active;
                }
                _ => {}
            }
        }
    }

    state.focus.focus_index = ctx.focus_index;
    state.focus.prev_focus_count = ctx.rollback.focus_count;

    // Issue #150: `state.commands_buf` is swapped into `ctx.commands` on
    // entry (see `Context::new`), so the per-frame `Vec::new()` allocation
    // for the command list is amortized to one allocation across the
    // session. `build_tree` now takes `&mut Vec<Command>` and `drain`s it,
    // leaving the Vec at `len == 0` with capacity preserved. We reclaim
    // that Vec into `state.commands_buf` after the frame so the next call
    // to `Context::new` can pick it up via `mem::take` (matches the #204
    // pattern for the other six recycled buffers).
    let mut tree = layout::build_tree(&mut ctx.commands);
    let area = crate::rect::Rect::new(0, 0, w, h);
    layout::compute(&mut tree, area);

    // Issue #155: reuse `state.frame_data` across frames. `collect_all` calls
    // `fd.clear()` first so the Vecs reset to len=0 with capacity preserved
    // from the prior frame, then refills them.
    let mut fd = std::mem::take(&mut state.frame_data);
    layout::collect_all(&tree, &mut fd);
    debug_assert_eq!(
        fd.scroll_infos.len(),
        fd.scroll_rects.len(),
        "scroll feedback vectors must stay aligned"
    );
    let raw_rects = std::mem::take(&mut fd.raw_draw_rects);
    state.layout_feedback.prev_scroll_infos = std::mem::take(&mut fd.scroll_infos);
    state.layout_feedback.prev_scroll_rects = std::mem::take(&mut fd.scroll_rects);
    state.layout_feedback.prev_hit_map = std::mem::take(&mut fd.hit_areas);
    state.layout_feedback.prev_group_rects = std::mem::take(&mut fd.group_rects);
    state.layout_feedback.prev_content_map = std::mem::take(&mut fd.content_areas);
    state.layout_feedback.prev_focus_rects = std::mem::take(&mut fd.focus_rects);
    state.layout_feedback.prev_focus_groups = std::mem::take(&mut fd.focus_groups);
    state.frame_data = fd;
    layout::render(&tree, buffer);
    // RAII guard ensuring the kitty clip frame is popped even if a raw-draw
    // callback panics — prevents stale scroll-clip state leaking into the
    // next region or subsequent frames.
    struct KittyClipGuard<'a>(&'a mut crate::buffer::Buffer);
    impl Drop for KittyClipGuard<'_> {
        fn drop(&mut self) {
            let _ = self.0.pop_kitty_clip();
        }
    }
    for rdr in raw_rects {
        if rdr.rect.width == 0 || rdr.rect.height == 0 {
            continue;
        }
        if let Some(cb) = ctx
            .deferred_draws
            .get_mut(rdr.draw_id)
            .and_then(|c| c.take())
        {
            buffer.push_clip(rdr.rect);
            buffer.push_kitty_clip(crate::buffer::KittyClipInfo {
                top_clip_rows: rdr.top_clip_rows,
                original_height: rdr.original_height,
            });
            {
                let guard = KittyClipGuard(buffer);
                // Explicit reborrow so the guard keeps ownership of the
                // outer `&mut Buffer` and pops on drop.
                cb(&mut *guard.0, rdr.rect);
                // Guard pops on drop at end of this scope.
            }
            buffer.pop_clip();
        }
    }
    debug_assert!(
        buffer.kitty_clip_info_stack.is_empty(),
        "kitty_clip_info_stack must be empty at end of frame"
    );
    state.hook_states = ctx.hook_states;
    state.named_states = ctx.named_states;
    // Issue #215: hand the keyed-state map back to FrameState so the next
    // frame can pick it up via `Context::new`. Mirrors the `named_states`
    // round-trip exactly.
    state.keyed_states = ctx.keyed_states;
    // Issue #262: hand the partial-chord buffer back so a chord spanning
    // multiple frames survives between them. Same round-trip as `keyed_states`.
    state.chord_states = ctx.chord;
    // Issue #248: hand the scheduler table back and GC any timer slot that was
    // not sampled this frame (mirrors the `named_states` round-trip lifecycle).
    let mut scheduler = ctx.scheduler;
    scheduler.gc_untouched();
    state.scheduler = scheduler;
    // Issue #234: hand the async task registry back so in-flight tasks and
    // pending results survive to the next frame (same round-trip lifecycle as
    // the scheduler table).
    #[cfg(feature = "async")]
    {
        // Pump the registry every frame (see the quit-path note): drains
        // completed results and honours handle-drop cancellations even on a
        // frame that called neither spawn nor poll.
        ctx.async_tasks.maintain();
        state.async_tasks = ctx.async_tasks;
    }
    state.screen_hook_map = ctx.screen_hook_map;
    state.diagnostics.notification_queue = ctx.rollback.notification_queue;
    // Issue #201: persist any in-frame `set_debug_layer` change.
    state.diagnostics.debug_layer = ctx.debug_layer;
    // Issue #268: persist any in-frame `set_inspector` change.
    state.diagnostics.inspector_mode = ctx.inspector_mode;
    // Issue #208: remember the focus index that finished this frame so the
    // next frame can compute `Response::gained_focus` / `lost_focus`.
    state.focus.prev_focus_index = Some(ctx.focus_index);
    // Issue #217: swap the freshly-built focus name map into the previous
    // slot for next-frame resolution; carry forward any unresolved pending
    // name (deferred until the named widget exists).
    state.focus.focus_name_map_prev = ctx.focus_name_map;
    state.focus.pending_focus_name = ctx.pending_focus_name;

    // Issue #204: reclaim the six per-frame `Vec`/`HashSet` allocations so the
    // next frame reuses the existing capacity instead of allocating fresh.
    // Frame-end invariants (asserted above at lines 1102–1121):
    //   - `rollback.group_stack` and `rollback.text_color_stack` are empty
    //   - `pending_tooltips` is empty
    // `context_stack` is asserted-empty by the consumers in `widgets_*`
    // modules (provider/use_context); on the rare panic-rollback path the
    // checkpoint truncates it back to the saved length, so we still
    // recover capacity.
    //
    // `deferred_draws`: most slots are emptied by the `take()` above, but
    // entries whose `RawDrawRect` had `width == 0 || height == 0` are
    // skipped at the loop guard and remain `Some(_)`. We explicitly
    // `clear()` to drop those callbacks here so they don't outlive the
    // frame; capacity is preserved. (Leaving them would not cause UB —
    // `Context::new` calls `.clear()` on the reclaimed Vec — but dropping
    // promptly matches user expectation that one-shot callbacks don't
    // survive past their frame.)
    //
    // `hovered_groups`: `clear()`-ed at the start of every frame inside
    // `build_hovered_groups`, so the existing entries are harmless to
    // reclaim with content; capacity is preserved.
    ctx.deferred_draws.clear();
    state.context_stack_buf = std::mem::take(&mut ctx.context_stack);
    state.deferred_draws_buf = std::mem::take(&mut ctx.deferred_draws);
    state.group_stack_buf = std::mem::take(&mut ctx.rollback.group_stack);
    state.text_color_stack_buf = std::mem::take(&mut ctx.rollback.text_color_stack);
    state.pending_tooltips_buf = std::mem::take(&mut ctx.pending_tooltips);
    state.hovered_groups_buf = std::mem::take(&mut ctx.hovered_groups);
    // Issue #273: this frame's recorded `cached` keys become next frame's
    // comparison baseline; the (now-stale) previous keys are reclaimed as the
    // recycled scratch buffer. Same alloc-reuse discipline as `commands_buf`.
    state.region_versions = std::mem::take(&mut ctx.region_versions_cur);
    state.region_versions_buf = std::mem::take(&mut ctx.region_versions_prev);
    // Issue #150: reclaim the drained command Vec so the next `Context::new`
    // picks it up via `mem::take(&mut state.commands_buf)`. After
    // `build_tree(&mut ctx.commands)` the Vec is at `len == 0` with capacity
    // preserved; mirror the #204 reclamation pattern for the other six
    // per-frame buffers.
    state.commands_buf = std::mem::take(&mut ctx.commands);

    let frame_time = frame_start.elapsed();
    let frame_time_us = frame_time.as_micros().min(u128::from(u64::MAX)) as u64;
    let frame_secs = frame_time.as_secs_f32();
    let inst_fps = if frame_secs > 0.0 {
        1.0 / frame_secs
    } else {
        0.0
    };
    state.diagnostics.fps_ema = if state.diagnostics.fps_ema == 0.0 {
        inst_fps
    } else {
        (state.diagnostics.fps_ema * 0.9) + (inst_fps * 0.1)
    };
    if state.diagnostics.debug_mode {
        layout::render_debug_overlay(
            &tree,
            buffer,
            frame_time_us,
            state.diagnostics.fps_ema,
            state.diagnostics.debug_layer,
        );
    }
    // Issue #268: render the devtools inspector panel (Ctrl+F12) on top of the
    // frame. Reuses the already-built tree and the focus snapshot threaded in
    // from `FrameState` (no new traversal beyond one focused-node DFS). The
    // name map was already swapped into `focus_name_map_prev` above, so it
    // reflects this frame's registrations.
    if state.diagnostics.inspector_mode {
        let focus = layout::InspectorFocus {
            focus_index: state.focus.focus_index,
            focus_count: state.focus.prev_focus_count,
            names: &state.focus.focus_name_map_prev,
            theme: &config.theme,
        };
        layout::render_inspector(&tree, buffer, &focus);
    }

    FrameKernelResult {
        should_quit: false,
        #[cfg(feature = "crossterm")]
        clipboard_text,
        #[cfg(feature = "crossterm")]
        should_copy_selection,
    }
}

fn run_frame(
    term: &mut impl Backend,
    state: &mut FrameState,
    config: &RunConfig,
    events: Vec<event::Event>,
    f: &mut impl FnMut(&mut context::Context),
) -> io::Result<bool> {
    let size = term.size();
    let kernel = run_frame_kernel(term.buffer_mut(), state, config, size, events, true, f);
    if kernel.should_quit {
        return Ok(false);
    }

    #[cfg(feature = "crossterm")]
    if state.selection.active {
        terminal::apply_selection_overlay(
            term.buffer_mut(),
            &state.selection,
            &state.layout_feedback.prev_content_map,
        );
    }
    #[cfg(feature = "crossterm")]
    if kernel.should_copy_selection {
        let text = terminal::extract_selection_text(
            term.buffer_mut(),
            &state.selection,
            &state.layout_feedback.prev_content_map,
        );
        if !text.is_empty() {
            terminal::copy_to_clipboard(&mut io::stdout(), &text)?;
        }
        state.selection.clear();
    }

    term.flush()?;
    #[cfg(feature = "crossterm")]
    if let Some(text) = kernel.clipboard_text {
        #[allow(clippy::print_stderr)]
        if let Err(e) = terminal::copy_to_clipboard(&mut io::stdout(), &text) {
            eprintln!("[slt] failed to copy to clipboard: {e}");
        }
    }
    state.diagnostics.tick = state.diagnostics.tick.wrapping_add(1);

    Ok(true)
}

#[cfg(feature = "crossterm")]
fn clear_frame_layout_cache(state: &mut FrameState) {
    state.layout_feedback.prev_hit_map.clear();
    state.layout_feedback.prev_group_rects.clear();
    state.layout_feedback.prev_content_map.clear();
    state.layout_feedback.prev_focus_rects.clear();
    state.layout_feedback.prev_focus_groups.clear();
    state.layout_feedback.prev_scroll_infos.clear();
    state.layout_feedback.prev_scroll_rects.clear();
    state.layout_feedback.last_mouse_pos = None;
    // Issue #273: a resize may change the geometry of every cached region, so
    // the previous frame's version keys are no longer a safe stability signal.
    // Dropping them forces a cache miss for all `cached` regions on the next
    // frame, matching the layout-feedback invalidation above.
    state.region_versions.clear();
}

#[cfg(feature = "crossterm")]
fn is_ctrl_c(ev: &Event) -> bool {
    matches!(
        ev,
        Event::Key(event::KeyEvent {
            code: KeyCode::Char('c'),
            modifiers,
            kind: event::KeyEventKind::Press,
        }) if modifiers.contains(KeyModifiers::CONTROL)
    )
}

#[cfg(feature = "crossterm")]
fn sleep_for_fps_cap(max_fps: Option<u32>, render_elapsed: Duration) {
    if let Some(fps) = max_fps.filter(|fps| *fps > 0) {
        let target = Duration::from_secs_f64(1.0 / fps as f64);
        if render_elapsed < target {
            std::thread::sleep(target - render_elapsed);
        }
    }
}

#[cfg(all(test, feature = "crossterm"))]
mod run_loop_tests {
    //! Issue #201 regression tests for the run-loop F12 / Shift+F12
    //! keybinding handler. Exercises [`process_run_loop_event`] directly
    //! so we don't need a real crossterm event source.
    use super::*;

    fn key(modifiers: event::KeyModifiers) -> Event {
        Event::Key(event::KeyEvent {
            code: KeyCode::F(12),
            kind: event::KeyEventKind::Press,
            modifiers,
        })
    }

    #[test]
    fn plain_f12_toggles_debug_mode() {
        let mut state = FrameState::default();
        let mut has_resize = false;
        assert!(!state.diagnostics.debug_mode);
        process_run_loop_event(&key(event::KeyModifiers::NONE), &mut state, &mut has_resize);
        assert!(state.diagnostics.debug_mode);
        process_run_loop_event(&key(event::KeyModifiers::NONE), &mut state, &mut has_resize);
        assert!(!state.diagnostics.debug_mode);
    }

    #[test]
    fn shift_f12_cycles_debug_layer_without_toggling_overlay() {
        let mut state = FrameState::default();
        let mut has_resize = false;
        // Default layer is `All`; debug overlay starts off.
        assert_eq!(state.diagnostics.debug_layer, DebugLayer::All);
        assert!(!state.diagnostics.debug_mode);

        process_run_loop_event(
            &key(event::KeyModifiers::SHIFT),
            &mut state,
            &mut has_resize,
        );
        assert_eq!(state.diagnostics.debug_layer, DebugLayer::TopMost);
        // Cycling does not flip the on/off state.
        assert!(!state.diagnostics.debug_mode);

        process_run_loop_event(
            &key(event::KeyModifiers::SHIFT),
            &mut state,
            &mut has_resize,
        );
        assert_eq!(state.diagnostics.debug_layer, DebugLayer::BaseOnly);

        process_run_loop_event(
            &key(event::KeyModifiers::SHIFT),
            &mut state,
            &mut has_resize,
        );
        assert_eq!(state.diagnostics.debug_layer, DebugLayer::All);
    }

    #[test]
    fn shift_f12_does_not_also_toggle_overlay() {
        // Regression for the modifier disambiguation: pre-fix, the F12
        // arm matched `..` modifiers so Shift+F12 would both cycle the
        // layer AND toggle the overlay on the same press.
        let mut state = FrameState::default();
        let mut has_resize = false;
        let before = state.diagnostics.debug_mode;
        process_run_loop_event(
            &key(event::KeyModifiers::SHIFT),
            &mut state,
            &mut has_resize,
        );
        assert_eq!(
            state.diagnostics.debug_mode, before,
            "Shift+F12 must not flip the on/off toggle"
        );
    }

    #[test]
    fn plain_f12_does_not_cycle_layer() {
        // Symmetric guard: pressing plain F12 must not change the active
        // layer, only the on/off flag.
        let mut state = FrameState::default();
        let mut has_resize = false;
        let before = state.diagnostics.debug_layer;
        process_run_loop_event(&key(event::KeyModifiers::NONE), &mut state, &mut has_resize);
        assert_eq!(state.diagnostics.debug_layer, before);
    }

    // ── Issue #268: Ctrl+F12 devtools inspector toggle ───────────────────

    #[test]
    fn ctrl_f12_toggles_inspector_independently() {
        let mut state = FrameState::default();
        let mut has_resize = false;
        assert!(!state.diagnostics.inspector_mode);

        // Ctrl+F12 flips the inspector without touching debug overlay state.
        process_run_loop_event(
            &key(event::KeyModifiers::CONTROL),
            &mut state,
            &mut has_resize,
        );
        assert!(state.diagnostics.inspector_mode);
        assert!(
            !state.diagnostics.debug_mode,
            "Ctrl+F12 must not toggle the F12 outline overlay"
        );
        assert_eq!(
            state.diagnostics.debug_layer,
            DebugLayer::All,
            "Ctrl+F12 must not cycle the debug layer"
        );

        // A second Ctrl+F12 toggles it back off.
        process_run_loop_event(
            &key(event::KeyModifiers::CONTROL),
            &mut state,
            &mut has_resize,
        );
        assert!(!state.diagnostics.inspector_mode);
    }

    #[test]
    fn plain_and_shift_f12_do_not_touch_inspector() {
        let mut state = FrameState::default();
        let mut has_resize = false;
        // Plain F12 (overlay toggle) leaves the inspector alone.
        process_run_loop_event(&key(event::KeyModifiers::NONE), &mut state, &mut has_resize);
        assert!(state.diagnostics.debug_mode);
        assert!(!state.diagnostics.inspector_mode);
        // Shift+F12 (layer cycle) also leaves the inspector alone.
        process_run_loop_event(
            &key(event::KeyModifiers::SHIFT),
            &mut state,
            &mut has_resize,
        );
        assert!(!state.diagnostics.inspector_mode);
    }

    // ── Issue #263: RunConfig::handle_suspend ────────────────────────────

    #[test]
    fn handle_suspend_defaults_to_true() {
        assert!(RunConfig::default().handle_suspend);
    }

    #[test]
    fn handle_suspend_builder_opts_out() {
        let cfg = RunConfig::default().handle_suspend(false);
        assert!(!cfg.handle_suspend);
    }

    #[test]
    fn handle_suspend_builder_is_independent_of_ctrl_c() {
        // Toggling suspend must not perturb the unrelated Ctrl+C toggle.
        let cfg = RunConfig::default()
            .handle_ctrl_c(false)
            .handle_suspend(false);
        assert!(!cfg.handle_ctrl_c);
        assert!(!cfg.handle_suspend);

        let cfg = RunConfig::default().handle_suspend(true);
        assert!(cfg.handle_suspend);
        assert!(cfg.handle_ctrl_c, "Ctrl+C default preserved");
    }

    // ── v0.21.1: resize debounce / coalesce ─────────────────────────────

    fn resize(w: u32, h: u32) -> Event {
        Event::Resize(w, h)
    }

    #[test]
    fn resize_batch_coalesces_to_single_invocation() {
        // Three resize events in one poll batch must collapse to exactly one
        // `on_resize` call (the helper that drives the single end-of-batch
        // call in `poll_events`). The final size is irrelevant to the count —
        // `handle_resize` re-reads `terminal::size()` — but we feed distinct
        // sizes to mirror a real drag burst.
        let batch = vec![resize(80, 24), resize(100, 30), resize(120, 40)];
        assert_eq!(
            resize_invocations_for_batch(&batch),
            1,
            "a burst of resizes must coalesce to one on_resize"
        );
    }

    #[test]
    fn resize_batch_without_resize_invokes_zero_times() {
        // A batch with no resize event must not trigger `on_resize` at all.
        let batch = vec![key(event::KeyModifiers::NONE)];
        assert_eq!(resize_invocations_for_batch(&batch), 0);
        // Empty batch is likewise a no-op.
        assert_eq!(resize_invocations_for_batch(&[]), 0);
    }

    #[test]
    fn resize_coalesce_uses_final_size_via_has_resize_flag() {
        // The single deferred `on_resize` is gated on `has_resize`, which
        // `process_run_loop_event` sets to `true` for any resize in the batch.
        // Feeding three resizes leaves the flag set once (idempotent), and the
        // coalescing helper agrees — this is exactly the `debug_assert_eq!`
        // invariant `poll_events` checks before its single `on_resize` call.
        let mut state = FrameState::default();
        let mut has_resize = false;
        let batch = vec![resize(80, 24), resize(100, 30), resize(120, 40)];
        for ev in &batch {
            process_run_loop_event(ev, &mut state, &mut has_resize);
        }
        assert!(has_resize, "any resize in the batch must set has_resize");
        assert_eq!(
            usize::from(has_resize),
            resize_invocations_for_batch(&batch)
        );
    }

    /// End-to-end test of the real signal-delivery wiring: install the
    /// handler, deliver a real `SIGCONT` through signal-hook's registry +
    /// background thread, then drop the guard and confirm it closes the
    /// registration and joins the thread without hanging or panicking.
    ///
    /// `SIGCONT`'s default disposition is "continue", so it is safe to raise on
    /// the running test process — unlike `SIGTSTP`, which would stop the test
    /// runner. The suspend (`SIGTSTP`) sequence itself is covered hermetically
    /// by the `write_suspend_sequence` unit tests in `terminal`.
    #[cfg(unix)]
    #[test]
    fn suspend_handler_installs_delivers_and_tears_down() {
        // In constrained sandboxes signal registration can fail; if so the
        // wiring under test cannot be exercised, so skip rather than flake.
        let Ok(guard) = install_suspend_handler(terminal::test_session_snapshot()) else {
            return;
        };

        // Deliver a real SIGCONT; the background thread must drain it. With no
        // prior SIGTSTP the handler's `has_terminal` guard makes this a no-op
        // re-enter (idempotency), which is exactly what we want to verify does
        // not corrupt state or crash the thread.
        let _ = signal_hook::low_level::raise(signal_hook::consts::SIGCONT);
        std::thread::sleep(Duration::from_millis(50));

        // Dropping the guard closes the registration and joins the thread.
        // If `Handle::close` failed to wake `Signals::forever`, this hangs and
        // the test times out — a real regression signal.
        drop(guard);
    }
}