rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Tab widget.
//!
//! # The tab strip is assembled by a layout
//!
//! BLUE22 §B.8 lists this control's defect as "tab width by hand". The width is measured and
//! clamped here (that half was already derived), but the *run* — where each tab starts once the
//! ones before it have taken their room — is now the answer of a [`FlexLayout`] rather than an
//! accumulator re-derived inside `tab_rect`. See [`TabWidget::tab_run`].

#[cfg(full_widgets)]
use crate::core::Size;
use crate::core::{Color, Font, HorizontalAlignment, ObjectId, Point, Rect};
use crate::event::{DragPayload, DragSession, Event, EventHandler};
#[cfg(full_widgets)]
use crate::layout::{
    AlignItems, AxisHints, FlexDirection, FlexLayout, FlexWrap, Hints, JustifyContent, LayoutParams,
};
use crate::render::RenderContext;
use crate::signal::Signal1;
#[cfg(full_widgets)]
use crate::style::EdgeOffsets;

use crate::widget::capability::coercion::{expect_bool, expect_string, expect_usize};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
#[cfg(full_widgets)]
use crate::widget::composite::CompositeBuilder;
use crate::widget::metrics::estimate_text_width;
#[cfg(feature = "image")]
use crate::widget::Image;
#[cfg(full_widgets)]
use crate::widget::WidgetFactory;
use crate::widget::{BaseWidget, Draw, SimpleRegistry, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
use std::cell::RefCell;
use std::rc::Rc;
/// Tab widget.
pub struct TabWidget {
    base: BaseWidget,
    tabs: Vec<Tab>,
    current_index: usize,
    tab_position: TabPosition,
    tab_shape: TabShape,
    closable: bool,
    movable: bool,
    /// Index of the tab a move gesture started on, and the drag state machine that decides
    /// whether the gesture has travelled far enough to count as a drag.
    ///
    /// Two pieces because they answer two different questions: the session says *whether*
    /// the pointer has moved past the click threshold, and the index says *which tab* is
    /// being carried. Tracking only the index (as `TabBar` did until it gained a session)
    /// makes "click" and "drag" the same gesture, so a stray pixel of movement while
    /// selecting a tab would silently reorder it.
    drag_session: Option<DragSession>,
    dragging_from: Option<usize>,
    /// Emitted with the new index when the selected tab changes; not emitted
    /// when the same index is re-applied.
    pub current_changed: Signal1<usize>,
    /// Emitted when the user requests that the tab at this absolute index be
    /// closed. The `closable` flag only gates hit-testing of the close button;
    /// this widget does not remove the tab itself — the host must handle the
    /// request and call `remove_tab`, so the index is still valid when emitted.
    pub tab_close_requested: Signal1<usize>,
    /// Emitted when a movable tab is dragged to a new index; the payload is
    /// `(old_index, new_index)`.
    ///
    /// `movable` was declared but read by nothing, and this signal did not exist, so a host
    /// could neither turn reordering on nor learn that it had happened. The drag gesture in
    /// [`TabWidget::handle_event`] is what emits it.
    pub tab_moved: Signal1<(usize, usize)>,
    /// Optional shared registry for child widget forwarding.
    registry: Option<Rc<RefCell<SimpleRegistry>>>,
}
/// Tab information.
pub struct Tab {
    title: String,
    #[cfg(feature = "image")]
    icon: Option<Image>,
    tooltip: String,
    enabled: bool,
    widget: Option<ObjectId>,
}
/// Tab position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TabPosition {
    /// Tabs at the top
    #[default]
    North,
    /// Tabs at the bottom
    South,
    /// Tabs at the left
    West,
    /// Tabs at the right
    East,
}

impl TabPosition {
    /// Parses a property token, accepting exactly the spellings
    /// [`tab_position_token`] publishes.
    pub fn from_token(token: &str) -> Option<Self> {
        match token {
            "north" => Some(TabPosition::North),
            "south" => Some(TabPosition::South),
            "west" => Some(TabPosition::West),
            "east" => Some(TabPosition::East),
            _ => None,
        }
    }
}

/// The token `tab_position` is carried as, matching the schema row's accepted spellings.
fn tab_position_token(position: TabPosition) -> &'static str {
    match position {
        TabPosition::North => "north",
        TabPosition::South => "south",
        TabPosition::West => "west",
        TabPosition::East => "east",
    }
}
/// Tab shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TabShape {
    /// Rounded tabs
    #[default]
    Rounded,
    /// Triangular tabs
    Triangular,
    /// Rectangular tabs
    Rectangular,
}
impl Tab {
    /// Creates a new tab.
    pub fn new(title: String) -> Self {
        Self {
            title,
            #[cfg(feature = "image")]
            icon: None,
            tooltip: String::new(),
            enabled: true,
            widget: None,
        }
    }
    /// Returns title.
    pub fn title(&self) -> &str {
        &self.title
    }
    /// Sets title.
    pub fn set_title(&mut self, title: String) {
        self.title = title;
    }
    #[cfg(feature = "image")]
    /// Returns icon.
    pub fn icon(&self) -> Option<&Image> {
        self.icon.as_ref()
    }
    #[cfg(feature = "image")]
    /// Sets icon.
    pub fn set_icon(&mut self, icon: Option<Image>) {
        self.icon = icon;
    }
    /// Returns tooltip.
    pub fn tooltip(&self) -> &str {
        &self.tooltip
    }
    /// Sets tooltip.
    pub fn set_tooltip(&mut self, tooltip: String) {
        self.tooltip = tooltip;
    }
    /// Returns whether tab is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }
    /// Sets enabled state.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }
    /// Returns widget.
    pub fn widget(&self) -> Option<ObjectId> {
        self.widget
    }
    /// Sets widget.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        self.widget = widget;
    }
}
impl TabWidget {
    /// Creates a tab widget.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::TabWidget, geometry, "TabWidget"),
            tabs: Vec::new(),
            current_index: 0,
            tab_position: TabPosition::North,
            tab_shape: TabShape::Rounded,
            closable: false,
            movable: false,
            drag_session: None,
            dragging_from: None,
            current_changed: Signal1::new(),
            tab_close_requested: Signal1::new(),
            tab_moved: Signal1::new(),
            registry: None,
        }
    }
    /// Sets the shared widget registry for child forwarding.
    pub fn set_registry(&mut self, registry: Rc<RefCell<SimpleRegistry>>) {
        self.registry = Some(registry);
        self.base.request_redraw();
    }
    /// Returns the shared widget registry, if set.
    pub fn registry(&self) -> Option<&Rc<RefCell<SimpleRegistry>>> {
        self.registry.as_ref()
    }
    /// Adds a tab.
    pub fn add_tab(&mut self, title: String, widget: Option<ObjectId>) -> usize {
        let mut tab = Tab::new(title);
        tab.widget = widget;
        if let Some(widget_id) = widget {
            self.base.add_child(widget_id);
        }
        self.tabs.push(tab);
        self.tabs.len().saturating_sub(1)
    }
    /// Inserts a tab at position.
    pub fn insert_tab(&mut self, index: usize, title: String, widget: Option<ObjectId>) {
        let was_empty = self.tabs.is_empty();
        let mut tab = Tab::new(title);
        tab.widget = widget;
        if let Some(widget_id) = widget {
            self.base.add_child(widget_id);
        }
        self.tabs.insert(index, tab);
        if !was_empty && self.current_index >= index {
            self.current_index += 1;
        }
    }
    /// Removes a tab.
    pub fn remove_tab(&mut self, index: usize) {
        if index < self.tabs.len() {
            if let Some(widget_id) = self.tabs[index].widget {
                self.base.remove_child(widget_id);
            }
            self.tabs.remove(index);
            if self.current_index >= index && self.current_index > 0 {
                self.current_index -= 1;
            }
            if self.tabs.is_empty() {
                self.current_index = 0;
            }
        }
    }
    /// Returns number of tabs.
    pub fn count(&self) -> usize {
        self.tabs.len()
    }
    /// Returns current tab index.
    pub fn current_index(&self) -> usize {
        self.current_index
    }
    /// Sets current tab index.
    pub fn set_current_index(&mut self, index: usize) {
        if index < self.tabs.len() && self.current_index != index {
            self.current_index = index;
            self.current_changed.emit(index);
            self.base.request_redraw();
        }
    }
    /// Returns current tab widget.
    pub fn current_widget(&self) -> Option<ObjectId> {
        self.tabs.get(self.current_index).and_then(|tab| tab.widget)
    }
    /// Returns tab at index.
    pub fn tab(&self, index: usize) -> Option<&Tab> {
        self.tabs.get(index)
    }
    /// Returns mutable tab at index.
    pub fn tab_mut(&mut self, index: usize) -> Option<&mut Tab> {
        self.tabs.get_mut(index)
    }
    /// Returns the text of the tab at the given index.
    pub fn tab_text(&self, index: usize) -> Option<&str> {
        self.tabs.get(index).map(|t| t.title.as_str())
    }
    /// Sets the text of the tab at the given index.
    pub fn set_tab_text(&mut self, index: usize, text: String) {
        if let Some(tab) = self.tabs.get_mut(index) {
            tab.title = text;
        }
        self.base.request_redraw();
    }
    /// Returns tab position.
    pub fn tab_position(&self) -> TabPosition {
        self.tab_position
    }
    /// Sets tab position.
    pub fn set_tab_position(&mut self, position: TabPosition) {
        self.tab_position = position;
        self.base.request_redraw();
    }
    /// Returns tab shape.
    pub fn tab_shape(&self) -> TabShape {
        self.tab_shape
    }
    /// Sets tab shape.
    pub fn set_tab_shape(&mut self, shape: TabShape) {
        self.tab_shape = shape;
        self.base.request_redraw();
    }
    /// Returns whether tabs are closable.
    pub fn closable(&self) -> bool {
        self.closable
    }
    /// Sets closable state.
    pub fn set_closable(&mut self, closable: bool) {
        self.closable = closable;
        self.base.request_redraw();
    }
    /// Returns whether tabs are movable.
    ///
    /// When true, pressing a tab and dragging the pointer past a neighbour's midpoint
    /// reorders the tabs and emits [`Self::tab_moved`]. When false the same gesture only
    /// selects, so the flag decides whether a drag has any effect at all.
    pub fn movable(&self) -> bool {
        self.movable
    }
    /// Sets movable state.
    ///
    /// A gesture already in progress is abandoned: turning reordering off mid-drag must
    /// not let the release that follows still move a tab, which is what dropping the live
    /// drag state here prevents.
    pub fn set_movable(&mut self, movable: bool) {
        self.movable = movable;
        if !movable {
            self.cancel_tab_drag();
        }
        self.base.request_redraw();
    }
    /// Moves the tab at `from` to `to` and emits [`Self::tab_moved`] with `(from, to)`.
    ///
    /// # Why `to` is clamped rather than rejected
    ///
    /// A drag reports positions from pointer coordinates, and a pointer past the last tab
    /// is "dropped at the end" — the intent — not a caller bug. An out-of-range `from`,
    /// however, can only be a caller error, so it is rejected without emitting.
    ///
    /// # Why the selection travels with the tab
    ///
    /// `current_index` is a slot, but the user's mental model is that the *page* moved.
    /// Leaving the index alone would silently switch to whichever tab took the slot the
    /// dragged one vacated.
    ///
    /// Returns `true` when a move happened.
    pub fn move_tab(&mut self, from: usize, to: usize) -> bool {
        if from >= self.tabs.len() {
            return false;
        }
        let to = to.min(self.tabs.len() - 1);
        if to == from {
            return false;
        }

        let tab = self.tabs.remove(from);
        self.tabs.insert(to, tab);

        self.current_index = match self.current_index {
            c if c == from => to,
            c if from < c && c <= to => c - 1,
            c if to <= c && c < from => c + 1,
            c => c,
        };

        self.tab_moved.emit((from, to));
        self.base.request_redraw();
        true
    }
    /// Starts a move gesture on the tab under `pos`.
    ///
    /// Only a movable, enabled tab arms a drag, so a click that happens to jitter still
    /// selects and nothing else. The session is opened with the tab's index as its payload
    /// so a future drop target can tell which tab is being carried.
    fn begin_tab_drag(&mut self, pos: Point) {
        if !self.movable {
            return;
        }
        let Some(index) = self.tab_at_position(pos) else {
            return;
        };
        if !self.tabs[index].enabled {
            return;
        }
        let payload = DragPayload::new(TAB_DRAG_TYPE, index.to_string()).with_origin(pos);
        self.drag_session = Some(DragSession::begin(payload, pos));
        self.dragging_from = Some(index);
    }
    /// Reorders the tabs as the pointer moves past a neighbour's midpoint.
    ///
    /// # Why the move is applied live rather than on release
    ///
    /// The tab strip swaps the two tabs the moment the pointer crosses the midpoint, so
    /// the strip the user sees while dragging is the arrangement they will get. Deferring
    /// it to the release makes the gesture feel unresponsive and gives no feedback about
    /// where the tab will land.
    fn update_tab_drag(&mut self, pos: Point) {
        let (active, from) = {
            let Some(session) = self.drag_session.as_mut() else {
                return;
            };
            session.update(pos, TAB_DRAG_THRESHOLD);
            (session.is_active(), self.dragging_from)
        };
        if !active {
            return;
        }
        let Some(from) = from else {
            return;
        };
        // The neighbour the pointer has passed: a move to the right lands on the next tab
        // once the pointer is past *that* tab's midpoint, and symmetrically to the left.
        // Deriving the target from geometry rather than from the dragged tab's own rect is
        // what lets a fast drag cross several neighbours without stalling on each one.
        let Some(target) = self.tab_at_position(pos) else {
            return;
        };
        if target == from {
            return;
        }
        // Move one step toward the target rather than jumping the whole distance: the tabs
        // between the two indices have to shift by one, which a single `move_tab(from,
        // target)` accomplishes, and the live `move_tab` re-emits so the host sees each
        // swap the user saw.
        self.move_tab(from, target);
        self.dragging_from = Some(target);
    }
    /// Ends a move gesture, keeping the reordering already applied.
    ///
    /// The session is closed without a further move: `update_tab_drag` already placed the
    /// tab under the pointer, so acting on the release position again would double-apply
    /// the last step.
    fn end_tab_drag(&mut self) {
        self.cancel_tab_drag();
    }
    /// Drops any in-progress move gesture without reordering further.
    fn cancel_tab_drag(&mut self) {
        self.drag_session = None;
        self.dragging_from = None;
    }
    /// Returns tab rectangle at index.
    ///
    /// Tab width is **measured**, not a constant. The literal `100` meant a title longer than
    /// ~13 characters was clipped at a fixed point and a two-character title reserved the same
    /// 100 px as a nine-character one, so the strip's appearance had nothing to do with its
    /// contents. Measuring the titles and clamping the result (the same `[40, 200]` window
    /// `tab_bar` uses) is what makes the band a function of what the tabs say.
    ///
    /// The computed width is also what the **overflow** rule divides up: when the tabs no
    /// longer fit the strip, every tab gets `width / count` so they all stay visible, rather
    /// than the later ones being drawn past the control's own right edge (the SVG backend emits
    /// absolute coordinates, so those tabs simply left the picture).
    /// The declared width of each tab as a **hint triple**, not a single number.
    ///
    /// # Why three numbers rather than one (BLUE22 · G-1)
    ///
    /// This used to return one width per tab, and `tab_run` handed each to `add_sized`, which
    /// writes the value into `min`, `pref` **and** `max` alike. For a strip that fits that is
    /// exactly right. For one that does not, it made the control lie: it had already decided the
    /// tabs must share the strip (the overflow rule below), computed each share, and then told the
    /// layout "this tab is never allowed to be narrower than its share" — while handing the layout
    /// a band smaller than the sum of those shares. `FlexLayout` could only believe the declaration
    /// and scale the run down to fit, so the strip's own overflow arithmetic and the layout's
    /// answer were each applied once and the two rounding steps compounded. Two 72 px tabs plus a
    /// 2 px gap in a 300 px strip came out 71 and 63 instead of a clean share of 149 each.
    ///
    /// The fix is not in the layout: it is that the **declaration has to say what the control
    /// means**. A tab's `min` is the narrowest it can be drawn, and that is
    /// [`MIN_TAB_WIDTH`]'s floor, not the share — the share is what the tab *wants* given that the
    /// strip is crowded, which is precisely `pref`/`max`. With the ceiling stated, the layout
    /// reaches the answer in one step and the 1 px compounding disappears, because it is no longer
    /// squeezing a child past a floor the child never had.
    ///
    /// Returns `(min, pref, max)` per tab, in strip order.
    fn tab_width_hints(&self) -> crate::compat::Vec<(i32, i32, i32)> {
        let rect = self.geometry();
        let count = self.tabs.len();
        if count == 0 {
            return crate::compat::Vec::new();
        }
        let measured: crate::compat::Vec<i32> = self
            .tabs
            .iter()
            .map(|tab| {
                // The shared estimate, not `chars().count() * TAB_CHAR_WIDTH`: one derivation of a
                // label's advance for the whole crate, matching what `TabView::tab_widths` uses and
                // what the renderer draws with. The hand-rolled form also mis-measured any
                // non-Latin caption, since it charged a fixed 8 px per cluster.
                (estimate_text_width(&tab.title, &Font::default(), 1.0) as i32 + TAB_TEXT_PADDING)
                    .clamp(MIN_TAB_WIDTH, MAX_TAB_WIDTH)
            })
            .collect();
        let total: i32 = measured.iter().sum::<i32>() + TAB_SPACING * (count as i32 - 1);
        let available = match self.tab_position {
            TabPosition::North | TabPosition::South => rect.width as i32,
            TabPosition::West | TabPosition::East => rect.height as i32,
        };
        if total <= available {
            // The strip fits: the measurement is both the wish and the bound, so the three numbers
            // agree and the drawn run is exactly what it always was.
            return measured.into_iter().map(|w| (w, w, w)).collect();
        }
        // Overflow: share the strip equally so every tab remains inside it. The gap must come out of
        // the band *before* the division, otherwise the last tab's trailing gap is charged to the
        // tabs themselves and the run overshoots the strip by `TAB_SPACING` — which is what made the
        // layout scale a second time even after this rule had run.
        let gaps = TAB_SPACING * (count as i32 - 1);
        let share = ((available - gaps) / count as i32).max(MIN_TAB_WIDTH / 2);
        // `pref == max == share` with `min` at the floor: the tab *wants* no more than its share, and
        // can survive down to the floor. A layout given this reaches the share itself rather than
        // having to squeeze past a floor that claimed to be the share.
        let floor = MIN_TAB_WIDTH / 2;
        crate::compat::vec![(floor.min(share), share, share); count]
    }

    /// The tab strip as a run, assembled by a layout rather than by an accumulator.
    ///
    /// # Why the strip is assembled
    ///
    /// BLUE22 §B.8 lists `tab_widget`'s defect as "tab width by hand", and the fix has two
    /// halves. The first is the width: `label_width + TAB_TEXT_PADDING`, clamped into
    /// `TAB_MIN_WIDTH..TAB_MAX_WIDTH` — which the widget does derive. The second is the **run**:
    /// each tab started at "the sum of the widths before it plus the spacing times its index", an
    /// accumulator of two separate terms re-derived inside `tab_rect` on every call. Handing the
    /// widths to a [`FlexLayout`] makes the run the layout's answer, and the cross axis comes from
    /// the tab's own declared height — so a North and a West strip are the same code with a
    /// different direction.
    ///
    /// The result is in **strip order and strip coordinates**, starting at `(0, 0)`: the caller
    /// translates it to wherever the strip lives. Keeping the assembly's origin at zero is what
    /// lets one function serve all four `TabPosition`s, whose tab boxes differ only by that
    /// translation.
    fn tab_run(&self) -> crate::compat::Vec<Rect> {
        let hints = self.tab_width_hints();
        if hints.is_empty() {
            return crate::compat::Vec::new();
        }
        let widths: crate::compat::Vec<i32> = hints.iter().map(|(_, pref, _)| *pref).collect();
        let horizontal = matches!(self.tab_position, TabPosition::North | TabPosition::South);
        // # Why the stripped profiles take the direct route
        //
        // `full_widgets` is "a device profile *and* an unstripped widget set" (principle #47), and
        // this module is only gated on the second half — so an Android `mobile-api` build has no
        // `WidgetFactory` here. Both arms read the same widths and the same `TAB_SPACING`, so the
        // fallback is the same run written the only way that profile can express it.
        #[cfg(not(full_widgets))]
        {
            let mut placed: crate::compat::Vec<Rect> = crate::compat::Vec::new();
            let mut cursor = 0i32;
            for width in widths.iter() {
                let box_rect = if horizontal {
                    Rect::new(cursor, 0, *width as u32, TAB_HEIGHT as u32)
                } else {
                    Rect::new(0, cursor, TAB_HEIGHT as u32, *width as u32)
                };
                placed.push(box_rect);
                cursor += *width + TAB_SPACING;
            }
            return placed;
        }
        #[cfg(full_widgets)]
        {
            // The strip must be wide enough for the tabs **and the gaps between them**: the layout
            // charges `TAB_SPACING` once per adjacent pair, so a strip sized at `sum(widths)` alone
            // is short by exactly that total. `remaining` then goes negative and the proportional
            // shrink pass — correctly, by its own rules — takes the shortfall off the tabs, which is
            // where the strip's 64s became 63s. The gaps are part of what the run occupies, so they
            // are part of the band the run is given.
            //
            // The count is the **tab** count, not `self.count()`: this function is building the run
            // it is about to hand to the layout, so it must count what it will place. The two agree
            // today, and reading `self.tabs` here is what keeps them agreeing if the accessor ever
            // grows a different meaning.
            let count = self.tabs.len() as i32;
            let gaps = TAB_SPACING * (count.saturating_sub(1));
            let extent = widths.iter().sum::<i32>() + gaps;
            let strip = if horizontal {
                Rect::new(0, 0, extent.max(0) as u32, TAB_HEIGHT as u32)
            } else {
                Rect::new(0, 0, TAB_HEIGHT as u32, extent.max(0) as u32)
            };
            let factory = WidgetFactory::new_with_defaults();
            let mut row = CompositeBuilder::new(
                Box::new(FlexLayout::with_params(
                    if horizontal { FlexDirection::Row } else { FlexDirection::Column },
                    FlexWrap::NoWrap,
                    JustifyContent::FlexStart,
                    AlignItems::Stretch,
                    TAB_SPACING,
                    0,
                )),
                EdgeOffsets::all(0),
                Size::new(0, 0),
            );
            for (index, tab) in self.tabs.iter().enumerate() {
                // The tab's declaration: its measured width **on the run's axis** as a real
                // `min`/`pref`/`max` triple, and `TAB_HEIGHT` across it.
                //
                // The three widths come from `tab_width_hints`, so a crowded strip declares the
                // share it means instead of claiming that share as its own floor (BLUE22 · G-1).
                // A tab is `TAB_HEIGHT` tall whatever the control was given, which is the whole
                // point of taking the height from the constant rather than from `geometry()`.
                let (min_width, pref_width, max_width) = hints.get(index).copied().unwrap_or((
                    MIN_TAB_WIDTH,
                    MIN_TAB_WIDTH,
                    MIN_TAB_WIDTH,
                ));
                let declared = Hints {
                    width: AxisHints::new(
                        min_width.max(0) as u32,
                        pref_width.max(0) as u32,
                        max_width.max(0) as u32,
                    ),
                    height: AxisHints::fixed(TAB_HEIGHT as u32),
                };
                // A vertical strip is the same declaration with the axes exchanged, which is the
                // only difference between the four `TabPosition`s' boxes.
                let declared = if horizontal {
                    declared
                } else {
                    Hints { width: declared.height, height: declared.width }
                };
                let created = row.add_with_hints(
                    &factory,
                    "label",
                    &tab.title,
                    declared,
                    LayoutParams::new(),
                );
                debug_assert!(created.is_some(), "a tab is a core control");
            }
            let mut placed: crate::compat::Vec<Rect> = crate::compat::Vec::new();
            row.arrange(strip, &mut |_, rect| placed.push(rect));
            while placed.len() < self.tabs.len() {
                placed.push(Rect::new(0, 0, 0, 0));
            }
            placed
        }
    }

    fn tab_rect(&self, index: usize) -> Option<Rect> {
        if index >= self.tabs.len() {
            return None;
        }
        let rect = self.geometry();
        // The run is in strip coordinates; each position translates it to where the strip lives.
        let run = self.tab_run();
        let tab = *run.get(index)?;
        let tab_width = tab.width as i32;
        let tab_height = TAB_HEIGHT;
        let along = if matches!(self.tab_position, TabPosition::North | TabPosition::South) {
            tab.x
        } else {
            tab.y
        };
        match self.tab_position {
            TabPosition::North => {
                Some(Rect::new(rect.x + along, rect.y, tab_width as u32, tab_height as u32))
            }
            TabPosition::South => Some(Rect::new(
                rect.x + along,
                rect.y + rect.height as i32 - tab_height,
                tab_width as u32,
                tab_height as u32,
            )),
            TabPosition::West => {
                Some(Rect::new(rect.x, rect.y + along, tab_width as u32, tab_height as u32))
            }
            TabPosition::East => Some(Rect::new(
                rect.x + rect.width as i32 - tab_width,
                rect.y + along,
                tab_width as u32,
                tab_height as u32,
            )),
        }
    }
    /// Returns content rectangle.
    fn content_rect(&self) -> Rect {
        let rect = self.geometry();
        let tab_height = TAB_HEIGHT;
        match self.tab_position {
            TabPosition::North => Rect::new(
                rect.x,
                rect.y + tab_height,
                rect.width,
                rect.height.saturating_sub(tab_height as u32),
            ),
            TabPosition::South => {
                Rect::new(rect.x, rect.y, rect.width, rect.height.saturating_sub(tab_height as u32))
            }
            TabPosition::West => Rect::new(
                rect.x + tab_height,
                rect.y,
                rect.width.saturating_sub(tab_height as u32),
                rect.height,
            ),
            TabPosition::East => {
                Rect::new(rect.x, rect.y, rect.width.saturating_sub(tab_height as u32), rect.height)
            }
        }
    }
    /// Returns index of tab at position.
    fn tab_at_position(&self, pos: Point) -> Option<usize> {
        for i in 0..self.tabs.len() {
            if let Some(tab_rect) = self.tab_rect(i) {
                if tab_rect.contains(pos) {
                    return Some(i);
                }
            }
        }
        None
    }
}
/// Height of the tab strip, in logical pixels.
const TAB_HEIGHT: i32 = 24;

/// Horizontal gap between adjacent tabs.
const TAB_SPACING: i32 = 2;

/// Widest a measured tab may become, and narrowest it may stay.
///
/// The same window `tab_bar` clamps to, so the two tab controls agree about what a tab looks
/// like even though they lay their bands out differently.
const MIN_TAB_WIDTH: i32 = 40;
const MAX_TAB_WIDTH: i32 = 200;

/// Padding added to a measured title before it is clamped.
const TAB_TEXT_PADDING: i32 = 24;

/// Side of a tab's close button, in logical pixels.
const CLOSE_SIZE: i32 = 12;

/// The drag payload type a tab move carries.
///
/// Named rather than an empty string so a drop target (or a future cross-control reorder)
/// can recognise that this gesture is a tab move and not, say, a card drag. The payload's
/// item id is the dragged tab's index, spelled as the same decimal the property layer uses.
const TAB_DRAG_TYPE: &str = "tab_widget_tab";

/// How far the pointer must travel before a press counts as a drag.
///
/// Without a threshold every click that jitters by one pixel would reorder a tab, because
/// the press and the move are the same gesture to the OS.
const TAB_DRAG_THRESHOLD: i32 = 4;

// Implement Widget trait
impl Widget for TabWidget {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(300, 200)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `TabWidget`'s property contract.
///
/// The doc comment here used to record that `closable`, `movable` and `tab_position` were
/// declared by `TAB_WIDGET_PROPERTIES` but answered by nothing, "so they stay exactly as
/// they were (not served)". That was a declaration nothing reads: the schema offered a
/// property the control refused, so a host could neither enable dragging nor learn whether
/// it was on. All three are served now, and `movable` additionally drives the drag gesture
/// in [`TabWidget::handle_event`] rather than merely being stored.
impl WidgetProperties for TabWidget {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "tab_count" => Ok(CapabilityValue::UInt(self.count() as u64)),
            "current_index" => Ok(CapabilityValue::UInt(self.current_index() as u64)),
            // Symmetric with the writer below: a value that can be set can be read back.
            // Without this arm the property would be write-only, which is the one-directional
            // contract rule #97 forbids.
            "text" | "title" => Ok(CapabilityValue::String(
                self.tabs.first().map(|tab| tab.title.clone()).unwrap_or_default(),
            )),
            "closable" => Ok(CapabilityValue::Bool(self.closable())),
            "movable" => Ok(CapabilityValue::Bool(self.movable())),
            "tab_position" => {
                Ok(CapabilityValue::String(tab_position_token(self.tab_position).to_string()))
            }
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "current_index" => {
                self.set_current_index(expect_usize(value)?);
                Ok(())
            }
            // The label route reaches every other control by name, and `create_tab_widget`
            // passes the caller's text through it. Refusing `text`/`title` here meant that
            // text was silently dropped: the factory built a tab widget, the shared label
            // helper called `set("text", ...)`, and this match fell through to
            // `base_property_set` — which has no such arm, so the title never reached a tab.
            // Applying it to the first tab makes the control answer the same property name
            // its constructor's parameter describes.
            "text" | "title" => {
                let text = expect_string(value)?;
                if let Some(first) = self.tabs.first_mut() {
                    first.title = text;
                } else {
                    self.add_tab(text, None);
                }
                self.base.request_redraw();
                Ok(())
            }
            "closable" => {
                self.set_closable(expect_bool(value)?);
                Ok(())
            }
            "movable" => {
                self.set_movable(expect_bool(value)?);
                Ok(())
            }
            // An unknown token is a parse failure, not a different placement: accepting
            // `"North"` and keeping `North` anyway would report success for a write that
            // changed nothing. The accepted spellings are the schema row's.
            "tab_position" => {
                let token = expect_string(value)?;
                let position =
                    TabPosition::from_token(&token).ok_or(CapabilityAccessError::OutOfRange)?;
                self.set_tab_position(position);
                Ok(())
            }
            // Derived from the tab list; the old writer had no arm for it either.
            "tab_count" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "tab_count",
            "current_index",
            "text",
            "title",
            "closable",
            "movable",
            "tab_position",
            BASE_PROPERTY_NAMES
        ]
    }

    /// Runs one of the commands `tab_widget` publishes.
    ///
    /// `add_tab` takes the title and the optional page widget and `remove_tab`
    /// takes the index to remove, so neither can complete without a payload: they
    /// are refused as [`CapabilityAccessError::OutOfRange`], meaning the name is
    /// valid and the argument is what is missing.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "add_tab" | "remove_tab" => Err(CapabilityAccessError::OutOfRange),
            // Any other `set_foo` name carries its value through the property route,
            // so the shared default reports that a payload is needed rather than
            // claiming the control has never heard of it.
            _ if name.starts_with("set_") => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl EventHandler for TabWidget {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        // The move gesture runs before the content forwarding below and reads only the tab
        // strip, so a drag that started on a tab never reaches the page widget — which is
        // what makes the strip behave as one control rather than as a set of drop targets.
        match event {
            Event::MousePress { pos, button } if *button == 1 => {
                if let Some(index) = self.tab_at_position(*pos) {
                    if self.tabs[index].enabled {
                        // Check if the click is on the close button area
                        if self.closable {
                            let close_size = 12;
                            if let Some(tab_rect) = self.tab_rect(index) {
                                let close_x = tab_rect.x + tab_rect.width as i32 - close_size - 5;
                                let close_y =
                                    tab_rect.y + (tab_rect.height as i32 - close_size) / 2;
                                let close_rect = Rect::new(
                                    close_x,
                                    close_y,
                                    close_size as u32,
                                    close_size as u32,
                                );
                                if close_rect.contains(*pos) {
                                    self.tab_close_requested.emit(index);
                                    return;
                                }
                            }
                        }
                        self.set_current_index(index);
                        // Selecting on press and *arming* the drag are separate: the
                        // selection has already happened, and only a pointer that travels
                        // past the threshold turns the same gesture into a reorder.
                        self.begin_tab_drag(*pos);
                    }
                }
            }
            Event::MouseMove { pos } => self.update_tab_drag(*pos),
            Event::MouseRelease { .. } => self.end_tab_drag(),
            _ => {}
        }
        let allow_child_event = match event {
            Event::MousePress { pos, .. }
            | Event::MouseRelease { pos, .. }
            | Event::MouseMove { pos } => self.content_rect().contains(*pos),
            _ => true,
        };
        // Forward content events only to the current widget.
        if allow_child_event {
            if let Some(widget_id) = self.current_widget() {
                if let Some(ref reg) = self.registry {
                    reg.borrow_mut().set_widget_geometry(widget_id, self.content_rect());
                    reg.borrow_mut().forward_event(widget_id, event);
                }
            }
        }
    }
}
impl Draw for TabWidget {
    fn draw(&mut self, context: &mut RenderContext) {
        // Draw base widget
        let _rect = self.geometry();
        let content_rect = self.content_rect();

        // Chrome colours resolve explicit style first, then the theme's resolved
        // style for this control, and only then a literal. The theme step is what
        // makes an appearance switch visible; previously every colour below was a
        // hardcoded literal, so light and dark rendered identically.
        //
        // `resolved_theme_style` takes and releases the global manager's lock
        // internally, so no guard is held across the draw (the mutex is not
        // re-entrant).
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("tab_widget");
        // `tab_widget` is not a control kind in the role table, so it classifies as
        // `Surface`, whose background is `theme.colors.background` — byte-identical
        // to the window behind it. The content area's fill is therefore a step toward
        // the foreground, so the page reads as a surface of its own.
        let resolved = style
            .background_color
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
            .unwrap_or(Color::rgb(255, 255, 255));
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .unwrap_or(Color::rgb(200, 200, 200));
        let text_color = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(Color::rgb(0, 0, 0));
        let content_background = resolved.blend(&text_color, 0.08);
        // Tab chrome is derived from the resolved pair: an inactive tab is pressed
        // toward the foreground, a disabled one further still, and the current tab
        // stays at the content colour so it reads as connected to its page.
        let inactive_tab = content_background.blend(&text_color, 0.06);
        let disabled_tab = content_background.blend(&text_color, 0.14);
        // A disabled tab's label is muted against the tab's own fill, which is what makes it
        // read as unavailable. This is used for the label; the fill above is the other half
        // of the same signal, so both come from the resolved pair.
        let disabled_text = text_color.blend(&disabled_tab, 0.5);
        // The close affordance is secondary chrome, not a second literal.
        let close_color = text_color.blend(&content_background, 0.4);

        // Draw content background
        context.fill_rect(content_rect, content_background);
        // Draw content border
        context.draw_rect(content_rect, border);
        // Draw tabs
        for i in 0..self.tabs.len() {
            if let Some(tab_rect) = self.tab_rect(i) {
                let tab = &self.tabs[i];
                let is_current = i == self.current_index;
                let is_enabled = tab.enabled;
                // Draw tab background
                let bg_color = if !is_enabled {
                    disabled_tab
                } else if is_current {
                    content_background
                } else {
                    inactive_tab
                };
                match self.tab_shape {
                    TabShape::Rounded => {
                        let radius = 4;
                        context.fill_rounded_rect(tab_rect, radius, bg_color);
                        // A current tab shares its edge with the content area, so its
                        // outline uses the surface border; a plain tab is outlined more
                        // faintly.
                        let border_color = if !is_enabled || is_current {
                            border
                        } else {
                            border.blend(&content_background, 0.5)
                        };
                        context.draw_rounded_rect_stroke(tab_rect, radius, border_color, 1);
                    }
                    TabShape::Triangular => {
                        // Real triangular tab: apex at the top-center, base along
                        // the bottom edge of the tab strip.
                        let apex_x = tab_rect.x + tab_rect.width as i32 / 2;
                        let base_y = tab_rect.y + tab_rect.height as i32;
                        let points = [
                            Point::new(apex_x, tab_rect.y),
                            Point::new(tab_rect.x, base_y),
                            Point::new(tab_rect.x + tab_rect.width as i32, base_y),
                        ];
                        context.draw_path(&points, true, bg_color, true, 0);
                        let border_color = if !is_enabled || is_current {
                            border
                        } else {
                            border.blend(&content_background, 0.5)
                        };
                        context.draw_path(&points, true, border_color, false, 1);
                    }
                    _ => {
                        context.fill_rect(tab_rect, bg_color);
                        let border_color = if !is_enabled || is_current {
                            border
                        } else {
                            border.blend(&content_background, 0.5)
                        };
                        context.draw_rect(tab_rect, border_color);
                    }
                };
                // Draw tab text.
                //
                // Centred on both axes and bounded to the tab. The previous form put the glyph
                // origin at the tab's midpoint and asked for `Left`, so a title started at the
                // tab's centre and ran off its right edge, with its top edge on the tab's
                // vertical midpoint. `draw_text_fitted` with `Center` states the intent and
                // elides a title that cannot fit, instead of letting it leave the control.
                let text_color = if !is_enabled { disabled_text } else { text_color };
                let font = Font::default();
                let tab_line = context.text_line(tab_rect, &font);
                let title_band = Rect {
                    x: tab_rect.x,
                    y: tab_line.y,
                    width: tab_rect.width.saturating_sub(if self.closable {
                        (CLOSE_SIZE + 10) as u32
                    } else {
                        0
                    }),
                    height: tab_line.height,
                };
                context.draw_text_fitted(
                    title_band,
                    &tab.title,
                    &font,
                    text_color,
                    HorizontalAlignment::Center,
                );
                // Draw close button if closable
                if self.closable {
                    // Vertically centred on the title's own line box rather than on the tab's
                    // middle: the two ruled the same row and used to disagree by half a line.
                    let close_x = tab_rect.x + tab_rect.width as i32 - CLOSE_SIZE - 5;
                    let close_y = tab_line.y + (tab_line.height as i32 - CLOSE_SIZE) / 2;
                    context.draw_line(
                        Point::new(close_x, close_y),
                        Point::new(close_x + CLOSE_SIZE, close_y + CLOSE_SIZE),
                        close_color,
                    );
                    context.draw_line(
                        Point::new(close_x + CLOSE_SIZE, close_y),
                        Point::new(close_x, close_y + CLOSE_SIZE),
                        close_color,
                    );
                }
            }
        }
        // Draw current widget via registry
        if let Some(widget_id) = self.current_widget() {
            if let Some(ref reg) = self.registry {
                reg.borrow_mut().set_widget_geometry(widget_id, content_rect);
                context.push_clip(
                    content_rect.x,
                    content_rect.y,
                    content_rect.width,
                    content_rect.height,
                );
                reg.borrow_mut().draw_widget(widget_id, context);
                context.pop_clip();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Point, Rect, Size};
    use crate::widget::svg::{render_to_svg, render_widget_to_svg};
    use std::sync::{Arc, Mutex};

    /// Helper to create unique test ObjectIds.
    fn wid1() -> ObjectId {
        1001
    }
    fn wid2() -> ObjectId {
        1002
    }

    // ── 1. Creation defaults ──────────────────────────────────────────────

    /// A crowded strip's tabs get **exactly** their declared share, with nothing shaved off.
    ///
    /// # The defect this pins (BLUE22 · G-1)
    ///
    /// The strip was sized at `sum(tab widths)` while the layout also charges `TAB_SPACING` for
    /// every adjacent pair, so the band the run was given was short by that total. `remaining` went
    /// negative and the proportional shrink pass took the difference off the tabs — one pixel each,
    /// which is why a 64 px share was drawn as 63. Nothing was *wrong* in either half; the band and
    /// the run simply disagreed about whether the gaps were part of the run's extent.
    ///
    /// The assertion is the whole share, per tab, because "the shortfall is distributed" is exactly
    /// what a 1 px loss looks like and exactly what must not happen here.
    #[test]
    fn tabwidget_a_crowded_strip_gives_every_tab_its_full_share() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 100, 120));
        tw.add_tab("Tab 1".to_string(), None);
        tw.add_tab("Tab 2".to_string(), None);

        let hints = tw.tab_width_hints();
        assert_eq!(hints.len(), 2, "two tabs, two declarations");
        // Crowded: the shares must be equal and come from the overflow rule.
        let (min, share, max) = hints[0];
        assert_eq!(hints[1], (min, share, max), "an overflowing strip shares equally");
        assert!(min < share, "a crowded tab may be squeezed below its share: {hints:?}");

        for index in 0..2 {
            let rect = tw.tab_rect(index).expect("the tab has a band");
            assert_eq!(
                rect.width as i32, share,
                "tab {index} must be drawn at its declared share, not one pixel narrower"
            );
        }
        // And the two boxes plus the gap are the strip exactly, so nothing was deferred either.
        let first = tw.tab_rect(0).expect("tab 0");
        let second = tw.tab_rect(1).expect("tab 1");
        assert_eq!(
            second.x,
            first.x + first.width as i32 + TAB_SPACING,
            "the second tab begins one gap after the first"
        );
        assert!(
            second.x + second.width as i32 <= tw.geometry().width as i32,
            "the run fits inside the control"
        );
    }

    /// A strip that fits is untouched by the overflow rule: the three numbers agree and the run is
    /// exactly the measurement.
    ///
    /// The companion to the test above — the G-1 fix must not make a comfortable strip behave as a
    /// crowded one, which is why the fitted case returns `min == pref == max`.
    #[test]
    fn tabwidget_a_strip_that_fits_declares_each_tab_as_fixed() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 600, 120));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        for (index, (min, pref, max)) in tw.tab_width_hints().into_iter().enumerate() {
            assert_eq!((min, max), (pref, pref), "tab {index} must be fixed when the strip fits");
            let rect = tw.tab_rect(index).expect("the tab has a band");
            assert_eq!(rect.width as i32, pref, "tab {index} draws at its measured width");
        }
    }

    #[test]
    fn tabwidget_creation_defaults() {
        let tw = TabWidget::new(Rect::new(10, 20, 400, 300));
        assert_eq!(tw.kind(), WidgetKind::TabWidget);
        assert_eq!(tw.geometry(), Rect::new(10, 20, 400, 300));
        assert_eq!(tw.count(), 0);
        assert_eq!(tw.current_index(), 0);
        assert!(tw.current_widget().is_none());
        assert_eq!(tw.tab_position(), TabPosition::North);
        assert_eq!(tw.tab_shape(), TabShape::Rounded);
        assert!(!tw.closable());
        assert!(!tw.movable());
        assert!(tw.is_visible());
        assert!(tw.is_enabled());
        assert!(tw.children().is_empty());
        assert!(tw.registry().is_none());
    }

    // ── 2. Adding tabs ────────────────────────────────────────────────────────

    #[test]
    fn tabwidget_add_tab_returns_index_and_increments_count() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        let idx0 = tw.add_tab("Tab A".to_string(), None);
        assert_eq!(idx0, 0);
        assert_eq!(tw.count(), 1);

        let idx1 = tw.add_tab("Tab B".to_string(), Some(wid1()));
        assert_eq!(idx1, 1);
        assert_eq!(tw.count(), 2);

        let idx2 = tw.add_tab("Tab C".to_string(), Some(wid2()));
        assert_eq!(idx2, 2);
        assert_eq!(tw.count(), 3);
    }

    #[test]
    fn tabwidget_add_tab_with_widget_updates_children() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("With Widget".to_string(), Some(wid1()));
        let children = tw.children();
        assert_eq!(children.len(), 1);
        assert!(children.contains(&wid1()));
    }

    #[test]
    fn tabwidget_add_tab_without_widget_does_not_add_child() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("No Widget".to_string(), None);
        assert!(tw.children().is_empty());
    }

    // ── 3. Inserting tabs at specific index ───────────────────────────────────

    #[test]
    fn tabwidget_insert_tab_at_front_shifts_indices() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        tw.insert_tab(0, "Inserted".to_string(), None);
        assert_eq!(tw.count(), 3);
        assert_eq!(tw.tab_text(0), Some("Inserted"));
        assert_eq!(tw.tab_text(1), Some("A"));
        assert_eq!(tw.tab_text(2), Some("B"));
    }

    #[test]
    fn tabwidget_insert_tab_at_end_acts_like_add() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.insert_tab(1, "B".to_string(), None);
        assert_eq!(tw.count(), 2);
        assert_eq!(tw.tab_text(1), Some("B"));
    }

    #[test]
    fn tabwidget_insert_tab_shifts_current_index() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        tw.set_current_index(1);
        tw.insert_tab(0, "X".to_string(), None);
        // current_index was 1, now should be 2 because a tab was inserted before it
        assert_eq!(tw.current_index(), 2);
    }

    #[test]
    fn tabwidget_insert_tab_with_widget_adds_child() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.insert_tab(0, "X".to_string(), Some(wid1()));
        let children = tw.children();
        assert_eq!(children.len(), 1);
        assert!(children.contains(&wid1()));
    }

    // ── 4. Removing tabs ─────────────────────────────────────────────────────

    #[test]
    fn tabwidget_remove_tab_reduces_count() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        tw.add_tab("C".to_string(), None);
        assert_eq!(tw.count(), 3);

        tw.remove_tab(1);
        assert_eq!(tw.count(), 2);
        assert_eq!(tw.tab_text(0), Some("A"));
        assert_eq!(tw.tab_text(1), Some("C"));
    }

    #[test]
    fn tabwidget_remove_tab_out_of_bounds_is_noop() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.remove_tab(5); // out of bounds
        assert_eq!(tw.count(), 1);
    }

    #[test]
    fn tabwidget_remove_last_tab_resets_current_index() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.remove_tab(0);
        assert_eq!(tw.count(), 0);
        assert_eq!(tw.current_index(), 0);
    }

    #[test]
    fn tabwidget_remove_tab_adjusts_current_index() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        tw.add_tab("C".to_string(), None);
        tw.set_current_index(2);
        tw.remove_tab(2);
        assert_eq!(tw.current_index(), 1);
    }

    #[test]
    fn tabwidget_remove_tab_with_widget_removes_child() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), Some(wid1()));
        tw.add_tab("B".to_string(), Some(wid2()));
        assert_eq!(tw.children().len(), 2);
        tw.remove_tab(0);
        assert_eq!(tw.children().len(), 1);
        assert!(!tw.children().contains(&wid1()));
    }

    // ── 5. Getting / setting current index ────────────────────────────────────

    #[test]
    fn tabwidget_set_current_index_normal() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), Some(wid1()));
        tw.add_tab("B".to_string(), Some(wid2()));
        tw.set_current_index(1);
        assert_eq!(tw.current_index(), 1);
        assert_eq!(tw.current_widget(), Some(wid2()));
    }

    #[test]
    fn tabwidget_set_current_index_out_of_bounds_is_noop() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.set_current_index(10);
        assert_eq!(tw.current_index(), 0);
    }

    #[test]
    fn tabwidget_set_current_index_same_value_is_noop() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        tw.set_current_index(0); // already 0
        assert_eq!(tw.current_index(), 0);
    }

    #[test]
    fn tabwidget_current_widget_on_empty_returns_none() {
        let tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert_eq!(tw.current_widget(), None);
    }

    #[test]
    fn tabwidget_set_current_index_round_trip() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        tw.add_tab("C".to_string(), None);
        tw.set_current_index(2);
        assert_eq!(tw.current_index(), 2);
        tw.set_current_index(0);
        assert_eq!(tw.current_index(), 0);
        tw.set_current_index(1);
        assert_eq!(tw.current_index(), 1);
    }

    // ── 6. Tab count after operations ─────────────────────────────────────────

    #[test]
    fn tabwidget_count_after_mixed_operations() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert_eq!(tw.count(), 0);
        tw.add_tab("A".to_string(), None);
        assert_eq!(tw.count(), 1);
        tw.add_tab("B".to_string(), None);
        assert_eq!(tw.count(), 2);
        tw.insert_tab(1, "C".to_string(), None);
        assert_eq!(tw.count(), 3);
        tw.remove_tab(0);
        assert_eq!(tw.count(), 2);
        tw.remove_tab(0);
        assert_eq!(tw.count(), 1);
        tw.remove_tab(0);
        assert_eq!(tw.count(), 0);
    }

    // ── 7. Setting tab text and tooltip ───────────────────────────────────────

    #[test]
    fn tabwidget_set_tab_text_updates_and_retrieves() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Original".to_string(), None);
        assert_eq!(tw.tab_text(0), Some("Original"));
        tw.set_tab_text(0, "Updated".to_string());
        assert_eq!(tw.tab_text(0), Some("Updated"));
    }

    #[test]
    fn tabwidget_set_tab_text_out_of_bounds_is_noop() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.set_tab_text(0, "Nope".to_string());
        // No panic, no change
        assert_eq!(tw.tab_text(0), None);
    }

    #[test]
    fn tabwidget_tab_text_returns_none_for_invalid_index() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Only".to_string(), None);
        assert_eq!(tw.tab_text(1), None);
        assert_eq!(tw.tab_text(usize::MAX), None);
    }

    #[test]
    fn tabwidget_tab_tooltip_set_and_get() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Tab".to_string(), None);
        let tab = tw.tab_mut(0).unwrap();
        assert_eq!(tab.tooltip(), "");
        tab.set_tooltip("Helpful hint".to_string());
        assert_eq!(tab.tooltip(), "Helpful hint");
        let tab_ref = tw.tab(0).unwrap();
        assert_eq!(tab_ref.tooltip(), "Helpful hint");
    }

    // ── 8. Enabling / disabling tabs ──────────────────────────────────────────

    #[test]
    fn tabwidget_tab_enabled_default() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Tab".to_string(), None);
        assert!(tw.tab(0).unwrap().is_enabled());
    }

    #[test]
    fn tabwidget_disable_tab_via_tab_mut() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Tab".to_string(), None);
        let tab = tw.tab_mut(0).unwrap();
        tab.set_enabled(false);
        assert!(!tw.tab(0).unwrap().is_enabled());
        // Re-enable
        let tab = tw.tab_mut(0).unwrap();
        tab.set_enabled(true);
        assert!(tw.tab(0).unwrap().is_enabled());
    }

    #[test]
    fn tabwidget_tab_title_via_tab_api() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Hello".to_string(), None);
        assert_eq!(tw.tab(0).unwrap().title(), "Hello");
        tw.tab_mut(0).unwrap().set_title("World".to_string());
        assert_eq!(tw.tab(0).unwrap().title(), "World");
    }

    // ── 9. Tab position and shape configuration ───────────────────────────────

    #[test]
    fn tabwidget_tab_position_default_is_north() {
        let tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert_eq!(tw.tab_position(), TabPosition::North);
    }

    #[test]
    fn tabwidget_set_tab_position_cycle() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.set_tab_position(TabPosition::South);
        assert_eq!(tw.tab_position(), TabPosition::South);
        tw.set_tab_position(TabPosition::West);
        assert_eq!(tw.tab_position(), TabPosition::West);
        tw.set_tab_position(TabPosition::East);
        assert_eq!(tw.tab_position(), TabPosition::East);
        tw.set_tab_position(TabPosition::North);
        assert_eq!(tw.tab_position(), TabPosition::North);
    }

    #[test]
    fn tabwidget_tab_shape_default_is_rounded() {
        let tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert_eq!(tw.tab_shape(), TabShape::Rounded);
    }

    #[test]
    fn tabwidget_set_tab_shape() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.set_tab_shape(TabShape::Triangular);
        assert_eq!(tw.tab_shape(), TabShape::Triangular);
        tw.set_tab_shape(TabShape::Rectangular);
        assert_eq!(tw.tab_shape(), TabShape::Rectangular);
        tw.set_tab_shape(TabShape::Rounded);
        assert_eq!(tw.tab_shape(), TabShape::Rounded);
    }

    #[test]
    fn tabwidget_closable_movable_default_false() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert!(!tw.closable());
        assert!(!tw.movable());
        tw.set_closable(true);
        tw.set_movable(true);
        assert!(tw.closable());
        assert!(tw.movable());
        tw.set_closable(false);
        tw.set_movable(false);
        assert!(!tw.closable());
        assert!(!tw.movable());
    }

    // ── 10. Min / max size via Widget trait ───────────────────────────────────

    #[test]
    fn tabwidget_min_size_default_none() {
        let tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert_eq!(tw.min_size(), None);
        assert_eq!(tw.max_size(), None);
    }

    #[test]
    fn tabwidget_set_min_max_size() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.set_min_size(Some(Size::new(100, 80)));
        tw.set_max_size(Some(Size::new(800, 600)));
        assert_eq!(tw.min_size(), Some(Size::new(100, 80)));
        assert_eq!(tw.max_size(), Some(Size::new(800, 600)));
    }

    // ── 11. Signal accessors ──────────────────────────────────────────────────

    #[test]
    fn tabwidget_current_changed_signal_emits_on_set_index() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);

        let emitted = Arc::new(std::sync::Mutex::new(None));
        tw.current_changed.connect({
            let emitted = Arc::clone(&emitted);
            move |idx: Arc<usize>| {
                *emitted.lock().unwrap() = Some(*idx);
            }
        });

        tw.set_current_index(1);
        assert_eq!(*emitted.lock().unwrap(), Some(1));
    }

    #[test]
    fn tabwidget_current_changed_not_emitted_for_same_index() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);

        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        tw.current_changed.connect({
            let count = Arc::clone(&count);
            move |_: Arc<usize>| {
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            }
        });

        tw.set_current_index(0); // same as default
        assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[test]
    fn tabwidget_current_changed_not_emitted_for_out_of_bounds() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);

        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        tw.current_changed.connect({
            let count = Arc::clone(&count);
            move |_: Arc<usize>| {
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            }
        });

        tw.set_current_index(5); // out of bounds
        assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[test]
    fn tabwidget_tab_close_requested_signal_accessible() {
        let tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        let emitted = Arc::new(std::sync::Mutex::new(None));
        tw.tab_close_requested.connect({
            let emitted = Arc::clone(&emitted);
            move |idx: Arc<usize>| {
                *emitted.lock().unwrap() = Some(*idx);
            }
        });
        // Manually emit — tabwidget doesn't auto-close, but the signal is public
        tw.tab_close_requested.emit(1usize);
        assert_eq!(*emitted.lock().unwrap(), Some(1));
    }

    // ── 12. Geometry delegation ───────────────────────────────────────────────

    #[test]
    fn tabwidget_geometry_via_widget_trait() {
        let tw = TabWidget::new(Rect::new(5, 10, 200, 150));
        assert_eq!(tw.geometry(), Rect::new(5, 10, 200, 150));
        assert_eq!(tw.geometry(), Rect::new(5, 10, 200, 150));
    }

    #[test]
    fn tabwidget_set_geometry_via_widget_trait() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 100, 100));
        tw.set_geometry(Rect::new(20, 30, 500, 400));
        assert_eq!(tw.geometry(), Rect::new(20, 30, 500, 400));
        assert_eq!(tw.position(), Point::new(20, 30));
        assert_eq!(tw.size(), Size::new(500, 400));
    }

    #[test]
    fn tabwidget_set_position_and_size() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 200, 100));
        tw.set_position(Point::new(50, 60));
        assert_eq!(tw.position(), Point::new(50, 60));
        assert_eq!(tw.size(), Size::new(200, 100));

        tw.set_size(Size::new(300, 150));
        assert_eq!(tw.position(), Point::new(50, 60));
        assert_eq!(tw.size(), Size::new(300, 150));
    }

    // ── 13. Widget ID and kind ────────────────────────────────────────────────

    #[test]
    fn tabwidget_kind_is_tabwidget() {
        let tw = TabWidget::new(Rect::new(0, 0, 100, 100));
        assert_eq!(tw.kind(), WidgetKind::TabWidget);
    }

    #[test]
    fn tabwidget_id_is_unique() {
        let tw1 = TabWidget::new(Rect::new(0, 0, 100, 100));
        let tw2 = TabWidget::new(Rect::new(0, 0, 100, 100));
        assert_ne!(tw1.id(), tw2.id());
    }

    #[test]
    fn tabwidget_accessible_name_falls_back_to_kind() {
        let tw = TabWidget::new(Rect::new(0, 0, 100, 100));
        assert_eq!(tw.accessible_name(), "TabWidget");
    }

    #[test]
    fn tabwidget_accessible_role_is_kind() {
        use crate::platform::accessibility::AccessibleRole;
        let tw = TabWidget::new(Rect::new(0, 0, 100, 100));
        assert_eq!(tw.accessible_role(), AccessibleRole::TabGroup);
    }

    // ── 14. Disabled state blocks events ──────────────────────────────────────

    #[test]
    fn tabwidget_disabled_does_not_switch_on_mouse_press() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);

        tw.set_current_index(0);
        // Disable the entire widget
        tw.set_enabled(false);

        // Click on tab 1's position
        // tab_rect(0) with North position at Rect(0,0,300,200) starts at x=0, y=0
        let event = Event::mouse_press(0, 0, 1);
        tw.handle_event(&event);

        // current_index should still be 0 because the widget is disabled
        assert_eq!(tw.current_index(), 0);
    }

    #[test]
    fn tabwidget_enabled_switches_on_mouse_press() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);

        tw.set_current_index(0);

        // The second tab's position comes from the control's own layout, not from a literal:
        // tab widths are measured from their titles, so a hardcoded x would pin this test to one
        // font's metrics and break every time a title changed. Reading `tab_rect` is also the
        // stronger assertion — it checks that a click lands on the tab the control believes is
        // there, which is the property that matters.
        let second = tw.tab_rect(1).expect("two tabs were added, so index 1 has a rectangle");
        let click_x = second.x + second.width as i32 / 2;
        let event = Event::mouse_press(click_x, second.y + 2, 1);
        tw.handle_event(&event);

        assert_eq!(tw.current_index(), 1);
    }

    #[test]
    fn tabwidget_disabled_tab_does_not_switch_on_mouse_press() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);
        // Disable tab at index 1
        tw.tab_mut(1).unwrap().set_enabled(false);

        tw.set_current_index(0);

        // Click on tab 1's position
        let event = Event::mouse_press(102, 0, 1);
        tw.handle_event(&event);

        // Should NOT switch because tab 1 is disabled
        assert_eq!(tw.current_index(), 0);
    }

    #[test]
    fn tabwidget_right_click_does_not_switch() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);

        tw.set_current_index(0);

        // Right-click on tab 1's position
        let event = Event::mouse_press(102, 0, 3);
        tw.handle_event(&event);

        // Should NOT switch because only button 1 (left click) triggers switch
        assert_eq!(tw.current_index(), 0);
    }

    #[test]
    fn tabwidget_click_outside_tabs_does_not_change_index() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("A".to_string(), None);
        tw.add_tab("B".to_string(), None);

        tw.set_current_index(0);

        // Click far to the right of any tab
        let event = Event::mouse_press(500, 0, 1);
        tw.handle_event(&event);

        assert_eq!(tw.current_index(), 0);
    }

    // ── 15. SVG output verification ───────────────────────────────────────────

    #[test]
    fn tabwidget_svg_output_via_render_to_svg() {
        // Holds the crate-wide theme guard: this test renders, and a concurrent
        // test that switches the appearance would otherwise change a later frame.
        let _theme_guard = crate::style::theme_test_guard();
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Home".to_string(), None);
        tw.add_tab("Settings".to_string(), None);

        let svg = render_to_svg(&mut tw);
        assert!(svg.starts_with("<svg"), "SVG should start with <svg");
        assert!(svg.ends_with("</svg>"), "SVG should end with </svg>");
        assert!(svg.contains("width=\"300\""), "SVG should contain width=\"300\"");
        assert!(svg.contains("height=\"200\""), "SVG should contain height=\"200\"");
        // Both tab titles are drawn. They are `font8x8` glyph geometry, not `<text>` elements, so
        // the titles are checked as ink on the **tab strip**: the strip is the control's top
        // `TAB_HEIGHT` rows, and one label per tab means one ink box per tab, each inside its own
        // tab rather than a single run spanning the strip.
        let title_boxes: Vec<(i32, i32, i32, i32)> = svg
            .lines()
            .filter(|line| line.contains("<path "))
            .filter_map(|line| {
                let d = line.find("d=\"")? + 3;
                let end = line[d..].find('"')? + d;
                let d = &line[d..end];
                let mut box_: Option<(i32, i32, i32, i32)> = None;
                for subpath in d.split('M').skip(1) {
                    let numbers: Vec<i32> = subpath
                        .split(|c: char| !c.is_ascii_digit() && c != '-')
                        .filter(|part| !part.is_empty())
                        .filter_map(|part| part.parse().ok())
                        .collect();
                    if numbers.len() < 4 {
                        continue;
                    }
                    let (x, y, w, h) = (numbers[0], numbers[1], numbers[2], numbers[3]);
                    box_ = Some(match box_ {
                        None => (x, y, x + w, y + h),
                        Some((l, t, r, b)) => (l.min(x), t.min(y), r.max(x + w), b.max(y + h)),
                    });
                }
                box_
            })
            .collect();
        assert_eq!(title_boxes.len(), 2, "one label per tab: {title_boxes:?}");
        for (index, title) in title_boxes.iter().enumerate() {
            assert!(
                (0..TAB_HEIGHT + 2).contains(&title.1) && title.3 <= TAB_HEIGHT + 2,
                "tab {index}'s title must sit on the tab strip, got {title:?}"
            );
            assert!(title.2 > title.0, "tab {index}'s title laid down ink: {title:?}");
        }
        // The two tabs are laid side by side, so the second label starts to the right of the
        // first: a widget that drew both titles at the same x would overlap them.
        assert!(
            title_boxes[1].0 > title_boxes[0].2,
            "the second tab's title follows the first: {title_boxes:?}"
        );
        // Should contain fill and stroke attributes from the rendering
        assert!(svg.contains("fill=") || svg.contains("stroke="));
    }

    #[test]
    fn tabwidget_svg_output_with_explicit_geometry() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 120, 80));
        tw.add_tab("X".to_string(), None);

        let svg = render_widget_to_svg(&mut tw, Rect::new(0, 0, 120, 80));
        assert!(svg.contains("width=\"120\""));
        assert!(svg.contains("height=\"80\""));
    }

    // ── 16. Tab accessor (tab / tab_mut) ──────────────────────────────────────

    #[test]
    fn tabwidget_tab_accessor_out_of_bounds() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert!(tw.tab(0).is_none());
        assert!(tw.tab_mut(0).is_none());
    }

    #[test]
    fn tabwidget_tab_mut_allows_widget_assignment() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Tab".to_string(), None);
        tw.tab_mut(0).unwrap().set_widget(Some(wid1()));
        // Widget assigned to tab 0 is also the current widget (index 0)
        assert_eq!(tw.tab(0).unwrap().widget(), Some(wid1()));
        assert_eq!(tw.current_widget(), Some(wid1()));
    }

    // ── 17. Registry round-trip ───────────────────────────────────────────────

    #[test]
    fn tabwidget_registry_set_and_get() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert!(tw.registry().is_none());
        let reg = Rc::new(RefCell::new(SimpleRegistry::new()));
        tw.set_registry(reg.clone());
        assert!(tw.registry().is_some());
        // Verify pointer identity
        assert!(Rc::ptr_eq(&reg, tw.registry().unwrap()));
    }

    // ── 18. Tab icon set/get ───────────────────────────────────────────────────

    #[cfg(feature = "image")]
    #[test]
    fn tabwidget_tab_icon_default_none() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        tw.add_tab("Tab".to_string(), None);
        assert!(tw.tab(0).unwrap().icon().is_none());
    }

    // ── 19. Movable tabs (drag to reorder) ─────────────────────────────────────

    /// Builds a strip of `count` tabs with wide, well-separated bands.
    fn movable_strip(count: usize) -> TabWidget {
        let mut tw = TabWidget::new(Rect::new(0, 0, 600, 200));
        for i in 0..count {
            tw.add_tab(format!("T{i}"), None);
        }
        tw.set_movable(true);
        tw
    }

    fn titles(tw: &TabWidget) -> Vec<String> {
        (0..tw.count()).map(|i| tw.tab_text(i).unwrap().to_string()).collect()
    }

    #[test]
    fn tabwidget_move_tab_reorders_and_emits() {
        let mut tw = movable_strip(3);
        let captured = Arc::new(Mutex::new(None::<(usize, usize)>));
        tw.tab_moved.connect({
            let captured = Arc::clone(&captured);
            move |value: Arc<(usize, usize)>| {
                *captured.lock().unwrap() = Some(*value);
            }
        });

        assert!(tw.move_tab(0, 2));
        assert_eq!(titles(&tw), vec!["T1", "T2", "T0"]);
        assert_eq!(*captured.lock().unwrap(), Some((0, 2)));

        // A move to the same index is not a move, so nothing is emitted.
        assert!(!tw.move_tab(1, 1));
        assert_eq!(*captured.lock().unwrap(), Some((0, 2)));

        // An out-of-range source is a caller error and does not reorder or emit.
        assert!(!tw.move_tab(99, 0));
        assert_eq!(*captured.lock().unwrap(), Some((0, 2)));
    }

    #[test]
    fn tabwidget_move_tab_clamps_the_target_to_the_last_tab() {
        let mut tw = movable_strip(3);
        // "Dropped past the end" is "moved to the end", not a refusal.
        assert!(tw.move_tab(0, 99));
        assert_eq!(titles(&tw), vec!["T1", "T2", "T0"]);
    }

    #[test]
    fn tabwidget_move_tab_keeps_the_selection_with_its_page() {
        let mut tw = movable_strip(3);
        tw.set_current_index(2);
        // Dragging the current tab must not leave the selection on the slot it vacated.
        assert!(tw.move_tab(2, 0));
        assert_eq!(titles(&tw), vec!["T2", "T0", "T1"]);
        assert_eq!(tw.current_index(), 0);

        // And dragging another tab across the selection shifts it by one slot.
        tw.set_current_index(0); // the dragged tab
        assert!(tw.move_tab(2, 0));
        assert_eq!(titles(&tw), vec!["T1", "T2", "T0"]);
        assert_eq!(tw.current_index(), 1);
    }

    /// A press on a tab of a *movable* strip that then travels reorders it.
    #[test]
    fn tabwidget_drag_reorders_a_movable_tab() {
        let mut tw = movable_strip(3);
        let first = tw.tab_rect(0).expect("tab 0 has a band");
        let third = tw.tab_rect(2).expect("tab 2 has a band");
        let press = Point::new(first.x + first.width as i32 / 2, first.y + 5);

        tw.handle_event(&Event::MousePress { pos: press, button: 1 });
        // A press alone must not reorder: the gesture is still a click at this point.
        assert_eq!(titles(&tw), vec!["T0", "T1", "T2"]);

        // Travel past the drag threshold and onto the third tab.
        tw.handle_event(&Event::MouseMove {
            pos: Point::new(third.x + third.width as i32 / 2, press.y),
        });
        assert_eq!(
            titles(&tw),
            vec!["T1", "T2", "T0"],
            "crossing two neighbours must carry the tab to the far end"
        );

        tw.handle_event(&Event::MouseRelease {
            pos: Point::new(third.x + third.width as i32 / 2, press.y),
            button: 1,
        });
        // The release settles the gesture; the live reorder already happened.
        assert_eq!(titles(&tw), vec!["T1", "T2", "T0"]);
    }

    /// The whole point of the flag: with it off, the very same gesture must not reorder.
    #[test]
    fn tabwidget_drag_does_nothing_when_not_movable() {
        let mut tw = TabWidget::new(Rect::new(0, 0, 600, 200));
        for i in 0..3 {
            tw.add_tab(format!("T{i}"), None);
        }
        assert!(!tw.movable());

        let first = tw.tab_rect(0).expect("tab 0 has a band");
        let third = tw.tab_rect(2).expect("tab 2 has a band");
        let y = first.y + 5;
        tw.handle_event(&Event::MousePress {
            pos: Point::new(first.x + first.width as i32 / 2, y),
            button: 1,
        });
        tw.handle_event(&Event::MouseMove { pos: Point::new(third.x + third.width as i32 / 2, y) });
        assert_eq!(titles(&tw), vec!["T0", "T1", "T2"]);
        // The press still selected, which is the behaviour a non-movable strip keeps.
        assert_eq!(tw.current_index(), 0);
    }

    /// A press-and-jitter must stay a click rather than a reorder.
    #[test]
    fn tabwidget_a_jitter_below_the_threshold_does_not_reorder() {
        let mut tw = movable_strip(3);
        let first = tw.tab_rect(0).expect("tab 0 has a band");
        let press = Point::new(first.x + first.width as i32 / 2, first.y + 5);
        tw.handle_event(&Event::MousePress { pos: press, button: 1 });
        tw.handle_event(&Event::MouseMove { pos: Point::new(press.x + 1, press.y) });
        assert_eq!(titles(&tw), vec!["T0", "T1", "T2"]);
    }

    /// Turning `movable` off mid-drag must abandon the gesture, not finish it.
    #[test]
    fn tabwidget_set_movable_false_cancels_a_live_drag() {
        let mut tw = movable_strip(3);
        let first = tw.tab_rect(0).expect("tab 0 has a band");
        let third = tw.tab_rect(2).expect("tab 2 has a band");
        let y = first.y + 5;
        tw.handle_event(&Event::MousePress {
            pos: Point::new(first.x + first.width as i32 / 2, y),
            button: 1,
        });
        tw.handle_event(&Event::MouseMove {
            pos: Point::new(first.x + first.width as i32 / 2 + 10, y),
        });
        tw.set_movable(false);
        tw.handle_event(&Event::MouseMove { pos: Point::new(third.x + third.width as i32 / 2, y) });
        assert_eq!(titles(&tw), vec!["T0", "T1", "T2"]);
    }

    #[test]
    fn tabwidget_movable_is_a_served_property() {
        use crate::widget::capability::properties_trait::{
            widget_property_get, widget_property_set,
        };
        use crate::widget::capability::CapabilityValue;

        let mut tw = TabWidget::new(Rect::new(0, 0, 300, 200));
        assert!(crate::widget::capability::widget_property_names(&tw)
            .expect("a tab widget declares properties")
            .contains(&"movable"));
        widget_property_set(&mut tw, "movable", CapabilityValue::Bool(true)).unwrap();
        assert!(tw.movable());
        assert_eq!(widget_property_get(&tw, "movable"), Ok(CapabilityValue::Bool(true)));

        // `tab_position` and `closable` round-trip through their tokens too.
        widget_property_set(&mut tw, "tab_position", CapabilityValue::String("south".to_string()))
            .unwrap();
        assert_eq!(tw.tab_position(), TabPosition::South);
        assert_eq!(
            widget_property_get(&tw, "tab_position"),
            Ok(CapabilityValue::String("south".to_string()))
        );
        assert!(widget_property_set(
            &mut tw,
            "tab_position",
            CapabilityValue::String("South".to_string())
        )
        .is_err());
        assert_eq!(tw.tab_position(), TabPosition::South);
    }
}