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
use super::*;
/// Options for [`Context::modal_with`].
///
/// Controls focus behavior when a modal overlay is active.
///
/// # Example
///
/// ```no_run
/// # let mut show = true;
/// # slt::run(|ui: &mut slt::Context| {
/// if show {
/// ui.modal_with(slt::context::ModalOptions { tab_trap: true }, |ui| {
/// ui.text("Are you sure?");
/// if ui.button("OK").clicked { show = false; }
/// });
/// }
/// # });
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ModalOptions {
/// When `true`, Tab/Shift+Tab navigation cannot leave the modal's focus
/// range, even if [`Context::set_focus_index`] or a mouse click moved
/// focus outside.
///
/// Default: `true` — aligned with WCAG 2.1 SC 2.4.3 (Focus Order),
/// which recommends trapping focus inside modal dialogs.
///
/// Set to `false` to preserve the legacy behavior where focus could
/// escape via programmatic means.
pub tab_trap: bool,
}
impl Default for ModalOptions {
fn default() -> Self {
Self { tab_trap: true }
}
}
/// Fluent builder for configuring containers before calling `.col()` or `.row()`.
///
/// Obtain one via [`Context::container`] or [`Context::bordered`]. Chain the
/// configuration methods you need, then finalize with `.col(|ui| { ... })` or
/// `.row(|ui| { ... })`.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// use slt::{Border, Color};
/// ui.container()
/// .border(Border::Rounded)
/// .p(1)
/// .grow(1)
/// .col(|ui| {
/// ui.text("inside a bordered, padded, growing column");
/// });
/// # });
/// ```
#[must_use = "ContainerBuilder does nothing until .col(), .row(), .line(), or .draw() is called"]
pub struct ContainerBuilder<'a> {
pub(crate) ctx: &'a mut Context,
/// Resolved main-axis gap, in cells. Signed (#222): negative means
/// adjacent children overlap, set via [`ContainerBuilder::gap_overlap`].
/// The public [`ContainerBuilder::gap`] setter takes `u32` and is
/// source-compatible; only `gap_overlap` can store a negative value.
pub(crate) gap: i32,
pub(crate) row_gap: Option<u32>,
pub(crate) col_gap: Option<u32>,
pub(crate) align: Align,
pub(crate) align_self_value: Option<Align>,
pub(crate) justify: Justify,
pub(crate) border: Option<Border>,
pub(crate) border_sides: BorderSides,
pub(crate) border_style: Style,
pub(crate) bg: Option<Color>,
pub(crate) text_color: Option<Color>,
pub(crate) dark_bg: Option<Color>,
pub(crate) dark_border_style: Option<Style>,
pub(crate) group_hover_bg: Option<Color>,
pub(crate) group_hover_border_style: Option<Style>,
pub(crate) group_name: Option<std::sync::Arc<str>>,
pub(crate) padding: Padding,
pub(crate) margin: Margin,
pub(crate) constraints: Constraints,
pub(crate) title: Option<(String, Style)>,
pub(crate) grow: u16,
/// Opt-in flex-shrink flag. Set via [`ContainerBuilder::shrink`].
///
/// When `true`, this container participates in proportional shrinking
/// if its parent row/column overflows. Default `false` keeps the
/// historic overflow-by-design behavior. Closes #161.
pub(crate) shrink_flag: bool,
/// Opt-in container-level flex-wrap flag. Set via
/// [`ContainerBuilder::wrap`].
///
/// When `true` on a row, children that overflow the available width flow
/// onto subsequent lines instead of overflowing past the right edge.
/// Default `false` keeps the historic single-line behavior. No-op on a
/// column. Closes #258.
pub(crate) wrap_flag: bool,
/// Optional flex-basis (initial main-axis size, in cells). Set via
/// [`ContainerBuilder::basis`]. `None` (default) falls back to the
/// child's min size, preserving current behavior. Closes #258.
pub(crate) basis: Option<u32>,
pub(crate) scroll_offset: Option<u32>,
/// Horizontal scroll offset for a scrollable row (#247). Set internally by
/// [`crate::Context::scrollable`] from `ScrollState::offset_x`; carried into
/// `BeginScrollableArgs` and applied by the tree builder only when the
/// finalizing direction is `Direction::Row`.
pub(crate) scroll_offset_x: Option<u32>,
pub(crate) theme_override: Option<Theme>,
}
/// Drawing context for the [`Context::canvas`] widget.
///
/// Provides pixel-level drawing on a braille character grid. Each terminal
/// cell maps to a 2x4 dot matrix, so a canvas of `width` columns x `height`
/// rows gives `width*2` x `height*4` pixel resolution.
/// A colored pixel in the canvas grid.
#[derive(Debug, Clone, Copy)]
struct CanvasPixel {
bits: u32,
color: Color,
}
/// Text label placed on the canvas.
#[derive(Debug, Clone)]
struct CanvasLabel {
x: usize,
y: usize,
text: String,
color: Color,
}
/// A layer in the canvas, supporting z-ordering.
#[derive(Debug, Clone)]
struct CanvasLayer {
grid: Vec<Vec<CanvasPixel>>,
labels: Vec<CanvasLabel>,
}
/// Drawing context for the canvas widget.
pub struct CanvasContext {
layers: Vec<CanvasLayer>,
cols: usize,
rows: usize,
px_w: usize,
px_h: usize,
current_color: Color,
/// Flat scratch buffer for `render()` pixel composition.
/// Capacity = `cols * rows`; flat index = `row * cols + col`.
scratch_pixels: Vec<CanvasPixel>,
/// Flat scratch buffer for `render()` label overlay.
/// Capacity = `cols * rows`; flat index = `row * cols + col`.
scratch_labels: Vec<Option<(char, Color)>>,
}
/// Integer square root for non-negative `i64` values, returning `isize`.
///
/// Uses an `f64` seed plus a bounded correction step to absorb rounding at
/// integer boundaries. Avoids the unconditional `f64` round-trip used in
/// hot canvas paths (e.g. `filled_circle`). Replace with `u64::isqrt()`
/// once the project MSRV reaches 1.84.
#[inline]
fn isqrt_i64(n: i64) -> isize {
if n <= 0 {
return 0;
}
let mut x = (n as f64).sqrt() as i64;
// Single correction step handles f64 rounding at integer boundaries.
while x > 0 && x.saturating_mul(x) > n {
x -= 1;
}
while (x + 1).saturating_mul(x + 1) <= n {
x += 1;
}
x as isize
}
impl CanvasContext {
pub(crate) fn new(cols: usize, rows: usize) -> Self {
let cell_count = cols.saturating_mul(rows);
Self {
layers: vec![Self::new_layer(cols, rows)],
cols,
rows,
px_w: cols * 2,
px_h: rows * 4,
current_color: Color::Reset,
scratch_pixels: vec![
CanvasPixel {
bits: 0,
color: Color::Reset,
};
cell_count
],
scratch_labels: vec![None; cell_count],
}
}
fn new_layer(cols: usize, rows: usize) -> CanvasLayer {
CanvasLayer {
grid: vec![
vec![
CanvasPixel {
bits: 0,
color: Color::Reset,
};
cols
];
rows
],
labels: Vec::new(),
}
}
fn current_layer_mut(&mut self) -> Option<&mut CanvasLayer> {
self.layers.last_mut()
}
fn dot_with_color(&mut self, x: usize, y: usize, color: Color) {
if x >= self.px_w || y >= self.px_h {
return;
}
let char_col = x / 2;
let char_row = y / 4;
let sub_col = x % 2;
let sub_row = y % 4;
const LEFT_BITS: [u32; 4] = [0x01, 0x02, 0x04, 0x40];
const RIGHT_BITS: [u32; 4] = [0x08, 0x10, 0x20, 0x80];
let bit = if sub_col == 0 {
LEFT_BITS[sub_row]
} else {
RIGHT_BITS[sub_row]
};
if let Some(layer) = self.current_layer_mut() {
let cell = &mut layer.grid[char_row][char_col];
let new_bits = cell.bits | bit;
if new_bits != cell.bits {
cell.bits = new_bits;
cell.color = color;
}
}
}
fn dot_isize(&mut self, x: isize, y: isize) {
if x >= 0 && y >= 0 {
self.dot(x as usize, y as usize);
}
}
/// Get the pixel width of the canvas.
pub fn width(&self) -> usize {
self.px_w
}
/// Get the pixel height of the canvas.
pub fn height(&self) -> usize {
self.px_h
}
/// Set a single pixel at `(x, y)`.
pub fn dot(&mut self, x: usize, y: usize) {
self.dot_with_color(x, y, self.current_color);
}
/// Draw a line from `(x0, y0)` to `(x1, y1)` using Bresenham's algorithm.
pub fn line(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
let (mut x, mut y) = (x0 as isize, y0 as isize);
let (x1, y1) = (x1 as isize, y1 as isize);
let dx = (x1 - x).abs();
let dy = -(y1 - y).abs();
let sx = if x < x1 { 1 } else { -1 };
let sy = if y < y1 { 1 } else { -1 };
let mut err = dx + dy;
loop {
self.dot_isize(x, y);
if x == x1 && y == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
err += dy;
x += sx;
}
if e2 <= dx {
err += dx;
y += sy;
}
}
}
/// Draw a rectangle outline from `(x, y)` with `w` width and `h` height.
pub fn rect(&mut self, x: usize, y: usize, w: usize, h: usize) {
if w == 0 || h == 0 {
return;
}
self.line(x, y, x + w.saturating_sub(1), y);
self.line(
x + w.saturating_sub(1),
y,
x + w.saturating_sub(1),
y + h.saturating_sub(1),
);
self.line(
x + w.saturating_sub(1),
y + h.saturating_sub(1),
x,
y + h.saturating_sub(1),
);
self.line(x, y + h.saturating_sub(1), x, y);
}
/// Draw a circle outline centered at `(cx, cy)` with radius `r`.
pub fn circle(&mut self, cx: usize, cy: usize, r: usize) {
let mut x = r as isize;
let mut y: isize = 0;
let mut err: isize = 1 - x;
let (cx, cy) = (cx as isize, cy as isize);
while x >= y {
for &(dx, dy) in &[
(x, y),
(y, x),
(-x, y),
(-y, x),
(x, -y),
(y, -x),
(-x, -y),
(-y, -x),
] {
let px = cx + dx;
let py = cy + dy;
self.dot_isize(px, py);
}
y += 1;
if err < 0 {
err += 2 * y + 1;
} else {
x -= 1;
err += 2 * (y - x) + 1;
}
}
}
/// Set the drawing color for subsequent shapes.
pub fn set_color(&mut self, color: Color) {
self.current_color = color;
}
/// Get the current drawing color.
pub fn color(&self) -> Color {
self.current_color
}
/// Draw a filled rectangle.
pub fn filled_rect(&mut self, x: usize, y: usize, w: usize, h: usize) {
if w == 0 || h == 0 {
return;
}
let x_end = x.saturating_add(w).min(self.px_w);
let y_end = y.saturating_add(h).min(self.px_h);
if x >= x_end || y >= y_end {
return;
}
for yy in y..y_end {
self.line(x, yy, x_end.saturating_sub(1), yy);
}
}
/// Draw a filled circle.
pub fn filled_circle(&mut self, cx: usize, cy: usize, r: usize) {
let (cx, cy, r) = (cx as isize, cy as isize, r as isize);
for y in (cy - r)..=(cy + r) {
let dy = y - cy;
let span_sq = (r * r - dy * dy).max(0);
// TODO(msrv): switch to u64::isqrt() when MSRV >= 1.84
let dx = isqrt_i64(span_sq as i64);
for x in (cx - dx)..=(cx + dx) {
self.dot_isize(x, y);
}
}
}
/// Draw a triangle outline.
pub fn triangle(&mut self, x0: usize, y0: usize, x1: usize, y1: usize, x2: usize, y2: usize) {
self.line(x0, y0, x1, y1);
self.line(x1, y1, x2, y2);
self.line(x2, y2, x0, y0);
}
/// Draw a filled triangle.
pub fn filled_triangle(
&mut self,
x0: usize,
y0: usize,
x1: usize,
y1: usize,
x2: usize,
y2: usize,
) {
let vertices = [
(x0 as isize, y0 as isize),
(x1 as isize, y1 as isize),
(x2 as isize, y2 as isize),
];
let min_y = vertices.iter().map(|(_, y)| *y).min().unwrap_or(0);
let max_y = vertices.iter().map(|(_, y)| *y).max().unwrap_or(-1);
for y in min_y..=max_y {
// A triangle has exactly 3 edges -> at most 3 intersections per
// scanline. A 4-element stack array avoids per-scanline heap
// allocations from the previous Vec<f64>.
let mut intersections = [0.0f64; 4];
let mut isect_count = 0usize;
for edge in [(0usize, 1usize), (1usize, 2usize), (2usize, 0usize)] {
let (x_a, y_a) = vertices[edge.0];
let (x_b, y_b) = vertices[edge.1];
if y_a == y_b {
continue;
}
let (x_start, y_start, x_end, y_end) = if y_a < y_b {
(x_a, y_a, x_b, y_b)
} else {
(x_b, y_b, x_a, y_a)
};
if y < y_start || y >= y_end {
continue;
}
let t = (y - y_start) as f64 / (y_end - y_start) as f64;
if isect_count < intersections.len() {
intersections[isect_count] = x_start as f64 + t * (x_end - x_start) as f64;
isect_count += 1;
}
}
intersections[..isect_count].sort_by(|a, b| a.total_cmp(b));
let mut i = 0usize;
while i + 1 < isect_count {
let x_start = intersections[i].ceil() as isize;
let x_end = intersections[i + 1].floor() as isize;
for x in x_start..=x_end {
self.dot_isize(x, y);
}
i += 2;
}
}
self.triangle(x0, y0, x1, y1, x2, y2);
}
/// Draw multiple points at once.
pub fn points(&mut self, pts: &[(usize, usize)]) {
for &(x, y) in pts {
self.dot(x, y);
}
}
/// Draw a polyline connecting the given points in order.
pub fn polyline(&mut self, pts: &[(usize, usize)]) {
for window in pts.windows(2) {
if let [(x0, y0), (x1, y1)] = window {
self.line(*x0, *y0, *x1, *y1);
}
}
}
/// Place a text label at pixel position `(x, y)`.
/// Text is rendered in regular characters overlaying the braille grid.
pub fn print(&mut self, x: usize, y: usize, text: &str) {
if text.is_empty() {
return;
}
let color = self.current_color;
if let Some(layer) = self.current_layer_mut() {
layer.labels.push(CanvasLabel {
x,
y,
text: text.to_string(),
color,
});
}
}
/// Start a new drawing layer. Shapes on later layers overlay earlier ones.
pub fn layer(&mut self) {
self.layers.push(Self::new_layer(self.cols, self.rows));
}
pub(crate) fn render(&mut self) -> Vec<Vec<(String, Color)>> {
let cell_count = self.cols.saturating_mul(self.rows);
// Reset reusable scratch buffers, growing them only if `cols`/`rows`
// changed since construction. `fill` keeps the existing allocation.
if self.scratch_pixels.len() < cell_count {
self.scratch_pixels.resize(
cell_count,
CanvasPixel {
bits: 0,
color: Color::Reset,
},
);
}
if self.scratch_labels.len() < cell_count {
self.scratch_labels.resize(cell_count, None);
}
for px in &mut self.scratch_pixels[..cell_count] {
*px = CanvasPixel {
bits: 0,
color: Color::Reset,
};
}
for slot in &mut self.scratch_labels[..cell_count] {
*slot = None;
}
let cols = self.cols;
let rows = self.rows;
for layer in &self.layers {
for (row, src_row) in layer.grid.iter().enumerate().take(rows) {
let row_offset = row * cols;
for (col, src) in src_row.iter().enumerate().take(cols) {
if src.bits == 0 {
continue;
}
let dst = &mut self.scratch_pixels[row_offset + col];
let merged = dst.bits | src.bits;
if merged != dst.bits {
dst.bits = merged;
dst.color = src.color;
}
}
}
for label in &layer.labels {
let row = label.y / 4;
if row >= rows {
continue;
}
let start_col = label.x / 2;
let row_offset = row * cols;
for (offset, ch) in label.text.chars().enumerate() {
let col = start_col + offset;
if col >= cols {
break;
}
self.scratch_labels[row_offset + col] = Some((ch, label.color));
}
}
}
let mut lines: Vec<Vec<(String, Color)>> = Vec::with_capacity(rows);
for row in 0..rows {
let row_offset = row * cols;
let mut segments: Vec<(String, Color)> = Vec::new();
let mut current_color: Option<Color> = None;
let mut current_text = String::new();
for col in 0..cols {
let idx = row_offset + col;
let (ch, color) = if let Some((label_ch, label_color)) = self.scratch_labels[idx] {
(label_ch, label_color)
} else {
let pixel = self.scratch_pixels[idx];
let ch = char::from_u32(0x2800 + pixel.bits).unwrap_or(' ');
(ch, pixel.color)
};
match current_color {
Some(c) if c == color => {
current_text.push(ch);
}
Some(c) => {
segments.push((std::mem::take(&mut current_text), c));
current_text.push(ch);
current_color = Some(color);
}
None => {
current_text.push(ch);
current_color = Some(color);
}
}
}
if let Some(color) = current_color {
segments.push((current_text, color));
}
lines.push(segments);
}
lines
}
}
macro_rules! define_breakpoint_methods {
(
base = $base:ident,
arg = $arg:ident : $arg_ty:ty,
xs = $xs_fn:ident => [$( $xs_doc:literal ),* $(,)?],
sm = $sm_fn:ident => [$( $sm_doc:literal ),* $(,)?],
md = $md_fn:ident => [$( $md_doc:literal ),* $(,)?],
lg = $lg_fn:ident => [$( $lg_doc:literal ),* $(,)?],
xl = $xl_fn:ident => [$( $xl_doc:literal ),* $(,)?],
at = $at_fn:ident => [$( $at_doc:literal ),* $(,)?]
) => {
$(#[doc = $xs_doc])*
pub fn $xs_fn(self, $arg: $arg_ty) -> Self {
if self.ctx.breakpoint() == Breakpoint::Xs {
self.$base($arg)
} else {
self
}
}
$(#[doc = $sm_doc])*
pub fn $sm_fn(self, $arg: $arg_ty) -> Self {
if self.ctx.breakpoint() == Breakpoint::Sm {
self.$base($arg)
} else {
self
}
}
$(#[doc = $md_doc])*
pub fn $md_fn(self, $arg: $arg_ty) -> Self {
if self.ctx.breakpoint() == Breakpoint::Md {
self.$base($arg)
} else {
self
}
}
$(#[doc = $lg_doc])*
pub fn $lg_fn(self, $arg: $arg_ty) -> Self {
if self.ctx.breakpoint() == Breakpoint::Lg {
self.$base($arg)
} else {
self
}
}
$(#[doc = $xl_doc])*
pub fn $xl_fn(self, $arg: $arg_ty) -> Self {
if self.ctx.breakpoint() == Breakpoint::Xl {
self.$base($arg)
} else {
self
}
}
$(#[doc = $at_doc])*
pub fn $at_fn(self, bp: Breakpoint, $arg: $arg_ty) -> Self {
if self.ctx.breakpoint() == bp {
self.$base($arg)
} else {
self
}
}
};
}
impl<'a> ContainerBuilder<'a> {
// ── border ───────────────────────────────────────────────────────
/// Apply a reusable [`ContainerStyle`] recipe. Only set fields override
/// the builder's current values. Chain multiple `.apply()` calls to compose.
///
/// If the style has an [`ContainerStyle::extends`] base, the base is applied
/// first, then the style's own fields override.
///
/// [`ThemeColor`] fields (`theme_bg`, `theme_text_color`, `theme_border_fg`)
/// are resolved against the active theme at apply time.
pub fn apply(mut self, style: &ContainerStyle) -> Self {
// Apply base style first if this style extends another
if let Some(base) = style.extends {
self = self.apply(base);
}
if let Some(v) = style.border {
self.border = Some(v);
}
if let Some(v) = style.border_sides {
self.border_sides = v;
}
if let Some(v) = style.border_style {
self.border_style = v;
}
if let Some(v) = style.bg {
self.bg = Some(v);
}
if let Some(v) = style.dark_bg {
self.dark_bg = Some(v);
}
if let Some(v) = style.dark_border_style {
self.dark_border_style = Some(v);
}
if let Some(v) = style.padding {
self.padding = v;
}
if let Some(v) = style.margin {
self.margin = v;
}
if let Some(v) = style.gap {
// `ContainerStyle::gap` stays `Option<u32>` (positive only); only
// `gap_overlap` produces a negative builder gap (#222).
self.gap = v as i32;
}
if let Some(v) = style.row_gap {
self.row_gap = Some(v);
}
if let Some(v) = style.col_gap {
self.col_gap = Some(v);
}
if let Some(v) = style.grow {
self.grow = v;
}
if let Some(v) = style.align {
self.align = v;
}
if let Some(v) = style.align_self {
self.align_self_value = Some(v);
}
if let Some(v) = style.justify {
self.justify = v;
}
if let Some(v) = style.text_color {
self.text_color = Some(v);
}
if let Some(w) = style.w {
self.constraints = self.constraints.w(w);
}
if let Some(h) = style.h {
self.constraints = self.constraints.h(h);
}
if let Some(v) = style.min_w {
self.constraints.set_min_width(Some(v));
}
if let Some(v) = style.max_w {
self.constraints.set_max_width(Some(v));
}
if let Some(v) = style.min_h {
self.constraints.set_min_height(Some(v));
}
if let Some(v) = style.max_h {
self.constraints.set_max_height(Some(v));
}
if let Some(v) = style.w_pct {
self.constraints.set_width_pct(Some(v));
}
if let Some(v) = style.h_pct {
self.constraints.set_height_pct(Some(v));
}
// Resolve ThemeColor fields against the active theme (overrides literal colors)
if let Some(tc) = style.theme_bg {
self.bg = Some(self.ctx.theme.resolve(tc));
}
if let Some(tc) = style.theme_text_color {
self.text_color = Some(self.ctx.theme.resolve(tc));
}
if let Some(tc) = style.theme_border_fg {
let color = self.ctx.theme.resolve(tc);
self.border_style = Style::new().fg(color);
}
self
}
/// Set the border style.
pub fn border(mut self, border: Border) -> Self {
self.border = Some(border);
self
}
/// Show or hide the top border.
pub fn border_top(mut self, show: bool) -> Self {
self.border_sides.top = show;
self
}
/// Show or hide the right border.
pub fn border_right(mut self, show: bool) -> Self {
self.border_sides.right = show;
self
}
/// Show or hide the bottom border.
pub fn border_bottom(mut self, show: bool) -> Self {
self.border_sides.bottom = show;
self
}
/// Show or hide the left border.
pub fn border_left(mut self, show: bool) -> Self {
self.border_sides.left = show;
self
}
/// Set which border sides are visible.
pub fn border_sides(mut self, sides: BorderSides) -> Self {
self.border_sides = sides;
self
}
/// Show only left and right borders. Shorthand for horizontal border sides.
pub fn border_x(self) -> Self {
self.border_sides(BorderSides {
top: false,
right: true,
bottom: false,
left: true,
})
}
/// Show only top and bottom borders. Shorthand for vertical border sides.
pub fn border_y(self) -> Self {
self.border_sides(BorderSides {
top: true,
right: false,
bottom: true,
left: false,
})
}
/// Set rounded border style. Shorthand for `.border(Border::Rounded)`.
pub fn rounded(self) -> Self {
self.border(Border::Rounded)
}
/// Set the style applied to the border characters.
pub fn border_style(mut self, style: Style) -> Self {
self.border_style = style;
self
}
/// Set the border foreground color.
pub fn border_fg(mut self, color: Color) -> Self {
self.border_style = self.border_style.fg(color);
self
}
/// Border style used when dark mode is active.
pub fn dark_border_style(mut self, style: Style) -> Self {
self.dark_border_style = Some(style);
self
}
/// Set the background color.
pub fn bg(mut self, color: Color) -> Self {
self.bg = Some(color);
self
}
/// Set the default text color for all child text elements in this container.
/// Individual `.fg()` calls on text elements will still override this.
pub fn text_color(mut self, color: Color) -> Self {
self.text_color = Some(color);
self
}
/// Background color used when dark mode is active.
pub fn dark_bg(mut self, color: Color) -> Self {
self.dark_bg = Some(color);
self
}
/// Background color applied when the parent group is hovered.
pub fn group_hover_bg(mut self, color: Color) -> Self {
self.group_hover_bg = Some(color);
self
}
/// Border style applied when the parent group is hovered.
pub fn group_hover_border_style(mut self, style: Style) -> Self {
self.group_hover_border_style = Some(style);
self
}
// ── padding (Tailwind: p, px, py, pt, pr, pb, pl) ───────────────
/// Set uniform padding on all sides.
pub fn p(mut self, value: u32) -> Self {
self.padding = Padding::all(value);
self
}
/// Set uniform padding on all sides. Deprecated alias for [`p`](Self::p).
#[deprecated(since = "0.20.0", note = "Use `p()` instead")]
pub fn pad(self, value: u32) -> Self {
self.p(value)
}
/// Set horizontal padding (left and right).
pub fn px(mut self, value: u32) -> Self {
self.padding.left = value;
self.padding.right = value;
self
}
/// Set vertical padding (top and bottom).
pub fn py(mut self, value: u32) -> Self {
self.padding.top = value;
self.padding.bottom = value;
self
}
/// Set top padding.
pub fn pt(mut self, value: u32) -> Self {
self.padding.top = value;
self
}
/// Set right padding.
pub fn pr(mut self, value: u32) -> Self {
self.padding.right = value;
self
}
/// Set bottom padding.
pub fn pb(mut self, value: u32) -> Self {
self.padding.bottom = value;
self
}
/// Set left padding.
pub fn pl(mut self, value: u32) -> Self {
self.padding.left = value;
self
}
/// Set per-side padding using a [`Padding`] value.
pub fn padding(mut self, padding: Padding) -> Self {
self.padding = padding;
self
}
// ── margin (Tailwind: m, mx, my, mt, mr, mb, ml) ────────────────
/// Set uniform margin on all sides.
pub fn m(mut self, value: u32) -> Self {
self.margin = Margin::all(value);
self
}
/// Set horizontal margin (left and right).
pub fn mx(mut self, value: u32) -> Self {
self.margin.left = value;
self.margin.right = value;
self
}
/// Set vertical margin (top and bottom).
pub fn my(mut self, value: u32) -> Self {
self.margin.top = value;
self.margin.bottom = value;
self
}
/// Set top margin.
pub fn mt(mut self, value: u32) -> Self {
self.margin.top = value;
self
}
/// Set right margin.
pub fn mr(mut self, value: u32) -> Self {
self.margin.right = value;
self
}
/// Set bottom margin.
pub fn mb(mut self, value: u32) -> Self {
self.margin.bottom = value;
self
}
/// Set left margin.
pub fn ml(mut self, value: u32) -> Self {
self.margin.left = value;
self
}
/// Set per-side margin using a [`Margin`] value.
pub fn margin(mut self, margin: Margin) -> Self {
self.margin = margin;
self
}
// ── sizing (Tailwind: w, h, min-w, max-w, min-h, max-h) ────────
/// Set a fixed width (sets both min and max width).
pub fn w(mut self, value: u32) -> Self {
self.constraints = self.constraints.w(value);
self
}
define_breakpoint_methods!(
base = w,
arg = value: u32,
xs = xs_w => [
"Width applied only at Xs breakpoint (< 40 cols).",
"",
"# Example",
"```ignore",
"ui.container().w(20).md_w(40).lg_w(60).col(|ui| { ... });",
"```"
],
sm = sm_w => ["Width applied only at Sm breakpoint (40-79 cols)."],
md = md_w => ["Width applied only at Md breakpoint (80-119 cols)."],
lg = lg_w => ["Width applied only at Lg breakpoint (120-159 cols)."],
xl = xl_w => ["Width applied only at Xl breakpoint (>= 160 cols)."],
at = w_at => ["Width applied only at the given breakpoint."]
);
/// Set a fixed height (sets both min and max height).
pub fn h(mut self, value: u32) -> Self {
self.constraints = self.constraints.h(value);
self
}
define_breakpoint_methods!(
base = h,
arg = value: u32,
xs = xs_h => ["Height applied only at Xs breakpoint (< 40 cols)."],
sm = sm_h => ["Height applied only at Sm breakpoint (40-79 cols)."],
md = md_h => ["Height applied only at Md breakpoint (80-119 cols)."],
lg = lg_h => ["Height applied only at Lg breakpoint (120-159 cols)."],
xl = xl_h => ["Height applied only at Xl breakpoint (>= 160 cols)."],
at = h_at => ["Height applied only at the given breakpoint."]
);
/// Set the minimum width constraint. Shorthand for [`min_width`](Self::min_width).
pub fn min_w(mut self, value: u32) -> Self {
self.constraints.set_min_width(Some(value));
self
}
define_breakpoint_methods!(
base = min_w,
arg = value: u32,
xs = xs_min_w => ["Minimum width applied only at Xs breakpoint (< 40 cols)."],
sm = sm_min_w => ["Minimum width applied only at Sm breakpoint (40-79 cols)."],
md = md_min_w => ["Minimum width applied only at Md breakpoint (80-119 cols)."],
lg = lg_min_w => ["Minimum width applied only at Lg breakpoint (120-159 cols)."],
xl = xl_min_w => ["Minimum width applied only at Xl breakpoint (>= 160 cols)."],
at = min_w_at => ["Minimum width applied only at the given breakpoint."]
);
/// Set the maximum width constraint. Shorthand for [`max_width`](Self::max_width).
pub fn max_w(mut self, value: u32) -> Self {
self.constraints.set_max_width(Some(value));
self
}
define_breakpoint_methods!(
base = max_w,
arg = value: u32,
xs = xs_max_w => ["Maximum width applied only at Xs breakpoint (< 40 cols)."],
sm = sm_max_w => ["Maximum width applied only at Sm breakpoint (40-79 cols)."],
md = md_max_w => ["Maximum width applied only at Md breakpoint (80-119 cols)."],
lg = lg_max_w => ["Maximum width applied only at Lg breakpoint (120-159 cols)."],
xl = xl_max_w => ["Maximum width applied only at Xl breakpoint (>= 160 cols)."],
at = max_w_at => ["Maximum width applied only at the given breakpoint."]
);
/// Set the minimum height constraint. Shorthand for [`min_height`](Self::min_height).
pub fn min_h(mut self, value: u32) -> Self {
self.constraints.set_min_height(Some(value));
self
}
define_breakpoint_methods!(
base = min_h,
arg = value: u32,
xs = xs_min_h => ["Minimum height applied only at Xs breakpoint (< 40 cols)."],
sm = sm_min_h => ["Minimum height applied only at Sm breakpoint (40-79 cols)."],
md = md_min_h => ["Minimum height applied only at Md breakpoint (80-119 cols)."],
lg = lg_min_h => ["Minimum height applied only at Lg breakpoint (120-159 cols)."],
xl = xl_min_h => ["Minimum height applied only at Xl breakpoint (>= 160 cols)."],
at = min_h_at => ["Minimum height applied only at the given breakpoint."]
);
/// Set the maximum height constraint. Shorthand for [`max_height`](Self::max_height).
pub fn max_h(mut self, value: u32) -> Self {
self.constraints.set_max_height(Some(value));
self
}
define_breakpoint_methods!(
base = max_h,
arg = value: u32,
xs = xs_max_h => ["Maximum height applied only at Xs breakpoint (< 40 cols)."],
sm = sm_max_h => ["Maximum height applied only at Sm breakpoint (40-79 cols)."],
md = md_max_h => ["Maximum height applied only at Md breakpoint (80-119 cols)."],
lg = lg_max_h => ["Maximum height applied only at Lg breakpoint (120-159 cols)."],
xl = xl_max_h => ["Maximum height applied only at Xl breakpoint (>= 160 cols)."],
at = max_h_at => ["Maximum height applied only at the given breakpoint."]
);
/// Set the minimum width constraint in cells. Deprecated alias for [`min_w`](Self::min_w).
#[deprecated(since = "0.20.0", note = "Use `min_w()` instead")]
pub fn min_width(self, value: u32) -> Self {
self.min_w(value)
}
/// Set the maximum width constraint in cells. Deprecated alias for [`max_w`](Self::max_w).
#[deprecated(since = "0.20.0", note = "Use `max_w()` instead")]
pub fn max_width(self, value: u32) -> Self {
self.max_w(value)
}
/// Set the minimum height constraint in rows. Deprecated alias for [`min_h`](Self::min_h).
#[deprecated(since = "0.20.0", note = "Use `min_h()` instead")]
pub fn min_height(self, value: u32) -> Self {
self.min_h(value)
}
/// Set the maximum height constraint in rows. Deprecated alias for [`max_h`](Self::max_h).
#[deprecated(since = "0.20.0", note = "Use `max_h()` instead")]
pub fn max_height(self, value: u32) -> Self {
self.max_h(value)
}
/// Set width as a percentage (1-100) of the parent container.
pub fn w_pct(mut self, pct: u8) -> Self {
self.constraints.set_width_pct(Some(pct.min(100)));
self
}
/// Set height as a percentage (1-100) of the parent container.
pub fn h_pct(mut self, pct: u8) -> Self {
self.constraints.set_height_pct(Some(pct.min(100)));
self
}
/// Set all size constraints at once using a [`Constraints`] value.
pub fn constraints(mut self, constraints: Constraints) -> Self {
self.constraints = constraints;
self
}
// ── flex ─────────────────────────────────────────────────────────
/// Set the gap (in cells) between child elements.
pub fn gap(mut self, gap: u32) -> Self {
self.gap = gap as i32;
self
}
/// Set a *negative* gap, causing adjacent children to overlap by `overlap`
/// cells on the main axis.
///
/// This is SLT's analogue of ratatui's `Layout::spacing(-1)`. The common
/// use is collapsing the duplicate border between two adjacent bordered
/// panels: with `gap_overlap(1)` each panel's shared edge lands in the
/// same column (row layout) or row (column layout), so the doubled border
///
/// ```text
/// ┌────┐┌────┐
/// │ ││ │
/// └────┘└────┘
/// ```
///
/// collapses to a single shared edge.
///
/// `gap_overlap(0)` is identical to `gap(0)` (no overlap). It composes with
/// the existing `gap` family: the last call wins, so call exactly one of
/// `gap` / `gap_overlap` per builder.
///
/// # Rendering note
///
/// SLT does not (yet) merge the shared cells into junction glyphs (`┬`,
/// `┼`, `┴`). When two bordered panels overlap, both write the shared
/// column/row and the later panel's border character wins by buffer-diff
/// order. To get a clean seam, give the panels compatible border styles or
/// drop one panel's shared side (e.g. `border_sides` without the left edge).
///
/// Large overlaps saturate gracefully — `gap_overlap(N)` past a child's
/// extent never panics or wraps; positions clamp at 0.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// use slt::Border;
/// // Two bordered panels sharing one border column.
/// ui.container().gap_overlap(1).row(|ui| {
/// ui.bordered(Border::Single).w(10).col(|ui| {
/// ui.text("left");
/// });
/// ui.bordered(Border::Single).w(10).col(|ui| {
/// ui.text("right");
/// });
/// });
/// # });
/// ```
pub fn gap_overlap(mut self, overlap: u32) -> Self {
self.gap = -(overlap as i32);
self
}
/// Set the gap between children for column layouts (vertical spacing).
/// Overrides `.gap()` when finalized with `.col()`.
pub fn row_gap(mut self, value: u32) -> Self {
self.row_gap = Some(value);
self
}
/// Set the gap between children for row layouts (horizontal spacing).
/// Overrides `.gap()` when finalized with `.row()`.
pub fn col_gap(mut self, value: u32) -> Self {
self.col_gap = Some(value);
self
}
define_breakpoint_methods!(
base = gap,
arg = value: u32,
xs = xs_gap => ["Gap applied only at Xs breakpoint (< 40 cols)."],
sm = sm_gap => ["Gap applied only at Sm breakpoint (40-79 cols)."],
md = md_gap => [
"Gap applied only at Md breakpoint (80-119 cols).",
"",
"# Example",
"```ignore",
"ui.container().gap(0).md_gap(2).col(|ui| { ... });",
"```"
],
lg = lg_gap => ["Gap applied only at Lg breakpoint (120-159 cols)."],
xl = xl_gap => ["Gap applied only at Xl breakpoint (>= 160 cols)."],
at = gap_at => ["Gap applied only at the given breakpoint."]
);
/// Set the flex-grow factor. `1` means the container expands to fill available space.
pub fn grow(mut self, grow: u16) -> Self {
self.grow = grow;
self
}
/// Expand to fill remaining space on the main axis. Shorthand for
/// [`grow(1)`](Self::grow).
///
/// Equivalent to CSS `flex: 1` and ratatui's `Constraint::Fill(1)`.
/// This is the most common case in flex layouts and reads more
/// naturally than `grow(1)` for new readers — the abstract "grow
/// factor" terminology is replaced by a self-documenting verb.
///
/// ```ignore
/// ui.container().fill().col(|ui| { ... });
/// // identical to:
/// ui.container().grow(1).col(|ui| { ... });
/// ```
///
/// For other weights (e.g. a 2:1 split between two siblings), use
/// `grow(N)` directly.
pub fn fill(self) -> Self {
self.grow(1)
}
/// Opt this container into proportional flex-shrink.
///
/// Marks this container as a shrink participant. When the parent
/// row / column overflows (its children's combined width or height
/// exceeds available space), shrink-flagged children scale their
/// fixed sizes by `available / fixed_total` (CSS `flex-shrink`-style).
/// Children without `.shrink()` keep their historic
/// overflow-by-design size and clip naturally.
///
/// Default for every container is `false` — opt in per child.
/// Equivalent to CSS `flex-shrink: 1` (vs the SLT default of `0`).
/// Closes #161.
///
/// # Example
///
/// Two siblings with combined fixed width `60` placed inside a
/// `40`-cell row. Without `.shrink()`, the row overflows; with
/// `.shrink()` on both, each scales to `40 * 30/60 = 20`:
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// // Without shrink — overflows the parent.
/// ui.row(|ui| {
/// ui.container().w(30).col(|ui| { ui.text("left"); });
/// ui.container().w(30).col(|ui| { ui.text("right"); });
/// });
///
/// // With shrink on both — proportional fit, no clipping.
/// ui.row(|ui| {
/// ui.container().w(30).shrink().col(|ui| { ui.text("left"); });
/// ui.container().w(30).shrink().col(|ui| { ui.text("right"); });
/// });
/// # });
/// ```
///
/// # Layout
///
/// Only fixed-width children with `grow == 0` participate. Grow
/// children already absorb leftover space and ignore the shrink
/// flag. Mixing shrink and non-shrink siblings is supported — only
/// the flagged ones contribute to the shrink budget.
pub fn shrink(mut self) -> Self {
self.shrink_flag = true;
self
}
/// Allow row children to wrap onto subsequent lines on main-axis overflow.
///
/// When a `.row()` finalized with `wrap()` has children whose combined
/// width exceeds the available width, the overflowing children flow onto
/// the next line, and lines stack on the cross axis. This is the
/// immediate-mode primitive for tag clouds, chip lists, wrapping toolbars,
/// and responsive card grids that reflow as the terminal resizes — without
/// per-frame breakpoint math. Equivalent to CSS `flex-wrap: wrap`.
///
/// Spacing: within-line (main-axis) spacing uses `gap` / `col_gap` as
/// usual; between-line (cross-axis) spacing uses `row_gap` when set, else
/// `gap`. A child wider than the full available width occupies its own
/// line (clipped, as a single-line row would clip) rather than producing
/// an empty line.
///
/// Row only. On `col()` this is a documented no-op (vertical-axis wrap is
/// out of scope). Default: no wrap (single-line, current
/// overflow-by-design behavior). Closes #258.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// // A chip list that reflows onto as many lines as the width needs.
/// ui.container().wrap().gap(1).row(|ui| {
/// for tag in ["rust", "tui", "flexbox", "wrap", "immediate-mode"] {
/// ui.container().p(1).col(|ui| { ui.text(tag); });
/// }
/// });
/// # });
/// ```
#[doc(alias = "flex-wrap")]
pub fn wrap(mut self) -> Self {
self.wrap_flag = true;
self
}
/// Set the flex-basis: the initial main-axis size (in cells) that `grow`
/// grows from and `shrink` (#161) shrinks from.
///
/// CSS resolves flex sizing as `basis` (initial) → distribute free space
/// by `grow` → distribute the deficit by `shrink`. By default SLT uses a
/// child's min size as that base; `basis(n)` overrides it so a child can
/// say "start at `n` cells, then grow / shrink from there". `None`
/// (default, i.e. not calling this) falls back to the min size, preserving
/// current behavior. Equivalent to CSS `flex-basis: <n>`. Closes #258.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// // Two cards that each start at 10 cells, then split the leftover.
/// ui.row(|ui| {
/// ui.container().basis(10).grow(1).col(|ui| { ui.text("a"); });
/// ui.container().basis(10).grow(1).col(|ui| { ui.text("b"); });
/// });
/// # });
/// ```
#[doc(alias = "flex-basis")]
pub fn basis(mut self, cells: u32) -> Self {
self.basis = Some(cells);
self
}
define_breakpoint_methods!(
base = grow,
arg = value: u16,
xs = xs_grow => ["Grow factor applied only at Xs breakpoint (< 40 cols)."],
sm = sm_grow => ["Grow factor applied only at Sm breakpoint (40-79 cols)."],
md = md_grow => ["Grow factor applied only at Md breakpoint (80-119 cols)."],
lg = lg_grow => ["Grow factor applied only at Lg breakpoint (120-159 cols)."],
xl = xl_grow => ["Grow factor applied only at Xl breakpoint (>= 160 cols)."],
at = grow_at => ["Grow factor applied only at the given breakpoint."]
);
define_breakpoint_methods!(
base = p,
arg = value: u32,
xs = xs_p => ["Uniform padding applied only at Xs breakpoint (< 40 cols)."],
sm = sm_p => ["Uniform padding applied only at Sm breakpoint (40-79 cols)."],
md = md_p => ["Uniform padding applied only at Md breakpoint (80-119 cols)."],
lg = lg_p => ["Uniform padding applied only at Lg breakpoint (120-159 cols)."],
xl = xl_p => ["Uniform padding applied only at Xl breakpoint (>= 160 cols)."],
at = p_at => ["Padding applied only at the given breakpoint."]
);
// ── alignment ───────────────────────────────────────────────────
/// Set the cross-axis alignment of child elements.
pub fn align(mut self, align: Align) -> Self {
self.align = align;
self
}
/// Center children on the cross axis. Shorthand for `.align(Align::Center)`.
pub fn center(self) -> Self {
self.align(Align::Center)
}
/// Set the main-axis content distribution mode.
pub fn justify(mut self, justify: Justify) -> Self {
self.justify = justify;
self
}
/// Distribute children with equal space between; first at start, last at end.
pub fn space_between(self) -> Self {
self.justify(Justify::SpaceBetween)
}
/// Distribute children with equal space around each child.
pub fn space_around(self) -> Self {
self.justify(Justify::SpaceAround)
}
/// Distribute children with equal space between all children and edges.
pub fn space_evenly(self) -> Self {
self.justify(Justify::SpaceEvenly)
}
/// Center children on both axes. Shorthand for `.justify(Justify::Center).align(Align::Center)`.
pub fn flex_center(self) -> Self {
self.justify(Justify::Center).align(Align::Center)
}
/// Override the parent's cross-axis alignment for this container only.
/// Like CSS `align-self`.
pub fn align_self(mut self, align: Align) -> Self {
self.align_self_value = Some(align);
self
}
// ── title ────────────────────────────────────────────────────────
/// Set a plain-text title rendered in the top border.
pub fn title(self, title: impl Into<String>) -> Self {
self.title_styled(title, Style::new())
}
/// Set a styled title rendered in the top border.
pub fn title_styled(mut self, title: impl Into<String>, style: Style) -> Self {
self.title = Some((title.into(), style));
self
}
// ── conditional / grouped builder helpers ───────────────────────
/// Apply `f` only if `cond` is true. Returns the builder for chaining.
///
/// Use this to attach a block of builder modifiers without breaking the
/// fluent chain. The closure takes the builder by value and must return
/// it (matching the rest of `ContainerBuilder`'s by-value API), so any
/// builder method (`.border()`, `.title()`, `.bg()`, etc.) can be chained
/// inside.
///
/// Zero allocation: the closure is inlined and skipped entirely when
/// `cond` is `false`.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// use slt::Border;
/// let highlighted = true;
/// ui.container()
/// .p(1)
/// .with_if(highlighted, |c| c.border(Border::Single).title("Active"))
/// .col(|ui| {
/// ui.text("body");
/// });
/// # });
/// ```
pub fn with_if(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {
if cond { f(self) } else { self }
}
/// Override the active theme for all widgets rendered inside this container.
///
/// The override is scoped to the container body (the closure passed to
/// `.col()`, `.row()`, or `.line()`). The parent theme is restored when
/// the container closes — including on panic.
///
/// All built-in widgets read `ctx.theme` directly for color decisions,
/// so this swap propagates through every nested widget without requiring
/// them to opt in. Nested `.theme(...)` calls correctly nest: the
/// innermost theme wins inside its own subtree, and the outer theme
/// resumes once it closes.
///
/// Independent of [`Context::provide`] / [`Context::use_context`] —
/// this directly mutates the active theme used by SLT-owned widgets,
/// while `provide`/`use_context` is the general-purpose context
/// injection mechanism for user code.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// use slt::{Border, Theme};
/// ui.container()
/// .theme(Theme::light())
/// .border(Border::Rounded)
/// .col(|ui| {
/// ui.text("This subtree renders with the light theme");
/// ui.button("Click me"); // also uses light theme colors
/// });
/// # });
/// ```
pub fn theme(mut self, theme: Theme) -> Self {
self.theme_override = Some(theme);
self
}
/// Apply `f` unconditionally. Useful for factoring out a block of builder
/// modifier calls while keeping the fluent chain intact.
///
/// The closure takes the builder by value and must return it.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// use slt::Border;
/// ui.container()
/// .with(|c| c.border(Border::Rounded).p(1))
/// .col(|ui| {
/// ui.text("body");
/// });
/// # });
/// ```
pub fn with(self, f: impl FnOnce(Self) -> Self) -> Self {
f(self)
}
// ── opt-in scoped cache (issue #273) ───────────────────────────────
/// Opt-in: declare a subtree **stable** when `version_key` is unchanged
/// from the previous frame at this call site.
///
/// This is an **author-controlled cache, not reactive binding**. Your
/// closure is still the app ([Principle 2 — "Your Closure IS the App"]):
/// `f` runs **every frame** exactly like `.col(f)`, so the rendered output
/// is **byte-for-byte identical** to an uncached container — there is no
/// retained widget identity, no message passing, no reactive subscription,
/// and no behavior change whatsoever when you do not call `cached`.
///
/// What `cached` adds is a single, principle-preserving signal: it records
/// the `version_key` you supply (a value you already own — e.g. a hash of
/// the non-streaming inputs, or `StreamingTextState::version` of the
/// *other* panes) and compares it to the key this call site recorded last
/// frame. A match is a *cache hit* (the subtree is declared unchanged); a
/// change, a new call site, the first frame, or a terminal resize is a
/// *miss*. The hit/miss tally is exposed via
/// [`Context::region_cache_hits`](crate::Context::region_cache_hits) /
/// [`Context::region_cache_misses`](crate::Context::region_cache_misses).
///
/// # Why output is identical even on a hit (current implementation)
///
/// Skipping `f` on a hit would require splicing the prior frame's recorded
/// `Command`s, replaying its focus / hit-map / scroll / raw-draw feedback,
/// and reusing its rendered cells — without that full replay the immediate-
/// mode invariant breaks (focus and interaction would silently drop). That
/// replay is deliberately **out of scope** here (it risks reintroducing a
/// retained tree, the thing Principle 2 forbids). So `cached` keeps the
/// invariant absolute — `f` always runs — and instead lands the *safe,
/// reversible* half: a measured, author-keyed stability gate plus
/// diagnostics. The streaming benchmark `bench_streaming_append_chat`
/// (`benches/benchmarks.rs`) quantifies the upstream cost this gate is
/// designed to eventually elide; see `docs/PERFORMANCE.md`.
///
/// # Pattern: cache the chrome, not the stream
///
/// During token streaming, wrap the *static* surroundings (chat history,
/// sidebar, status bar) keyed off everything *except* the stream, and
/// leave the stream itself uncached — it changes every token:
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// # let history_version = 3u64;
/// # let mut stream = slt::StreamingTextState::new();
/// ui.container().cached(history_version, |ui| {
/// ui.text("…long chat transcript…"); // unchanged this token
/// });
/// ui.streaming_text(&mut stream); // changes every token
/// # });
/// ```
///
/// [Principle 2 — "Your Closure IS the App"]: https://docs.rs/slt
pub fn cached(self, version_key: u64, f: impl FnOnce(&mut Context)) -> Response {
// Record the key / classify hit-vs-miss BEFORE running the body so the
// declaration order (and thus the per-call-site slot index) matches
// the order regions are authored, exactly like the hook cursor.
let _hit = self.ctx.record_cached_region(version_key);
// Always run the body: byte-identical output, immediate-mode invariant
// preserved. `_hit` is the gate a future cell-level cache would use.
self.col(f)
}
// ── internal ─────────────────────────────────────────────────────
/// Set the vertical scroll offset in rows. Used internally by [`Context::scrollable`].
///
/// This is a crate-internal helper; external callers should use
/// [`Context::scrollable`] together with a [`ScrollState`].
///
/// Hidden from rustdoc with `#[doc(hidden)]` so it does not appear in the
/// public API surface, while remaining callable for backwards compatibility
/// (cargo-semver-checks still tracks the symbol). Promote to `pub(crate)`
/// at v1.0.
///
/// [`ScrollState`]: crate::widgets::ScrollState
#[doc(hidden)]
pub fn scroll_offset(mut self, offset: u32) -> Self {
self.scroll_offset = Some(offset);
self
}
/// Internal entry point that takes an already-shared `Arc<str>`.
///
/// Used by `Context::group()` so the name allocated in the public path
/// is pushed onto `group_stack` and threaded into `BeginContainerArgs`
/// through a single `Arc::clone` instead of two `String` allocations.
/// Closes #145 (double `to_string`) and completes the `Arc<str>`
/// migration in #139.
pub(crate) fn group_name_arc(mut self, name: std::sync::Arc<str>) -> Self {
self.group_name = Some(name);
self
}
/// Finalize the builder as a vertical (column) container.
///
/// The closure receives a `&mut Context` for rendering children.
/// Returns a [`Response`] with click/hover state for this container.
pub fn col(self, f: impl FnOnce(&mut Context)) -> Response {
self.finish(Direction::Column, f)
}
/// Finalize the builder as a horizontal (row) container.
///
/// The closure receives a `&mut Context` for rendering children.
/// Returns a [`Response`] with click/hover state for this container.
pub fn row(self, f: impl FnOnce(&mut Context)) -> Response {
self.finish(Direction::Row, f)
}
/// Finalize the builder as an inline text line.
///
/// Like [`row`](ContainerBuilder::row) but gap is forced to zero
/// for seamless inline rendering of mixed-style text.
pub fn line(mut self, f: impl FnOnce(&mut Context)) -> Response {
self.gap = 0;
self.finish(Direction::Row, f)
}
/// Finalize the builder as a raw-draw region with direct buffer access.
///
/// The closure receives `(&mut Buffer, Rect)` after layout is computed.
/// Use `buf.set_char()`, `buf.set_string()`, `buf.get_mut()` to write
/// directly into the terminal buffer. Writes outside `rect` are clipped.
///
/// The closure must be `'static` because it is deferred until after layout.
/// To capture local data, clone or move it into the closure:
/// ```ignore
/// let data = my_vec.clone();
/// ui.container().w(40).h(20).draw(move |buf, rect| {
/// // use `data` here
/// });
/// ```
pub fn draw(self, f: impl FnOnce(&mut crate::buffer::Buffer, Rect) + 'static) {
let draw_id = self.ctx.deferred_draws.len();
self.ctx.deferred_draws.push(Some(Box::new(f)));
self.ctx.skip_interaction_slot();
self.ctx.commands.push(Command::RawDraw {
draw_id,
constraints: self.constraints,
grow: self.grow,
margin: self.margin,
});
}
/// Like [`draw`](Self::draw), but carries owned per-frame `data` through
/// to the deferred closure as a borrow.
///
/// Raw-draw closures must be `'static` because they run after layout is
/// computed — which normally forces callers to snapshot any borrowed
/// state into an owned value before passing it in. `draw_with` makes
/// that explicit: hand the snapshot over, borrow it inside the closure.
///
/// # Example
///
/// ```no_run
/// # use slt::{Buffer, Rect, Style};
/// # slt::run(|ui: &mut slt::Context| {
/// let points: Vec<(u32, u32)> = (0..20).map(|i| (i, i * 2)).collect();
/// ui.container().w(40).h(20).draw_with(points, |buf, rect, points| {
/// for (x, y) in points {
/// if rect.contains(*x, *y) {
/// buf.set_char(*x, *y, '●', Style::new());
/// }
/// }
/// });
/// # });
/// ```
pub fn draw_with<D: 'static>(
self,
data: D,
f: impl FnOnce(&mut crate::buffer::Buffer, Rect, &D) + 'static,
) {
let draw_id = self.ctx.deferred_draws.len();
self.ctx
.deferred_draws
.push(Some(Box::new(move |buf, rect| f(buf, rect, &data))));
self.ctx.skip_interaction_slot();
self.ctx.commands.push(Command::RawDraw {
draw_id,
constraints: self.constraints,
grow: self.grow,
margin: self.margin,
});
}
/// Custom drawing with click and hover detection.
///
/// Like [`draw`](Self::draw), but the returned [`Response`] reports
/// `clicked` and `hovered` based on the laid-out region — exactly like
/// `.col()` or `.row()`.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// let resp = ui.container()
/// .w(40).h(10)
/// .draw_interactive(|buf, rect| {
/// buf.set_string(rect.x, rect.y, "Click me!", slt::Style::new());
/// });
/// if resp.clicked {
/// // handle click
/// }
/// # });
/// ```
pub fn draw_interactive(
self,
f: impl FnOnce(&mut crate::buffer::Buffer, Rect) + 'static,
) -> Response {
let draw_id = self.ctx.deferred_draws.len();
self.ctx.deferred_draws.push(Some(Box::new(f)));
let interaction_id = self.ctx.next_interaction_id();
self.ctx.commands.push(Command::RawDraw {
draw_id,
constraints: self.constraints,
grow: self.grow,
margin: self.margin,
});
self.ctx.response_for(interaction_id)
}
fn finish(mut self, direction: Direction, f: impl FnOnce(&mut Context)) -> Response {
let interaction_id = self.ctx.next_interaction_id();
// `row_gap` / `col_gap` are `Option<u32>` (positive override); fall back
// to the signed builder `gap`, which alone can carry an overlap (#222).
let resolved_gap: i32 = match direction {
Direction::Column => self.row_gap.map(|g| g as i32).unwrap_or(self.gap),
Direction::Row => self.col_gap.map(|g| g as i32).unwrap_or(self.gap),
};
// Cross-axis (between-line) gap for a wrapping row (#258): `row_gap`
// when set, else the builder `gap`. Only consulted by the layout pass
// when this container is a wrapping `Direction::Row`.
let resolved_cross_gap: i32 = self.row_gap.map(|g| g as i32).unwrap_or(self.gap);
let in_hovered_group = self
.group_name
.as_ref()
.map(|name| self.ctx.is_group_hovered(name))
.unwrap_or(false)
|| self
.ctx
.rollback
.group_stack
.last()
.map(|name| self.ctx.is_group_hovered(name))
.unwrap_or(false);
let in_focused_group = self
.group_name
.as_ref()
.map(|name| self.ctx.is_group_focused(name))
.unwrap_or(false)
|| self
.ctx
.rollback
.group_stack
.last()
.map(|name| self.ctx.is_group_focused(name))
.unwrap_or(false);
let resolved_bg = if self.ctx.rollback.dark_mode {
self.dark_bg.or(self.bg)
} else {
self.bg
};
let resolved_border_style = if self.ctx.rollback.dark_mode {
self.dark_border_style.unwrap_or(self.border_style)
} else {
self.border_style
};
let bg_color = if in_hovered_group || in_focused_group {
self.group_hover_bg.or(resolved_bg)
} else {
resolved_bg
};
let border_style = if in_hovered_group || in_focused_group {
self.group_hover_border_style
.unwrap_or(resolved_border_style)
} else {
resolved_border_style
};
let group_name = self.group_name.take();
let is_group_container = group_name.is_some();
// Opt-in flex-shrink (#161). Push a marker the layout pass picks up
// and applies to the next `BeginContainer` / `BeginScrollable`,
// mirroring the existing `FocusMarker` / `InteractionMarker` pattern.
// This avoids touching every `BeginContainerArgs` construction site
// across the widget modules — only `ContainerBuilder.shrink()`
// emits the marker, and `LayoutNode::shrink` defaults to `false`.
if self.shrink_flag {
self.ctx.commands.push(Command::ShrinkMarker);
}
// Opt-in flex-wrap / flex-basis (#258). Same marker pattern as shrink:
// pushed just before the matching `Begin*`, picked up by the layout
// pass and applied to the next node. Both default off / `None`, so
// unflagged containers are byte-identical to pre-#258.
if self.wrap_flag {
self.ctx
.commands
.push(Command::WrapMarker(resolved_cross_gap));
}
if let Some(basis) = self.basis {
self.ctx.commands.push(Command::BasisMarker(basis));
}
if let Some(scroll_offset) = self.scroll_offset {
// #247: carry the finalizing `.row()` / `.col()` direction and both
// axis offsets. The tree builder applies the offset matching
// `direction`; the cross-axis offset is `0` for a single-axis
// scroller (the common case).
self.ctx
.commands
.push(Command::BeginScrollable(Box::new(BeginScrollableArgs {
grow: self.grow,
direction,
border: self.border,
border_sides: self.border_sides,
border_style,
bg_color,
align: self.align,
align_self: self.align_self_value,
justify: self.justify,
gap: resolved_gap,
padding: self.padding,
margin: self.margin,
constraints: self.constraints,
title: self.title,
scroll_offset,
scroll_offset_x: self.scroll_offset_x.unwrap_or(0),
group_name,
})));
} else {
self.ctx
.commands
.push(Command::BeginContainer(Box::new(BeginContainerArgs {
direction,
gap: resolved_gap,
align: self.align,
align_self: self.align_self_value,
justify: self.justify,
border: self.border,
border_sides: self.border_sides,
border_style,
bg_color,
padding: self.padding,
margin: self.margin,
constraints: self.constraints,
title: self.title,
grow: self.grow,
group_name,
})));
}
self.ctx.rollback.text_color_stack.push(self.text_color);
// Swap active theme if a per-subtree override was requested.
// The previous theme is restored after `f` returns — including on
// panic, so no widget ever sees a leaked override theme.
let theme_save = self.theme_override.map(|t| {
let prev = self.ctx.theme;
self.ctx.theme = t;
// Also keep dark_mode flag in sync so `dark_*` style variants
// resolve to the new theme's brightness, not the stale flag.
self.ctx.rollback.dark_mode = t.is_dark;
(prev, prev.is_dark)
});
// catch_unwind guards the restore path against panics inside `f`.
// The overlay/group bookkeeping that follows assumes `theme` reflects
// the parent scope, so we must restore before propagating the panic.
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self.ctx)));
if let Some((prev, prev_dark)) = theme_save {
self.ctx.theme = prev;
self.ctx.rollback.dark_mode = prev_dark;
}
self.ctx.rollback.text_color_stack.pop();
self.ctx.commands.push(Command::EndContainer);
self.ctx.rollback.last_text_idx = None;
if let Err(panic) = result {
std::panic::resume_unwind(panic);
}
if is_group_container {
self.ctx.rollback.group_stack.pop();
self.ctx.rollback.group_count = self.ctx.rollback.group_count.saturating_sub(1);
}
self.ctx.response_for(interaction_id)
}
}
#[cfg(test)]
mod hotfix_tests {
//! Regression tests for v0.19.1 A3 hotfixes (issues #143, #144, #146, #149).
use super::*;
// -- #143: filled_triangle stack-array intersections ----------------
/// Filling a triangle must paint the same pixel set whether the
/// previous Vec<f64> path or the new inline-array path is used.
#[test]
fn filled_triangle_paints_expected_interior() {
let mut canvas = CanvasContext::new(20, 20);
canvas.filled_triangle(2, 2, 18, 4, 6, 18);
// Sample a point that must be filled (lies clearly inside the
// triangle) and a point that must remain empty.
let lines = canvas.render();
// Pixel (8, 8) -> char cell (4, 2). Pull bits via re-render fallback.
let inside_row = 8 / 4;
let outside_row = 0;
// Each row must be present in the rendered output.
assert!(lines.len() > inside_row);
assert!(lines.len() > outside_row);
// Inside row must contain at least one non-blank braille glyph.
let inside: String = lines[inside_row].iter().map(|(s, _)| s.as_str()).collect();
assert!(
inside.chars().any(|c| c != '\u{2800}' && c != ' '),
"expected filled glyphs inside triangle, got: {inside:?}"
);
}
/// Tall triangles previously allocated O(H) Vecs; the new path must
/// still produce filled output for many scanlines without panicking.
#[test]
fn filled_triangle_handles_tall_triangle_without_panic() {
let mut canvas = CanvasContext::new(8, 50);
canvas.filled_triangle(0, 0, 15, 0, 8, 199);
let lines = canvas.render();
assert_eq!(lines.len(), 50);
}
/// Degenerate horizontal triangle (all three vertices on the same row)
/// must not panic and must produce no fill (only the outline edges).
#[test]
fn filled_triangle_degenerate_horizontal_is_safe() {
let mut canvas = CanvasContext::new(20, 20);
canvas.filled_triangle(0, 0, 10, 0, 19, 0);
let _ = canvas.render();
}
// -- #146: integer isqrt for filled_circle -------------------------
#[test]
fn isqrt_i64_matches_floor_sqrt_for_small_values() {
for n in 0i64..=10_000 {
let expected = (n as f64).sqrt().floor() as isize;
assert_eq!(isqrt_i64(n), expected, "mismatch at n={n}");
}
}
#[test]
fn isqrt_i64_handles_perfect_squares_and_boundaries() {
for k in 0i64..=4096 {
assert_eq!(isqrt_i64(k * k), k as isize);
if k > 0 {
assert_eq!(isqrt_i64(k * k - 1), (k - 1) as isize);
}
}
}
#[test]
fn isqrt_i64_clamps_non_positive_to_zero() {
assert_eq!(isqrt_i64(0), 0);
assert_eq!(isqrt_i64(-1), 0);
assert_eq!(isqrt_i64(i64::MIN), 0);
}
/// `filled_circle` should produce a symmetric span around its center
/// after switching from f64 sqrt to integer isqrt.
#[test]
fn filled_circle_renders_without_panic_and_is_non_empty() {
let mut canvas = CanvasContext::new(20, 20);
canvas.filled_circle(10, 10, 6);
let lines = canvas.render();
let any_filled = lines
.iter()
.flatten()
.any(|(s, _)| s.chars().any(|c| c != '\u{2800}' && c != ' '));
assert!(any_filled, "filled_circle produced empty output");
}
// -- #149: scroll_offset visibility (compile-time check) -----------
/// The `scroll_offset` helper must remain callable from inside the crate.
/// It is `#[doc(hidden)] pub` (Option B from the issue) so it is removed
/// from rustdoc but still semver-tracked; this test compiles only when
/// the path is reachable.
#[test]
fn scroll_offset_is_crate_internal_api() {
let _ = ContainerBuilder::scroll_offset;
}
}
#[cfg(test)]
mod flex_wrap_tests {
//! Render-level regression tests for flex-wrap / flex-basis (#258).
use crate::test_utils::TestBackend;
/// A wrapping row of labels wider than the backend must flow the
/// overflowing label onto the second terminal row, not clip it off the
/// right edge. Each label is a 1-cell-tall text node, so a line is one
/// cell tall and a wrap is visible as text on row 1.
#[test]
fn wrap_row_flows_overflow_to_second_line() {
// Backend is 12 wide. `col_gap(1)` sets within-line spacing only, so
// the cross-axis (between-line) gap falls back to 0. "alpha"(5) + 1 +
// "bravo"(5) = 11 fits line 0; "gamma" overflows (11 + 1 + 5 = 17 >
// 12) to line 1, immediately below with no blank gap row.
let mut tb = TestBackend::new(12, 4);
tb.render(|ui| {
let _ = ui.container().wrap().col_gap(1).row(|ui| {
ui.text("alpha");
ui.text("bravo");
ui.text("gamma");
});
});
// Line 0 holds the first two labels; the third wrapped to line 1.
tb.assert_line_contains(0, "alpha");
tb.assert_line_contains(0, "bravo");
tb.assert_line_contains(1, "gamma");
}
/// `wrap()` is opt-in: without it the overflowing label clips off the
/// right edge rather than wrapping, so nothing appears on row 1.
#[test]
fn no_wrap_row_keeps_single_line() {
let mut tb = TestBackend::new(12, 4);
tb.render(|ui| {
let _ = ui.container().col_gap(1).row(|ui| {
ui.text("alpha");
ui.text("bravo");
ui.text("gamma");
});
});
// Single line: first label on row 0, nothing wrapped to row 1.
tb.assert_line_contains(0, "alpha");
assert_eq!(tb.line(1), "");
}
}
#[cfg(test)]
mod cached_region_tests {
//! Issue #273 — opt-in scoped cached region.
//!
//! The invariant under test: `cached(key, f)` is byte-identical to an
//! uncached container in EVERY case (the body always runs), and it
//! correctly classifies each call site as a hit (key unchanged) or miss
//! (key changed / new / first frame / post-resize) so the hit/miss
//! diagnostics — and a future cell-level cache — have a sound gate.
use crate::event::Event;
use crate::test_utils::{EventBuilder, TestBackend};
use std::cell::Cell;
/// First frame is always a miss, output identical to a plain container.
#[test]
fn cached_region_byte_identical_on_first_frame() {
let mut cached = TestBackend::new(40, 6);
cached.render(|ui| {
let _ = ui.container().cached(7, |ui| {
ui.text("static chrome line one");
ui.text("static chrome line two");
});
});
let mut plain = TestBackend::new(40, 6);
plain.render(|ui| {
let _ = ui.container().col(|ui| {
ui.text("static chrome line one");
ui.text("static chrome line two");
});
});
assert_eq!(
cached.buffer().snapshot_format(),
plain.buffer().snapshot_format(),
"cached region must render byte-identically to an uncached container"
);
}
/// An unchanged key is a hit on the second frame. The body still runs
/// every frame (immediate-mode invariant), so the content stays visible
/// and identical — `cached` only flips the hit classification.
#[test]
fn cached_region_hit_on_unchanged_key_body_still_runs() {
let mut tb = TestBackend::new(40, 4);
let runs = Cell::new(0u32);
let hits = Cell::new(0u32);
let misses = Cell::new(0u32);
let frame = |tb: &mut TestBackend| {
tb.render(|ui| {
let _ = ui.container().cached(99, |ui| {
runs.set(runs.get() + 1);
ui.text("stable");
});
hits.set(ui.region_cache_hits());
misses.set(ui.region_cache_misses());
});
};
frame(&mut tb);
assert_eq!(runs.get(), 1, "first frame runs the body");
assert_eq!(misses.get(), 1, "first frame is a miss");
assert_eq!(hits.get(), 0);
tb.assert_contains("stable");
frame(&mut tb);
// Body STILL runs (byte-identical guarantee) even though the key
// matched — the only observable change is the hit classification.
assert_eq!(runs.get(), 2, "body re-runs every frame regardless of hit");
assert_eq!(hits.get(), 1, "unchanged key on the second frame is a hit");
assert_eq!(misses.get(), 0);
tb.assert_contains("stable");
}
/// A changed key is a miss and the new content renders.
#[test]
fn cached_region_miss_on_key_change() {
let mut tb = TestBackend::new(40, 4);
let hits = Cell::new(0u32);
let misses = Cell::new(0u32);
tb.render(|ui| {
let _ = ui.container().cached(1, |ui| {
ui.text("first");
});
hits.set(ui.region_cache_hits());
misses.set(ui.region_cache_misses());
});
assert_eq!(misses.get(), 1);
tb.assert_contains("first");
tb.render(|ui| {
let _ = ui.container().cached(2, |ui| {
ui.text("second");
});
hits.set(ui.region_cache_hits());
misses.set(ui.region_cache_misses());
});
assert_eq!(hits.get(), 0, "changed key is not a hit");
assert_eq!(misses.get(), 1, "changed key is a miss");
tb.assert_contains("second");
}
/// A resize clears the persisted keys, forcing the next frame to miss even
/// when the author passes the same key.
#[test]
fn cached_region_invalidates_on_resize() {
let mut tb = TestBackend::new(40, 4);
let hits = Cell::new(0u32);
tb.render(|ui| {
let _ = ui.container().cached(5, |ui| {
ui.text("body");
});
});
// Second frame, same key, no resize → hit.
tb.render(|ui| {
let _ = ui.container().cached(5, |ui| {
ui.text("body");
});
hits.set(ui.region_cache_hits());
});
assert_eq!(hits.get(), 1, "same key without resize is a hit");
// Now resize: the persisted region keys are cleared, so the SAME key
// is treated as a fresh slot (miss) on the post-resize frame.
tb.render_with_events(vec![Event::Resize(60, 8)], 0, 0, |ui| {
let _ = ui.container().cached(5, |ui| {
ui.text("body");
});
hits.set(ui.region_cache_hits());
});
assert_eq!(hits.get(), 0, "resize forces a cache miss for all regions");
}
/// Focus + hit-map continuity: a button inside a cached region keeps
/// firing `clicked` across cached (hit) frames because the body always
/// runs, so its focusable + hit-area are re-registered every frame.
#[test]
fn cached_region_preserves_focus_and_hit_map() {
let mut tb = TestBackend::new(30, 5);
let clicked = Cell::new(false);
// Frame 1: register the button so its hit-area lands in the feedback
// map for the next frame's click resolution. Same key both frames.
tb.render(|ui| {
let _ = ui.container().cached(3, |ui| {
let _ = ui.button("Go");
});
});
// Frame 2: click on the button's cell — even though the region is a
// cache hit, the body re-ran and re-registered the hit-area, so the
// click resolves.
tb.render_with_events(EventBuilder::new().click(2, 0).build(), 0, 1, |ui| {
let _ = ui.container().cached(3, |ui| {
let resp = ui.button("Go");
if resp.clicked {
clicked.set(true);
}
});
});
assert!(
clicked.get(),
"button inside a cached region must still receive clicks across hit frames"
);
}
/// Raw-draw inside a cached region: the deferred draw runs on every frame
/// including cache-hit frames (deferred draws are one-shot per frame, and
/// the body always runs, so they re-register).
#[test]
fn cached_region_raw_draw_replays() {
let mut tb = TestBackend::new(20, 3);
let frame = |tb: &mut TestBackend| {
tb.render(|ui| {
let _ = ui.container().cached(8, |ui| {
ui.container().w(5).h(1).draw(|buf, rect| {
buf.set_string(rect.x, rect.y, "XXXXX", crate::style::Style::new());
});
});
});
};
frame(&mut tb);
tb.assert_contains("XXXXX");
// Second frame is a cache hit, but the raw draw must still paint.
frame(&mut tb);
tb.assert_contains("XXXXX");
}
/// Two adjacent cached regions get independent per-call-site slots; one
/// changing its key does not disturb the other's hit classification.
#[test]
fn cached_regions_do_not_collide_per_call_site() {
let mut tb = TestBackend::new(40, 6);
let hits = Cell::new(0u32);
let misses = Cell::new(0u32);
// Frame 1: both new → 2 misses.
tb.render(|ui| {
let _ = ui.container().cached(10, |ui| {
ui.text("region A");
});
let _ = ui.container().cached(20, |ui| {
ui.text("region B");
});
});
// Frame 2: A unchanged (hit), B changed (miss).
tb.render(|ui| {
let _ = ui.container().cached(10, |ui| {
ui.text("region A");
});
let _ = ui.container().cached(21, |ui| {
ui.text("region B2");
});
hits.set(ui.region_cache_hits());
misses.set(ui.region_cache_misses());
});
assert_eq!(hits.get(), 1, "region A unchanged → exactly one hit");
assert_eq!(misses.get(), 1, "region B changed → exactly one miss");
tb.assert_contains("region A");
tb.assert_contains("region B2");
}
}