rust_widgets 2.9.2

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
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Spin box widget for numeric input.
//!
//! # The value box yields to the step column
//!
//! BLUE22 §F.2.2 puts this control first in the §B.8 migration queue, and the reason is the one
//! insight the whole composite section rests on: the sibling-column relation reads
//! `leftPadding: padding + (mirrored ? up.width : down.width)`, i.e. **the text side's inset is
//! the sibling column's width**. The value's box is therefore not "the field minus a constant"
//! — it is whatever the column leaves.
//!
//! That relation is stated once in `SpinBox::row_widths`: the value takes the remainder, so the
//! column pushes it narrower when the column grows, and no second placement can disagree about
//! which edge the column sits on.
//!
//! The public accessors (`SpinBox::editable_rect`, `SpinBox::up_button`,
//! `SpinBox::down_button`) keep their names and their meaning: they report the derivation's
//! answer rather than a second copy of it, so the paint path, the hit test and the tests all read
//! one geometry.
use crate::compat::{format, Box, Rc, String, ToString};
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler, WheelScroll};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::style::EdgeOffsets;
use crate::widget::decorations::{
    DecorationLayout, DecorationMetrics, DecorationSlots, DECORATION_GAP,
};
use crate::widget::metrics::{dimensions, effective_font, estimate_text_width, ControlMetrics};
use std::cell::{Ref, RefCell};

use crate::widget::capability::coercion::{
    expect_bool, expect_f64, expect_horizontal_alignment, expect_string, expect_text_direction,
    expect_u32, horizontal_alignment_to_str, text_direction_to_str,
};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::numeric::ordered_clamp_f64;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

use super::input_validator::{InputValidator, ValidationState, Validator};
use super::lineedit::LineEdit;
use crate::data_binding::{Formatter, ValidationError, Validator as ValueValidator};
use crate::widget::display_widgets::slider::{LinkMode, NumericLinkSlot};

/// Upper bound on [`SpinBox::decimals`], matching the widest precision the default
/// display grammar can print. A larger precision would render digits that are pure
/// binary noise, which is worse than refusing the setting.
pub const SPIN_BOX_MAX_DECIMALS: u32 = 9;

/// Width of one step button in the spin box's trailing button column: 20.
///
/// See [`dimensions::SPIN_BOX_STEP_BUTTON_WIDTH`] for why the number lives in the shared table:
/// the assembled row's step column, the hint's floor and the arrow's box are three readings of it.
const SPIN_BOX_BUTTON_WIDTH: u32 = dimensions::SPIN_BOX_STEP_BUTTON_WIDTH;

/// The buttons stacked in the trailing column, counted for the width derivation.
///
/// Reads the shared table so the assembly, the hint's floor and the column's own width are one
/// fact; see [`dimensions::SPIN_BOX_STEP_BUTTONS`].
const SPIN_BOX_BUTTONS: u32 = dimensions::SPIN_BOX_STEP_BUTTONS;

/// Shape of the step arrows drawn inside the button column: 4 px of half-span, 5 px of drop.
///
/// One fact for both arrows: they carried five literals each (`4`, `4.0`, and three
/// halved `2.0`s) whose relations were only correct because they happened to be written
/// together, so changing the arrow's size meant finding all ten.
const SPIN_BOX_ARROW_HALF_SPAN: f32 = 4.0;
const SPIN_BOX_ARROW_DROP: f32 = 5.0;

/// Spin box widget for numeric input.
///
/// # Integer or decimal (BLUE20 layer 4c)
///
/// The value is stored as an `f64` and the displayed precision is a setting
/// ([`SpinBox::decimals`]). `decimals == 0` is the integer case and is the default, so
/// the widget's integer behaviour is unchanged: every integer accessor round-trips
/// exactly, and `"5"` displays as `"5"`. Raising `decimals` does not add a *second*
/// control — `double_spin_box` is already an alias of this one — it adds the decimal
/// mode the alias promises. Two near-identical controls would have to be maintained in
/// lockstep and would drift; one control with a precision setting cannot.
pub struct SpinBox {
    base: BaseWidget,
    /// Shown value. Held as `f64` so a decimal spin box and an integer spin box are the
    /// same widget; `decimals == 0` restricts it to whole numbers.
    value: f64,
    /// Lower bound of the value range; also the value that triggers
    /// `special_value_text`.
    minimum: f64,
    /// Upper bound of the value range; the value a wrapping `step_up` from
    /// `maximum` lands on.
    maximum: f64,
    /// Amount added or subtracted per step. Applied to the current value, so a
    /// step may be clamped (or wrapped) rather than landing on a multiple.
    single_step: f64,
    /// Digits shown after the decimal separator. `0` means an integer spin box, which
    /// is the default and the previous behaviour.
    ///
    /// Not a display-only filter: the value itself is rounded to this precision on every
    /// write, so `get("value")` cannot report a number the user never could have entered.
    decimals: u32,
    /// Text placed before the number in the displayed value; display only — it
    /// is not part of the parsed numeric value.
    prefix: String,
    /// Text placed after the number in the displayed value; display only.
    suffix: String,
    /// Replaces the formatted number in the display whenever the value equals
    /// `minimum`, e.g. `"Auto"` for a value of 0. `None` always shows the
    /// number.
    special_value_text: Option<String>,
    /// The last formatted value text, keyed by the inputs `value_text` reads.
    ///
    /// `draw` asks for it every frame, and formatting the number built a `String` each time. The
    /// text is a pure function of `(value, minimum, decimals, special_value_text)`, so those are
    /// the key; a setter that changes one makes the next call rebuild (WDGT-06).
    value_text_cache: RefCell<Option<ValueTextCache>>,
    /// When true, stepping past `minimum` jumps to `maximum` (and vice versa)
    /// instead of clamping. Affects only the step buttons / keyboard stepping,
    /// not `set_value`.
    wrapping: bool,
    /// The writing direction the field is laid out in.
    ///
    /// # What the direction moves, and why the buttons are the whole of it
    ///
    /// In a right-to-left field the **value is read from the right**, so the step column belongs on
    /// the *leading* edge (the right) rather than the trailing one (the left) — the same edge the
    /// value starts from, which is what keeps the number next to the buttons that change it. Before
    /// this, a spin box under an RTL locale drew its value in the right-hand two thirds and its
    /// steppers on the left, so the two halves were in different reading orders.
    ///
    /// The value's own text alignment follows the same field: `Left` in LTR, `Right` in RTL. Both
    /// are properties of **one** value read by every box below, so the column and the text cannot
    /// disagree about which edge they are anchored to.
    direction: crate::core::TextDirection,
    /// How the value is aligned within its own box.
    ///
    /// Horizontal only: the value's box is centred vertically in the row band by the row's own
    /// layout, so a `top`/`bottom` value would be one this control could never honour —
    /// [`crate::widget::capability::coercion::expect_horizontal_alignment`] refuses those rather
    /// than accepting a write that does nothing. Defaults to left, so a caller that never asks
    /// behaves exactly as it did.
    alignment: crate::core::Alignment,
    /// Emitted with the new value after any change, including clamping by
    /// `minimum` / `maximum`. Not emitted when the value is set to the value it
    /// already had.
    pub value_changed: Signal1<i32>,
    /// Emitted without a payload when an in-progress edit is committed or
    /// cancelled (Enter, focus loss, or step).
    pub editing_finished: GenericSignal,
    /// How one step chooses its distance.
    step_type: SpinBoxStepType,
    /// Whether the user is typing a value into the field.
    editing: bool,
    /// The text entry's editing engine.
    ///
    /// # Why the entry is a real `LineEdit` rather than a character buffer
    ///
    /// The previous entry was a `String` plus a cursor and a selection anchor maintained here:
    /// it accepted digits through `insert_entry_char`, deleted one byte at a time, and had no
    /// clipboard, no IME commit and no word-wise navigation. [`LineEdit`] already owns every one
    /// of those behaviours (and the event gating the rest of the crate trusts it for), so the
    /// spin box hosts one and asks it what the text and caret are. The numeric stepping below is
    /// unchanged; only the *text* half of an edit is delegated.
    ///
    /// The field is hosted rather than registered as a tree child because a `SpinBox` is
    /// constructed before it has a window or a registry; its rectangle is written by
    /// [`SpinBox::place_entry`] from the same `editable_rect` the paint path uses.
    entry: LineEdit,
    /// The rule the typed entry is checked against, or `None` for a free numeric field.
    ///
    /// A spin box bounds its value but has no opinion about the *text* being assembled: a
    /// caller with a domain rule (an order code, a partially typed range) installs it here.
    /// The state is reported, not enforced — the value setter still clamps, so a caller can
    /// always leave the field.
    validator: Option<Box<dyn Validator>>,
    /// Cached three-way outcome for the current entry text (or the formatted value when idle).
    validation_state: ValidationState,
    /// The message for the current non-acceptable text, or `""` when it is acceptable.
    validation_message: &'static str,
    /// Whether a step reports `value_changed` while an edit is still open.
    ///
    /// `true` is the historical behaviour: pressing a step button during a typed edit publishes
    /// the new value immediately. `false` defers the notification to the commit, so a host
    /// validating on every `value_changed` sees one value rather than one per keystroke/step.
    keyboard_tracking: bool,
    /// Whether a deferred step changed the value and still owes a `value_changed`.
    pending_value_emit: bool,
    /// Which step button is held down, for auto-repeat: `Some(true)` is the up button.
    held_step: Option<bool>,
    /// Emitted with the formatter/validator message when a typed value is refused.
    ///
    /// A spin box used to end the edit silently on an unparsable buffer. The value was left
    /// alone, which is correct, but the user got no reason and a host could not distinguish
    /// "cancelled" from "rejected". The signal is the missing half.
    pub validation_failed: Signal1<String>,
    /// The reactive model value this control consumes through the property bridge.
    binding: Option<crate::data_binding::Binding<CapabilityValue>>,
    /// Milliseconds accumulated while a step button is held.
    repeat_elapsed: u32,
    /// A value-level rule from `data_binding`, applied when a typed entry is committed.
    ///
    /// Distinct from [`Self::validator`], which inspects the *text* as it is typed. This one sees
    /// the parsed `f64` and may clamp or refuse it; the trait is public, so it is exposed through
    /// [`Self::set_numeric_validator`] (the name `set_validator` is already taken by the text
    /// grammar setter and adding a second method of the same name is not possible in Rust).
    numeric_validator: Option<Box<dyn crate::data_binding::Validator<f64>>>,
    /// The shared value/range link the slider publishes while a pair is bound.
    numeric_link: NumericLinkSlot,
    /// Memoised prefix/suffix advances keyed by the font and the two strings (I-P65).
    decoration_cache: RefCell<Option<(Font, String, String, u32, u32)>>,
}

/// How a spin box chooses the distance of one step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SpinBoxStepType {
    /// Every step moves by `single_step`.
    #[default]
    SingleStep,
    /// The step grows with the magnitude of the value, so large values move faster.
    ///
    /// The distance is `max(single_step, 10^(digits(value) - 1))`, which keeps a press
    /// meaningful at 1 and at 100000 without the caller having to change the step.
    AdaptiveDecimalStep,
}

/// Memoised output of [`SpinBox::value_text`].
struct ValueTextCache {
    value_bits: u64,
    minimum_bits: u64,
    decimals: u32,
    special: Option<String>,
    text: String,
}
/// The number ↔ text half of the spin box's display grammar.
///
/// # Why this is a `Formatter` and not two private helpers
///
/// The control's own formatting and parsing used to be separate: `formatted_value` printed with
/// one rule and `commit_edit` parsed with `str::parse::<f64>`, so a value with a prefix, a
/// suffix or a non-default precision could be shown but not typed back. One trait with both
/// directions is what makes the round trip a property of the grammar rather than of two call
/// sites that happen to agree.
struct SpinBoxNumberFormatter {
    decimals: u32,
}

impl Formatter<f64> for SpinBoxNumberFormatter {
    fn format(&self, value: &f64) -> String {
        match self.decimals {
            0 => format!("{}", round_to_i32(*value)),
            n => format!("{:.*}", n as usize, value),
        }
    }

    fn parse(&self, text: &str) -> Result<f64, ValidationError> {
        text.trim().parse::<f64>().ok().filter(|value| value.is_finite()).ok_or_else(|| {
            ValidationError::new(format!("`{}` is not a finite number", text.trim()))
        })
    }
}

/// Clamps and rounds a value to the spin box's range and precision.
///
/// `Validator` is allowed to return a repaired value (`Ok(clamped)`) rather than reject, which is
/// exactly the range rule: a number outside the bounds is moved to the bound, not refused. NaN is
/// the one value that is rejected, because it has no position in an ordered range.
struct SpinBoxRangeValidator {
    minimum: f64,
    maximum: f64,
    decimals: u32,
}

impl ValueValidator<f64> for SpinBoxRangeValidator {
    fn validate(&self, value: f64) -> Result<f64, ValidationError> {
        if value.is_nan() {
            return Err(ValidationError::new(String::from(
                "NaN has no position in a numeric range",
            )));
        }
        let clamped = ordered_clamp_f64(value, self.minimum, self.maximum);
        Ok(round_to_decimals(clamped, self.decimals))
    }
}

impl SpinBox {
    /// Binds this control's `value` property to a reactive model value.
    ///
    /// The initial model value is applied immediately, and (when the control is mounted) later
    /// model changes are written through the property contract. The reverse direction is
    /// [`Self::sync_to_binding`].
    pub fn bind_value(&mut self, binding: &crate::data_binding::Binding<CapabilityValue>) {
        self.binding = Some(binding.clone());
        #[cfg(not(alloc_frugal))]
        {
            if let Some(id) = crate::widget::runtime::registry_id_of(self.base.id()) {
                crate::data_binding::bind_widget_property(binding, "spin_box.value", id, "value");
                return;
            }
        }
        if let CapabilityValue::Int(value) = binding.get() {
            self.set_value_f64(value as f64);
            binding.announce_synced("value");
        }
    }

    /// Pushes the current numeric value into the bound model, reporting whether one is bound.
    pub fn sync_to_binding(&mut self) -> bool {
        let Some(binding) = self.binding.clone() else {
            return false;
        };
        binding.set(CapabilityValue::Int(i64::from(self.value())));
        binding.announce_synced("value");
        true
    }

    /// The reactive value this control consumes, if it is bound.
    pub fn bound_value(&self) -> Option<&crate::data_binding::Binding<CapabilityValue>> {
        self.binding.as_ref()
    }

    /// The band the whole control is painted in: full width, one text field tall, centred.
    ///
    /// # Why the control is not its own rectangle
    ///
    /// A spin box is a **field plus a step column**, and both are chrome of a fixed height:
    /// [`dimensions::TEXT_FIELD_MIN_HEIGHT`] is what every field in this crate occupies. This
    /// control used to be the one exception — the 240x120 census cell drew a 240x120 slab
    /// whose buttons were **120 px tall** (`spin_box.svg` carried `rect x=200 width=20
    /// height=120` twice) — so a spin box and the text field it sits beside in the same form
    /// were different objects. The band is the single derivation the surface, the button
    /// column, the value's line box and the hit test all read.
    fn row_band(&self) -> Rect {
        ControlMetrics::full_width_band(self.geometry(), dimensions::TEXT_FIELD_MIN_HEIGHT)
    }

    /// The trailing button column: the **remainder** of the band, not a fixed rectangle.
    ///
    /// # Why the column is derived from its width rather than from the band's edge
    ///
    /// This is BLUE22 §B.9's rule: a sub-part's box is derived from its siblings, so a
    /// sub-part that grows *pushes* its neighbours rather than overlapping them. The buttons
    /// were placed at `band.right() - button_width * 2` and the value's text at the field's
    /// leading padding — two derivations from two different edges with no relation between
    /// them, which is why a wider button or a larger font ran the value underneath the
    /// buttons (`spin_box`'s value was drawn at x = 4 with the column starting at x = 200).
    ///
    /// The column's width is now what the layout hands back for the step column, so it is one
    /// reading of the same assembly the value's box comes from — not a second piece of arithmetic
    /// that happens to agree.
    fn button_column(&self) -> Rect {
        self.assemble_row().1
    }

    /// The box the user may type in: whatever the button column leaves.
    ///
    /// The sibling-column relation derives exactly this —
    /// the text area *yields* to the button column, so the two cannot overlap at any font or
    /// button size.
    fn editable_rect(&self) -> Rect {
        self.assemble_row().0
    }

    /// The upper/lower half of the button column that the *up* step owns.
    fn up_button(&self) -> Rect {
        let column = self.button_column();
        let half = column.height / 2;
        Rect::new(column.x, column.y, column.width, half)
    }

    /// The upper/lower half of the button column that the *down* step owns.
    ///
    /// Derived from the same column as [`Self::up_button`], so the two tile it: they were
    /// two independent `+ height`/`+ height / 2` expressions in `draw` and a third spelling
    /// in the hit test.
    fn down_button(&self) -> Rect {
        let column = self.button_column();
        let half = column.height / 2;
        Rect::new(
            column.x,
            column.y + column.height.saturating_sub(half) as i32,
            column.width,
            half,
        )
    }

    /// The value box and the step column.
    ///
    /// # Why the split is one relation
    ///
    /// This is the sibling-column relation — `leftPadding: padding + down.width` — stated once: the
    /// value takes the remainder and the step column declares its own width, so a wider column, or
    /// a larger font on the buttons, narrows the value rather than running underneath it, and no
    /// code here can express the overlap the comment above records.
    ///
    /// # Why the column is two boxes and not one
    ///
    /// The column's two halves are `up` and `down`, tiled vertically by
    /// [`SpinBox::up_button`]/[`SpinBox::down_button`] from the column's own box, which is the same
    /// `VBox` relation expressed as one halving of a rectangle. The two buttons are what the
    /// column's *width* is derived from (the width is one button's, doubled), so they decide it.
    ///
    /// # What the split is measured from
    ///
    /// Both numbers come from the shared table ([`dimensions::SPIN_BOX_STEP_BUTTON_WIDTH`],
    /// [`dimensions::TEXT_FIELD_PADDING_H`]), so the hint `size_hint` reports and the boxes this
    /// method hands the paint path are two readings of one derivation.
    fn assemble_row(&self) -> (Rect, Rect) {
        let band = self.row_band();
        let (value_width, column_width) = Self::row_widths(band.width, self.step_column_width());
        // # Why the direction is resolved to two edges, once
        //
        // The step column sits at the **trailing** edge of the band and the value fills from the
        // other side. In LTR that is the right edge; in RTL the reading order is reversed and it is
        // the left one, so the number stays next to the buttons that change it.
        let rtl = self.direction.is_right_to_left();
        let (column_x, value_x) = if rtl {
            (band.x, band.x + column_width as i32)
        } else {
            (band.x + value_width as i32, band.x)
        };
        (
            Rect::new(value_x, band.y, value_width, band.height),
            Rect::new(column_x, band.y, column_width, band.height),
        )
    }

    /// Hands the hosted [`LineEdit`] the value box it edits.
    ///
    /// The field must sit in exactly the rectangle the paint path draws the value into, or a
    /// click's caret and the glyphs under it disagree. It is written at construction-equivalent
    /// points (`set_geometry`, a direction/alignment change, the start of an edit) rather than
    /// every frame; `editable_rect` is the single derivation both sides read.
    fn place_entry(&mut self) {
        let rect = self.editable_rect();
        if self.entry.geometry() != rect {
            self.entry.set_geometry(rect);
        }
    }

    /// The value's and the step column's widths for a band `band_width` wide.
    ///
    /// # The two cases
    ///
    /// * The band holds both: the column keeps the width it declares and the value takes the
    ///   remainder. That is the `fill` value column's statement, and it is why a wider column
    ///   narrows the value by exactly the same amount.
    /// * The band is narrower than the column plus the value's floor (the field's own padding):
    ///   tiling at those sizes cannot work, so the shortfall is shared **proportionally** (G-1).
    ///   Keeping the column 40 px in a 30 px band would leave the value zero wide, and a numeric
    ///   field with no visible number is a worse outcome than one whose steppers are compressed.
    ///   The integer remainder goes to the leading column so the pair sums to exactly `band_width`.
    fn row_widths(band_width: u32, column_width: u32) -> (u32, u32) {
        let value_floor = dimensions::TEXT_FIELD_PADDING_H;
        let total = value_floor.saturating_add(column_width);
        if total <= band_width || total == 0 {
            let column = column_width.min(band_width);
            return (band_width - column, column);
        }
        let scaled = |width: u32| -> u32 {
            ((u64::from(width) * u64::from(band_width)) / u64::from(total)) as u32
        };
        let value = scaled(value_floor);
        let column = scaled(column_width);
        let short = band_width.saturating_sub(value.saturating_add(column));
        (value + short, column)
    }

    /// The width the step column occupies: two buttons, clamped to the band.
    ///
    /// One derivation for both arms of [`Self::assemble_row`] *and* for the `size_hint` floor, so
    /// the hint a layout is told and the column the control draws cannot disagree.
    fn step_column_width(&self) -> u32 {
        dimensions::SPIN_BOX_STEP_BUTTON_WIDTH
            .saturating_mul(SPIN_BOX_BUTTONS)
            .min(self.row_band().width)
    }

    /// The writing direction the field runs in.
    pub fn direction(&self) -> crate::core::TextDirection {
        self.direction
    }

    /// Sets the writing direction.
    ///
    /// The step column moves to the other edge and the value's box yields to it there, and the value
    /// is anchored to the leading edge — the whole effect, spelled through the one `direction` the
    /// layout, the paint and the hit test read, so the three cannot disagree about which side the
    /// buttons are on.
    pub fn set_direction(&mut self, direction: crate::core::TextDirection) {
        if self.direction == direction {
            return;
        }
        self.direction = direction;
        self.place_entry();
        self.base.request_redraw();
        self.base.request_layout();
    }

    /// How the value is aligned within its own box.
    pub fn alignment(&self) -> crate::core::Alignment {
        self.alignment
    }

    /// Sets how the value is aligned within its own box.
    ///
    /// Horizontal only. A `top`/`bottom` alignment is **ignored**, because the value's box is
    /// centred vertically in the row band by the row's own layout — the property route refuses it
    /// through [`crate::widget::capability::coercion::expect_horizontal_alignment`], and this setter
    /// matching that keeps the two entry points from disagreeing.
    pub fn set_alignment(&mut self, alignment: crate::core::Alignment) {
        if alignment.to_horizontal().is_none() || self.alignment == alignment {
            return;
        }
        self.alignment = alignment;
        self.base.request_redraw();
    }

    /// Creates a spin box with default range 0-99 and integer precision.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::SpinBox, geometry, "SpinBox"),
            value: 0.0,
            minimum: 0.0,
            maximum: 99.0,
            single_step: 1.0,
            decimals: 0,
            prefix: String::new(),
            suffix: String::new(),
            special_value_text: None,
            value_text_cache: RefCell::new(None),
            wrapping: false,
            // Left-to-right is the default because the crate's default locale is; a host in an RTL
            // locale sets it, and every box below follows.
            direction: crate::core::TextDirection::LeftToRight,
            alignment: crate::core::Alignment::Left,
            value_changed: Signal1::new(),
            editing_finished: GenericSignal::new(),
            step_type: SpinBoxStepType::SingleStep,
            editing: false,
            entry: LineEdit::new(Rect::new(0, 0, 0, 0)),
            validator: None,
            validation_state: ValidationState::Acceptable,
            validation_message: "",
            keyboard_tracking: true,
            pending_value_emit: false,
            held_step: None,
            validation_failed: Signal1::new(),
            binding: None,
            repeat_elapsed: 0,
            numeric_validator: None,
            numeric_link: Rc::new(RefCell::new(None)),
            decoration_cache: RefCell::new(None),
        }
    }

    /// The shared link slot this spin box publishes while a slider is bound.
    pub(crate) fn numeric_link_slot(&self) -> NumericLinkSlot {
        Rc::clone(&self.numeric_link)
    }

    /// Whether a slider is currently bound to this spin box.
    pub fn is_linked(&self) -> bool {
        self.numeric_link.borrow().as_ref().is_some_and(|link| link.is_attached())
    }

    /// The direction values cross the current link in, or `None` when unbound.
    pub fn link_mode(&self) -> Option<LinkMode> {
        self.numeric_link
            .borrow()
            .as_ref()
            .filter(|link| link.is_attached())
            .map(|link| link.mode())
    }

    /// The value every reader sees: the link's when bound, this control's own otherwise.
    fn current_value(&self) -> f64 {
        match &*self.numeric_link.borrow() {
            Some(link) => link.spin_value(),
            None => self.value,
        }
    }

    /// Publishes a value to the bound link and refreshes its bounds snapshot.
    fn publish_to_link(&self, value: f64) {
        if let Some(link) = self.numeric_link.borrow().as_ref() {
            link.set_spin_value(value);
            link.set_bounds(self.minimum, self.maximum, self.decimals);
        }
    }
    /// Returns the current value, as an integer.
    ///
    /// Rounds rather than truncates: with `decimals == 3` and a value of `2.7`, "the
    /// value as an integer" is `3`, and truncation would also turn `-2.7` into `-2`, an
    /// error that grows with magnitude. The exact value is [`Self::value_f64`].
    pub fn value(&self) -> i32 {
        round_to_i32(self.current_value())
    }
    /// Returns the current value at full precision.
    pub fn value_f64(&self) -> f64 {
        self.current_value()
    }
    /// Sets the value, clamped to the range and rounded to [`Self::decimals`].
    pub fn set_value(&mut self, value: i32) {
        self.set_value_f64(value as f64);
    }
    /// Sets the value as a decimal, clamped and rounded to [`Self::decimals`].
    ///
    /// A non-finite input is ignored rather than stored: `NaN` has no position in a
    /// range, and storing it would make every later comparison (`==`, `<`) false and the
    /// control unreadable. `±inf` is a legitimate open bound, so it is clamped normally.
    pub fn set_value_f64(&mut self, value: f64) {
        if self.apply_value_f64(value) {
            self.value_changed.emit(self.value());
        }
    }

    /// Stores a clamped, rounded value without reporting it. Returns whether it changed.
    ///
    /// Split out of [`Self::set_value_f64`] because the step paths need the change test and
    /// the deferred notification separately: `keyboard_tracking == false` moves the value
    /// now and publishes it when the edit ends.
    fn apply_value_f64(&mut self, value: f64) -> bool {
        let rule = SpinBoxRangeValidator {
            minimum: self.minimum,
            maximum: self.maximum,
            decimals: self.decimals,
        };
        let Ok(rounded) = rule.validate(value) else {
            return false;
        };
        // `==` on two f64s that both passed through the same rounding is exact: this is
        // not approximate comparison, it is "did the write change anything".
        if self.current_value() == rounded {
            return false;
        }
        self.value = rounded;
        self.publish_to_link(rounded);
        self.revalidate();
        self.base.request_redraw();
        true
    }

    /// Moves the value by one step and reports it unless tracking is deferred.
    ///
    /// A suppressed step still moves the value; only the notification waits for
    /// [`Self::commit_edit`] / [`Self::cancel_edit`], which is what `keyboard_tracking`
    /// promises. The pending flag is what makes the eventual commit emit exactly once.
    fn step_to(&mut self, value: f64) {
        if !self.apply_value_f64(value) {
            return;
        }
        if self.editing && !self.keyboard_tracking {
            self.pending_value_emit = true;
        } else {
            self.value_changed.emit(self.value());
        }
    }

    /// Publishes a value change a deferred step still owes.
    ///
    /// `already_reported` is set by a commit whose parsed value was published by
    /// [`Self::set_value_f64`]; without it the same change would be announced twice.
    fn flush_pending_value(&mut self, already_reported: bool) {
        if self.pending_value_emit {
            self.pending_value_emit = false;
            if !already_reported {
                self.value_changed.emit(self.value());
            }
        }
    }
    /// Returns minimum value, as an integer.
    pub fn minimum(&self) -> i32 {
        round_to_i32(self.minimum)
    }
    /// Returns the minimum at full precision.
    pub fn minimum_f64(&self) -> f64 {
        self.minimum
    }
    /// Sets minimum value.
    pub fn set_minimum(&mut self, minimum: i32) {
        self.set_minimum_f64(minimum as f64);
    }
    /// Sets the minimum as a decimal, re-clamping the range and the value.
    pub fn set_minimum_f64(&mut self, minimum: f64) {
        if minimum.is_nan() || self.minimum == minimum {
            return;
        }
        self.minimum = minimum;
        if self.maximum < self.minimum {
            self.maximum = self.minimum;
        }
        self.publish_to_link(self.current_value());
        self.set_value_f64(self.current_value()); // Re-clamp
        self.base.request_redraw();
    }
    /// Returns maximum value, as an integer.
    pub fn maximum(&self) -> i32 {
        round_to_i32(self.maximum)
    }
    /// Returns the maximum at full precision.
    pub fn maximum_f64(&self) -> f64 {
        self.maximum
    }
    /// Sets maximum value.
    pub fn set_maximum(&mut self, maximum: i32) {
        self.set_maximum_f64(maximum as f64);
    }
    /// Sets the maximum as a decimal, re-clamping the range and the value.
    pub fn set_maximum_f64(&mut self, maximum: f64) {
        if maximum.is_nan() || self.maximum == maximum {
            return;
        }
        self.maximum = maximum;
        if self.minimum > self.maximum {
            self.minimum = self.maximum;
        }
        self.publish_to_link(self.current_value());
        self.set_value_f64(self.current_value()); // Re-clamp
        self.base.request_redraw();
    }
    /// Sets both minimum and maximum in one call.
    /// This is a convenience writer; query bounds via `minimum()` and `maximum()`.
    pub fn set_range(&mut self, minimum: i32, maximum: i32) {
        self.set_range_f64(minimum as f64, maximum as f64);
    }
    /// Sets both bounds as decimals in one call.
    ///
    /// The bounds are ordered before being stored, so `set_range_f64(10.0, 0.0)` names
    /// the range `[0.0, 10.0]` instead of leaving an inverted pair that `set_value_f64`
    /// would then clamp against (principle #17, and the panic `ordered_clamp_f64`
    /// exists to prevent is only half the story — an inverted *stored* pair silently
    /// collapses the range to a point).
    pub fn set_range_f64(&mut self, minimum: f64, maximum: f64) {
        if minimum.is_nan() || maximum.is_nan() {
            return;
        }
        self.minimum = minimum.min(maximum);
        self.maximum = minimum.max(maximum);
        self.publish_to_link(self.current_value());
        self.set_value_f64(self.current_value()); // Re-clamp
        self.base.request_redraw();
    }
    /// Returns the number of digits shown after the decimal separator.
    pub fn decimals(&self) -> u32 {
        self.decimals
    }
    /// Sets the display precision, `0` for an integer spin box.
    ///
    /// Values above [`SPIN_BOX_MAX_DECIMALS`] are clamped rather than accepted: the
    /// digits past that point are binary noise, and printing them would show the user a
    /// number the widget does not actually hold. Changing the precision re-rounds the
    /// current value immediately, so what is displayed and what is stored agree. It does
    /// **not** emit `value_changed`: no step was taken, and a caller counting changes
    /// would otherwise see a phantom one.
    pub fn set_decimals(&mut self, decimals: u32) {
        let decimals = decimals.min(SPIN_BOX_MAX_DECIMALS);
        if self.decimals == decimals {
            return;
        }
        self.decimals = decimals;
        self.value = round_to_decimals(self.current_value(), decimals);
        self.publish_to_link(self.value);
        self.revalidate();
        self.base.request_redraw();
    }
    /// Returns single step value, as an integer.
    pub fn single_step(&self) -> i32 {
        round_to_i32(self.single_step)
    }
    /// Returns the step at full precision.
    pub fn single_step_f64(&self) -> f64 {
        self.single_step
    }
    /// Sets single step value.
    ///
    /// A step of zero would make `step_up`/`step_down` do nothing at all, which looks
    /// like a broken button rather than a configured one, so the magnitude is floored at
    /// `1` in integer mode. In decimal mode the floor is one unit of the last displayed
    /// place (`0.01` at two decimals), because `0.5` is a meaningful step for a decimal
    /// spin box and a meaningful step must never round to "no step".
    pub fn set_single_step(&mut self, step: i32) {
        self.set_single_step_f64(step as f64);
    }
    /// Sets the step as a decimal, floored at the smallest representable increment.
    pub fn set_single_step_f64(&mut self, step: f64) {
        let floor = self.smallest_step();
        self.single_step = if step.is_nan() { floor } else { step.abs().max(floor) };
        self.base.request_redraw();
    }
    /// The smallest step that still changes the displayed value.
    fn smallest_step(&self) -> f64 {
        if self.decimals == 0 {
            1.0
        } else {
            10f64.powi(-(self.decimals as i32))
        }
    }
    /// Returns prefix text.
    pub fn prefix(&self) -> &str {
        &self.prefix
    }
    /// Sets prefix text.
    pub fn set_prefix(&mut self, prefix: String) {
        if self.prefix == prefix {
            return;
        }
        self.prefix = prefix;
        self.base.request_redraw();
    }
    /// Returns suffix text.
    pub fn suffix(&self) -> &str {
        &self.suffix
    }
    /// Sets suffix text.
    pub fn set_suffix(&mut self, suffix: String) {
        if self.suffix == suffix {
            return;
        }
        self.suffix = suffix;
        self.base.request_redraw();
    }
    /// Returns special value text.
    pub fn special_value_text(&self) -> Option<&str> {
        self.special_value_text.as_deref()
    }
    /// Sets special value text.
    pub fn set_special_value_text(&mut self, text: Option<String>) {
        if self.special_value_text == text {
            return;
        }
        self.special_value_text = text;
        self.base.request_redraw();
    }
    /// Returns whether wrapping is enabled.
    pub fn wrapping(&self) -> bool {
        self.wrapping
    }
    /// Sets wrapping state.
    pub fn set_wrapping(&mut self, wrapping: bool) {
        if self.wrapping == wrapping {
            return;
        }
        self.wrapping = wrapping;
        self.base.request_redraw();
    }
    /// Increments value by single step.
    pub fn step_up(&mut self) {
        let mut new_value = self.current_value() + self.step_amount();
        if new_value > self.maximum {
            if self.wrapping {
                new_value = self.minimum;
            } else {
                new_value = self.maximum;
            }
        }
        self.step_to(new_value);
    }
    /// Decrements value by single step.
    pub fn step_down(&mut self) {
        let mut new_value = self.current_value() - self.step_amount();
        if new_value < self.minimum {
            if self.wrapping {
                new_value = self.maximum;
            } else {
                new_value = self.minimum;
            }
        }
        self.step_to(new_value);
    }

    /// The distance one step moves under the current [`SpinBoxStepType`].
    pub fn step_amount(&self) -> f64 {
        match self.step_type {
            SpinBoxStepType::SingleStep => self.single_step,
            SpinBoxStepType::AdaptiveDecimalStep => {
                let magnitude = self.current_value().abs();
                if magnitude < 10.0 {
                    return self.single_step;
                }
                let digits = magnitude.log10().floor() as i32;
                let adaptive = 10f64.powi(digits);
                adaptive.max(self.single_step)
            }
        }
    }

    /// How one step chooses its distance.
    pub fn step_type(&self) -> SpinBoxStepType {
        self.step_type
    }

    /// Sets how one step chooses its distance.
    pub fn set_step_type(&mut self, step_type: SpinBoxStepType) {
        if self.step_type == step_type {
            return;
        }
        self.step_type = step_type;
    }

    /// Whether the value can be incremented without wrapping.
    pub fn can_step_up(&self) -> bool {
        self.wrapping || self.current_value() < self.maximum
    }

    /// Whether the value can be decremented without wrapping.
    pub fn can_step_down(&self) -> bool {
        self.wrapping || self.current_value() > self.minimum
    }

    /// Whether the user is currently typing a value into the field.
    pub fn is_editing(&self) -> bool {
        self.editing
    }

    /// The text typed since the current edit began.
    ///
    /// Delegates to the hosted [`LineEdit`]. When no edit is open the entry is empty, which is
    /// the same answer the previous character-buffer implementation gave.
    pub fn entry_text(&self) -> &str {
        self.entry.text()
    }

    /// The hosted text editor, so a host can inspect the text, caret and selection engine this
    /// control is now built on.
    pub fn line_edit(&self) -> &LineEdit {
        &self.entry
    }

    /// The entry's insertion point, in bytes from the start of [`Self::entry_text`].
    ///
    /// The unit is bytes because that is what [`crate::widget::LineEdit`]'s caret uses; the value
    /// is meaningful while [`Self::is_editing`] is true and is what the paint path draws.
    pub fn entry_cursor_position(&self) -> usize {
        self.entry.cursor_position()
    }

    /// Places the entry's caret, clamped to the buffer and snapped to a character boundary.
    ///
    /// This is the programmatic "put the caret here", so it drops any selection — the same
    /// rule the other text fields follow. Nothing happens when the field is not editing,
    /// because an idle field has no entry to place a caret in.
    pub fn set_entry_cursor_position(&mut self, position: usize) {
        if !self.editing {
            return;
        }
        self.entry.set_cursor_position(position);
        self.base.request_redraw();
    }

    /// The selected run of the entry as ordered `(start, end)` byte offsets, or `None`.
    pub fn entry_selection_range(&self) -> Option<(usize, usize)> {
        self.entry.selection_range()
    }

    /// Selects the whole entry, starting an edit when the field is idle.
    ///
    /// Selecting the value a user is about to replace is the common gesture behind a typed
    /// commit (`select_all` then digits), so an idle field begins an edit first rather than
    /// reporting success with nothing selected.
    pub fn select_all(&mut self) {
        if !self.editing {
            self.begin_edit();
        }
        self.entry.select_all();
        self.base.request_redraw();
    }

    /// The rule this field's entry is checked against, or `None` for a free numeric field.
    pub fn validator(&self) -> Option<&dyn Validator> {
        self.validator.as_deref()
    }

    /// Installs a host rule, replacing any current one, and revalidates the entry.
    ///
    /// The extension point for a domain rule the library cannot enumerate; a built-in grammar
    /// installed through [`Self::set_validator`] ends up in the same box, so the field consults
    /// exactly one rule at a time.
    pub fn set_dyn_validator(&mut self, validator: Option<Box<dyn Validator>>) {
        let unchanged = match (self.validator.as_deref(), validator.as_deref()) {
            (Some(current), Some(next)) => {
                current.builtin().is_some() && current.builtin() == next.builtin()
            }
            _ => false,
        };
        if unchanged {
            return;
        }
        self.validator = validator;
        self.revalidate();
        self.base.request_redraw();
    }

    /// Sets the built-in grammar, revalidating the entry.
    pub fn set_validator(&mut self, validator: Option<InputValidator>) {
        match (self.validator.as_deref(), validator) {
            (None, None) => return,
            (Some(current), Some(next)) if current.builtin() == Some(next) => return,
            _ => {}
        }
        self.validator = validator.map(|rule| Box::new(rule) as Box<dyn Validator>);
        self.revalidate();
        self.base.request_redraw();
    }

    /// Installs a text predicate as the entry's rule.
    ///
    /// This is the fallback the issue asks for when a `set_validator(Validator<f64>)` cannot be
    /// spelled: the name `set_validator` already publishes the text-grammar setter, and Rust has
    /// no method overloading. The predicate is the same three-way check every [`Validator`] is,
    /// with the outcome collapsed to `Acceptable` / `Invalid`; `Intermediate` is unreachable
    /// because a boolean predicate has no "not finished yet" answer. Use
    /// [`Self::set_dyn_validator`] when that distinction matters.
    pub fn set_text_validator<F>(&mut self, predicate: F)
    where
        F: Fn(&str) -> bool + Send + Sync + 'static,
    {
        self.set_dyn_validator(Some(Box::new(PredicateValidator::new(predicate))));
    }

    /// The value-level rule applied when a typed entry is committed.
    pub fn numeric_validator(&self) -> Option<&dyn crate::data_binding::Validator<f64>> {
        self.numeric_validator.as_deref()
    }

    /// Installs a [`crate::data_binding::Validator`] over the parsed value.
    ///
    /// # Why the name is not `set_validator`
    ///
    /// The issue asks for `set_validator(Validator)` if the `data_binding` trait is public (it
    /// is). This control already publishes `set_validator(Option<InputValidator>)`, the text
    /// grammar setter every field in the crate shares, and Rust cannot overload one name with a
    /// second generic method. Renaming the existing setter would be a breaking change to a
    /// published vocabulary for no behavioural gain, so the value rule is exposed here under its
    /// own name. A refusal keeps the edit open and marks the field invalid rather than silently
    /// discarding what the user typed.
    pub fn set_numeric_validator(
        &mut self,
        validator: Option<Box<dyn crate::data_binding::Validator<f64>>>,
    ) {
        self.numeric_validator = validator;
        self.base.request_redraw();
    }

    /// Whether the current entry text satisfies the rule (true without a validator).
    pub fn is_valid(&self) -> bool {
        self.validation_state.is_acceptable()
    }

    /// The three-way outcome for the current entry text.
    ///
    /// `Intermediate` is not a failure: it is text the user is still assembling, and a form
    /// can keep its submit affordance disabled without accusing the user.
    pub fn validation_state(&self) -> ValidationState {
        self.validation_state
    }

    /// The message for the current non-acceptable text, or `""` when it is acceptable.
    pub fn validation_message(&self) -> &'static str {
        self.validation_message
    }

    /// Applies the validator's own repair to the entry (or to the value when idle).
    ///
    /// Returns whether anything changed. A repaired entry stays an entry: the caret moves to
    /// the end and the commit still parses it, so a repair is visible to the user rather than
    /// silently replacing the value under them.
    pub fn fixup(&mut self) -> bool {
        let text =
            if self.editing { self.entry.text().to_string() } else { self.formatted_value() };
        let Some(repaired) = self.validator.as_deref().and_then(|validator| validator.fixup(&text))
        else {
            return false;
        };
        if repaired == text {
            return false;
        }
        if self.editing {
            self.entry.set_text(repaired);
            let end = self.entry.text().len();
            self.entry.set_cursor_position(end);
            self.revalidate();
            self.base.request_redraw();
            return true;
        }
        let Ok(value) = repaired.trim().parse::<f64>() else {
            return false;
        };
        let before = self.current_value();
        self.set_value_f64(value);
        self.current_value() != before
    }

    /// Whether a step reports `value_changed` while an edit is open.
    ///
    /// The default is `true`, which is the behaviour this control always had: stepping during
    /// an edit publishes immediately. Turning it off defers the notification to the commit,
    /// so a host that validates per change sees one final value.
    pub fn keyboard_tracking(&self) -> bool {
        self.keyboard_tracking
    }

    /// Sets whether a step reports `value_changed` while an edit is open.
    ///
    /// Re-enabling tracking publishes any change a deferred step already made, so a host is
    /// never left believing the value it last heard is current.
    ///
    /// Only the steppers are deferred: a programmatic [`Self::set_value`] is a host write, not a
    /// keystroke, and always reports.
    pub fn set_keyboard_tracking(&mut self, tracking: bool) {
        if self.keyboard_tracking == tracking {
            return;
        }
        self.keyboard_tracking = tracking;
        if tracking {
            let pending = self.pending_value_emit;
            self.pending_value_emit = false;
            if pending {
                self.value_changed.emit(self.value());
            }
        }
    }

    /// Recomputes the cached validation state from the text the field currently shows.
    ///
    /// Cheap when no rule is installed — the common case — so the callers below can invoke it
    /// unconditionally at every point the text can change.
    fn revalidate(&mut self) {
        if self.validator.is_none() {
            self.validation_state = ValidationState::Acceptable;
            self.validation_message = "";
            return;
        }
        let text =
            if self.editing { self.entry.text().to_string() } else { self.formatted_value() };
        let (state, message) = match self.validator.as_deref() {
            Some(validator) => {
                let state = validator.state(&text);
                let message = if state.is_acceptable() { "" } else { validator.message() };
                (state, message)
            }
            None => (ValidationState::Acceptable, ""),
        };
        self.validation_state = state;
        self.validation_message = message;
    }

    /// Starts a typed edit, seeded with the current value's text and a caret at its end.
    pub fn begin_edit(&mut self) {
        if self.editing {
            return;
        }
        let current_text = self.formatted_value();
        self.entry.set_text(current_text);
        let end = self.entry.text().len();
        self.entry.set_cursor_position(end);
        self.editing = true;
        self.place_entry();
        self.revalidate();
        self.base.request_redraw();
    }

    /// Commits the typed text, parsing it into the value.
    ///
    /// Returns whether a value was parsed and accepted. An unparsable buffer — or one a
    /// [`Self::set_numeric_validator`] rule refuses — leaves the value alone rather than silently
    /// resetting it. A refused value keeps the edit open so the user can correct it; an
    /// unparsable buffer ends the edit, so the field cannot get stuck in a state the user cannot
    /// leave.
    pub fn commit_edit(&mut self) -> bool {
        if !self.editing {
            return false;
        }
        let formatter = SpinBoxNumberFormatter { decimals: self.decimals };
        let range = SpinBoxRangeValidator {
            minimum: self.minimum,
            maximum: self.maximum,
            decimals: self.decimals,
        };
        let parsed =
            match formatter.parse(self.entry.text()).and_then(|value| range.validate(value)) {
                Ok(value) => match self.numeric_validator.as_deref() {
                    Some(rule) => match rule.validate(value) {
                        Ok(value) => Some(value),
                        Err(reason) => {
                            // The rule refuses this number: keep the text so the user can fix it.
                            self.validation_state = ValidationState::Invalid;
                            self.validation_message = "the value is not accepted";
                            self.validation_failed.emit(reason.message.clone());
                            self.base.request_redraw();
                            return false;
                        }
                    },
                    None => Some(value),
                },
                Err(error) => {
                    // The text is not a number in this field's grammar. Report why, then end the edit
                    // so the field cannot get stuck; the value itself is left untouched.
                    self.validation_failed.emit(error.message.clone());
                    None
                }
            };
        self.editing = false;
        self.entry.set_text(String::new());
        self.entry.set_cursor_position(0);
        let mut reported = false;
        if let Some(value) = parsed {
            let before = self.current_value();
            self.set_value_f64(value);
            reported = self.current_value() != before;
        }
        self.revalidate();
        self.flush_pending_value(reported);
        self.editing_finished.emit();
        self.base.request_redraw();
        parsed.is_some()
    }

    /// Abandons the typed text without changing the value.
    pub fn cancel_edit(&mut self) {
        if !self.editing {
            return;
        }
        self.editing = false;
        self.entry.set_text(String::new());
        self.entry.set_cursor_position(0);
        self.revalidate();
        self.flush_pending_value(false);
        self.editing_finished.emit();
        self.base.request_redraw();
    }

    /// Advances the held-button repeat. Returns whether another frame is due.
    ///
    /// A held step button repeats after an initial delay, then at a steady interval; this is
    /// what turns one press into a continuous adjustment.
    pub fn tick(&mut self, delta_ms: u32) -> bool {
        let Some(up) = self.held_step else {
            return false;
        };
        self.repeat_elapsed = self.repeat_elapsed.saturating_add(delta_ms);
        let delay = 400u32;
        let interval = 120u32;
        if self.repeat_elapsed < delay {
            return true;
        }
        let mut remaining = self.repeat_elapsed - delay;
        let mut stepped = false;
        while remaining >= interval {
            remaining -= interval;
            if up {
                self.step_up();
            } else {
                self.step_down();
            }
            stepped = true;
        }
        self.repeat_elapsed = delay + remaining;
        if stepped {
            self.base.request_redraw();
        }
        true
    }

    /// Stops any held-button repeat, called when the pointer leaves or is released.
    pub fn stop_repeat(&mut self) {
        self.held_step = None;
        self.repeat_elapsed = 0;
    }
    /// Returns the formatted number, without prefix or suffix.
    ///
    /// The precision comes from [`Self::decimals`], so an integer spin box prints `5`
    /// and a two-decimal one prints `1.50` — the same digits the user could have typed.
    /// Trailing zeros are kept, because dropping them would make a two-decimal spin box
    /// look like it had accepted `1.5` when it holds `1.50`.
    pub fn formatted_value(&self) -> String {
        // One grammar for display and for parsing: the same `Formatter` instance is what
        // `commit_edit` parses with, so a shown value is always a value that types back.
        SpinBoxNumberFormatter { decimals: self.decimals }.format(&self.current_value())
    }
    /// Returns display text: the special value text, or prefix + number + suffix.
    ///
    /// # Why this is the *announcement* string and not what is drawn
    ///
    /// Reading out `$12` is correct — a screen reader should hear the unit. But **drawing** it as one
    /// string puts the prefix inside the value's glyph run, which makes the value's own origin include
    /// it: the caret lands after the `$` at position 0, and a select-all would take the `$` with it. The
    /// painter therefore draws `Self::value_text` in the value's box and the two slots in their own,
    /// while this stays the form a caller announces or logs — which is why it is `pub`.
    ///
    /// See [`crate::widget::decorations`] for the full argument.
    pub fn display_text(&self) -> String {
        if let Some(special) = &self.special_value_text {
            if self.current_value() == self.minimum {
                return special.clone();
            }
        }
        format!("{}{}{}", self.prefix, self.formatted_value(), self.suffix)
    }

    /// The text drawn inside the value's own box: the special value text, or just the number.
    ///
    /// The slots are **excluded**, which is what makes the value's origin independent of them.
    fn value_text(&self) -> String {
        if let Some(special) = &self.special_value_text {
            if self.current_value() == self.minimum {
                return special.clone();
            }
        }
        self.formatted_value()
    }

    /// The cached value text, recomputed only when an input of [`Self::value_text`] changes.
    ///
    /// The returned `Ref` lets the paint path borrow the string without a per-frame allocation;
    /// `value_text` remains the value-returning form the property contract uses.
    fn value_text_cached(&self) -> Ref<'_, str> {
        let value_bits = self.current_value().to_bits();
        let minimum_bits = self.minimum.to_bits();
        let stale = match self.value_text_cache.borrow().as_ref() {
            Some(cache) => {
                cache.value_bits != value_bits
                    || cache.minimum_bits != minimum_bits
                    || cache.decimals != self.decimals
                    || cache.special != self.special_value_text
            }
            None => true,
        };
        if stale {
            let text = self.value_text();
            *self.value_text_cache.borrow_mut() = Some(ValueTextCache {
                value_bits,
                minimum_bits,
                decimals: self.decimals,
                special: self.special_value_text.clone(),
                text,
            });
        }
        Ref::map(self.value_text_cache.borrow(), |cache| {
            cache.as_ref().expect("the cache was just filled").text.as_str()
        })
    }

    /// The prefix/suffix advances, measured once per (font, strings) pair (I-P65).
    fn decoration_widths(&self, context: &RenderContext, font: &Font) -> (u32, u32) {
        if let Some((cached_font, prefix, suffix, prefix_width, suffix_width)) =
            self.decoration_cache.borrow().as_ref()
        {
            if cached_font == font && prefix == &self.prefix && suffix == &self.suffix {
                return (*prefix_width, *suffix_width);
            }
        }
        let prefix_width =
            if self.prefix.is_empty() { 0 } else { context.measure_text(&self.prefix, font).width };
        let suffix_width =
            if self.suffix.is_empty() { 0 } else { context.measure_text(&self.suffix, font).width };
        *self.decoration_cache.borrow_mut() = Some((
            font.clone(),
            self.prefix.clone(),
            self.suffix.clone(),
            prefix_width,
            suffix_width,
        ));
        (prefix_width, suffix_width)
    }
}

/// Rounds to the nearest integer, saturating instead of wrapping out of `i32`.
///
/// `as i32` truncates *and* saturates silently since Rust 1.45, which is two surprises
/// at once; the round-then-saturate here is explicit about both halves. The saturation
/// matters because `f64::INFINITY` is a legal bound, and an unbounded spin box reading
/// its `i32` value must not report `i32::MAX` for `0.0`.
fn round_to_i32(value: f64) -> i32 {
    if value.is_nan() {
        return 0;
    }
    let rounded = value.round();
    if rounded >= i32::MAX as f64 {
        i32::MAX
    } else if rounded <= i32::MIN as f64 {
        i32::MIN
    } else {
        rounded as i32
    }
}

/// Rounds `value` to `decimals` places after the decimal separator.
///
/// # Why this goes through the decimal text
///
/// The obvious form is `(value * 10^n).round() / 10^n`, and it can disagree with what the
/// widget prints. `format!("{:.n}", x)` is correctly rounded *once*, from `x`; the scale
/// form rounds an intermediate product that carries its own representation error, and a
/// product that lands on a tie rounds the wrong way. Measured on this build,
/// `2.0965 x 1000.0` is exactly `2096.5000000000005`, so the scale form gives `2.097` while
/// the text says `2.096`. Those are the same number printed two ways, and a spin box whose
/// stored value disagrees with its own display is showing the user a figure it does not
/// hold. Taking the text as the authority is what makes the two agree to the digit.
///
/// # What this does *not* do
///
/// It does not "round the way a human would read the literal". `1.005` and `2.675` as
/// `f64` **are** `1.00499999999999989...` and `2.67499999999999982...`, so rounding them to
/// two places gives `1.00` and `2.67` — correctly, and the same answer a decimal parser
/// would produce from the identical text. No rounding scheme can recover a midpoint the
/// input never stored; that would require carrying the value as decimal text instead of
/// `f64`, which is a much larger change than this setting. The invariant guaranteed here is
/// the one that matters: **the stored value equals the number the widget prints.**
pub(crate) fn round_to_decimals(value: f64, decimals: u32) -> f64 {
    if decimals == 0 {
        let rounded = value.round();
        // `-0.0` and `0.0` compare equal but format differently (`-0`), and a value of
        // `-0.4` rounded to integers is zero, not "negative zero".
        return if rounded == 0.0 { 0.0 } else { rounded };
    }
    if !value.is_finite() {
        return value;
    }
    let text = format!("{:.*}", decimals as usize, value);
    text.parse::<f64>().unwrap_or(value)
}
// Implement Widget trait

/// A boolean text predicate adapted to the field's three-way [`Validator`] contract.
///
/// Kept private: the public entry point is [`SpinBox::set_text_validator`], which boxes the
/// predicate here so the field consults one rule box like every other grammar.
struct PredicateValidator {
    predicate: Box<dyn Fn(&str) -> bool + Send + Sync>,
}

impl PredicateValidator {
    fn new<F>(predicate: F) -> Self
    where
        F: Fn(&str) -> bool + Send + Sync + 'static,
    {
        Self { predicate: Box::new(predicate) }
    }
}

impl core::fmt::Debug for PredicateValidator {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str("PredicateValidator")
    }
}

impl Validator for PredicateValidator {
    fn state(&self, text: &str) -> ValidationState {
        if (self.predicate)(text) {
            ValidationState::Acceptable
        } else {
            ValidationState::Invalid
        }
    }

    fn message(&self) -> &'static str {
        "the text is not accepted"
    }

    fn filter(&self, text: &str) -> String {
        // A predicate judges a whole string, so it cannot filter a single character without
        // inventing a context. The field revalidates after every change instead.
        text.to_string()
    }
}

impl Widget for SpinBox {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn set_geometry(&mut self, geometry: Rect) {
        self.base.set_geometry(geometry);
        // The hosted entry is positioned by the same boxes the paint path uses, so a resize or a
        // move must carry it along rather than leaving it at the old value box.
        self.place_entry();
    }

    fn size_hint(&self) -> Size {
        // Width follows the *formatted* text, not the integer value: a spin box showing
        // `1234.50` is wider than one showing `1234`, and sizing off the integer form would
        // clip the decimals it was explicitly asked to display.
        //
        // The text is a **content** width and is handed to `ControlMetrics::implicit_size`
        // as such, with the step column expressed as the floor rather than added on top. That
        // is the whole reason the metric exists: the number a layout is told and the box the
        // control draws are then two readings of one formula. The two are deliberately not
        // bit-identical here — a hint is measured with a nominal advance per character
        // because `size_hint` has no `RenderContext` to measure with, while the paint path
        // *fits* the value into the box this hint produced. A hint that is a few pixels
        // generous is the safe direction; one that is short would elide the very digits the
        // caller asked for.
        let value = self.formatted_value();
        // The shared estimate, not `len() * 8`: the paragraph above argues the hint may be a few
        // pixels generous, which is true of a nominal per-cluster advance and false of a byte
        // count — a CJK value measured three times its drawn width, so the step column was pushed
        // further right than the digits needed and the hint stopped describing the control.
        let text_width = estimate_text_width(&value, effective_font(self.style()), 1.0);
        let field_air = (dimensions::TEXT_FIELD_MIN_HEIGHT / 2).saturating_sub(8);
        let padding = EdgeOffsets {
            top: field_air,
            right: dimensions::TEXT_FIELD_PADDING_H,
            bottom: field_air,
            left: dimensions::TEXT_FIELD_PADDING_H,
        };
        // The floor is the field's own height plus the step column the band tiles; every term
        // is a value from the shared table, so the hint and the paint cannot disagree about
        // how many pixels the buttons take.
        let floor = Size::new(
            dimensions::TEXT_FIELD_PADDING_H * 2 + SPIN_BOX_BUTTON_WIDTH * SPIN_BOX_BUTTONS,
            dimensions::TEXT_FIELD_MIN_HEIGHT,
        );
        ControlMetrics::implicit_size(Size::new(text_width, 0), padding, floor)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
    /// Resolves a published event name to the control's own signal.
    ///
    /// # Why this is explicit per control
    ///
    /// `connect_event` validates a name against the capability table and registers a hub slot; only
    /// `event_signal_dyn` joins that name to the signal the control actually emits. Without it a name
    /// is valid and inert, which is the silent failure `tools/check_event_signal_dyn.sh` exists to
    /// make impossible. The arm set is checked against the capability's published names, so this
    /// list cannot drift from what the control advertises.
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        use crate::signal::EventSignalRef;
        #[allow(unused_imports)]
        use crate::widget::capability::CapabilityValue;
        match name {
            "value_changed" => {
                Some(EventSignalRef::mapped("value_changed", &self.value_changed, |v| {
                    CapabilityValue::Int(*v as i64)
                }))
            }
            "editing_finished" => {
                Some(EventSignalRef::unit("editing_finished", &self.editing_finished))
            }
            "validation_failed" => {
                Some(EventSignalRef::mapped("validation_failed", &self.validation_failed, |v| {
                    CapabilityValue::String(v.clone())
                }))
            }
            _ => None,
        }
    }
}

/// `SpinBox`'s property contract.
///
/// # Integers stay integers (principle #21)
///
/// The three numeric properties report `Int` whenever `decimals == 0`, which is the
/// default, so existing callers that write `{"value": 3}` and read back `Int(3)` are
/// unaffected. Only a caller that has opted into decimals sees a `Float`, and a caller
/// that sends an `Int` to a decimal spin box is accepted (it is an exact number) rather
/// than rejected as a type error.
impl WidgetProperties for SpinBox {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        // Integer mode reports integers; the caller that set `decimals(0)` asked for an
        // integer spin box and should not have to unwrap a float to read it.
        let as_number = |value: f64| {
            if self.decimals == 0 {
                CapabilityValue::Int(round_to_i32(value) as i64)
            } else {
                CapabilityValue::Float(value)
            }
        };
        match name {
            "minimum" => Ok(as_number(self.minimum_f64())),
            "maximum" => Ok(as_number(self.maximum_f64())),
            "value" => Ok(as_number(self.value_f64())),
            "single_step" => Ok(as_number(self.single_step_f64())),
            "decimals" => Ok(CapabilityValue::UInt(u64::from(self.decimals()))),
            "prefix" => Ok(CapabilityValue::String(self.prefix().to_string())),
            "suffix" => Ok(CapabilityValue::String(self.suffix().to_string())),
            // The announcement form: `$12`, or the special text at the minimum. Published because it is
            // what a caller shows in a log or reads aloud, and re-deriving it from `value` + the two
            // slots in the consumer is the second derivation this contract exists to remove.
            "display_text" => Ok(CapabilityValue::String(self.display_text())),
            // Just the number, without the unit marks — the string the painter puts in the value's box.
            "value_text" => Ok(CapabilityValue::String(self.value_text())),
            "special_value_text" => match self.special_value_text() {
                Some(text) => Ok(CapabilityValue::String(text.to_string())),
                None => Ok(CapabilityValue::Null),
            },
            "wrapping" => Ok(CapabilityValue::Bool(self.wrapping())),
            "keyboard_tracking" => Ok(CapabilityValue::Bool(self.keyboard_tracking())),
            "direction" => {
                Ok(CapabilityValue::String(text_direction_to_str(self.direction()).to_string()))
            }
            "alignment" => Ok(CapabilityValue::String(
                horizontal_alignment_to_str(self.alignment()).to_string(),
            )),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        // A number arrives as `Int` or `Float` depending on how the caller spelled it
        // (`3` vs `3.0`), and both mean the same value. Accepting both is what keeps
        // `{"value": 3}` valid after a spin box has been given decimals.
        fn number(value: CapabilityValue) -> Result<f64, CapabilityAccessError> {
            match value {
                CapabilityValue::Int(int) => Ok(int as f64),
                other => expect_f64(other),
            }
        }
        match name {
            "minimum" => {
                self.set_minimum_f64(number(value)?);
                Ok(())
            }
            "maximum" => {
                self.set_maximum_f64(number(value)?);
                Ok(())
            }
            "value" => {
                self.set_value_f64(number(value)?);
                Ok(())
            }
            "single_step" => {
                self.set_single_step_f64(number(value)?);
                Ok(())
            }
            "decimals" => {
                // The declared kind is `UInt`, so read it as one; a negative is a value error, not
                // a type error, which is the distinction `OutOfRange` exists to preserve.
                if matches!(value, CapabilityValue::Int(v) if v < 0) {
                    return Err(CapabilityAccessError::OutOfRange);
                }
                self.set_decimals(expect_u32(value)?);
                Ok(())
            }
            "prefix" => {
                self.set_prefix(expect_string(value)?);
                Ok(())
            }
            "suffix" => {
                self.set_suffix(expect_string(value)?);
                Ok(())
            }
            "special_value_text" => {
                match value {
                    CapabilityValue::Null => self.set_special_value_text(None),
                    other => self.set_special_value_text(Some(expect_string(other)?)),
                }
                Ok(())
            }
            "keyboard_tracking" => {
                self.set_keyboard_tracking(expect_bool(value)?);
                Ok(())
            }
            "wrapping" => {
                self.set_wrapping(expect_bool(value)?);
                Ok(())
            }
            "direction" => {
                self.set_direction(expect_text_direction(value)?);
                Ok(())
            }
            "alignment" => {
                self.set_alignment(expect_horizontal_alignment(value)?);
                Ok(())
            }
            // Both are derived from the value and the two slots, so a writer would be a second way to
            // say something the control already answers — and one of the two could disagree.
            "display_text" | "value_text" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        // Mirrors `SPIN_BOX_PROPERTIES`.
        property_names_of![
            "minimum",
            "maximum",
            "value",
            "single_step",
            "decimals",
            "prefix",
            "suffix",
            "special_value_text",
            "wrapping",
            "keyboard_tracking",
            "direction",
            "alignment",
            "display_text",
            "value_text",
            BASE_PROPERTY_NAMES
        ]
    }

    /// Runs one of the commands `spin_box` publishes.
    ///
    /// `step_up` / `step_down` are the zero-argument actions: they move the value by
    /// `single_step` and wrap when wrapping is enabled, which is exactly the effect a
    /// caller asking for "one step" means. `set_range` and `set_value` assign state and
    /// therefore need a payload, so they are answered through the property route rather
    /// than guessed at; `OutOfRange` says the name is right and the invocation is not.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "step_up" => {
                self.step_up();
                Ok(())
            }
            "step_down" => {
                self.step_down();
                Ok(())
            }
            "set_range" | "set_value" => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl SpinBox {
    /// Handle click/tap on the increment/decrement buttons.
    ///
    /// # Why this takes no rectangle or width
    ///
    /// It used to take both and re-derive the buttons as `rect.right() - button_width * 2`,
    /// which was a **third** copy of the column's arithmetic (one in `draw`, one in the
    /// event arm, one here) — three spellings that described the same two buttons and
    /// agreed only while nobody edited one of them. The boxes now come from the same
    /// accessors the paint path uses, and the caller passes only what it alone knows: where
    /// the pointer landed.
    fn handle_button_click(&mut self, pos: Point) {
        if self.down_button().contains_point(pos) {
            self.step_down();
            self.base.clicked.emit();
        } else if self.up_button().contains_point(pos) {
            self.step_up();
            self.base.clicked.emit();
        }
    }
}
impl EventHandler for SpinBox {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MousePress { pos, button, .. } => {
                if *button == 1 {
                    if self.up_button().contains_point(*pos) {
                        self.held_step = Some(true);
                        self.repeat_elapsed = 0;
                        self.handle_button_click(*pos);
                    } else if self.down_button().contains_point(*pos) {
                        self.held_step = Some(false);
                        self.repeat_elapsed = 0;
                        self.handle_button_click(*pos);
                    } else if self.editable_rect().contains_point(*pos) {
                        // A press in the value box starts a typed edit rather than stepping, and
                        // the hosted field places the caret where the pointer landed — the same
                        // gesture every other text field in the crate performs.
                        if !self.editing {
                            self.begin_edit();
                        }
                        self.place_entry();
                        self.entry.handle_event(event);
                    }
                }
            }
            Event::MouseDoubleClick { pos, .. } | Event::MouseMove { pos }
                if self.editing && self.editable_rect().contains_point(*pos) =>
            {
                self.entry.handle_event(event);
            }
            Event::MouseRelease { .. } => {
                if self.editing {
                    self.entry.handle_event(event);
                }
                self.stop_repeat();
            }
            Event::MouseLeave { .. } => self.stop_repeat(),
            #[cfg(feature = "touch")]
            Event::TouchBegin { pos, .. } => {
                // I-P65: touch follows the same held-button path as the mouse, so pressing and
                // holding a stepper repeats on a touch device too.
                if self.up_button().contains_point(*pos) {
                    self.held_step = Some(true);
                    self.repeat_elapsed = 0;
                } else if self.down_button().contains_point(*pos) {
                    self.held_step = Some(false);
                    self.repeat_elapsed = 0;
                }
                self.handle_button_click(*pos);
            }
            #[cfg(feature = "touch")]
            Event::TouchEnd { .. } => self.stop_repeat(),
            // Platform-committed text (a printable character or an IME commit) is the input a
            // touch keyboard and an input method actually deliver. The hosted field already
            // owns that path, so the spin box only has to start an edit and pass it on.
            Event::TextInput { .. } | Event::ImeCommit { .. } | Event::ImePreedit { .. } => {
                let started = !self.editing;
                if started {
                    self.begin_edit();
                    // The first typed character replaces the seeded value rather than appending
                    // to it, which is what a user typing into a populated numeric field expects.
                    self.entry.select_all();
                }
                self.place_entry();
                self.entry.handle_event(event);
                self.revalidate();
                self.base.request_redraw();
            }
            Event::KeyPress { key, .. } => {
                if self.editing {
                    match *key {
                        // Enter commits and Escape abandons: the spin box owns the numeric
                        // contract, while every other key goes to the hosted field (caret,
                        // selection, clipboard and undo included).
                        13 => {
                            self.commit_edit();
                        }
                        27 => self.cancel_edit(),
                        // The legacy forward-delete code the old buffer accepted; `LineEdit`
                        // spells the same operation as key 46.
                        127 => {
                            self.entry.delete();
                            self.revalidate();
                            self.base.request_redraw();
                        }
                        _ => {
                            self.place_entry();
                            self.entry.handle_event(event);
                            self.revalidate();
                            self.base.request_redraw();
                        }
                    }
                    return;
                }
                match *key {
                    38 => {
                        // Up arrow
                        self.step_up();
                    }
                    40 => {
                        // Down arrow
                        self.step_down();
                    }
                    33 => {
                        // Page Up takes a larger step (ten single steps).
                        let target =
                            (self.current_value() + self.single_step * 10.0).min(self.maximum);
                        self.step_to(target);
                    }
                    34 => {
                        // Page Down.
                        let target =
                            (self.current_value() - self.single_step * 10.0).max(self.minimum);
                        self.step_to(target);
                    }
                    36 => self.set_value_f64(self.minimum),
                    35 => self.set_value_f64(self.maximum),
                    13 => {
                        // Enter begins a typed edit.
                        self.begin_edit();
                    }
                    27 => {
                        // Escape outside an edit has nothing to finish: the old path emitted
                        // `editing_finished` here with no edit open, which reported an event
                        // that had not happened.
                    }
                    48..=57 | 46 | 45 => {
                        // A printable numeric key starts an edit from the current value, with the
                        // seeded value selected so the typed digit replaces rather than appends.
                        self.begin_edit();
                        self.entry.select_all();
                        self.place_entry();
                        self.entry.handle_event(event);
                        self.revalidate();
                    }
                    // Unknown key; ignore
                    _ => {}
                }
            }
            Event::Wheel { delta, modifiers } => {
                // One notch is one step; a positive y reveals lower values.
                let scroll = WheelScroll::from_event(*delta, *modifiers, 1);
                if scroll.lines_y > 0 {
                    self.step_down();
                } else if scroll.lines_y < 0 {
                    self.step_up();
                }
            }
            // `commit_edit` already emits `editing_finished`; emitting it again here made one
            // focus loss report two finishes to a host counting them. A focus loss while not
            // editing falls through to the catch-all arm below.
            Event::FocusLost if self.editing => {
                self.commit_edit();
            }
            // Other events are not relevant for this widget
            _ => {}
        }
    }
}
impl Draw for SpinBox {
    fn draw(&mut self, context: &mut RenderContext) {
        // ── The band actually painted ──
        //
        // Every measurement below is taken from one of the four derived boxes (`row_band`,
        // `editable_rect`, `up_button`, `down_button`), so they cannot disagree about where
        // the field is, how tall the buttons are or where the value may be written. The
        // control's own rectangle decides *where* the band sits and nothing else.
        let band = self.row_band();
        // A band with no room left is not a spin box: the guard keeps the two buttons and
        // the value from being emitted as zero-extent elements, which is the shape the SVG
        // census reads as an invisible control.
        if band.width == 0 || band.height == 0 {
            return;
        }
        let editable = self.editable_rect();
        let down_button = self.down_button();
        let up_button = self.up_button();
        // The value's own text origin. The slots are laid out *below* from the same `editable` box, so
        // the value's start is derived once rather than the two being separate sums of the same padding.
        let style = self.style();
        let bg = style.background_color.unwrap_or(Color::rgb(255, 255, 255));
        let text_color = style.text_color.unwrap_or(Color::rgb(0, 0, 0));
        // The stepper buttons are part of this control's own chrome, so they follow
        // the widget's style instead of a fixed grey: the theme resolved a colour for
        // the spin box, and a literal made the two button wells ignore it (and stay
        // light in a dark theme). The arrows are ink drawn on those wells, so they
        // read `text_color` — the same colour the value's text uses.
        let button_bg = style.background_color.unwrap_or(Color::rgb(240, 240, 240));
        let button_border = style.border_color.unwrap_or(Color::rgb(200, 200, 200));
        let arrow_color = style.text_color.unwrap_or(Color::rgb(100, 100, 100));
        // # Why the field and its buttons acknowledge the pointer
        //
        // The two step buttons are the whole affordance of a spin box — a user who does not
        // know they are pressable has a read-only number — and they used to paint `button_bg`
        // unconditionally, so hovering one changed nothing. Measured before this: of the 27
        // controls in `input_widgets/`, only `command_link`, `line_edit` and `range_slider`
        // read `is_hovered()` at all.
        //
        // The weight comes from [`crate::style::StateOverlay::fill_blend`] rather than a literal,
        // so the overlay the preset theme's `"<kind>:hover"` / `"<kind>:pressed"` keys derive and
        // the overlay painted here move a control by the **same** amount. A private constant here
        // would drift the first time the theme's weight changed (the defect `slider`'s halo and
        // `radiobutton`'s ring avoid by reading the same source).
        //
        // The pointer is not tracked per-button: `BaseWidget` owns `hovered`/`pressed` for the
        // control as a whole, and `down_button`/`up_button` are disjoint halves of it, so "the
        // control is hovered" and "the pointer is over a button" are the same fact for every
        // point inside the band. Splitting them would need a second hover field to disagree
        // with the first.
        let overlay = crate::style::StateOverlay::from_base(
            self.base.is_hovered(),
            self.base.is_pressed(),
            self.base.draws_focus_ring(),
        );
        let blend = overlay.fill_blend();
        // The buttons step toward their own ink, which is `arrow_color`'s source — so a theme
        // that recolours the arrows recolours the hover that reveals them.
        let step_fill = |base: Color| {
            if blend > 0.0 {
                base.blend(&base.contrast_color(), blend)
            } else {
                base
            }
        };
        // The effective font, so the field's value is drawn in the same font the hint measured
        // (D09-STYLE-02).
        let font = effective_font(style);
        // Draw background. The field also acknowledges the pointer, so the whole control reads
        // as one interactive object rather than only its buttons doing so.
        context.fill_rect(band, step_fill(bg));
        // Draw border
        if let Some(border_color) = style.border_color {
            context.draw_rect(band, border_color);
        }
        // Draw up/down buttons. Each is the half of the trailing column it owns, so the two
        // are the same height whatever the band is, and neither can overlap the value. Each
        // steps toward its own ink while the pointer is on the control; see `step_fill`.
        context.fill_rect(down_button, step_fill(button_bg));
        context.draw_rect(down_button, button_border);
        // A button at its bound is painted dimmed, so the control says "there is nowhere
        // further to go" before the user presses it. A wrapping box never reaches a bound.
        let down_arrow =
            if self.can_step_down() { arrow_color } else { arrow_color.with_alpha(90) };
        let up_arrow = if self.can_step_up() { arrow_color } else { arrow_color.with_alpha(90) };
        draw_step_arrow(context, down_button, false, down_arrow);
        context.fill_rect(up_button, step_fill(button_bg));
        context.draw_rect(up_button, button_border);
        draw_step_arrow(context, up_button, true, up_arrow);
        // Draw text. The value is bounded to the **editable** box, so it is fitted into the
        // space the button column left instead of being written from the field's leading
        // padding and allowed to run under the buttons.
        //
        // # Why the slots are drawn separately rather than concatenated
        //
        // `display_text()` still produces the announcement form (`$12`), because that is what a screen
        // reader should hear. What is *painted* is `value_text()` inside the value's own box, with the
        // prefix in its box on the leading side and the suffix anchored to the trailing one. Drawing the
        // concatenated string instead put the `$` inside the value's glyph run, so the value's origin
        // included it — the caret would sit after the `$` at the start of the field, and a select-all
        // would copy the unit along with the number.
        // Widths only: the slot strings are borrowed from the control and never copied. The
        // old code built a `DecorationSlots` with two `String` clones per frame just to ask
        // for two advances, and the empty slots here carry no support row/counter to lay out.
        let (prefix_width, suffix_width) = self.decoration_widths(context, font);
        let metrics = DecorationMetrics { prefix_width, suffix_width };
        let slots = DecorationSlots::default();
        let line_height = font.effective_line_height().max(1.0) as u32;
        let layout = DecorationLayout::compute(
            editable,
            dimensions::TEXT_FIELD_PADDING_H,
            line_height,
            DECORATION_GAP,
            metrics,
            0,
            &slots,
        );
        // I-P65: the idle path borrows the cached string instead of producing a `String` per
        // frame.
        let cached_value = if self.editing { None } else { Some(self.value_text_cached()) };
        let value_text: &str =
            if self.editing { self.entry.text() } else { cached_value.as_deref().unwrap_or("") };
        // The value's own line box and horizontal alignment, derived once: the painted run, the
        // selection band and the caret all read them, so the decorations cannot land beside the
        // glyphs they belong to.
        let value_line = context.text_line(editable, font);
        let align = self.alignment.to_horizontal().unwrap_or(HorizontalAlignment::Left);
        let value_box =
            Rect::new(layout.value.x, value_line.y, layout.value.width, value_line.height);
        // While an edit is open the entry's own caret and selection are painted, so
        // `entry_cursor_position` / `select_all` are visible rather than model-only state.
        let entry_origin = if self.editing {
            let advance = context.measure_text(value_text, font).width as i32;
            Some(crate::render::fitted_origin(value_box, advance, align))
        } else {
            None
        };
        // I-P65: the three prefix advances the edit frame needs are measured once and shared by
        // the selection band and the caret.
        let caret = self.entry.cursor_position().min(value_text.len());
        let selection = self.entry_selection_range();
        let (start_prefix, end_prefix, caret_prefix) = if let Some((start, end)) = selection {
            let start_prefix = context.measure_text(&value_text[..start], font).width as i32;
            let end_prefix = context.measure_text(&value_text[..end], font).width as i32;
            let caret_prefix = if caret == end {
                end_prefix
            } else if caret == start {
                start_prefix
            } else {
                context.measure_text(&value_text[..caret], font).width as i32
            };
            (start_prefix, end_prefix, caret_prefix)
        } else {
            let caret_prefix = context.measure_text(&value_text[..caret], font).width as i32;
            (caret_prefix, caret_prefix, caret_prefix)
        };
        if let (Some(origin), Some(_)) = (entry_origin, selection) {
            // The selection band is derived from the field's own ink and fill, so it reads on
            // both appearances without a second theme token to keep in step.
            let selection_fill = text_color.blend(&bg, 0.3).blend(&bg, 0.25);
            let start_x = origin.x + start_prefix;
            let end_x = origin.x + end_prefix;
            let right_edge = value_box.x + value_box.width as i32;
            let left = start_x.clamp(value_box.x, right_edge);
            let right = end_x.clamp(value_box.x, right_edge).max(left);
            context.fill_rect(
                Rect::new(left, value_line.y, (right - left) as u32, value_line.height.max(1)),
                selection_fill,
            );
        }
        if !value_text.is_empty() {
            context.draw_text_fitted_cow(value_box, value_text, font, text_color, align);
        }
        if let Some(origin) = entry_origin {
            // The insertion point, from the same origin and shared prefix measurement as the
            // band, clipped to the value's box.
            let caret_x = origin.x + caret_prefix;
            let caret_x = caret_x
                .clamp(value_box.x, value_box.x + value_box.width as i32 - 1)
                .max(value_box.x);
            context.draw_line(
                Point::new(caret_x, value_line.y),
                Point::new(caret_x, value_line.y + value_line.height as i32),
                text_color,
            );
        }
        // The slots are chrome, not content, so they are drawn a step toward the field's own fill —
        // the same "less prominent than the value" reading `lineedit` uses for the same two slots.
        let slot_color = text_color.blend(&bg, 0.35);
        let line = context.text_line(editable, font);
        if let Some(prefix_box) = layout.prefix {
            context.draw_text(
                Point::new(prefix_box.x, line.y),
                &self.prefix,
                font,
                slot_color,
                HorizontalAlignment::Left,
            );
        }
        if let Some(suffix_box) = layout.suffix {
            context.draw_text(
                Point::new(suffix_box.x, line.y),
                &self.suffix,
                font,
                slot_color,
                HorizontalAlignment::Left,
            );
        }
    }
}

/// Draws one step arrow inside `button`, pointing up when `up` is set.
///
/// # Why the origin is the box's centre line, not its edge
///
/// The chevron is a **shape**, not text, so it is centred on the box rather than placed by
/// a text origin — the five literals per arrow (`4`, and the three `4.0 / 2.0` halves) were
/// each an independent offset from the button's midpoint, and none of them was named. The
/// two shapes here are the same three-point chevron reflected about the midpoint, so the up
/// and down arrows cannot disagree about the arrow's size or its drop.
fn draw_step_arrow(context: &mut RenderContext, button: Rect, up: bool, color: Color) {
    let cx = button.x as f32 + button.width as f32 / 2.0;
    let cy = button.y as f32 + button.height as f32 / 2.0;
    let span = SPIN_BOX_ARROW_HALF_SPAN;
    // A downward chevron opens downward; an upward one is the same shape with the drop
    // negated, so the two are one derivation read with a sign.
    let drop = if up { -SPIN_BOX_ARROW_DROP } else { SPIN_BOX_ARROW_DROP };
    let left = Point::from_f32(cx - span, cy - drop / 2.0);
    let tip = Point::from_f32(cx, cy + drop / 2.0);
    let right = Point::from_f32(cx + span, cy - drop / 2.0);
    context.draw_line(left, tip, color);
    context.draw_line(tip, right, color);
    context.draw_line(right, left, color);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Rect;

    /// The paint path's value text is memoised and refreshes when any input changes (WDGT-06).
    #[test]
    fn the_drawn_value_is_cached_and_refreshes_when_an_input_changes() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(12);
        assert_eq!(&*sb.value_text_cached(), sb.value_text().as_str());
        assert_eq!(&*sb.value_text_cached(), sb.value_text().as_str(), "a second frame reuses it");

        sb.set_decimals(2);
        assert_eq!(&*sb.value_text_cached(), sb.value_text().as_str());
        sb.set_special_value_text(Some("Zero".to_string()));
        sb.set_value(0);
        assert_eq!(&*sb.value_text_cached(), "Zero");
        sb.set_special_value_text(None);
        assert_eq!(&*sb.value_text_cached(), sb.value_text().as_str());
    }

    #[test]
    fn spinbox_creation_defaults() {
        let sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert_eq!(sb.value(), 0);
        assert_eq!(sb.minimum(), 0);
        assert_eq!(sb.maximum(), 99);
        assert_eq!(sb.single_step(), 1);
        assert!(sb.prefix().is_empty());
        assert!(sb.suffix().is_empty());
        assert!(!sb.wrapping());
        assert!(sb.special_value_text().is_none());
    }

    #[test]
    fn spinbox_set_value() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(50);
        assert_eq!(sb.value(), 50);
        sb.set_value(200); // clamp to max
        assert_eq!(sb.value(), 99);
        sb.set_value(-10); // clamp to min
        assert_eq!(sb.value(), 0);
    }

    #[test]
    fn spinbox_set_range() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_minimum(-50);
        sb.set_maximum(200);
        assert_eq!(sb.minimum(), -50);
        assert_eq!(sb.maximum(), 200);
    }

    #[test]
    fn spinbox_set_range_reclamps_value() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(50);
        sb.set_range(60, 100);
        assert_eq!(sb.value(), 60);
    }

    #[test]
    fn spinbox_prefix_suffix() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_prefix("$".to_string());
        assert_eq!(sb.prefix(), "$");
        sb.set_suffix(" USD".to_string());
        assert_eq!(sb.suffix(), " USD");
        sb.set_prefix(String::new());
        assert!(sb.prefix().is_empty());
    }

    /// The two forms differ: the announcement string carries the unit marks, and the drawn value does
    /// not.
    ///
    /// # The defect this pins
    ///
    /// The painter used the concatenated string, so the value's own glyph run contained the `$` — which
    /// made the value's origin include it. That is the same string a caret would be measured against, so
    /// on a spin box it was invisible (there is no caret), but it made `value_text` and `display_text` the
    /// same thing, and the two are genuinely different statements: one is read out, one is drawn.
    #[test]
    fn the_announcement_string_carries_the_units_and_the_drawn_value_does_not() {
        use crate::widget::capability::WidgetProperties;

        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(12);
        assert_eq!(sb.value_text(), "12", "the drawn value is the number alone");
        assert_eq!(sb.display_text(), "12", "and with no units the two agree");

        sb.set_prefix("$".to_string());
        sb.set_suffix(" USD".to_string());
        assert_eq!(sb.value_text(), "12", "the units are not part of the value");
        assert_eq!(sb.display_text(), "$12 USD", "but they are part of the announcement");

        // Both are reachable through the contract, and neither is writable.
        assert_eq!(sb.get("display_text").unwrap().as_str(), Some("$12 USD"));
        assert_eq!(sb.get("value_text").unwrap().as_str(), Some("12"));
        assert!(sb.set("display_text", CapabilityValue::String("x".into())).is_err());
        assert!(sb.set("value_text", CapabilityValue::String("x".into())).is_err());
    }

    /// The prefix is drawn to the **left** of the value and the suffix to its right, as two runs.
    ///
    /// This is what makes the slots chrome rather than content, and it is readable from the SVG: three
    /// separate `draw_text` calls produce three paths, and their order on the x axis is the layout.
    #[test]
    fn the_slots_are_drawn_on_either_side_of_the_value() {
        // 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 sb = SpinBox::new(Rect::new(0, 0, 200, 24));
        sb.set_value(7);
        sb.set_prefix("$".to_string());
        sb.set_suffix("%".to_string());
        let svg = crate::widget::svg::render_to_svg(&mut sb);

        let mut runs = crate::widget::svg::text_ink_boxes(&svg);
        runs.sort_by_key(|b| b.0);
        assert_eq!(runs.len(), 3, "a prefix, a value and a suffix are three runs: {runs:?}");
        // Read left to right the order is prefix, value, suffix.
        assert!(
            runs[0].2 <= runs[1].0,
            "the prefix ({:?}) must end before the value ({:?}) begins",
            runs[0],
            runs[1]
        );
        assert!(
            runs[1].2 <= runs[2].0,
            "the value ({:?}) must end before the suffix ({:?}) begins",
            runs[1],
            runs[2]
        );
        // And with no slots at all there is exactly one run, so the slots are what added the others.
        let mut bare = SpinBox::new(Rect::new(0, 0, 200, 24));
        bare.set_value(7);
        let bare_svg = crate::widget::svg::render_to_svg(&mut bare);
        assert_eq!(crate::widget::svg::text_ink_boxes(&bare_svg).len(), 1);
    }

    /// A prefix wide enough to consume the field's inner box leaves the value **no room**, and the clamp
    /// is what stops the two from overlapping.
    ///
    /// # Why the assertion is "no overlap", not "only one run"
    ///
    /// The prefix is 17 characters in a field whose editable box is roughly 170 px wide, so the prefix
    /// legitimately takes almost all of it. How much is left for the value depends on the **face**: the
    /// bitmap face advances a glyph a full box per cluster, so the value's box clamps to zero width and
    /// nothing is painted for it, while an outline face's narrower glyphs leave the value a few pixels and
    /// it is painted after the prefix. Asserting "one run" pinned the bitmap advance rather than the
    /// layout. The guarantee the clamp provides is that the value never runs under the prefix, so the test
    /// asserts that: the value's ink begins at or after the prefix's ends, whether it was painted at all.
    #[test]
    fn a_prefix_wide_enough_to_fill_the_field_leaves_the_value_no_room() {
        // 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 sb = SpinBox::new(Rect::new(0, 0, 200, 24));
        sb.set_value(7);
        assert_eq!(sb.value_text(), "7");

        let mut bare = SpinBox::new(Rect::new(0, 0, 200, 24));
        bare.set_value(7);
        let bare_runs =
            crate::widget::svg::text_ink_boxes(&crate::widget::svg::render_to_svg(&mut bare));
        assert_eq!(bare_runs.len(), 1, "the value is drawn when nothing squeezes it");

        sb.set_prefix("a-very-long-prefix".to_string());
        let svg = crate::widget::svg::render_to_svg(&mut sb);
        let mut runs = crate::widget::svg::text_ink_boxes(&svg);
        runs.sort_by_key(|b| b.0);
        // The prefix is 17 characters and takes essentially the whole editable box. Under the bitmap
        // face its advance is wide enough to clamp the value's box to zero width, so the value is not
        // painted at all; an outline face's glyphs are narrower, so the prefix leaves the value a few
        // pixels and it *is* painted — legitimately, after the prefix. "One run" therefore encoded the
        // bitmap face's advance, not the layout. What the layout actually guarantees is **no overlap**:
        // the clamp keeps the value's box (and so its ink) from running under the prefix. That is the
        // property asserted here, and it holds whichever face is in use.
        assert!(runs.len() <= 2, "a prefix and a value are the only runs the field has: {runs:?}");
        assert!(!runs.is_empty(), "the prefix was drawn: {runs:?}");
        if runs.len() == 2 {
            assert!(
                runs[0].2 <= runs[1].0,
                "the value ({:?}) must not overlap the prefix ({:?})",
                runs[1],
                runs[0]
            );
        }
        // And what was drawn starts at or after the field's padding — nothing was pushed off the leading
        // edge.
        assert!(
            runs[0].0 >= sb.editable_rect().x + dimensions::TEXT_FIELD_PADDING_H as i32,
            "the prefix must not escape the field: {runs:?}"
        );
    }

    #[test]
    fn spinbox_single_step() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_single_step(5);
        assert_eq!(sb.single_step(), 5);
        sb.set_single_step(0); // floors at 1
        assert_eq!(sb.single_step(), 1);
    }

    #[test]
    fn spinbox_wrapping() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert!(!sb.wrapping());
        sb.set_wrapping(true);
        assert!(sb.wrapping());
        sb.set_wrapping(false);
        assert!(!sb.wrapping());
    }

    #[test]
    fn spinbox_step_up() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(50);
        sb.step_up();
        assert_eq!(sb.value(), 51);
    }

    #[test]
    fn spinbox_step_up_clamps() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(99);
        sb.step_up();
        assert_eq!(sb.value(), 99); // clamped to max
    }

    #[test]
    fn spinbox_step_up_wraps() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_wrapping(true);
        sb.set_value(99);
        sb.step_up();
        assert_eq!(sb.value(), 0); // wraps to min
    }

    #[test]
    fn spinbox_step_down() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(50);
        sb.step_down();
        assert_eq!(sb.value(), 49);
    }

    #[test]
    fn spinbox_step_down_clamps() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value(0);
        sb.step_down();
        assert_eq!(sb.value(), 0); // clamped to min
    }

    #[test]
    fn spinbox_step_down_wraps() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_wrapping(true);
        sb.set_value(0);
        sb.step_down();
        assert_eq!(sb.value(), 99); // wraps to max
    }

    #[test]
    fn spinbox_special_value_text() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert!(sb.special_value_text().is_none());
        sb.set_special_value_text(Some("Zero".to_string()));
        assert_eq!(sb.special_value_text(), Some("Zero"));
        sb.set_special_value_text(None);
        assert!(sb.special_value_text().is_none());
    }

    #[test]
    fn spinbox_geometry_delegation() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_geometry(Rect::new(10, 10, 200, 30));
        assert_eq!(sb.geometry(), Rect::new(10, 10, 200, 30));
    }

    #[test]
    fn spinbox_visibility() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert!(sb.is_visible());
        sb.hide();
        assert!(!sb.is_visible());
        sb.show();
        assert!(sb.is_visible());
    }

    #[test]
    fn spinbox_enabled() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert!(sb.is_enabled());
        sb.set_enabled(false);
        assert!(!sb.is_enabled());
        sb.set_enabled(true);
        assert!(sb.is_enabled());
    }

    #[test]
    fn spinbox_id_kind() {
        let sb_a = SpinBox::new(Rect::new(0, 0, 100, 24));
        let sb_b = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert_ne!(sb_a.id(), sb_b.id());
        assert_eq!(sb_a.kind(), WidgetKind::SpinBox);
        assert_eq!(sb_b.kind(), WidgetKind::SpinBox);
    }

    #[test]
    fn spinbox_signal_accessors() {
        let sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        let _value_changed = &sb.value_changed;
        let _editing_finished = &sb.editing_finished;
    }

    // ── Decimal mode (BLUE20 layer 4c) ─────────────────────────────────────────

    /// The default must be an integer spin box, or every existing caller changes
    /// behaviour. This is the forward-compatibility half of the feature (principle #21).
    #[test]
    fn spinbox_defaults_to_integer_precision() {
        let sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert_eq!(sb.decimals(), 0);
        assert_eq!(sb.formatted_value(), "0", "integer mode must print no decimals");
    }

    /// The round trip the task names: `set_decimals(2)` then `set_value(1.5)`.
    #[test]
    fn spinbox_decimal_round_trip() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(2);
        sb.set_value_f64(1.5);
        assert_eq!(sb.value_f64(), 1.5);
        assert_eq!(sb.value(), 2, "the integer reading rounds, it does not truncate");
        assert_eq!(sb.formatted_value(), "1.50", "a two-decimal box shows two decimals");
    }

    /// Steps in decimal mode move by the decimal step, not by one.
    #[test]
    fn spinbox_decimal_step() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(2);
        sb.set_single_step_f64(0.25);
        sb.set_value_f64(1.0);
        sb.step_up();
        assert_eq!(sb.value_f64(), 1.25);
        sb.step_down();
        sb.step_down();
        assert_eq!(sb.value_f64(), 0.75);
    }

    /// A step smaller than one displayed unit would make the buttons look broken, so
    /// the floor is the unit of the last displayed place — not a hardcoded `1`.
    #[test]
    fn spinbox_decimal_step_floor_is_the_last_place() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(2);
        sb.set_single_step_f64(0.0);
        assert_eq!(sb.single_step_f64(), 0.01);
        sb.set_single_step_f64(-0.5);
        assert_eq!(sb.single_step_f64(), 0.5, "a negative step is a magnitude, not a direction");
    }

    /// Changing the precision must re-round the stored value, or the display and the
    /// value disagree and the control reports digits the user could not have entered.
    #[test]
    fn spinbox_set_decimals_rerounds_the_value() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(4);
        sb.set_value_f64(1.23456);
        assert_eq!(sb.value_f64(), 1.2346);
        sb.set_decimals(2);
        assert_eq!(sb.value_f64(), 1.23);
        sb.set_decimals(0);
        assert_eq!(sb.value_f64(), 1.0);
    }

    /// Storing and displaying must agree to the digit. `2.0965` at three places is the
    /// case that separates the two implementations on this build: the scale form computes
    /// `2096.5000000000005` and rounds it to `2.097`, while a correctly-rounded decimal
    /// formatter prints `2.096`. Using the text as the authority is what keeps the stored
    /// value equal to the digits on screen.
    #[test]
    fn spinbox_stored_value_equals_the_printed_value() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(3);
        sb.set_value_f64(2.0965);
        assert_eq!(
            sb.formatted_value(),
            "2.096",
            "the printed digits must be the correctly-rounded ones"
        );
        assert_eq!(
            sb.value_f64(),
            2.096,
            "and the stored value must be exactly the number that was printed — the scale \
             form would store 2.097 here and disagree with its own display"
        );
    }

    /// A literal that is already below the midpoint must round **down**. This is the
    /// honest half of the rounding story: no scheme can recover digits the input never
    /// held, and `1.005` as an `f64` is `1.004999...`, so `1.00` is the correct answer —
    /// and the same one a decimal parser produces from the identical text.
    #[test]
    fn spinbox_rounds_a_below_midpoint_literal_down() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(2);
        sb.set_value_f64(1.005);
        assert_eq!(
            sb.formatted_value(),
            "1.00",
            "1.005 as an f64 is 1.004999...; 1.00 is the correct rounding of the value that was \
             actually stored, not a rounding failure"
        );
        assert_eq!(sb.value_f64(), 1.0);
        // The same text through a decimal parser lands on the same `f64`, which is the
        // proof that this is the input's limit and not the widget's rounding bug.
        let parsed: f64 = "1.005".parse().unwrap();
        assert_eq!(parsed, 1.005, "the literal and the parsed text must be the same f64");
    }

    /// `NaN` has no position in a range. Storing it would make every later comparison
    /// false and the control unreadable, so the write must be refused rather than kept.
    #[test]
    fn spinbox_rejects_nan_and_keeps_the_previous_value() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_value_f64(3.0);
        sb.set_value_f64(f64::NAN);
        assert_eq!(sb.value_f64(), 3.0);
        sb.set_minimum_f64(f64::NAN);
        assert_eq!(sb.minimum_f64(), 0.0);
        sb.set_maximum_f64(f64::NAN);
        assert_eq!(sb.maximum_f64(), 99.0);
    }

    /// Infinity is a legitimate open bound, so it is clamped, not rejected.
    #[test]
    fn spinbox_infinite_bounds_are_a_valid_range() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_maximum_f64(f64::INFINITY);
        sb.set_range_f64(0.0, f64::INFINITY);
        sb.set_value_f64(1.0e9);
        assert_eq!(sb.value_f64(), 1.0e9);
    }

    /// Crossed bounds name the same range in either order. Storing an inverted pair
    /// would silently collapse the range to a single point.
    #[test]
    fn spinbox_crossed_decimal_bounds_are_ordered() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_range_f64(10.0, 0.0);
        assert_eq!(sb.minimum_f64(), 0.0);
        assert_eq!(sb.maximum_f64(), 10.0);
        sb.set_value_f64(20.0);
        assert_eq!(sb.value_f64(), 10.0);
    }

    /// `-0.0` formats as `-0`, which reads as a defect. Rounding to integers must
    /// normalise it — and `decimals == 0` is exactly where the sign can be lost.
    #[test]
    fn spinbox_negative_zero_rounds_to_zero() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_minimum(-5);
        sb.set_value_f64(-0.4);
        assert_eq!(sb.value_f64(), 0.0);
        assert_eq!(sb.formatted_value(), "0", "a zero must not be printed as `-0`");
    }

    /// The property route must stay integer-typed until decimals are enabled, and
    /// report `Float` afterwards — the declaration says `Number`, and this is what
    /// that word means at runtime.
    #[test]
    fn spinbox_value_property_switches_carrier_with_decimals() {
        use crate::widget::capability::WidgetProperties;
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        assert_eq!(sb.get("value").unwrap(), CapabilityValue::Int(0));
        assert_eq!(sb.set("value", CapabilityValue::Int(7)), Ok(()));
        assert_eq!(sb.get("value").unwrap(), CapabilityValue::Int(7));

        sb.set("decimals", CapabilityValue::Int(2)).unwrap();
        // The schema declares `UInt`, so the read answers `UInt`; the writer still accepts a
        // non-negative `Int` (the JSON form of a small number) — the two facts this test pins.
        assert_eq!(sb.get("decimals").unwrap(), CapabilityValue::UInt(2));
        // A decimal write is accepted and read back as a Float.
        assert_eq!(sb.set("value", CapabilityValue::Float(2.5)), Ok(()));
        assert_eq!(sb.get("value").unwrap(), CapabilityValue::Float(2.5));
        // An integer write still works, which is what keeps `{"value": 3}` valid.
        assert_eq!(sb.set("value", CapabilityValue::Int(3)), Ok(()));
        assert_eq!(sb.get("value").unwrap(), CapabilityValue::Float(3.0));
    }

    /// A precision beyond what the display grammar can print is clamped, not accepted:
    /// the digits past that point are binary noise the widget does not hold.
    #[test]
    fn spinbox_decimals_are_bounded_and_negative_is_refused() {
        use crate::widget::capability::WidgetProperties;
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(99);
        assert_eq!(sb.decimals(), SPIN_BOX_MAX_DECIMALS);
        assert_eq!(
            sb.set("decimals", CapabilityValue::Int(-1)),
            Err(CapabilityAccessError::OutOfRange),
            "a negative precision is a value error, not a silently accepted magnitude"
        );
        assert_eq!(sb.decimals(), SPIN_BOX_MAX_DECIMALS, "the refused write must not take effect");
    }

    /// The width must follow the formatted text; sizing off the integer form clips
    /// exactly the decimals the caller asked to display.
    ///
    /// # What this pins, and why the range is widened first
    ///
    /// The box starts with the default `0..=99`, and `set_decimals` re-clamps the value to
    /// that range — so the old form of this test (`set_value(1234)` then `set_decimals(2)`)
    /// never measured `1234.00` at all: it measured `99` against `99.00`, whose two
    /// characters are both under the hint's floor and therefore both produce the same width.
    /// The comparison passed only because the pre-migration formula had no floor to reach.
    /// The range is widened so the value survives the precision change and the assertion
    /// measures the thing its message claims: the formatted text driving the width.
    #[test]
    fn spinbox_size_hint_accounts_for_decimals() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_range(0, 1_000_000);
        sb.set_value(1234);
        assert_eq!(sb.formatted_value(), "1234", "the value must survive the setup");
        let integer_width = sb.size_hint().width;
        sb.set_decimals(2);
        assert_eq!(sb.formatted_value(), "1234.00", "two more digits than the integer form");
        assert!(
            sb.size_hint().width > integer_width,
            "a two-decimal box showing 1234.00 must be wider than one showing 1234"
        );
    }

    /// The reported size and the painted band are two readings of one formula.
    ///
    /// # Why this exists
    ///
    /// This is BLUE22 §B.6 rule 3: a composite's own `size_hint` must be derived through
    /// `ControlMetrics::implicit_size` over a floor from the `dimensions` table, so the drawn
    /// box and the reported size agree. Before the migration the hint was
    /// `Size::new(val_w.max(60), 24)` — a free-standing literal — while `draw` painted
    /// `geometry()`: the reported 24 px height and the 120 px slab on screen were two
    /// different descriptions of the same control.
    #[test]
    fn the_reported_height_is_the_band_that_is_painted() {
        let sb = SpinBox::new(Rect::new(0, 0, 240, 120));
        let band = sb.row_band();
        assert_eq!(
            band.height,
            dimensions::TEXT_FIELD_MIN_HEIGHT,
            "the painted band is the field's own height, whatever rectangle the control was given"
        );
        assert_eq!(
            sb.size_hint().height,
            band.height,
            "a layout must be told the height the control actually draws"
        );
        // Centred in the area it was given, not stretched across it.
        assert_eq!(band.width, 240);
        assert_eq!(band.y, (120 - dimensions::TEXT_FIELD_MIN_HEIGHT as i32) / 2);
    }

    /// The value can never be laid over the step column: the two tile the band.
    ///
    /// # Why this exists
    ///
    /// This is BLUE22 §B.9 — a sub-part's box is derived from its siblings. The buttons used
    /// to sit at `geometry().right() - 20 * 2` while the text was written from the field's
    /// leading edge with no upper bound, so a wider button or a larger font put the value
    /// *underneath* the buttons. Deriving the editable box as "whatever the column leaves"
    /// makes that overlap unrepresentable.
    #[test]
    fn the_value_box_ends_where_the_button_column_begins() {
        // Widths at which both boxes are representable: the column is
        // `SPIN_BOX_BUTTON_WIDTH * SPIN_BOX_BUTTONS` (40) **plus the value column's own floor**, and
        // a band narrower than that cannot hold both — see
        // `a_band_narrower_than_the_step_column_overhangs`.
        let narrowest =
            (SPIN_BOX_BUTTON_WIDTH * SPIN_BOX_BUTTONS) + dimensions::TEXT_FIELD_PADDING_H;
        for width in [narrowest, 64, 240, 400] {
            let sb = SpinBox::new(Rect::new(0, 0, width, 120));
            let editable = sb.editable_rect();
            let column = sb.button_column();
            assert_eq!(
                editable.x + editable.width as i32,
                column.x,
                "the two boxes must share an edge at control width {width}"
            );
            assert_eq!(
                editable.width + column.width,
                sb.row_band().width,
                "the two boxes must tile the band at control width {width}"
            );
            assert!(
                column.x + column.width as i32 <= sb.row_band().x + sb.row_band().width as i32,
                "the button column must stay inside the band at control width {width}"
            );
        }
    }

    /// An RTL spin box mirrors its assembly: the step column moves to the other edge and the value
    /// yields to it there.
    ///
    /// # The defect this pins
    ///
    /// The field had no direction at all. Every placement was derived from `band.x` and
    /// `band.right()`, so under an RTL locale the value was written from the field's *left* padding
    /// and the steppers stayed on the right: the number and the buttons that change it were at
    /// opposite ends in the wrong reading order. The assertion is **geometric** (which edge the
    /// column is at, and that the two boxes still tile) **and** in the document (the value's ink moves
    /// to the other side), because a layout-only assertion would not notice a draw that asked for the
    /// mirrored boxes and then ignored them.
    #[test]
    fn an_rtl_spin_box_mirrors_its_step_column_and_its_value() {
        use crate::core::TextDirection;
        use crate::widget::svg::render_to_svg;
        let _theme_guard = crate::style::theme_test_guard();

        let band = |sb: &SpinBox| sb.row_band();
        let mut ltr = SpinBox::new(Rect::new(0, 0, 240, 120));
        ltr.set_value(12);
        let mut rtl = SpinBox::new(Rect::new(0, 0, 240, 120));
        rtl.set_value(12);
        rtl.set_direction(TextDirection::RightToLeft);

        assert_eq!(ltr.direction(), TextDirection::LeftToRight, "left-to-right by default");
        assert_eq!(rtl.direction(), TextDirection::RightToLeft, "and it reports what was set");

        // The column is at the trailing edge in LTR and the leading one in RTL.
        let ltr_band = band(&ltr);
        let rtl_band = band(&rtl);
        assert_eq!(
            ltr.button_column().x + ltr.button_column().width as i32,
            ltr_band.x + ltr_band.width as i32,
            "in LTR the column ends at the band's right edge"
        );
        assert_eq!(rtl.button_column().x, rtl_band.x, "in RTL it starts at the band's left edge");

        // And the two boxes tile the band either way, so mirroring did not lose a column.
        for (sb, label) in [(&ltr, "ltr"), (&rtl, "rtl")] {
            let editable = sb.editable_rect();
            let column = sb.button_column();
            assert_eq!(
                editable.width + column.width,
                sb.row_band().width,
                "the two boxes must tile the band in {label}"
            );
            let (left, right) =
                if editable.x < column.x { (editable, column) } else { (column, editable) };
            assert_eq!(
                left.x + left.width as i32,
                right.x,
                "the two boxes must share an edge in {label}"
            );
        }

        // The value's own box moved to the other side, which is the half a layout assertion misses.
        assert!(
            rtl.editable_rect().x > ltr.editable_rect().x,
            "the value yields to the column, so in RTL its box starts further right: ltr={} rtl={}",
            ltr.editable_rect().x,
            rtl.editable_rect().x
        );

        // And it is *painted* that way: the two documents differ, which a mirrored layout that the
        // draw then ignored would not achieve.
        let ltr_svg = render_to_svg(&mut ltr);
        let rtl_svg = render_to_svg(&mut rtl);
        assert_ne!(
            ltr_svg, rtl_svg,
            "an RTL spin box must not paint the same picture as an LTR one"
        );
    }

    /// A band narrower than the step column keeps both columns inside it.
    ///
    /// # What this pins (and what G-1 changed)
    ///
    /// The step column is 40 px (two 20 px buttons) and the value column's floor is the field's own
    /// padding, so a 30 px band cannot hold both at those sizes — arithmetic, not a bug.
    ///
    /// Before G-1 was resolved the value column kept its floor and the step column was pushed past
    /// the band's trailing edge, which on the SVG backend means **no step buttons in the picture at
    /// all** rather than step buttons that overflow. The teardown of a numeric field that silently
    /// loses its steppers is exactly the kind of loss that is worse than a compressed control, so
    /// the assertion is containment.
    ///
    /// The case is not reachable from a real form: a spin box's `size_hint` floor is the whole
    /// column plus twice the field padding, which is wider than this band.
    #[cfg(device_profile)]
    #[test]
    fn a_band_narrower_than_the_step_column_keeps_both_inside_it() {
        let width = 30u32;
        let sb = SpinBox::new(Rect::new(0, 0, width, 120));
        let band = sb.row_band();
        let value = sb.editable_rect();
        let column = sb.button_column();
        for (label, rect) in [("value", value), ("step column", column)] {
            assert!(
                rect.x >= band.x && rect.x + rect.width as i32 <= band.x + band.width as i32,
                "the {label} must stay inside the band: {rect:?} in {band:?}"
            );
            assert!(rect.width > 0, "and neither is dropped: the {label} is {rect:?}");
        }
        // They still tile the band: the value yields to the column, which is the control's relation.
        assert_eq!(value.x + value.width as i32, column.x, "the two boxes share an edge");
        assert_eq!(value.width + column.width, width, "and they account for the band");
    }

    /// The two step buttons tile the column and never overlap each other.
    #[test]
    fn the_step_buttons_tile_their_column() {
        for height in [0u32, 10, 48, 120] {
            let sb = SpinBox::new(Rect::new(0, 0, 200, height));
            let up = sb.up_button();
            let down = sb.down_button();
            assert_eq!(up.x, down.x, "both buttons occupy the one column at height {height}");
            assert_eq!(up.width, down.width);
            assert_eq!(
                up.y + up.height as i32,
                down.y,
                "the up button must end where the down button begins at height {height}"
            );
            assert_eq!(
                up.height + down.height,
                sb.button_column().height,
                "the two buttons must tile the column at height {height}"
            );
        }
    }

    /// A press lands on the step the *pointed-at* button performs.
    ///
    /// The hit test used to re-derive the buttons from a `button_width` argument of its own,
    /// so the clickable column and the painted one were two independent derivations of the
    /// same edge. This drives the press through the same accessors the paint path uses.
    #[test]
    fn a_press_on_each_half_steps_in_the_direction_that_is_painted() {
        let rect = Rect::new(0, 0, 200, 120);
        let top = SpinBox::new(rect).up_button();
        let bottom = SpinBox::new(rect).down_button();

        let mut sb = SpinBox::new(rect);
        sb.set_value(50);
        sb.handle_event(&Event::MousePress {
            pos: Point::new(top.x + 1, top.y + 1),
            button: 1,
            modifiers: 0,
        });
        assert_eq!(sb.value(), 51, "the upper half of the column must step up");

        sb.handle_event(&Event::MousePress {
            pos: Point::new(bottom.x + 1, bottom.y + 1),
            button: 1,
            modifiers: 0,
        });
        assert_eq!(sb.value(), 50, "the lower half of the column must step down");
    }

    /// A wider step column pushes the value box narrower rather than overlapping it.
    ///
    /// # What this pins
    ///
    /// This is the sibling-column relation — `leftPadding: padding + down.width` — stated as a
    /// *test*: the value's box is derived from the column rather than from the band's far edge, so a
    /// wider column must move the value's trailing edge. The relation was previously satisfied by
    /// two independent subtractions from two different edges, which is why a wider button or a
    /// larger font ran the value underneath the buttons instead of narrowing it.
    #[test]
    fn a_wider_step_column_pushes_the_value_box() {
        let width = 240u32;
        let band_width = ControlMetrics::full_width_band(
            Rect::new(0, 0, width, 120),
            dimensions::TEXT_FIELD_MIN_HEIGHT,
        )
        .width;
        // Two step buttons of the shared width: the column the assembly derives.
        let column = SPIN_BOX_BUTTON_WIDTH * SPIN_BOX_BUTTONS;
        let sb = SpinBox::new(Rect::new(0, 0, width, 120));
        let editable = sb.editable_rect();
        assert_eq!(
            editable.width,
            band_width - column,
            "the value box is the band minus the column, not minus a constant from its own edge"
        );
        assert_eq!(
            editable.width + sb.button_column().width,
            band_width,
            "the two boxes consume the band between them"
        );
    }

    /// A press on the field itself is not a step.
    #[test]
    fn a_press_inside_the_value_box_does_not_step() {
        let mut sb = SpinBox::new(Rect::new(0, 0, 200, 120));
        sb.set_value(50);
        let editable = sb.editable_rect();
        sb.handle_event(&Event::MousePress {
            pos: Point::new(editable.x + 1, editable.y + editable.height as i32 / 2),
            button: 1,
            modifiers: 0,
        });
        assert_eq!(sb.value(), 50, "the text area is where the user types, not where they step");
    }

    /// Setting the precision re-rounds the value but must not claim the value changed:
    /// no step was taken, so a caller counting `value_changed` would see a phantom one.
    #[test]
    fn spinbox_set_decimals_does_not_emit_value_changed() {
        use crate::compat::Arc;
        use core::sync::atomic::{AtomicU32, Ordering};
        let mut sb = SpinBox::new(Rect::new(0, 0, 100, 24));
        sb.set_decimals(3);
        sb.set_value_f64(1.2345);
        // `Signal1::connect` requires `Send + Sync + 'static`, so the counter is an
        // atomic behind an `Arc` rather than an `Rc<Cell<..>>`.
        let seen = Arc::new(AtomicU32::new(0));
        let counter = seen.clone();
        sb.value_changed.connect(move |_| {
            counter.fetch_add(1, Ordering::SeqCst);
        });
        sb.set_decimals(1);
        assert_eq!(
            seen.load(Ordering::SeqCst),
            0,
            "re-rounding on a precision change is not a value change"
        );
        assert_eq!(sb.value_f64(), 1.2);
        sb.step_up();
        assert_eq!(seen.load(Ordering::SeqCst), 1, "a real step still emits");
    }

    // ── D09-STYLE-02: the hint measures with the font the paint uses ──

    /// A caller-authored `style.font` must widen the spin box hint.
    #[test]
    fn a_custom_font_grows_the_spin_box_hint() {
        let mut baseline = SpinBox::new(Rect::new(0, 0, 200, 24));
        baseline.set_decimals(2);
        baseline.set_range_f64(0.0, 1_000_000_000.0);
        baseline.set_value_f64(987654321.25);
        let base_hint = baseline.size_hint();

        let mut big = SpinBox::new(Rect::new(0, 0, 200, 24));
        big.set_decimals(2);
        big.set_range_f64(0.0, 1_000_000_000.0);
        big.set_value_f64(987654321.25);
        big.set_style(
            crate::style::WidgetStyle::default().with_font(crate::core::Font::simple("Test", 30.0)),
        );
        let big_hint = big.size_hint();

        assert!(
            big_hint.width > base_hint.width,
            "a larger font must widen the hint: {} vs {}",
            big_hint.width,
            base_hint.width
        );
    }

    /// A typed value is committed on Enter and abandoned on Escape.
    #[test]
    fn a_typed_value_is_committed_or_cancelled() {
        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_range_f64(0.0, 1000.0);
        for key in [49u32, 50, 51] {
            spin.handle_event(&Event::KeyPress { key, modifiers: 0 });
        }
        assert!(spin.is_editing());
        assert_eq!(spin.value(), 0, "nothing is committed while typing");
        spin.handle_event(&Event::KeyPress { key: 13, modifiers: 0 });
        assert_eq!(spin.value(), 123);
        assert!(!spin.is_editing());

        spin.begin_edit();
        spin.handle_event(&Event::KeyPress { key: 27, modifiers: 0 });
        assert_eq!(spin.value(), 123);
        assert!(!spin.is_editing());
    }

    /// Wheel, PageUp/PageDown and a held button all step the value.
    #[test]
    fn wheel_page_keys_and_auto_repeat_step_the_value() {
        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_range_f64(0.0, 1000.0);
        spin.set_value_f64(100.0);

        spin.handle_event(&Event::Wheel { delta: Point::new(0, -1), modifiers: 0 });
        assert_eq!(spin.value(), 101, "a notch up increments");
        spin.handle_event(&Event::Wheel { delta: Point::new(0, 1), modifiers: 0 });
        assert_eq!(spin.value(), 100);

        spin.handle_event(&Event::KeyPress { key: 33, modifiers: 0 });
        assert_eq!(spin.value(), 110, "PageUp takes ten steps");
        spin.handle_event(&Event::KeyPress { key: 34, modifiers: 0 });
        assert_eq!(spin.value(), 100);

        let up = spin.up_button();
        let center = Point::new(up.x + up.width as i32 / 2, up.y + up.height as i32 / 2);
        spin.handle_event(&Event::MousePress { pos: center, button: 1, modifiers: 0 });
        let after_press = spin.value();
        assert!(spin.tick(16), "a held button keeps owing frames");
        assert!(spin.tick(600));
        assert!(spin.value() > after_press, "holding the button repeats");
        spin.handle_event(&Event::MouseRelease { pos: center, button: 1 });
        assert!(!spin.tick(500));
    }

    /// The adaptive step grows with the magnitude, and a bound disables its button.
    #[test]
    fn adaptive_steps_and_bound_aware_buttons() {
        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_range_f64(0.0, 1000.0);
        spin.set_value_f64(500.0);
        spin.set_step_type(SpinBoxStepType::AdaptiveDecimalStep);
        assert_eq!(spin.step_type(), SpinBoxStepType::AdaptiveDecimalStep);
        assert!(spin.step_amount() > spin.single_step() as f64);

        spin.set_value_f64(1000.0);
        assert!(!spin.can_step_up());
        assert!(spin.can_step_down());
        let at_max = crate::widget::svg::render_to_svg(&mut spin);
        spin.set_value_f64(0.0);
        let at_min = crate::widget::svg::render_to_svg(&mut spin);
        assert_ne!(at_max, at_min, "a bound must be visible in the arrow column");
    }

    // ── COMP-03: the LineEdit-backed entry ─────────────────────────────────

    /// Typed text reaches the hosted `LineEdit`, and Enter parses it into the value.
    #[test]
    fn text_input_edits_the_hosted_line_edit_and_commit_parses() {
        use crate::compat::Arc;
        use core::sync::atomic::{AtomicU32, Ordering};

        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_range_f64(0.0, 999.0);
        let finished = Arc::new(AtomicU32::new(0));
        let counter = Arc::clone(&finished);
        spin.editing_finished.connect(move || {
            counter.fetch_add(1, Ordering::SeqCst);
        });

        spin.begin_edit();
        spin.select_all();
        spin.handle_event(&Event::TextInput { text: "42".into() });
        assert_eq!(spin.entry_text(), "42", "the hosted field owns the entry text");
        assert_eq!(spin.line_edit().text(), "42");
        assert_eq!(spin.value(), 0, "nothing is committed while the entry is open");

        spin.handle_event(&Event::KeyPress { key: 13, modifiers: 0 });
        assert_eq!(spin.value(), 42);
        assert!(!spin.is_editing());
        assert_eq!(finished.load(Ordering::SeqCst), 1, "one commit is one finish");
    }

    /// Selection and caret are the hosted field's, not a second buffer's.
    #[test]
    fn selection_and_caret_come_from_the_hosted_line_edit() {
        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_value(7);
        spin.select_all();
        let len = spin.entry_text().len();
        assert_eq!(spin.entry_selection_range(), Some((0, len)));
        assert_eq!(spin.entry_cursor_position(), len);

        spin.set_entry_cursor_position(0);
        assert_eq!(spin.entry_cursor_position(), 0);
        assert_eq!(spin.entry_selection_range(), None, "placing the caret drops the selection");
        assert_eq!(spin.line_edit().cursor_position(), 0);
    }

    /// The keyboard path reaches the field, so a shifted selection really extends.
    #[test]
    fn navigation_keys_move_the_hosted_fields_caret() {
        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_value(123);
        spin.begin_edit();
        spin.set_entry_cursor_position(0);
        spin.handle_event(&Event::KeyPress { key: 39, modifiers: 0 });
        assert_eq!(spin.entry_cursor_position(), 1);
        // Shift+Right extends from the caret rather than moving it alone.
        spin.handle_event(&Event::KeyPress { key: 39, modifiers: 1 });
        assert_eq!(spin.entry_selection_range(), Some((1, 2)));
    }

    /// A boolean text predicate is exposed and is consulted as the entry is typed.
    #[test]
    fn a_text_validator_predicate_marks_the_entry() {
        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_text_validator(|text| text.parse::<f64>().is_ok_and(|value| value % 2.0 == 0.0));
        spin.begin_edit();
        spin.select_all();
        spin.handle_event(&Event::TextInput { text: "3".into() });
        assert!(!spin.is_valid(), "3 is not an even number by the installed rule");
        assert!(!spin.validation_message().is_empty());
        spin.select_all();
        spin.handle_event(&Event::TextInput { text: "4".into() });
        assert!(spin.is_valid());
    }

    /// A `data_binding::Validator` sees the parsed value and may repair it.
    #[test]
    fn a_numeric_validator_repairs_the_committed_value() {
        #[derive(Debug)]
        struct ClampAtTen;
        impl crate::data_binding::Validator<f64> for ClampAtTen {
            fn validate(&self, value: f64) -> Result<f64, crate::data_binding::ValidationError> {
                Ok(value.min(10.0))
            }
        }

        let mut spin = SpinBox::new(Rect::new(0, 0, 200, 40));
        spin.set_range_f64(0.0, 100.0);
        spin.set_numeric_validator(Some(Box::new(ClampAtTen)));
        spin.begin_edit();
        spin.select_all();
        spin.handle_event(&Event::TextInput { text: "50".into() });
        assert!(spin.commit_edit());
        assert_eq!(spin.value(), 10, "the rule repaired the parsed value");

        // A refusing rule keeps the edit open so the user can correct the text.
        #[derive(Debug)]
        struct RefuseAll;
        impl crate::data_binding::Validator<f64> for RefuseAll {
            fn validate(&self, value: f64) -> Result<f64, crate::data_binding::ValidationError> {
                Err(crate::data_binding::ValidationError::new(format!("refused {value}")))
            }
        }
        spin.set_numeric_validator(Some(Box::new(RefuseAll)));
        spin.begin_edit();
        spin.select_all();
        spin.handle_event(&Event::TextInput { text: "5".into() });
        assert!(!spin.commit_edit());
        assert!(spin.is_editing(), "a refused value stays editable");
    }
}