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
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Single-line text edit widget.
use crate::compat::{Box, Rc, RefCell, String, ToString, Vec};
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::dnd::{DragPayload, DragSource, DropEffect, DropTarget};
#[cfg(test)]
use crate::event::FocusReason;
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::undo::{UndoStack, ValueCommand};
use crate::widget::capability::coercion::{
expect_bool, expect_horizontal_alignment, expect_string, expect_usize,
horizontal_alignment_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::decorations::{
DecorationLayout, DecorationMetrics, DecorationSlots, DECORATION_GAP,
};
use crate::widget::metrics::{
active_profile, dimensions, effective_font, estimate_text_width, profile_metrics,
ControlMetrics,
};
/// Trailing room a text field leaves for the caret, added to the measured value.
const LINE_EDIT_CARET_ROOM: u32 = 10;
/// Narrowest a text field may be, so an empty one is still a field.
const LINE_EDIT_MIN_WIDTH: u32 = 80;
/// Height of a text field.
const LINE_EDIT_HEIGHT: u32 = 24;
/// How long a click counts toward a multi-click streak, in milliseconds.
///
/// Matches the platform convention for double- and triple-click detection: two presses
/// inside this window are one gesture, and a third makes it a line selection.
const MULTI_CLICK_WINDOW_MS: u32 = 400;
/// Width of the opt-in clear button, in logical pixels.
const CLEAR_BUTTON_SIZE: u32 = 16;
use crate::widget::text_utils::{byte_index_of_char, floor_char_boundary};
use crate::widget::widget_trait::InputMethodQuery;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Single-line text edit widget.
pub struct LineEdit {
base: BaseWidget,
text: String,
placeholder_text: String,
max_length: Option<usize>,
echo_mode: EchoMode,
cursor_position: usize,
selection_start: Option<usize>,
read_only: bool,
undo_stack: UndoStack,
history_target: Rc<RefCell<String>>,
/// Whether this field currently owns keyboard focus.
///
/// Tracked here because the caret is only drawn for the focused field, and the
/// library's focus router sends `FocusGained` / `FocusLost` (see
/// `crate::widget::runtime::focus_widget`). Without it the field had no way to
/// know, and the caret was never drawn at all.
focused: bool,
/// The five non-value strings this field shows: `prefix`/`suffix` inside it, and
/// `helper`/`error`/`counter` on the row below.
///
/// Held as one record rather than five fields so a caller assembling a form from a document can
/// replace all five in one step, and so the painted state is one value that can be compared.
decorations: DecorationSlots,
/// The caret's blink state, advanced by [`LineEdit::tick`].
///
/// Borrowed from [`crate::style::CursorBlink`] rather than reimplemented, so this field's caret
/// keeps the tempo and phase logic of every other caret in the crate.
cursor_blink: crate::style::CursorBlink,
/// The rule this field enforces as text arrives, or `None` for a free-form field.
///
/// # Why this is a boxed trait object
///
/// A host that owns a domain type — an order code, a range, a product identifier — has a
/// rule the library cannot enumerate. The field therefore holds the extension point itself
/// rather than a closed enum, and the two shipped grammars implement the same trait. See
/// [`Validator`].
validator: Option<Box<dyn Validator>>,
/// The current three-way outcome, recomputed whenever the value or the rule changes.
///
/// Cached rather than derived on every read so a form that asks `is_valid()` while it
/// builds a frame does not re-run the rule per call.
validation_state: ValidationState,
/// The message for the current invalid value, or `""` when it is valid.
validation_message: &'static str,
/// The validator's value-specific message for the current value, when it supplied one.
///
/// [`Validator::message`] is a static sentence; [`Validator::message_for`] may name the bound
/// and the refused input. Held apart from `validation_message` so the static fallback stays
/// allocation-free and `validation_message()` keeps its published meaning (I-27).
validation_message_detail: Option<String>,
/// Whether the current `error` decoration was written by the validator.
///
/// Only an error the validator set is cleared by it: a caller's own refusal message must
/// not disappear because the text happened to become valid for the field's grammar.
validation_error_active: bool,
/// The uncommitted input-method composition, or `None` when no IME session is active.
/// # Why the preedit is a field of the *field*, and not an overlay widget
///
/// [`crate::widget::input_widgets::ime_preedit::ImePreedit`] draws a composition string with an
/// underline, and that is the right thing to draw — but on its own it is an *overlay*: the string
/// it shows never reaches any text model, so committing it had nowhere to go and the "preedit"
/// could not be edited, cancelled or committed. That is BLUE24 §12 U-5's gap exactly
/// ("how composition strings enter the text model").
///
/// The three methods a real IME needs are [`LineEdit::set_composition`],
/// [`LineEdit::commit_composition`] and [`LineEdit::cancel_composition`], and they are correct
/// **because** the composition is held apart from `text`: while a session is active the field's
/// value must not change (a `text_changed` per keystroke would fire a form's validation on a word
/// the user has not finished typing), and cancelling must restore the text exactly as it was.
composition: Option<String>,
/// How the field's value is aligned within its own box.
///
/// Horizontal only: the value is centred vertically in the field band as a matter of the
/// field'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,
/// Whether a pointer drag is currently extending a selection.
///
/// Set by [`LineEdit::press_at`] and cleared by [`LineEdit::end_drag`]. It exists so a
/// `MouseMove` that is *not* part of a gesture — a bare hover, which arrives on every
/// pointer step over the field — cannot move a caret the user never grabbed.
dragging_selection: bool,
/// Emitted after the widget's text changes: on edit commits, and after an
/// undo/redo restores a snapshot. Not emitted when a programmatic
/// `set_text` is given the text the field already holds.
pub text_changed: Signal1<String>,
/// Emitted when editing ends — the field loses focus or Enter is pressed.
/// Carries no payload.
pub editing_finished: GenericSignal,
/// Emitted when Enter is pressed in the field, after the edit is committed.
pub return_pressed: GenericSignal,
/// Emitted when a context menu is requested at this point in the field.
///
/// The field deliberately does not build a menu: cut/copy/paste items belong to the
/// host's menu implementation, and the same signal serves a right-click and the
/// Menu/Application key. The payload is the request position in window coordinates;
/// the host decides which items apply (a read-only field, for example, offers copy
/// only) and supplies the menu itself.
pub context_menu_requested: Signal1<Point>,
/// Emitted when the selected range changes.
///
/// Carries no payload because the range is read back through
/// [`Self::selection_range`], which is also what a keyboard or pointer extension updates.
pub selection_changed: GenericSignal,
/// Emitted with the new caret byte offset whenever it moves.
pub cursor_position_changed: Signal1<usize>,
/// Emitted when the value changes through a *user* edit path.
///
/// [`Self::text_changed`] fires for every mutation, including a programmatic
/// [`Self::set_text`]; this signal is the user-only half, so a host can tell a keystroke,
/// paste, cut, drop or undo apart from a field refresh. Programmatic writes must not make a
/// form look edited, which is exactly what the undifferentiated signal could not express.
pub text_edited: Signal1<String>,
/// Emitted with the new value whenever undo availability changes.
pub undo_available: Signal1<bool>,
/// Emitted with the new value whenever redo availability changes.
pub redo_available: Signal1<bool>,
/// Emitted with the new value whenever copying the selection becomes possible or impossible.
pub copy_available: Signal1<bool>,
/// Whether a pointer drag may carry the selection out of the field.
///
/// **On** by default, which is what every field did before the switch existed and what
/// [`Self::set_drag_enabled`] documents: a press and drag inside the field selects, and a drag
/// that leaves the box starts moving the selected text. The field, the constructor and the
/// setter all say the same thing (I-03).
drag_enabled: bool,
/// Last availability values announced, so each signal is edge-triggered rather than emitted
/// on every caret move that left it unchanged.
undo_available_announced: bool,
redo_available_announced: bool,
copy_available_announced: bool,
/// Whether the value has been edited since the last programmatic [`Self::set_text`].
///
/// A form can use this to warn about unsaved changes without comparing snapshots.
modified: bool,
/// Whether a clear button is painted at the trailing edge when the field holds text.
///
/// Opt-in because it is a visible change to every field that turns it on; the default
/// keeps a plain field byte for byte.
clear_button_enabled: bool,
/// Whether [`EchoMode::Password`] reveals the value while the field is focused.
///
/// The canonical echo enum is shared with the platform layer, so the fourth echo mode is
/// expressed as a field-level modifier instead of a new enum variant that every backend
/// would have to learn.
password_echo_on_edit: bool,
/// Horizontal scroll offset in logical pixels, for a value wider than the field.
///
/// Zero unless the caret or the pointer has driven the value past the field's trailing
/// edge, so a value that fits paints exactly where it always did.
scroll_x: i32,
/// Clock accumulated from [`Self::tick`], used to measure click streaks.
clock_ms: u32,
/// Number of presses in the current multi-click streak.
press_streak: u8,
/// Clock reading of the most recent press, in milliseconds.
last_press_ms: u32,
/// Bumped whenever an input of the painted string or of its advances changes.
///
/// The value's text, the echo mode, the placeholder and the focus flag all decide what
/// `draw` paints, so each of them advances this revision. The advance cache keys on it, which
/// is what makes its entries unreachable as soon as the string they measured no longer exists.
text_revision: u64,
/// Memoised advances of the painted value, the selection edges and the caret prefix.
///
/// A frame used to shape the same string up to five times: the whole value for its origin,
/// the value again for the caret, one prefix per selection edge, and the caret's prefix. The
/// advances are pure functions of the text, the font, the echo mode and the DPI scale, so the
/// cache reuses them until one of those inputs changes.
text_advances: RefCell<TextAdvanceCache>,
/// Cumulative advances at every character boundary of the field's value.
///
/// The **hit test** and the **scroll bounds** read this table, which is measured with the same
/// context-free ruler ([`estimate_text_width`]) for both. Before it existed, a press built a
/// zero-sized paint backend and shaped the whole value (I-P03), while `ensure_caret_visible`
/// estimated with a different ruler than `draw` measured with (I-P13) — two rulers that drifted
/// apart and made the scroll boundary jitter.
prefix_advances: RefCell<PrefixAdvances>,
/// Memoised decoration layout, keyed by the field box, text revision, DPI and font.
///
/// `draw` asks for the layout once per frame, and every frame used to re-measure the prefix,
/// the suffix and the counter. Issue I-P13.
layout_cache: RefCell<Option<LayoutCacheEntry>>,
/// Memoised value-derived readings: the character count and the usage counter text.
value_readings: RefCell<ValueReadings>,
/// The reactive model value this field consumes through the property bridge.
///
/// Present only after [`LineEdit::bind_text`]. The reverse direction is explicit
/// ([`LineEdit::sync_to_binding`]) because the setter path runs inside the widget borrow, so
/// writing to the model there would re-enter the runtime.
binding: Option<crate::data_binding::Binding<CapabilityValue>>,
}
/// Which of the field's two strings an advance is measured from.
///
/// The caret measures a prefix of the field's **value** while the selection band measures a
/// prefix of what is **painted**; the two differ whenever the echo mode masks the value.
#[derive(Clone, Copy, PartialEq, Eq)]
enum AdvanceSource {
/// The string `draw` paints, after echo mode and placeholder are applied.
Display,
/// The field's own value.
Value,
}
/// Where a value mutation came from, which decides what happens to the undo history.
#[derive(Clone, Copy, PartialEq, Eq)]
enum EditOrigin {
/// A programmatic write: the field is the "saved" state, so no undo entry is recorded and
/// the history that described the previous value is discarded.
Programmatic,
/// A user edit: the previous value is recorded so it can be undone.
User,
}
/// Cumulative advances at every character boundary of the field's value (I-P03).
///
/// Keyed by the same `(revision, font)` pair the paint-time cache uses, so an edit, an echo-mode
/// change or a new font rebuilds the table exactly once. `scale` is fixed at `1.0`, which is the
/// ruler the hit test and the scroll bounds already used — the value's own box is in logical
/// pixels.
#[derive(Default)]
struct PrefixAdvances {
revision: u64,
font: Option<Font>,
/// `(byte offset, cumulative advance)` for every character boundary, from `0` to `len`.
cuts: Vec<(usize, i32)>,
}
impl PrefixAdvances {
/// Rebuilds the table for `text`, measuring each cluster with the shared estimator.
fn rebuild(&mut self, revision: u64, font: &Font, text: &str) {
self.revision = revision;
self.font = Some(font.clone());
self.cuts.clear();
self.cuts.push((0, 0));
let mut advance = 0i32;
for (start, ch) in text.char_indices() {
let end = start + ch.len_utf8();
advance =
advance.saturating_add(estimate_text_width(&text[start..end], font, 1.0) as i32);
self.cuts.push((end, advance));
}
}
/// The total advance of the value.
fn total(&self) -> i32 {
self.cuts.last().map(|(_, advance)| *advance).unwrap_or(0)
}
/// The cumulative advance at `byte`, or `None` when `byte` is not a boundary of the value.
fn advance_at(&self, byte: usize) -> Option<i32> {
let index = self.cuts.partition_point(|(offset, _)| *offset < byte);
match self.cuts.get(index) {
Some((offset, advance)) if *offset == byte => Some(*advance),
_ => None,
}
}
/// How many characters the value has.
fn count(&self) -> usize {
self.cuts.len().saturating_sub(1)
}
/// The byte offset of the boundary that follows `count` characters.
fn byte_at(&self, count: usize) -> usize {
self.cuts.get(count).map(|(offset, _)| *offset).unwrap_or(0)
}
}
/// The memoised decoration layout and the inputs it was derived from (I-P13).
struct LayoutCacheEntry {
field: Rect,
revision: u64,
dpi_bits: u32,
font: Font,
layout: DecorationLayout,
}
/// The character count and usage counter for the current value, memoised per revision (I-P13).
#[derive(Default)]
struct ValueReadings {
revision: u64,
limit: Option<usize>,
count: usize,
counter: Option<String>,
}
/// Memoised advances for the value, the selection edges and the caret prefix.
#[derive(Default)]
struct TextAdvanceCache {
revision: u64,
font: Option<Font>,
echo_mode: Option<EchoMode>,
dpi_bits: u32,
/// `(from, to, advance)` for slices of the painted value.
display: Vec<(usize, usize, i32)>,
/// `(from, to, advance)` for slices of the field's own value.
value: Vec<(usize, usize, i32)>,
}
/// Text echo mode for a line edit.
///
/// Re-exported from [`crate::platform::EchoMode`] — the widget layer and the
/// platform layer name the **same three modes**, so a mode read back from a
/// native control (`widget_echo_mode()`) can be handed straight to this widget
/// with no conversion, and neither copy can drift from the other
/// (principle #54).
///
/// The former local variant `PasswordEchoOnEdit` was removed with this change: it
/// had no consumer outside this file and its "implementation" was a placeholder
/// that behaved exactly like `Password` (principle #5). Adding a real one back
/// means adding it to the canonical enum and to every backend that must honour
/// it.
pub use crate::platform::EchoMode;
/// An input grammar a text field enforces as the user types.
///
/// Defined in [`input_validator`](super::input_validator) and re-exported here so
/// `lineedit::InputValidator` keeps naming it: the field is what carries the grammar.
pub use super::input_validator::InputValidator;
/// The three-way outcome of validating the field's value.
pub use super::input_validator::ValidationState;
/// The rule a field consults while its value changes.
pub use super::input_validator::Validator;
/// The published token naming a [`ValidationState`].
fn validation_state_token(state: ValidationState) -> &'static str {
match state {
ValidationState::Invalid => "invalid",
ValidationState::Intermediate => "intermediate",
ValidationState::Acceptable => "acceptable",
}
}
/// The [`EchoMode`] a published token names, or `None` for an unknown token.
fn echo_mode_from_token(token: &str) -> Option<EchoMode> {
match token {
"normal" => Some(EchoMode::Normal),
"password" => Some(EchoMode::Password),
"no_echo" => Some(EchoMode::NoEcho),
_ => None,
}
}
impl LineEdit {
/// Creates an empty line edit with geometry.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::LineEdit, geometry, "LineEdit"),
text: String::new(),
placeholder_text: String::new(),
max_length: None,
echo_mode: EchoMode::Normal,
cursor_position: 0,
selection_start: None,
read_only: false,
validator: None,
validation_state: ValidationState::Acceptable,
validation_message: "",
validation_message_detail: None,
validation_error_active: false,
undo_stack: UndoStack::new(),
history_target: Rc::new(RefCell::new(String::new())),
focused: false,
decorations: DecorationSlots::default(),
cursor_blink: crate::style::CursorBlink::new(),
composition: None,
alignment: crate::core::Alignment::Left,
dragging_selection: false,
text_changed: Signal1::new(),
editing_finished: GenericSignal::new(),
return_pressed: GenericSignal::new(),
context_menu_requested: Signal1::new(),
selection_changed: GenericSignal::new(),
cursor_position_changed: Signal1::new(),
text_edited: Signal1::new(),
undo_available: Signal1::new(),
redo_available: Signal1::new(),
copy_available: Signal1::new(),
drag_enabled: true,
undo_available_announced: false,
redo_available_announced: false,
copy_available_announced: false,
modified: false,
clear_button_enabled: false,
password_echo_on_edit: false,
scroll_x: 0,
clock_ms: 0,
press_streak: 0,
text_revision: 0,
text_advances: RefCell::new(TextAdvanceCache::default()),
prefix_advances: RefCell::new(PrefixAdvances::default()),
layout_cache: RefCell::new(None),
value_readings: RefCell::new(ValueReadings::default()),
last_press_ms: 0,
binding: None,
}
}
/// Binds this field's `text` property to a reactive model value.
///
/// The initial model value is applied immediately, and (when the field is mounted) later
/// model changes are written through the property contract. Both the slider and the field are
/// the two low-risk controls COMP-26 names as the first consumers of the bridge.
pub fn bind_text(&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, "line_edit.text", id, "text");
return;
}
}
if let CapabilityValue::String(value) = binding.get() {
self.set_text(value);
binding.announce_synced("text");
}
}
/// Pushes this field's current text 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::String(self.text.clone()));
binding.announce_synced("text");
true
}
/// The reactive value this field consumes, if it is bound.
pub fn bound_text(&self) -> Option<&crate::data_binding::Binding<CapabilityValue>> {
self.binding.as_ref()
}
/// Returns current text.
pub fn text(&self) -> &str {
&self.text
}
/// The rule this field enforces, or `None` for a free-form field.
pub fn validator(&self) -> Option<&dyn Validator> {
self.validator.as_deref()
}
/// Installs a host rule, replacing any current one, and revalidates the value.
///
/// This is the extension point for a domain rule the library cannot enumerate. A built-in
/// grammar assigned through [`Self::set_validator`] still works: both paths store the rule
/// in the same box, so the field consults exactly one validator at a time.
pub fn set_dyn_validator(&mut self, validator: Option<Box<dyn Validator>>) {
// A built-in assigned twice is the one case that can be recognised without downcasting,
// so re-applying it does not revalidate and repaint for nothing.
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 current value.
///
/// The `phone_input` / `email_input` constructors are the usual callers; a host that wants
/// one control to switch grammars can use it directly.
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();
}
/// Whether the current value satisfies the field's rule (true without a validator).
pub fn is_valid(&self) -> bool {
self.validation_state.is_acceptable()
}
/// The three-way outcome for the current value.
///
/// `Intermediate` is not a failure: it is a value the user is still assembling, and a form
/// can keep its submit affordance disabled without accusing the user. `Acceptable` is the
/// state a field without a validator always reports.
pub fn validation_state(&self) -> ValidationState {
self.validation_state
}
/// The message for the current non-acceptable value, or `""` when it is acceptable.
pub fn validation_message(&self) -> &'static str {
self.validation_message
}
/// The message for the current non-acceptable value, or `""` when it is acceptable.
///
/// Prefers the rule's value-specific text ([`Validator::message_for`]), so a range refusal can
/// name the bound and the value that missed it (I-27).
pub fn validation_message_text(&self) -> &str {
match self.validation_message_detail.as_deref() {
Some(detail) => detail,
None => self.validation_message,
}
}
/// Applies the validator's own repair to the current value.
///
/// Returns whether the value changed. The repair runs through [`Self::set_text`], so it is
/// undoable and emits `text_changed` like any other programmatic write. A rule with no
/// repair, or a value already in its nearest form, returns `false`.
pub fn fixup(&mut self) -> bool {
let Some(validator) = self.validator.as_deref() else {
return false;
};
let Some(repaired) = validator.fixup(&self.text) else {
return false;
};
if repaired == self.text {
return false;
}
// A repair is an edit the field performs for the user, so it stays undoable: undoing it
// must put back the value the user actually typed.
self.apply_text(repaired, EditOrigin::User);
true
}
/// Recomputes validity and mirrors it into the `error` decoration.
///
/// Only a **definite** refusal is painted as an error. An intermediate value is one the
/// user is still typing, and painting it red turns every entry into an accusation — the
/// three-way state exists precisely so the two cases can be told apart.
///
/// Only a message the validator wrote is cleared here: a caller's own refusal text must
/// survive a value that happens to satisfy the grammar.
fn revalidate(&mut self) {
// The rule is consulted in two short borrows and its answers copied out, so the
// decoration writes below never overlap the borrow of `self.validator`.
let state = match self.validator.as_deref() {
Some(validator) => validator.state(&self.text),
None => ValidationState::Acceptable,
};
let mut message = "";
let mut detail: Option<String> = None;
if let Some(validator) = self.validator.as_deref() {
if !state.is_acceptable() {
message = validator.message();
// A value-specific message is held only when it actually says something else, so
// a rule that inherits the static text costs no allocation (I-27).
let quoted = validator.message_for(&self.text);
if quoted.as_ref() != message {
detail = Some(quoted.into_owned());
}
}
}
self.validation_state = state;
self.validation_message = message;
self.validation_message_detail = detail;
if state.is_invalid() {
let shown = self.validation_message_text();
if self.decorations.error.as_str() != shown {
let mut next = self.decorations.clone();
next.error = shown.to_string();
self.set_decorations(next);
}
self.validation_error_active = true;
} else if self.validation_error_active {
self.validation_error_active = false;
if !self.decorations.error.is_empty() {
let mut next = self.decorations.clone();
next.error.clear();
self.set_decorations(next);
}
}
}
/// How the field's value is aligned within its own box.
pub fn alignment(&self) -> crate::core::Alignment {
self.alignment
}
/// Sets how the field's value is aligned within its own box.
///
/// Horizontal only. A `top`/`bottom` alignment is **ignored**, because the value is centred
/// vertically in the field band by the field'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();
}
/// Returns whether this field currently has keyboard focus.
pub fn is_focused(&self) -> bool {
self.focused
}
/// Sets the focus flag directly.
///
/// The runtime normally drives this through `FocusGained` / `FocusLost`, the same
/// way the other input controls are driven; this setter exists for hosts and tests
/// that need to place focus without an event round-trip.
pub fn set_focused(&mut self, focused: bool) {
if self.focused == focused {
return;
}
self.focused = focused;
self.invalidate_text_advances();
// The caret blinks exactly while the field holds focus, so the blink state is driven from
// the same flag `draw` reads rather than from a parallel notion of "active".
if focused {
self.cursor_blink.start();
} else {
self.cursor_blink.stop();
}
self.base.request_redraw();
}
/// Advances the caret's blink by `delta_ms` and reports whether another frame is needed.
///
/// The crate's `tick(delta_ms) -> bool` convention: `true` while the caret is still cycling, so
/// a host schedules the next frame only for a field that is actually blinking. A blurred field
/// or a read-only one returns `false` immediately — a steady caret has no next frame.
pub fn tick(&mut self, delta_ms: u32) -> bool {
// The clock runs even while blurred: the click streak it measures begins with the press
// that focuses the field, and a stopped clock would make every first click look like a
// continuation of the previous one.
self.clock_ms = self.clock_ms.wrapping_add(delta_ms);
if !self.focused || self.read_only {
return false;
}
let running = self.cursor_blink.tick(delta_ms);
if running {
self.base.request_redraw();
}
running
}
/// Sets text and emits text_changed signal if different.
///
/// This is the **programmatic** entry point: the write is the field's clean state, so it is
/// neither recorded in the undo history nor allowed to leave a history entry that predates it
/// (Ctrl+Z must not jump back to a value the application itself replaced). User edits go
/// through [`Self::insert_str`], [`Self::backspace`] and [`Self::delete`], which record their
/// previous value.
pub fn set_text(&mut self, text: impl Into<String>) {
self.apply_text(text.into(), EditOrigin::Programmatic);
}
/// Filters, clamps and commits `text`, attributing the change to `origin`.
fn apply_text(&mut self, text: String, origin: EditOrigin) -> bool {
// The grammar is a property of the field, not of the typing path: a value it cannot
// represent must not enter the model from a programmatic write either. Surrounding
// whitespace is trimmed here (not on a keystroke, where a space is a separator the
// user is typing *between* groups).
let text = match self.validator.as_deref() {
Some(validator) => validator.filter(&text).trim().to_string(),
None => text,
};
// `max_length` is enforced here as well as in `insert_text`.
//
// # Why the two paths have to agree
//
// `insert_text` clamped to the limit and this did not, so a programmatic `set_text` could leave
// the field holding a longer value than its own limit — and once the `counter` is derived from
// the value and that limit, the two disagreed visibly (`8/5`). A limit the control enforces only
// for typing is not a limit, it is a hint. The truncation goes through `floor_char_boundary`
// because `max_length` counts **characters** and the slice is in bytes.
let text = match self.max_length {
Some(max) if text.chars().count() > max => {
let byte = byte_index_of_char(&text, max);
text[..byte].to_string()
}
_ => text,
};
self.commit_text(text, origin)
}
/// Stores `text` and publishes the consequences, honouring `origin` for history handling.
///
/// Returns whether the value actually changed, so an edit path that produced the same string
/// can avoid reporting an edit that did not happen. The previous value moves into the history
/// record instead of being copied into a scratch string (I-P01).
fn commit_text(&mut self, text: String, origin: EditOrigin) -> bool {
if self.text == text {
return false;
}
let before = core::mem::replace(&mut self.text, text);
self.finish_text_change(before, origin)
}
/// Publishes a value mutation the caller made **in place** on `self.text`.
///
/// `before` is the value as it was before the mutation. The typing paths hand it over rather
/// than cloning the value into a scratch buffer and assigning it back, which is what made a
/// single keystroke allocate the whole string several times (I-P01).
///
/// The grammar and the limit are still enforced here, because they are properties of the
/// field rather than of the typing path; the allocation that needs only happens when one of
/// them is actually installed.
fn commit_in_place(&mut self, before: String, origin: EditOrigin) -> bool {
if let Some(validator) = self.validator.as_deref() {
let filtered = validator.filter(&self.text);
let trimmed = filtered.trim();
if trimmed != self.text {
self.text = trimmed.to_string();
}
}
if let Some(max) = self.max_length {
if self.text.chars().count() > max {
let byte = byte_index_of_char(&self.text, max);
self.text.truncate(byte);
}
}
if self.text == before {
return false;
}
self.finish_text_change(before, origin)
}
/// Publishes the consequences of a value that has already been written to `self.text`.
///
/// `before` is the previous value, moved in from the caller so the undo record does not need
/// a third copy of the string.
fn finish_text_change(&mut self, before: String, origin: EditOrigin) -> bool {
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
self.invalidate_text_advances();
self.revalidate();
match origin {
EditOrigin::User => {
// One copy for the undo command and one for the shared history target: the two
// are separate stores, and both must hold the *post*-edit value.
let after = self.text.clone();
*self.history_target.borrow_mut() = after.clone();
self.undo_stack.push(Box::new(ValueCommand::new(
self.history_target.clone(),
before,
after,
"Edit text",
"line_edit_text",
)));
}
EditOrigin::Programmatic => {
// A programmatic write is the saved state by definition: the history that could
// restore a value before it no longer describes this field.
*self.history_target.borrow_mut() = self.text.clone();
self.undo_stack.clear();
}
}
self.cursor_position = self.text.len();
self.selection_start = None;
if origin == EditOrigin::Programmatic {
self.modified = false;
}
self.ensure_caret_visible();
self.notify_caret_change(before_cursor, before_selection);
self.refresh_edit_capabilities();
self.text_changed.emit(self.text.clone());
self.base.request_redraw();
true
}
/// Undo the latest text mutation.
pub fn undo(&mut self) -> bool {
if self.undo_stack.undo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Redo the latest undone text mutation.
pub fn redo(&mut self) -> bool {
if self.undo_stack.redo().is_err() {
return false;
}
self.restore_history_text();
true
}
/// Returns whether a text mutation can be undone.
pub fn can_undo(&self) -> bool {
self.undo_stack.can_undo()
}
/// Returns whether a text mutation can be redone.
pub fn can_redo(&self) -> bool {
self.undo_stack.can_redo()
}
fn restore_history_text(&mut self) {
let text = self.history_target.borrow().clone();
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
self.text = text;
self.invalidate_text_advances();
self.cursor_position = self.text.len();
self.selection_start = None;
self.modified = true;
self.ensure_caret_visible();
self.notify_caret_change(before_cursor, before_selection);
self.refresh_edit_capabilities();
self.text_changed.emit(self.text.clone());
self.base.request_redraw();
}
/// Returns placeholder text.
pub fn placeholder_text(&self) -> &str {
&self.placeholder_text
}
/// Sets placeholder text.
pub fn set_placeholder_text(&mut self, text: String) {
// A same-value write paints the same placeholder; queueing a frame for it is the
// wheel-spinning the other text setters already avoid (WDGT-15).
if self.placeholder_text == text {
return;
}
self.placeholder_text = text;
self.invalidate_text_advances();
self.base.request_redraw();
}
/// Returns maximum text length **in characters**.
pub fn max_length(&self) -> Option<usize> {
self.max_length
}
/// Sets maximum text length, **in characters**, truncating the value if needed.
///
/// # `max_length` counts characters, so this cannot truncate by byte
///
/// The limit is a character budget: it is what the user typing sees and what
/// [`Self::counter_text`] reports. An earlier revision truncated with
/// `self.text.truncate(max)`, which is a **byte** index — so `"héllo"` (5 chars, 6 bytes)
/// under a limit of 3 was cut to `"hé"` (2 chars) rather than `"hél"`, and a limit that
/// happened to fall inside a multi-byte character would have split it. The truncation
/// therefore goes through [`byte_index_of_char`], the same conversion `insert_text` and
/// `set_text` use, so all three agree about what the limit means.
pub fn set_max_length(&mut self, max_length: Option<usize>) {
if self.max_length == max_length {
return;
}
self.max_length = max_length;
// The counter decoration (and therefore the layout) depends on the limit, so the memoised
// layout and readings are invalidated even when nothing is truncated (I-P13).
self.invalidate_text_advances();
// Truncate if needed
if let Some(max) = max_length {
if self.text.chars().count() > max {
let byte = byte_index_of_char(&self.text, max);
self.text.truncate(byte);
self.clamp_caret();
// A shrinking limit makes every longer value unreachable, so the
// history that could restore one is cleared and the shared target
// is re-synced to the truncated value. Without this, undo/redo
// would re-apply an over-limit string.
*self.history_target.borrow_mut() = self.text.clone();
self.undo_stack.clear();
self.refresh_edit_capabilities();
self.text_changed.emit(self.text.clone());
}
}
self.base.request_redraw();
}
/// The current value's length **in characters**.
///
/// The frame `max_length` and the counter are expressed in, so a limit test never has to
/// compare a character budget against a byte length. Memoised per text revision, because
/// `draw` and `semantic_state` both read it every frame (I-P13).
fn char_count(&self) -> usize {
self.value_readings().0
}
/// The character count and usage counter text for the current value, memoised per revision.
fn value_readings(&self) -> (usize, Option<String>) {
if let Ok(mut cache) = self.value_readings.try_borrow_mut() {
if cache.revision != self.text_revision || cache.limit != self.max_length {
let count = self.text.chars().count();
cache.revision = self.text_revision;
cache.limit = self.max_length;
cache.count = count;
cache.counter = DecorationLayout::counter_text(count, self.max_length);
}
return (cache.count, cache.counter.clone());
}
let count = self.text.chars().count();
(count, DecorationLayout::counter_text(count, self.max_length))
}
/// Snaps the caret and the selection anchor to a real character boundary inside the value.
///
/// The caret is a **byte** offset (that is what a slice needs), while every move the user makes
/// — Left, Right, Backspace, Delete — is a **character** step. Rounding the stored offset down to
/// a boundary after any of those keeps `&text[..cursor]` total without making the caret's own
/// arithmetic guess where a character begins, which is what a bare `+= 1` did: on `"é"` a single
/// Right put the caret *inside* the character, and the next insert then snapped to the end
/// instead of at the position the user had moved to.
fn clamp_caret(&mut self) {
let len = self.text.len();
self.cursor_position = floor_char_boundary(&self.text, self.cursor_position.min(len));
if let Some(start) = self.selection_start {
self.selection_start = Some(floor_char_boundary(&self.text, start.min(len)));
}
}
/// Returns whether the value has been edited since the last programmatic write.
///
/// Typing, pasting, cutting and deleting set this flag; [`Self::set_text`] clears it, so a
/// host can implement a "discard unsaved changes" prompt without holding its own snapshot.
pub fn is_modified(&self) -> bool {
self.modified
}
/// Sets the modified flag, for a host that has just saved the value.
pub fn set_modified(&mut self, modified: bool) {
if self.modified == modified {
return;
}
self.modified = modified;
}
/// Whether a clear button is painted at the trailing edge of the field.
pub fn clear_button_enabled(&self) -> bool {
self.clear_button_enabled
}
/// Enables or disables the trailing clear button.
///
/// The button appears only while the field holds text, and a press on it clears the value
/// through the ordinary edit path (undoable, announced through `text_changed`). Off by
/// default, because it changes the pixels of a field that turns it on.
pub fn set_clear_button_enabled(&mut self, enabled: bool) {
if self.clear_button_enabled == enabled {
return;
}
self.clear_button_enabled = enabled;
self.base.request_redraw();
}
/// Whether the value is revealed while the field is focused in password mode.
pub fn password_echo_on_edit(&self) -> bool {
self.password_echo_on_edit
}
/// Reveals the value while the field is focused in [`EchoMode::Password`].
///
/// This is the fourth echo mode a text field needs: the value is masked while the user is
/// away, and readable while they are typing it. It only affects [`EchoMode::Password`];
/// [`EchoMode::NoEcho`] never paints the value at all.
pub fn set_password_echo_on_edit(&mut self, enabled: bool) {
if self.password_echo_on_edit == enabled {
return;
}
self.password_echo_on_edit = enabled;
self.invalidate_text_advances();
self.base.request_redraw();
}
/// The horizontal scroll offset applied to the value, in logical pixels.
pub fn scroll_x(&self) -> i32 {
self.scroll_x
}
/// Sets the horizontal scroll offset, clamped to the value's own width.
///
/// A value that fits the field always reports zero, so the common case never scrolls.
pub fn set_scroll_x(&mut self, offset: i32) {
let max = self.max_scroll_x();
let offset = offset.clamp(0, max);
if self.scroll_x == offset {
return;
}
self.scroll_x = offset;
self.base.request_redraw();
}
/// Whether the field paints the plain value rather than its mask.
///
/// Password echo on edit reveals only while the field owns focus; every other mode is
/// unaffected.
fn reveals_value(&self) -> bool {
self.echo_mode == EchoMode::Password && self.password_echo_on_edit && self.focused
}
/// Invalidates the memoised advances after an input they depend on changes.
fn invalidate_text_advances(&mut self) {
self.text_revision = self.text_revision.wrapping_add(1);
}
/// The advance of `text[from..to]`, memoised for the current value/echo/font/scale.
///
/// The borrows are `try_borrow`/`try_borrow_mut` so a re-entrant paint (a backend that asks a
/// widget to measure while it is already inside this method) falls back to measuring instead
/// of panicking.
fn cached_advance(
&self,
context: &RenderContext,
source: AdvanceSource,
text: &str,
font: &Font,
from: usize,
to: usize,
) -> i32 {
let dpi_bits = context.dpi_scale().to_bits();
if let Ok(cache) = self.text_advances.try_borrow() {
if cache.revision == self.text_revision
&& cache.echo_mode == Some(self.echo_mode)
&& cache.dpi_bits == dpi_bits
&& cache.font.as_ref() == Some(font)
{
let entries = match source {
AdvanceSource::Display => &cache.display,
AdvanceSource::Value => &cache.value,
};
if let Some((_, _, advance)) =
entries.iter().find(|(start, end, _)| *start == from && *end == to)
{
return *advance;
}
}
}
let advance =
if from < to { context.measure_text(&text[from..to], font).width as i32 } else { 0 };
if let Ok(mut cache) = self.text_advances.try_borrow_mut() {
if cache.revision != self.text_revision
|| cache.echo_mode != Some(self.echo_mode)
|| cache.dpi_bits != dpi_bits
|| cache.font.as_ref() != Some(font)
{
cache.revision = self.text_revision;
cache.echo_mode = Some(self.echo_mode);
cache.dpi_bits = dpi_bits;
cache.font = Some(font.clone());
cache.display.clear();
cache.value.clear();
}
let entries = match source {
AdvanceSource::Display => &mut cache.display,
AdvanceSource::Value => &mut cache.value,
};
// A moved caret or selection adds one entry per distinct offset within a revision, so
// the list is capped. The oldest entry is evicted rather than the whole list dropped:
// clearing it threw away the value's own advance on every 33rd caret move, which is
// the one entry every frame needs (I-P13).
if entries.len() >= 32 {
entries.remove(0);
}
entries.push((from, to, advance));
}
advance
}
/// Reports a caret/selection change to the host when either actually moved.
///
/// Centralised so every path that moves the caret — keyboard, pointer, IME, programmatic
/// writes — has the same notification timing.
fn notify_caret_change(&mut self, before_cursor: usize, before_selection: Option<usize>) {
if self.cursor_position != before_cursor {
self.cursor_position_changed.emit(self.cursor_position);
}
if self.selection_start != before_selection {
self.selection_changed.emit();
}
// Copyability follows the selection and the echo mode, so every caret move is a place it
// can change; `refresh_edit_capabilities` emits only when the answer actually differs.
self.refresh_edit_capabilities();
}
/// Whether the current selection can be copied to the clipboard.
///
/// [`EchoMode::NoEcho`] deliberately contributes nothing (see the copy path), so a selection it
/// hides is not a copyable one.
fn can_copy(&self) -> bool {
self.echo_mode != EchoMode::NoEcho && self.selection_range().is_some()
}
/// Emits the three availability signals when their answers have changed.
fn refresh_edit_capabilities(&mut self) {
let undo = self.can_undo();
if undo != self.undo_available_announced {
self.undo_available_announced = undo;
self.undo_available.emit(undo);
}
let redo = self.can_redo();
if redo != self.redo_available_announced {
self.redo_available_announced = redo;
self.redo_available.emit(redo);
}
let copy = self.can_copy();
if copy != self.copy_available_announced {
self.copy_available_announced = copy;
self.copy_available.emit(copy);
}
}
/// Emits [`Self::text_edited`] when a user gesture actually changed the value.
///
/// The change is read from the text revision instead of comparing against a snapshot taken
/// before the gesture: the snapshot cloned the whole value on **every** key, including the
/// navigation keys that change nothing (I-P01).
fn emit_text_edited_if_revision_moved(&self, revision: u64) {
if self.text_revision != revision {
self.text_edited.emit(self.text.clone());
}
}
/// Returns whether a press at `pos` lands on the clear button's hit area.
fn clear_button_hit(&self, pos: Point) -> bool {
if !self.clear_button_enabled || self.text.is_empty() || self.read_only {
return false;
}
self.clear_button_rect().contains_point(pos)
}
/// The clear button's box, in the field's trailing content corner.
fn clear_button_rect(&self) -> Rect {
let field = self.field_rect();
let padding = dimensions::TEXT_FIELD_PADDING_H as i32;
let size = CLEAR_BUTTON_SIZE as i32;
Rect::new(
(field.x + field.width as i32 - padding - size).max(field.x),
field.y + ((field.height as i32 - size) / 2).max(0),
size as u32,
size as u32,
)
}
/// The widest offset the value can scroll, in pixels.
///
/// Derived from the same measurement the paint uses, so a value that fits reports zero and
/// [`Self::set_scroll_x`] cannot park the value in empty space.
fn max_scroll_x(&self) -> i32 {
if self.text.is_empty() {
return 0;
}
let font = effective_font(self.base.style());
let (_, width) = self.value_box_geometry();
// The same table the hit test reads, so the scrolled origin, the pointer's view of it and
// the paint all describe one ruler (I-P13).
let advance = self.with_prefix_advances(font, |advances| advances.total());
(advance + LINE_EDIT_CARET_ROOM as i32 - width).max(0)
}
/// The value box's left edge and width, measured without a paint context.
fn value_box_geometry(&self) -> (i32, i32) {
let field = self.field_rect();
let font = effective_font(self.base.style());
let padding = dimensions::TEXT_FIELD_PADDING_H as i32;
let gap = DECORATION_GAP as i32;
let inner_left = field.x + padding;
let inner_right = field.x + field.width as i32 - padding;
let prefix_width = if self.decorations.prefix.is_empty() {
0
} else {
estimate_text_width(&self.decorations.prefix, font, 1.0) as i32
};
let suffix_width = if self.decorations.suffix.is_empty() {
0
} else {
estimate_text_width(&self.decorations.suffix, font, 1.0) as i32
};
let left = if prefix_width > 0 { inner_left + prefix_width + gap } else { inner_left };
let clear_room = if self.clear_button_enabled { CLEAR_BUTTON_SIZE as i32 + gap } else { 0 };
let right = if suffix_width > 0 {
inner_right - suffix_width - gap - clear_room
} else {
inner_right - clear_room
};
(left, (right - left).max(0))
}
/// Scrolls the value so the caret is inside the visible box.
///
/// Called after every edit and caret move. A value narrower than the field keeps `scroll_x`
/// at zero, which is what preserves the existing pixels for every non-overflowing value.
fn ensure_caret_visible(&mut self) {
if self.text.is_empty() {
self.scroll_x = 0;
return;
}
let font = effective_font(self.base.style());
let (_, width) = self.value_box_geometry();
let caret = floor_char_boundary(&self.text, self.cursor_position.min(self.text.len()));
// The caret's prefix width comes from the same table the hit test and `draw`'s scroll
// bounds use, instead of a second, differently-rounded estimate (I-P13).
let caret_advance = self.with_prefix_advances(font, |advances| {
advances.advance_at(caret).unwrap_or_else(|| advances.total())
});
let caret_room = LINE_EDIT_CARET_ROOM as i32;
// Reveal the caret with one caret of slack before the trailing edge, which is the same
// slack `size_hint` reserves so the marker never sits on the border.
if caret_advance - self.scroll_x > width - caret_room {
self.scroll_x = (caret_advance - width + caret_room).max(0);
} else if caret_advance < self.scroll_x {
self.scroll_x = caret_advance;
}
self.scroll_x = self.scroll_x.clamp(0, self.max_scroll_x());
}
/// The byte range of the word around `index`, for a double-click selection.
///
/// A word is a run of characters that are not whitespace; a press on whitespace selects the
/// run itself (which is what makes a double-click on a gap select the gap rather than
/// silently doing nothing).
fn word_range_at(&self, index: usize) -> (usize, usize) {
let index = floor_char_boundary(&self.text, index.min(self.text.len()));
// The character the press landed on; at the end of the value the class is taken from the
// character before it, so a double-click on the trailing edge selects the last word.
let sampled = self.text[index..]
.chars()
.next()
.or_else(|| self.text[..index].chars().next_back())
.unwrap_or(' ');
let same_class = |ch: char| ch.is_whitespace() == sampled.is_whitespace();
let mut start = index;
for (i, ch) in self.text[..index].char_indices().rev() {
if !same_class(ch) {
break;
}
start = i;
}
let mut end = index;
for (i, ch) in self.text[index..].char_indices() {
if !same_class(ch) {
break;
}
end = index + i + ch.len_utf8();
}
// A press on the boundary between two words selects the word, not the empty run.
if start == end {
if let Some((i, ch)) = self.text[..index].char_indices().next_back() {
return (i, i + ch.len_utf8());
}
}
(start, end)
}
/// The byte offset of the start of the word before `from`.
fn previous_word_boundary(&self, from: usize) -> usize {
let mut offset = floor_char_boundary(&self.text, from.min(self.text.len()));
while offset > 0 {
let (index, ch) = self.text[..offset].char_indices().next_back().unwrap_or((0, ' '));
if !ch.is_whitespace() {
break;
}
offset = index;
}
while offset > 0 {
let (index, ch) = self.text[..offset].char_indices().next_back().unwrap_or((0, ' '));
if ch.is_whitespace() {
break;
}
offset = index;
}
offset
}
/// The byte offset of the start of the word after `from`.
fn next_word_boundary(&self, from: usize) -> usize {
let mut offset = floor_char_boundary(&self.text, from.min(self.text.len()));
while offset < self.text.len() {
let ch = self.text[offset..].chars().next().unwrap_or(' ');
if !ch.is_whitespace() {
break;
}
offset += ch.len_utf8();
}
while offset < self.text.len() {
let ch = self.text[offset..].chars().next().unwrap_or(' ');
if ch.is_whitespace() {
break;
}
offset += ch.len_utf8();
}
offset
}
/// Returns echo mode.
pub fn echo_mode(&self) -> EchoMode {
self.echo_mode
}
/// Sets echo mode.
pub fn set_echo_mode(&mut self, mode: EchoMode) {
if self.echo_mode == mode {
return;
}
self.echo_mode = mode;
self.invalidate_text_advances();
// NoEcho removes the copyable payload, and the other modes restore it.
self.refresh_edit_capabilities();
self.base.request_redraw();
}
/// Returns cursor position.
pub fn cursor_position(&self) -> usize {
self.cursor_position
}
/// Sets cursor position (a byte offset into the value), snapped to a character boundary.
///
/// The offset is a byte index because that is what a slice needs, but a caller passing an
/// arbitrary number must not be able to leave the caret inside a character — otherwise the next
/// insert would silently round to the end of the value instead of landing where it was put.
pub fn set_cursor_position(&mut self, position: usize) {
let position = floor_char_boundary(&self.text, position.min(self.text.len()));
if self.cursor_position == position && self.selection_start.is_none() {
return;
}
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
self.cursor_position = position;
self.selection_start = None;
self.ensure_caret_visible();
self.notify_caret_change(before_cursor, before_selection);
self.base.request_redraw();
}
/// Returns selection start position.
pub fn selection_start(&self) -> Option<usize> {
self.selection_start
}
/// Returns the selected byte range, if anything is selected.
///
/// This is the spelling `TextArea` and `TextEdit` already publish (WDGT-14), so selection
/// handling can move between the three fields without a per-widget adapter. The ends are
/// snapped to character boundaries and returned low-to-high, which is the same rule
/// [`Self::selected_text`] slices with — the two cannot disagree about what is selected.
/// Returns `None` when the anchor is absent or collapses onto the caret, so an empty selection
/// is not reported as a zero-length range.
pub fn selection_range(&self) -> Option<(usize, usize)> {
let anchor = self.selection_start?;
let len = self.text.len();
let start = floor_char_boundary(&self.text, anchor.min(len));
let end = floor_char_boundary(&self.text, self.cursor_position.min(len));
if start == end {
return None;
}
Some(if start < end { (start, end) } else { (end, start) })
}
/// Selects `length` bytes starting at `start`, clamped to the value.
///
/// Both ends are snapped to character boundaries and clamped to the value's length, so a
/// caller computing a highlight from a search offset cannot leave the selection inside a
/// character. The caret is left at the range's end, which is the convention
/// [`Self::select_all`] and [`Self::select_with_modifiers`] already follow, so a following
/// `Shift`-movement extends from the end the user just selected to.
///
/// The unit matches [`Self::selection_range`] and [`Self::cursor_position`] — **byte**
/// offsets — because those are the offsets this control's public surface already speaks.
/// A zero length clears the selection instead of reporting an empty range.
pub fn set_selection(&mut self, start: usize, length: usize) {
let len = self.text.len();
let start = floor_char_boundary(&self.text, start.min(len));
let end = floor_char_boundary(&self.text, start.saturating_add(length).min(len));
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
if start == end {
self.selection_start = None;
self.cursor_position = start;
} else {
self.selection_start = Some(start);
self.cursor_position = end;
}
self.ensure_caret_visible();
self.notify_caret_change(before_cursor, before_selection);
self.base.request_redraw();
}
/// The selected length **in bytes**, or zero when nothing is selected.
///
/// The same unit as [`Self::set_selection`] and the offsets [`Self::selection_range`] returns.
pub fn selection_length(&self) -> usize {
self.selection_range().map(|(start, end)| end - start).unwrap_or(0)
}
/// Returns selected text.
///
/// The two offsets are snapped to character boundaries before slicing, so a caret left inside a
/// character (by a caller's `set`, or by an older `+= 1` step) reads the characters it actually
/// covers instead of panicking.
pub fn selected_text(&self) -> String {
if let Some(start) = self.selection_start {
let start = floor_char_boundary(&self.text, start.min(self.text.len()));
let end = floor_char_boundary(&self.text, self.cursor_position.min(self.text.len()));
let (start, end) = if start < end { (start, end) } else { (end, start) };
self.text[start..end].to_string()
} else {
String::new()
}
}
/// Selects all text.
pub fn select_all(&mut self) {
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
self.selection_start = Some(0);
self.cursor_position = self.text.len();
self.notify_caret_change(before_cursor, before_selection);
self.base.request_redraw();
}
/// Clears selection.
pub fn clear_selection(&mut self) {
if self.selection_start.is_none() {
return;
}
self.selection_start = None;
self.selection_changed.emit();
self.refresh_edit_capabilities();
self.base.request_redraw();
}
/// Selects `target` (a byte offset) honouring the modifier keys held at the time.
///
/// # What this is the single entry point for
///
/// Every keyboard movement in this field — Left, Right, Home, End — and every pointer
/// gesture funnels through here, so the anchor rule is written once. Before it existed,
/// each of the four movements carried its own copy of the shift test, and a press could
/// not extend at all. The two behaviours are:
///
/// * **Shift** — extend: the caret moves to `target` and the *anchor* stays put, so the
/// selection becomes the range between them. With no anchor yet, the current caret is
/// adopted as the anchor first (`Home` on a fresh field then selects back to the start).
/// * **No modifier** — replace: the caret moves and any selection is dropped.
///
/// # Why Home/End must not re-anchor while extending
///
/// The first cut of this helper re-anchored at the caret before moving, for every key. That
/// made an extension **irreversible**: `Shift+Home` on a caret at 5 selected `0..=5` and left
/// the anchor at 5, so the following `Shift+End` selected `5..=len` rather than sweeping to
/// the end. The anchor belongs to the whole gesture — it is where the gesture *began* — so
/// only a press with no Shift (which starts one) may move it.
///
/// `target` is clamped and snapped to a character boundary, so a caller passing a byte
/// offset computed from a pixel can never put the caret inside a character.
pub fn select_with_modifiers(&mut self, target: usize, modifiers: crate::shortcut::Modifiers) {
let target = floor_char_boundary(&self.text, target.min(self.text.len()));
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
if modifiers.contains(crate::shortcut::Modifiers::SHIFT) {
// Adopt the caret as the anchor only when this extension is the *first* one; a
// gesture already in flight keeps the anchor it started with.
if self.selection_start.is_none() {
self.selection_start = Some(self.cursor_position);
}
self.cursor_position = target;
} else {
self.selection_start = None;
self.cursor_position = target;
}
self.normalize_selection();
self.ensure_caret_visible();
self.notify_caret_change(before_cursor, before_selection);
self.base.request_redraw();
}
/// Places the caret at `pos` and starts a pointer selection.
///
/// A press with no modifier begins a *new* selection anchored at the pressed character:
/// the anchor is where the pointer went down, so dragging away from it selects the span
/// between them (the behaviour every text field has). Holding Shift extends from the
/// existing anchor instead, which is the pointer's version of the same modifier rule
/// [`Self::select_with_modifiers`] applies to the keyboard.
///
/// # Why the anchor is a **character index**, not a position
///
/// `index` is a byte offset and is converted once, here, by `Self::byte_index_at_x`.
/// Pressing past the end of the value is not a no-op: the press anchors at the end and
/// the following drag then selects backwards, which is how a user selects the tail of a
/// value shorter than the field.
pub fn press_at(&mut self, index: usize, modifiers: crate::shortcut::Modifiers) {
let index = floor_char_boundary(&self.text, index.min(self.text.len()));
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
let shift = modifiers.contains(crate::shortcut::Modifiers::SHIFT);
if !shift {
// A press with no Shift **starts** a gesture, so it re-anchors where it landed.
self.selection_start = Some(index);
self.cursor_position = index;
} else {
// A Shift-press **extends**: the anchor is kept (adopted from the caret when the
// gesture is new) and the caret moves to where the pointer went down. Leaving the
// caret alone here — an earlier revision did — made a shift-press a no-op that only
// re-anchored, so `Shift`-clicking to the start of a value selected nothing and a
// following drag grew from a point the user had not pressed.
if self.selection_start.is_none() {
self.selection_start = Some(self.cursor_position);
}
self.cursor_position = index;
}
self.dragging_selection = true;
self.ensure_caret_visible();
self.notify_caret_change(before_cursor, before_selection);
// Deliberately **not** passed through `normalize_selection`.
//
// A press that lands exactly on the caret produces a zero-width anchor/caret pair, and
// collapsing it to "no selection" is right for a *result* — but this is the *start* of a
// gesture, and the anchor is the whole point: the drag that follows grows the range from
// it. Normalising here deleted the anchor the press had just set, so a drag backwards over
// the value selected nothing; the end of the gesture normalises instead.
self.base.request_redraw();
}
/// Extends an in-progress pointer selection to the character at `index`.
///
/// Only a gesture that began with [`Self::press_at`] continues here, so a bare hover —
/// this control is not animated and a `MouseMove` arrives on every pointer step — cannot
/// move a caret the user never grabbed. The anchor is left where the press put it.
pub fn drag_to(&mut self, index: usize) {
if !self.dragging_selection {
return;
}
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
self.cursor_position = floor_char_boundary(&self.text, index.min(self.text.len()));
self.normalize_selection();
self.ensure_caret_visible();
self.notify_caret_change(before_cursor, before_selection);
self.base.request_redraw();
}
/// Ends a pointer selection. Returns whether one was in progress.
///
/// This is where a zero-width gesture is collapsed: a press that never moved leaves the caret
/// exactly on its anchor, and a highlight of no width is not a selection. The collapse happens
/// here, at the end, rather than in [`Self::press_at`] — see the note there, and
/// `Self::normalize_selection`.
pub fn end_drag(&mut self) -> bool {
let was_dragging = core::mem::replace(&mut self.dragging_selection, false);
if was_dragging {
self.normalize_selection();
}
was_dragging
}
/// Collapses a zero-width anchor/caret pair to "no selection".
///
/// A caret that sits exactly on its anchor has selected nothing, but keeping the anchor
/// set would make a later Shift-press extend from a position the user did not choose and
/// leave `selected_text` reporting an empty range. Dropping it here keeps "there is a
/// selection" and "`selected_text` is non-empty" the same statement.
fn normalize_selection(&mut self) {
if self.selection_start == Some(self.cursor_position) {
self.selection_start = None;
}
}
/// The byte offset of the character *before* the caret.
///
/// Delegates to the shared [`crate::widget::text_utils::previous_char_boundary`]: this control,
/// `TextArea`, `TextEdit` and `MentionEdit` all step a caret the same way, and the copies had
/// drifted (WDGT-11).
fn previous_char_boundary(&self) -> usize {
crate::widget::text_utils::previous_char_boundary(&self.text, self.cursor_position)
}
/// The byte offset of the character *after* the caret.
fn next_char_boundary(&self) -> usize {
crate::widget::text_utils::next_char_boundary(&self.text, self.cursor_position)
}
/// The byte offset a horizontal pixel `x` points at.
///
/// # How the pixel is turned into an index
///
/// The value's advances are read from [`PrefixAdvances`] — the same context-free ruler the
/// scroll bounds use — and the caret goes to the boundary nearest the click (I-P03). This used
/// to construct a zero-sized paint backend and shape the whole value on every press and every
/// drag step, i.e. a cold start of the whole measurement stack for the field's most frequent
/// pointer operation. The cache is rebuilt only when the text revision or the font changes, so
/// consecutive clicks and a drag read one table.
///
/// The value is clipped to the same [`Self::value_box_geometry`] box the paint and the press
/// hit-test use, and the result is snapped to a character boundary, which is what keeps
/// `&self.text[..caret]` total when the value contains multi-byte characters.
fn byte_index_at_x(&self, x: i32) -> usize {
if self.text.is_empty() {
return 0;
}
let font = effective_font(self.base.style());
let (left, width) = self.value_box_geometry();
// The pointer's distance from the value's origin, clamped to the value's own box so a
// press on the field's padding (or past the end of a short value) reads as "the nearest
// end" rather than as a negative index.
let dx = (x - left + self.scroll_x).clamp(0, width);
self.with_prefix_advances(font, |advances| {
// The pointer's offset is turned into a character count by the value's own advance,
// exactly as the previous shaping-based implementation did, and then stepped back one
// boundary because the caret sits *before* the character it is nearest. Both numbers
// come from the cached table, so a press measures nothing and allocates nothing.
let total = advances.total().max(1) as f32;
let chars = advances.count().max(1);
let boundary = ((dx as f32 * chars as f32 / total).round() as usize).min(chars);
let boundary = boundary.saturating_sub(1);
advances.byte_at(boundary)
})
}
/// Runs `f` with the value's cumulative advance table, rebuilding it when its inputs moved.
///
/// Falls back to a one-shot table when the cache is already borrowed (a re-entrant paint that
/// asks this field to measure while it is inside the cache), rather than panicking.
fn with_prefix_advances<R>(&self, font: &Font, f: impl FnOnce(&PrefixAdvances) -> R) -> R {
if let Ok(mut cache) = self.prefix_advances.try_borrow_mut() {
if cache.revision != self.text_revision || cache.font.as_ref() != Some(font) {
cache.rebuild(self.text_revision, font, &self.text);
}
return f(&cache);
}
let mut fresh = PrefixAdvances::default();
fresh.rebuild(self.text_revision, font, &self.text);
f(&fresh)
}
/// Inserts text at cursor position.
///
/// # The limit is in characters, so the room left is too
///
/// `max_length` is a **character** budget (it is what the user sees and what the counter
/// reports), but this compared it against `self.text.len()`, a byte length. On `"héllo"` — five
/// characters, six bytes — a limit of six therefore computed `6 - 6 == 0` bytes of room and
/// refused a perfectly legal insert. Counting both sides in characters makes the field accept
/// exactly the value its own counter says it is allowed to hold.
pub fn insert_str(&mut self, text: &str) {
if text.is_empty() {
return;
}
// Check max length and truncate if needed
// The slice is taken through `byte_index_of_char` because the budget is in characters and
// the slice is in bytes, so cutting at the budget's byte offset could split a character.
let effective_text = if let Some(max) = self.max_length {
let available = max.saturating_sub(self.char_count());
if available == 0 {
return;
}
let incoming = text.chars().count();
if incoming > available {
let boundary = byte_index_of_char(text, available);
&text[..boundary]
} else {
text
}
} else {
text
};
// The grammar filters what may enter the model, before the caret/selection math so the
// insertion length is the filtered one. A plain field pays nothing here.
let filtered;
let effective_text = match self.validator.as_deref() {
Some(validator) => {
filtered = validator.filter(effective_text);
filtered.as_str()
}
None => effective_text,
};
// Handle selection, **in place**: the value is edited where it lives instead of being
// cloned into a scratch buffer for every key (I-P01). The pre-edit value is captured once
// because the undo record needs it — nothing else copies the string.
if effective_text.is_empty() && self.selection_start.is_none() {
return;
}
let before = self.text.clone();
if let Some(start) = self.selection_start {
let start = floor_char_boundary(&self.text, start.min(self.text.len()));
let end = floor_char_boundary(&self.text, self.cursor_position.min(self.text.len()));
let (start, end) = if start < end { (start, end) } else { (end, start) };
self.text.replace_range(start..end, effective_text);
self.cursor_position = start + effective_text.len();
} else {
let at = floor_char_boundary(&self.text, self.cursor_position.min(self.text.len()));
self.text.insert_str(at, effective_text);
self.cursor_position = at + effective_text.len();
}
self.selection_start = None;
self.commit_in_place(before, EditOrigin::User);
self.modified = true;
// `set_text` may have clamped the value to `max_length`, which can move the caret it
// recomputed; snap it back onto a boundary inside whatever the field now holds.
self.clamp_caret();
self.ensure_caret_visible();
}
/// Inserts text at the caret.
///
/// # Deprecated
///
/// [`Self::insert_str`] is the name shared by `TextArea` and `TextEdit` (WDGT-14). This alias
/// enters exactly the same path, so migrating is a rename with no behaviour change.
#[deprecated(note = "use `insert_str`, the name shared by the other text fields (WDGT-14)")]
pub fn insert_text(&mut self, text: &str) {
self.insert_str(text);
}
/// Starts or updates an input-method composition without changing the field's value.
///
/// # The three methods an IME session needs, and why they are a set (BLUE24 §12 U-5)
///
/// A platform input method reports a **preedit** (the uncommitted string it is building) and then
/// either commits it or cancels. Mapping that onto a text field takes exactly these three
/// operations, and none of them is expressible as `insert_str`:
///
/// * `set_composition` — the user is still typing. The field's **value must not change**: firing
/// `text_changed` on every keystroke of an unfinished word would run a form's validation
/// against text the user has not committed, which is the defect this separation exists to
/// prevent.
/// * `commit_composition` — the input method accepted its candidate. Now the string enters the
/// model, through the ordinary edit path (so `max_length`, the selection replacement and
/// `text_changed` all apply as they do for any other insert).
/// * `cancel_composition` — the user pressed Escape. The composition is dropped and the value is
/// exactly what it was, because it was never touched.
///
/// An empty string clears the composition without committing it, which is what an input method
/// sends when it withdraws.
pub fn set_composition(&mut self, preedit: &str) {
let next = if preedit.is_empty() { None } else { Some(preedit.to_string()) };
if self.composition == next {
return;
}
self.composition = next;
self.base.request_redraw();
}
/// The uncommitted composition, or `None` when no IME session is active.
pub fn composition(&self) -> Option<&str> {
self.composition.as_deref()
}
/// Whether an input-method composition is in progress.
pub fn has_composition(&self) -> bool {
self.composition.is_some()
}
/// Accepts the composition: the preedit becomes text, through the ordinary insert path.
///
/// Returns `true` when something was committed. A commit with no active composition is a no-op
/// rather than an error: an input method may commit and clear in either order, and a field that
/// refused the second call would report a failure for a normal sequence.
pub fn commit_composition(&mut self) -> bool {
let Some(preedit) = self.composition.take() else {
return false;
};
// Through `insert_text`, so `max_length`, the selection replacement and `text_changed`
// behave exactly as they do for any other insertion — a committed composition is text.
self.insert_str(&preedit);
self.base.request_redraw();
true
}
/// Drops the composition without changing the field's value.
///
/// Returns `true` when there was one. The text is untouched **by construction**, not by
/// restoring a snapshot: the composition was never written into it.
pub fn cancel_composition(&mut self) -> bool {
let had = self.composition.take().is_some();
if had {
self.base.request_redraw();
}
had
}
/// Deletes selected text or the character before the caret.
///
/// # The deletion is one *character*, not one byte
///
/// `new_text.remove(self.cursor_position - 1)` removes the byte before the caret, which on a
/// multi-byte character deletes a fragment of it — and panics outright when the caret sits
/// immediately after a multi-byte character, because `cursor_position - 1` is then inside that
/// character and `String::remove` requires a boundary. Stepping back to the previous character's
/// start deletes the whole thing, which is what a user means by “backspace”.
pub fn backspace(&mut self) {
if let Some(start) = self.selection_start {
// Delete selection
let start = floor_char_boundary(&self.text, start.min(self.text.len()));
let end = floor_char_boundary(&self.text, self.cursor_position.min(self.text.len()));
let (start, end) = if start < end { (start, end) } else { (end, start) };
if start == end {
// An empty selection is not a deletion; fall through to the character case.
self.selection_start = None;
self.backspace();
return;
}
let before = self.text.clone();
self.text.replace_range(start..end, "");
self.cursor_position = start;
self.selection_start = None;
self.commit_in_place(before, EditOrigin::User);
self.modified = true;
} else if self.cursor_position > 0 {
// Delete the character before the caret, from its own start to the caret.
let caret = floor_char_boundary(&self.text, self.cursor_position.min(self.text.len()));
let previous =
self.text[..caret].char_indices().next_back().map(|(index, _)| index).unwrap_or(0);
let before = self.text.clone();
self.text.replace_range(previous..caret, "");
self.cursor_position = previous;
self.commit_in_place(before, EditOrigin::User);
self.modified = true;
}
}
/// Deletes selected text or the character after the caret.
pub fn delete(&mut self) {
if let Some(_start) = self.selection_start {
// Delete selection
self.backspace(); // Same logic
} else if self.cursor_position < self.text.len() {
// Delete the *character* after the caret, not the single byte it starts on.
let caret = floor_char_boundary(&self.text, self.cursor_position.min(self.text.len()));
let next = self.text[caret..]
.char_indices()
.nth(1)
.map(|(index, _)| caret + index)
.unwrap_or(self.text.len());
let before = self.text.clone();
self.text.replace_range(caret..next, "");
self.commit_in_place(before, EditOrigin::User);
self.modified = true;
}
}
/// Returns whether the line edit is read-only.
pub fn is_read_only(&self) -> bool {
self.read_only
}
/// Sets the read-only state.
///
/// Repaints because the state is draw-visible: a read-only field suppresses the caret (see
/// [`Draw`]), so toggling it without a redraw left the marker on a field that had just become
/// uneditable — or, going the other way, left the user with no caret in a field they could now
/// type into.
pub fn set_read_only(&mut self, ro: bool) {
if self.read_only == ro {
return;
}
self.read_only = ro;
self.base.request_redraw();
}
/// Clears all text.
pub fn clear(&mut self) {
self.set_text(String::new());
}
/// Whether the selected text may be dragged out of the field.
pub fn drag_enabled(&self) -> bool {
self.drag_enabled
}
/// Enables or disables dragging the selection out of the field.
///
/// On by default, which is the behaviour every field had before the switch existed: a press
/// and drag inside the field selects, and a drag that leaves the box starts moving the
/// selected text. A host that wants the gesture to stay inside the field turns it off. The
/// switch is not draw-visible, so it queues no frame.
pub fn set_drag_enabled(&mut self, enabled: bool) {
if self.drag_enabled == enabled {
return;
}
self.drag_enabled = enabled;
}
/// The published spelling of an [`EchoMode`].
fn echo_mode_token(mode: EchoMode) -> &'static str {
match mode {
EchoMode::Normal => "normal",
EchoMode::Password => "password",
EchoMode::NoEcho => "no_echo",
}
}
/// The `*`-masked form of `text`, as [`EchoMode::Password`] presents it.
///
/// One definition for the two readers that must agree: the paint path
/// (`LineEdit::draw`) and the clipboard path copies with it, so a copy can never mask the
/// value differently from the way the field drew it.
fn mask_text(text: &str) -> String {
// One star per **character**: `len()` is a byte count, so a password containing a
// multi-byte character produced several stars per character and the mask's length did not
// match the value's (I-02).
"*".repeat(text.chars().count())
}
/// The text a copy or cut gesture may place on the platform clipboard, or `None`
/// when the echo mode forbids copying the value at all.
///
/// # Why masking is not only a paint concern
///
/// The system clipboard is process-global: anything written to it is readable by every
/// other application. So [`EchoMode`] has to gate the copy path as well as the drawing
/// path — a masked field that copied the real value would leak the plaintext the moment a
/// user selected it and pressed Copy, and the mask on screen would have been the only
/// thing that was ever masked. The masked form is exactly what the field paints, so the
/// clipboard never carries more than the screen shows, and [`EchoMode::NoEcho`], which
/// shows nothing, copies nothing.
#[cfg(not(alloc_frugal))]
fn clipboard_selection(&self) -> Option<String> {
let selection = self.selected_text();
if selection.is_empty() {
return None;
}
match self.echo_mode {
EchoMode::Normal => Some(selection),
EchoMode::Password => Some(Self::mask_text(&selection)),
EchoMode::NoEcho => None,
}
}
/// Copy the current selection to the platform clipboard (no-op when empty).
///
/// The clipboard receives [`LineEdit::clipboard_selection`] rather than
/// [`LineEdit::selected_text`], so a masked field copies its mask.
#[cfg(not(alloc_frugal))]
fn copy_selection_to_clipboard(&self) {
if let Some(text) = self.clipboard_selection() {
crate::set_clipboard_text(&text);
}
}
/// The text a copy or cut gesture may place on the platform clipboard, or `None`
/// The field the control actually paints.
///
/// # Why the field is not the control's rectangle
///
/// A text field is a *fixed-height band*: the active profile's text-field height is the
/// content floor every field in this crate shares — Material and Cupertino's 48 px, or
/// macOS's compact 22 px. Painting `rect` made a 240x120 census cell a 240x120 white
/// slab — a rectangle pretending to be a field — and it also made `size_hint`'s 24 disagree
/// with the ink by a factor of five. [`ControlMetrics::full_width_band`] keeps the full
/// width, takes the profile's height and centres it, which is exactly what stops a field
/// from drawing as a 120 px panel.
///
/// Everything the control paints **and everything it hit-tests** is placed from this
/// one box, so the clickable area cannot drift away from the ink.
fn field_rect(&self) -> Rect {
ControlMetrics::full_width_band(
self.geometry(),
profile_metrics(active_profile()).text_field_min_height,
)
}
// ---------------------------------------------------------------------------
// Decoration slots
// ---------------------------------------------------------------------------
/// Returns the five decoration strings this field shows.
pub fn decorations(&self) -> &DecorationSlots {
&self.decorations
}
/// Replaces the whole decoration set at once.
///
/// Prefer the individual setters when only one slot changes; this exists because a caller
/// assembling a form from a document has all five at once and five separate calls would repaint
/// five times.
pub fn set_decorations(&mut self, decorations: DecorationSlots) {
let changed = self.decorations != decorations;
self.decorations = decorations;
if changed {
// The slots decide the value's box and the support row, so the memoised layout is
// stale as soon as they change (I-P13).
self.invalidate_text_advances();
self.base.request_layout();
self.base.request_redraw();
}
}
/// Returns the unit marker written before the value.
pub fn prefix(&self) -> &str {
&self.decorations.prefix
}
/// Sets the unit marker written before the value.
///
/// # Why this does not touch `text`
///
/// The prefix is **chrome**, not content: it is drawn in its own box, so the caret can still sit at
/// the start of what the user is editing and a select-all copies the value alone. Folding it into
/// `text` would make all three of those wrong while looking the same on screen.
pub fn set_prefix(&mut self, prefix: impl Into<String>) {
let mut next = self.decorations.clone();
next.prefix = prefix.into();
self.set_decorations(next);
}
/// Returns the unit marker written after the value.
pub fn suffix(&self) -> &str {
&self.decorations.suffix
}
/// Sets the unit marker written after the value, anchored to the field's trailing edge.
pub fn set_suffix(&mut self, suffix: impl Into<String>) {
let mut next = self.decorations.clone();
next.suffix = suffix.into();
self.set_decorations(next);
}
/// Returns the quiet hint shown below the field.
pub fn helper_text(&self) -> &str {
&self.decorations.helper
}
/// Sets the quiet hint shown below the field, displaced by any error.
pub fn set_helper_text(&mut self, helper: impl Into<String>) {
let mut next = self.decorations.clone();
next.helper = helper.into();
self.set_decorations(next);
}
/// Returns the refusal message shown below the field.
pub fn error_text(&self) -> &str {
&self.decorations.error
}
/// Sets the refusal message, which displaces the helper and paints in the theme's error colour.
///
/// Pass an empty string to clear it. This does not *validate* anything — it is the caller's report
/// — but [`Self::set_max_length`] does drive the counter and the over-limit state on its own,
/// because the field knows both numbers itself.
pub fn set_error_text(&mut self, error: impl Into<String>) {
let mut next = self.decorations.clone();
next.error = error.into();
self.set_decorations(next);
}
/// Returns the usage counter shown at the field's trailing lower edge, if any.
///
/// Derived from the value's length and `max_length` rather than stored, so it cannot go stale: a
/// counter the caller has to keep in step with the text is a counter that will disagree with it.
pub fn counter_text(&self) -> Option<String> {
self.value_readings().1
}
/// Returns whether the current value exceeds `max_length`.
///
/// The field's own answer, so an over-long value is *reported* rather than silently truncated.
pub fn is_over_limit(&self) -> bool {
DecorationLayout::over_limit(self.char_count(), self.max_length) > 0
}
/// The boxes the field's five regions occupy, measured for the current font.
///
/// # Why the layout is computed from `field_rect()` and not from `geometry()`
///
/// The decoration slots belong to the **field**, which on a tall control is a band centred inside
/// it. Measuring from the control's rectangle would put the helper row under the control instead of
/// under the field, and the support row would be as wide as the cell rather than as the input.
fn decoration_layout(&self, context: &mut RenderContext) -> DecorationLayout {
let field = self.field_rect();
let style = self.base.style();
// The effective font, taken through the shared accessor so this layout, `byte_index_at_x`
// and `draw` all measure with one font (D09-STYLE-02).
let font = effective_font(style);
let dpi_bits = context.dpi_scale().to_bits();
// The layout depends on the field box, the font, the DPI and the five decoration slots
// (plus the counter, which follows the value and the limit). All of those advance
// `text_revision`, so one revision comparison covers the whole input (I-P13).
if let Ok(cache) = self.layout_cache.try_borrow() {
if let Some(entry) = cache.as_ref() {
if entry.field == field
&& entry.revision == self.text_revision
&& entry.dpi_bits == dpi_bits
&& entry.font == *font
{
return entry.layout;
}
}
}
let metrics = DecorationMetrics::measure(&self.decorations, |text| {
context.measure_text(text, font).width
});
let counter_width =
self.counter_text().map(|text| context.measure_text(&text, font).width).unwrap_or(0);
let line_height = font.effective_line_height().max(1.0) as u32;
let layout = DecorationLayout::compute(
field,
dimensions::TEXT_FIELD_PADDING_H,
line_height,
DECORATION_GAP,
metrics,
counter_width,
&self.decorations,
);
if let Ok(mut cache) = self.layout_cache.try_borrow_mut() {
*cache = Some(LayoutCacheEntry {
field,
revision: self.text_revision,
dpi_bits,
font: font.clone(),
layout,
});
}
layout
}
/// The caret's window rectangle and byte offset, as a native IME asks for them.
///
/// # Why this is measured without a `RenderContext`
///
/// The IME query is answered on a `&self` borrow between frames, when no paint context is
/// available. [`estimate_text_width`] is the crate's context-free model of the renderer's
/// ruler, and [`crate::render::fitted_origin`] is the same origin function `draw` lays the
/// value out with, so the reported caret rides with the glyphs instead of drifting from them.
/// The box arithmetic mirrors [`DecorationLayout::compute`]: the prefix and suffix slots keep
/// their own edges, and the value — and therefore the caret — is placed between them.
fn caret_query(&self) -> InputMethodQuery {
let field = self.field_rect();
let font = effective_font(self.base.style());
let padding = dimensions::TEXT_FIELD_PADDING_H as i32;
let gap = DECORATION_GAP as i32;
let inner_left = field.x + padding;
let inner_right = field.x + field.width as i32 - padding;
let prefix_width = if self.decorations.prefix.is_empty() {
0
} else {
estimate_text_width(&self.decorations.prefix, font, 1.0) as i32
};
let suffix_width = if self.decorations.suffix.is_empty() {
0
} else {
estimate_text_width(&self.decorations.suffix, font, 1.0) as i32
};
let value_left =
if prefix_width > 0 { inner_left + prefix_width + gap } else { inner_left };
let value_right =
if suffix_width > 0 { inner_right - suffix_width - gap } else { inner_right };
let value_width = (value_right - value_left).max(0) as u32;
// The same value box and alignment `draw` uses, so a centred or right-aligned value keeps
// its caret on its own glyphs rather than at the field's leading edge.
let fit = crate::render::TEXT_FIT_MARGIN as i32;
let value_box = Rect::new(
value_left - fit,
field.y,
value_width.saturating_add((fit * 2) as u32),
field.height,
);
let value_align = self.alignment.to_horizontal().unwrap_or(HorizontalAlignment::Left);
// The text the field paints, which is what the value's advance is measured from. The
// caret's prefix is measured from `text` itself, exactly as `draw` does, so a masked
// field still reports the position of the caret in its own value.
let masked: String;
let display_text: &str = if self.text.is_empty() && !self.placeholder_text.is_empty() {
&self.placeholder_text
} else {
match self.echo_mode {
EchoMode::Normal => &self.text,
EchoMode::NoEcho => "",
EchoMode::Password => {
masked = Self::mask_text(&self.text);
&masked
}
}
};
let value_advance = estimate_text_width(display_text, font, 1.0) as i32;
let value_origin = crate::render::fitted_origin(value_box, value_advance, value_align);
let caret_byte = floor_char_boundary(self.text.as_str(), self.cursor_position);
// The caret's prefix advance comes from the same table the pointer hit test and the scroll
// bounds read, so the IME window, the pointer and the paint agree (I-P13).
let prefix_advance = self.with_prefix_advances(font, |advances| {
advances.advance_at(caret_byte).unwrap_or_else(|| advances.total())
});
let caret_x = (value_origin.x + prefix_advance - self.scroll_x)
.min(value_left + value_width as i32)
.max(value_left);
// The caret spans the field's content band, inset so it does not touch the border — the
// same two-pixel inset `draw` uses.
let caret_top = field.y + 2;
let caret_height = field.height.saturating_sub(4).max(1);
InputMethodQuery {
caret_rect: Rect::new(caret_x, caret_top, 1, caret_height),
caret_byte: Some(caret_byte),
}
}
}
// Implement Widget trait
impl Widget for LineEdit {
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
}
/// Reports the caret an IME candidate window should anchor to while this field is focused.
///
/// A text field always has an insertion point, so the answer is always `Some`; the rectangle
/// is derived from the same field band and font the paint path uses.
fn input_method_query(&self) -> Option<InputMethodQuery> {
Some(self.caret_query())
}
/// Turns a context-menu request into this field's signal.
///
/// The field knows the point and the selection; the host knows the menu. Emitting the
/// request (rather than opening a popup here) keeps the cut/copy/paste policy in one
/// place and lets the same signal serve a right-click and a keyboard request.
fn context_menu_event(&mut self, pos: Point) -> bool {
self.context_menu_requested.emit(pos);
true
}
/// A selected value is the field's drag payload.
///
/// The payload uses the `text/plain` type so a drag can land in any other text control
/// without an adapter. A masked field contributes its mask, exactly as copy does.
fn drag_source_mut(&mut self) -> Option<&mut dyn DragSource> {
Some(self)
}
/// The field accepts plain text dropped at the pointer.
fn drop_target_mut(&mut self) -> Option<&mut dyn DropTarget> {
Some(self)
}
fn size_hint(&self) -> Size {
// The shared estimate plus the caret's own trailing room, rather than `len() * 8 + 10`.
// The 10 px was making the same point — a text field leaves the caret somewhere to be —
// but the multiplier was a byte count, so any non-ASCII value asked for three times the
// width it would draw. The font is the **effective** one the draw path uses (D09-STYLE-02),
// so a text scale or custom face moves the hint and the ink together.
let font = effective_font(self.style());
let text_w = estimate_text_width(self.text(), font, 1.0) + LINE_EDIT_CARET_ROOM;
Size::new(text_w.max(LINE_EDIT_MIN_WIDTH), LINE_EDIT_HEIGHT)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
// The caret blink is the whole animation: without a trait-visible `tick` a host holding
// `&mut dyn Widget` could not advance it, so the caret never blinked on screen.
fn tick(&mut self, delta_ms: u32) -> bool {
LineEdit::tick(self, delta_ms)
}
fn is_animating(&self) -> bool {
self.focused && !self.read_only
}
/// Reports the **interaction** state: `Disabled` when inert, else pressed / hovered / focused.
///
/// # Why the refusal is no longer reported here
///
/// This used to return `Error` while the field carried a refusal message. That made the
/// refusal and the interaction compete for one value, and the interaction won whenever the
/// pointer was over the field — so `"line_edit:error"` stopped applying exactly when the user
/// moved the pointer onto the field to see what was wrong. The meaning moved to
/// [`Self::semantic_state`], which is orthogonal and so holds at the same time as `Hover`.
///
/// `Disabled` still outranks everything: an inert field cannot be interacted with, so the
/// interaction channel is what describes it, and the meaning channel reports the refusal
/// separately.
fn widget_state(&self) -> crate::style::WidgetState {
use crate::style::WidgetState;
if !self.base.is_enabled() {
return WidgetState::Disabled;
}
if self.base.is_pressed() {
WidgetState::Pressed
} else if self.base.is_hovered() {
WidgetState::Hover
} else if self.base.draws_focus_ring() {
WidgetState::Focused
} else {
WidgetState::Normal
}
}
/// Reports the field's **meaning**: `Error` while it carries a refusal or is over its limit.
///
/// The other half of the split [`Widget::widget_state`] documents. The two are independent, so
/// a hovered refusal keeps the hover fill **and** the error border — which is what the plan's
/// criterion asks for and what a single-valued chain could not express.
fn semantic_state(&self) -> crate::style::SemanticState {
if !self.decorations.error.is_empty() || self.is_over_limit() {
return crate::style::SemanticState::Error;
}
crate::style::SemanticState::None
}
/// 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 {
"text_changed" => {
Some(EventSignalRef::mapped("text_changed", &self.text_changed, |v| {
CapabilityValue::String(v.clone())
}))
}
"editing_finished" => {
Some(EventSignalRef::unit("editing_finished", &self.editing_finished))
}
"return_pressed" => Some(EventSignalRef::unit("return_pressed", &self.return_pressed)),
"context_menu_requested" => Some(EventSignalRef::mapped(
"context_menu_requested",
&self.context_menu_requested,
|v| CapabilityValue::String(format!("{v:?}")),
)),
"selection_changed" => {
Some(EventSignalRef::unit("selection_changed", &self.selection_changed))
}
"cursor_position_changed" => Some(EventSignalRef::mapped(
"cursor_position_changed",
&self.cursor_position_changed,
|v| CapabilityValue::UInt(*v as u64),
)),
"text_edited" => Some(EventSignalRef::mapped("text_edited", &self.text_edited, |v| {
CapabilityValue::String(v.clone())
})),
"undo_available" => {
Some(EventSignalRef::mapped("undo_available", &self.undo_available, |v| {
CapabilityValue::Bool(*v)
}))
}
"redo_available" => {
Some(EventSignalRef::mapped("redo_available", &self.redo_available, |v| {
CapabilityValue::Bool(*v)
}))
}
"copy_available" => {
Some(EventSignalRef::mapped("copy_available", &self.copy_available, |v| {
CapabilityValue::Bool(*v)
}))
}
_ => None,
}
}
}
/// `LineEdit`'s property contract.
///
/// # The decoration slots
///
/// `prefix`, `suffix`, `helper`, `error` and `counter` are all published here. They are the five strings
/// a text entry shows that are **not** its value, and before they existed the control could only be
/// announced and driven by its text and placeholder.
///
/// `counter` is published read-only: it is derived from the value's own length and `max_length`, so a
/// caller that could write it would be able to make the count disagree with the text it counts.
///
/// `echo_mode` is intentionally absent: the centralised layer never exposed it,
/// so publishing it here would add a property rather than preserve one.
impl WidgetProperties for LineEdit {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"text" => Ok(CapabilityValue::String(self.text().to_string())),
"placeholder_text" => Ok(CapabilityValue::String(self.placeholder_text().to_string())),
"max_length" => match self.max_length() {
Some(len) => Ok(CapabilityValue::UInt(len as u64)),
None => Ok(CapabilityValue::Null),
},
"read_only" => Ok(CapabilityValue::Bool(self.is_read_only())),
"cursor_position" => Ok(CapabilityValue::UInt(self.cursor_position() as u64)),
"echo_mode" => {
Ok(CapabilityValue::String(Self::echo_mode_token(self.echo_mode()).to_string()))
}
"prefix" => Ok(CapabilityValue::String(self.prefix().to_string())),
"suffix" => Ok(CapabilityValue::String(self.suffix().to_string())),
"helper" => Ok(CapabilityValue::String(self.helper_text().to_string())),
"error" => Ok(CapabilityValue::String(self.error_text().to_string())),
"counter" => match self.counter_text() {
Some(text) => Ok(CapabilityValue::String(text)),
None => Ok(CapabilityValue::Null),
},
"over_limit" => Ok(CapabilityValue::Bool(self.is_over_limit())),
"valid" => Ok(CapabilityValue::Bool(self.is_valid())),
"validation_state" => Ok(CapabilityValue::String(
validation_state_token(self.validation_state()).to_string(),
)),
"validation_message" => {
Ok(CapabilityValue::String(self.validation_message_text().to_string()))
}
"alignment" => Ok(CapabilityValue::String(
horizontal_alignment_to_str(self.alignment()).to_string(),
)),
"modified" => Ok(CapabilityValue::Bool(self.is_modified())),
"clear_button_enabled" => Ok(CapabilityValue::Bool(self.clear_button_enabled())),
"password_echo_on_edit" => Ok(CapabilityValue::Bool(self.password_echo_on_edit())),
"drag_enabled" => Ok(CapabilityValue::Bool(self.drag_enabled())),
"scroll_x" => Ok(CapabilityValue::Int(self.scroll_x() as i64)),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"text" => {
self.set_text(expect_string(value)?);
Ok(())
}
"placeholder_text" => {
self.set_placeholder_text(expect_string(value)?);
Ok(())
}
"max_length" => {
match value {
CapabilityValue::Null => self.set_max_length(None),
other => self.set_max_length(Some(expect_usize(other)?)),
}
Ok(())
}
"read_only" => {
self.set_read_only(expect_bool(value)?);
Ok(())
}
"echo_mode" => {
let token = expect_string(value)?;
let mode = echo_mode_from_token(&token).ok_or(CapabilityAccessError::OutOfRange)?;
self.set_echo_mode(mode);
Ok(())
}
"prefix" => {
self.set_prefix(expect_string(value)?);
Ok(())
}
"suffix" => {
self.set_suffix(expect_string(value)?);
Ok(())
}
"helper" => {
self.set_helper_text(expect_string(value)?);
Ok(())
}
"error" => {
self.set_error_text(expect_string(value)?);
Ok(())
}
// Derived from the value and the limit: a writer would be a second way to say what the
// text already determines, and one of the two would be able to disagree.
"counter" | "over_limit" => Err(CapabilityAccessError::ReadOnlyProperty),
// Derived from the value and the field's grammar, exactly like the two above.
"valid" | "validation_state" | "validation_message" => {
Err(CapabilityAccessError::ReadOnlyProperty)
}
"cursor_position" => {
self.set_cursor_position(expect_usize(value)?);
Ok(())
}
"alignment" => {
self.set_alignment(expect_horizontal_alignment(value)?);
Ok(())
}
"modified" => {
self.set_modified(expect_bool(value)?);
Ok(())
}
"clear_button_enabled" => {
self.set_clear_button_enabled(expect_bool(value)?);
Ok(())
}
"password_echo_on_edit" => {
self.set_password_echo_on_edit(expect_bool(value)?);
Ok(())
}
"drag_enabled" => {
self.set_drag_enabled(expect_bool(value)?);
Ok(())
}
"scroll_x" => {
let offset = match value {
CapabilityValue::Int(v) => v as i32,
CapabilityValue::UInt(v) => v as i32,
_ => return Err(CapabilityAccessError::TypeMismatch),
};
self.set_scroll_x(offset);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
// Mirrors `LINE_EDIT_PROPERTIES`.
property_names_of![
"text",
"placeholder_text",
"max_length",
"read_only",
"echo_mode",
"cursor_position",
"prefix",
"suffix",
"helper",
"error",
"counter",
"over_limit",
"valid",
"validation_state",
"validation_message",
"alignment",
"modified",
"clear_button_enabled",
"password_echo_on_edit",
"drag_enabled",
"scroll_x",
BASE_PROPERTY_NAMES
]
}
/// Runs one of the commands `line_edit` publishes.
///
/// Both are zero-argument actions with a direct method on the control, so both
/// run rather than being routed through the property path: `clear` assigns the
/// empty text and `select_all` selects without changing it.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"clear" => {
self.clear();
Ok(())
}
"select_all" => {
self.select_all();
Ok(())
}
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl LineEdit {
/// Routes a key event through the shared selection entry point instead of mutating
/// `selection_start` directly.
///
/// # Why the dispatch was pulled out of `handle_event`
///
/// The four arrows and Home/End each carried their own copy of the shift test — six
/// copies of one rule, each free to drift from the others. They now all call
/// [`LineEdit::select_with_modifiers`] (the same entry point the pointer gesture uses),
/// so what Shift means is written once (principle #101: one concept, one path).
///
/// The helper is inherent rather than a trait method because `EventHandler` declares
/// only `handle_event`; the trait impl below is a thin façade over it.
///
/// Returns whether the key was consumed. A key this field does not handle leaves the
/// event to the rest of the chain rather than being silently swallowed.
fn handle_key(&mut self, key: u32, modifiers: crate::shortcut::Modifiers) -> bool {
match key {
8 => {
// Backspace
self.backspace();
}
46 => {
// Delete
self.delete();
}
13 => {
// Enter/Return
self.return_pressed.emit();
self.editing_finished.emit();
}
27 => {
// Escape
self.editing_finished.emit();
}
37 => {
// Left arrow. A plain press deselects and steps one character back; a
// Shift press extends from the anchor rather than replacing it, so the
// range grows instead of collapsing to a caret (see `select_with_modifiers`).
// Primary (Ctrl/Cmd) steps by **word**, which is the convention every desktop
// text field follows; the boundary helper only walks when it is held.
let by_word = modifiers.contains(crate::shortcut::Modifiers::PRIMARY);
if self.cursor_position > 0 {
let target = if by_word {
self.previous_word_boundary(self.cursor_position)
} else {
self.previous_char_boundary()
};
self.select_with_modifiers(target, modifiers);
} else if !modifiers.contains(crate::shortcut::Modifiers::SHIFT) {
// Already at the start, and no Shift: the key cannot move the caret, but it
// still owes the user the deselect every other plain press performs. It used
// to be dropped entirely, which left a stale range alive after an arrow press
// that plainly meant "just move". A Shift press here has nothing to extend to.
self.clear_selection();
self.base.request_redraw();
}
}
39 => {
// Right arrow. Same contract as Left, stepping forward.
let by_word = modifiers.contains(crate::shortcut::Modifiers::PRIMARY);
if self.cursor_position < self.text.len() {
let target = if by_word {
self.next_word_boundary(self.cursor_position)
} else {
self.next_char_boundary()
};
self.select_with_modifiers(target, modifiers);
} else if !modifiers.contains(crate::shortcut::Modifiers::SHIFT) {
// Already at the end: see the Left arm — the deselect still applies.
self.clear_selection();
self.base.request_redraw();
}
}
36 => {
// Home
self.select_with_modifiers(0, modifiers);
}
35 => {
// End
self.select_with_modifiers(self.text.len(), modifiers);
}
65 if modifiers.contains(crate::shortcut::Modifiers::PRIMARY) => {
// Primary+A: Select all
self.select_all();
}
86 if modifiers.contains(crate::shortcut::Modifiers::PRIMARY) => {
// Primary+V: Paste from the platform clipboard.
#[cfg(not(alloc_frugal))]
{
let pasted = crate::get_clipboard_text();
if !pasted.is_empty() {
self.insert_str(&pasted);
}
}
#[cfg(alloc_frugal)]
{
// Clipboard integration is unavailable in the mini profile.
self.base.redraw_requested.emit();
}
}
67 if modifiers.contains(crate::shortcut::Modifiers::PRIMARY) => {
// Primary+C: Copy selection to the platform clipboard.
#[cfg(not(alloc_frugal))]
{
self.copy_selection_to_clipboard();
}
#[cfg(alloc_frugal)]
{
// Clipboard integration is unavailable in the mini profile.
self.base.redraw_requested.emit();
}
}
88 if modifiers.contains(crate::shortcut::Modifiers::PRIMARY) => {
// Primary+X: Copy selection, then delete it.
//
// The two halves have different conditions on purpose. What reaches the
// clipboard is `clipboard_selection`, which a masked field limits to its mask
// (and `NoEcho` to nothing); the *deletion* is the edit the user asked for and
// happens whenever there is a selection, so a cut in a password field still
// removes what the user cut.
#[cfg(not(alloc_frugal))]
{
let had_selection = !self.selected_text().is_empty();
if let Some(text) = self.clipboard_selection() {
crate::set_clipboard_text(&text);
}
if had_selection {
self.backspace(); // removes the selection
}
}
#[cfg(alloc_frugal)]
{
// Clipboard integration is unavailable in the mini profile.
self.base.redraw_requested.emit();
}
}
90 if modifiers.contains(crate::shortcut::Modifiers::PRIMARY)
&& modifiers.contains(crate::shortcut::Modifiers::SHIFT) =>
{
// Primary+Shift+Z is the other conventional redo chord. It used to fall into the
// plain undo arm below, so the field undid the edit the user meant to redo; the
// other editable controls in this family bind it (I-01).
let _ = self.redo();
}
90 if modifiers.contains(crate::shortcut::Modifiers::PRIMARY) => {
let _ = self.undo();
}
89 if modifiers.contains(crate::shortcut::Modifiers::PRIMARY) => {
let _ = self.redo();
}
_ => {
// Character input. A control chord must not be swallowed as text, nor may an
// unmapped **non-printable** key be: both used to be typed as their bare
// character, so `Ctrl+B` inserted `b` and `Ctrl+Z` inserted `z`.
//
// The two chords this field swaps the meaning of are the right ones for the
// host: undo/redo are `Primary+Z`/`Primary+Y` (handled above), and the
// accelerator convention is `from_event_bits_primary_is_ctrl`.
// Character input. A control chord must not be swallowed as text, nor may an
// unmapped **non-printable** key be: both used to be typed as their bare
// character, so `Ctrl+B` inserted `b` and `Ctrl+Z` inserted `z`.
//
// # Why the three modifiers are tested one at a time
//
// Combining them with `|` and asking `contains` is not the predicate it reads
// as: `Modifiers::contains` compares the *value* of the mask, so
// `contains(CTRL | ALT | META)` is true only when **all three** are held at once.
// A `Ctrl+B` carries CTRL alone and therefore failed the combined test, which is
// exactly the defect this arm exists to stop. Three separate `contains` calls say
// what is meant: none of the three is held.
let chord_held = modifiers.contains(crate::shortcut::Modifiers::CTRL)
|| modifiers.contains(crate::shortcut::Modifiers::ALT)
|| modifiers.contains(crate::shortcut::Modifiers::META);
if !chord_held {
// Only a **printable** key is content. `char::from_u32(0)` is `\0`, and 9, 10
// and 13 are Tab/Enter/CR — none of them is something a user typed into a
// text field, and all of them are control codes the host owns.
if let Some(ch) = char::from_u32(key).filter(|c| !c.is_control()) {
if ch.is_ascii_graphic() || ch == ' ' {
self.insert_str(&ch.to_string());
}
}
}
}
}
true
}
}
impl LineEdit {
/// Tells the host that the value changed during this event.
///
/// The queue is only touched for a **mounted** field: a value callback is registered through
/// the widget registry, so an unmounted `LineEdit` (the shape most unit tests use) has no
/// reader, and injecting there would put an event into a process-wide queue that no frame will
/// drain. The trigger carries no text — [`crate::app::dispatch_trigger`] reads the live value —
/// so a later edit cannot make an earlier notification describe the wrong string.
///
/// `revision` is the [`Self::text_revision`] read before the gesture; a gesture that did not
/// move the value (every arrow, Home/End, or a refused insert) announces nothing (I-P01).
#[cfg(not(alloc_frugal))]
fn announce_value_changed_if_revision_moved(&self, revision: u64) {
if self.text_revision == revision {
return;
}
// A widget's own `base().id()` is not the id the registry mounted it under, and the
// trigger queue and callback table are keyed by the **registry** id. Resolving the
// translation here is what makes the notification address the control the host holds;
// injecting with the own id would queue an event no callback could ever match.
let Some(id) = crate::widget::runtime::registry_id_of(self.base.id()) else {
return;
};
if !crate::widget::runtime::is_mounted(id) {
return;
}
let _ = crate::inject_widget_trigger_event(
id,
crate::platform::WidgetTriggerKind::ValueChanged,
);
}
/// The allocation-frugal build has no trigger queue and no host callbacks.
#[cfg(alloc_frugal)]
fn announce_value_changed_if_revision_moved(&self, _revision: u64) {}
}
impl EventHandler for LineEdit {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
if !self.base.is_enabled() {
return;
}
if self.read_only {
// Read-only fields still allow copying the current selection.
#[cfg(not(alloc_frugal))]
if let Event::KeyPress { key: 67, modifiers: 2 } = event {
self.copy_selection_to_clipboard();
}
return;
}
match event {
Event::KeyPress { key, modifiers } => {
// A user edit has to reach `on_value_changed` without the host polling the text.
//
// The trigger is queued only when the value actually moved: every navigation key
// (`Left`, `Home`, a shortcut chord) also arrives here, and announcing those would
// make a form validate on a keystroke that changed nothing. `set_text` is
// deliberately not the injection point because a host calling it already knows the
// value it just wrote.
let revision = self.text_revision;
self.handle_key(*key, crate::shortcut::Modifiers::from_event_bits(*modifiers));
self.announce_value_changed_if_revision_moved(revision);
self.emit_text_edited_if_revision_moved(revision);
}
// Platform-committed text (D09-INPUT-01).
//
// The desktop backends deliver a printable character or an IME commit as
// `Event::TextInput`/`Event::ImeCommit`, not as a `KeyPress`, so a handler that only
// matches `KeyPress` never receives what the user typed. Routing both variants into
// `insert_text` — the same entry point the `KeyPress` printable path calls — keeps the
// field's focus, read-only, selection-replacement, `max_length`, undo and
// `text_changed` contract in one place rather than duplicating it here. The
// `read_only`/`is_enabled` early returns above already gate this branch.
Event::TextInput { text } => {
let revision = self.text_revision;
self.insert_str(text);
self.announce_value_changed_if_revision_moved(revision);
self.emit_text_edited_if_revision_moved(revision);
}
// A commit ends the composition as well as inserting its text. Clearing the preedit
// first is what keeps the underlined preview from surviving the string it previewed:
// an input method may deliver the commit before its `preedit_end`, and the field would
// otherwise paint both the committed text and a stale composition.
Event::ImeCommit { text } => {
let revision = self.text_revision;
self.composition = None;
self.insert_str(text);
self.announce_value_changed_if_revision_moved(revision);
self.emit_text_edited_if_revision_moved(revision);
}
// The uncommitted composition belongs to the field while the user is building it: the
// value does not change, but the inline preedit at the caret does. Without this arm an
// input method's preview reached no text model at all, because `set_composition` had
// no event producer inside the widget layer.
Event::ImePreedit { text, .. } => {
self.set_composition(text);
}
Event::FocusLost => {
self.set_focused(false);
self.editing_finished.emit();
}
Event::FocusGained { .. } => {
self.set_focused(true);
}
// A press focuses the field only when it lands on the **painted band**, not on
// the control's rectangle. The two used to be the same box, so the hit test
// silently agreed with the ink by accident; once the field became a centred
// 48 px band in a 120 px cell, testing `geometry()` would let a user focus the
// field by clicking 60 px below it — on the window background, nowhere near
// any ink. The test is against `field_rect()` for exactly that reason.
Event::MousePress { pos, button, modifiers, .. }
if *button == 1 && self.field_rect().contains_point(*pos) =>
{
// The clear button owns its corner of the field and consumes the press before the
// caret can move there: a click meant to erase must not also select text.
if self.clear_button_hit(*pos) {
let revision = self.text_revision;
// The button is a user gesture, so its erase stays undoable even though the
// programmatic `clear()` entry point is a pristine write (I-04).
self.apply_text(String::new(), EditOrigin::User);
self.modified = true;
self.press_streak = 0;
self.emit_text_edited_if_revision_moved(revision);
return;
}
// Track a multi-click streak so a third press can select the whole value. The
// platform reports a double click separately; the press that precedes it is what
// tells this field the streak is still growing.
let elapsed = self.clock_ms.wrapping_sub(self.last_press_ms);
if self.press_streak > 0 && elapsed <= MULTI_CLICK_WINDOW_MS {
self.press_streak = self.press_streak.saturating_add(1);
} else {
self.press_streak = 1;
}
self.last_press_ms = self.clock_ms;
self.set_focused(true);
// A press places the caret where the user aimed and starts a selection.
//
// Previously a press only focused the field, so the caret stayed wherever it
// happened to be — `set_text` leaves it at the end, so clicking into the middle
// of an existing value and typing appended instead of inserting, and there was
// no way at all to select with the pointer. `press_at` is the pointer's
// counterpart to `select_with_modifiers`: it anchors where the press landed,
// and a following drag extends without a key being held, because a drag *is*
// the gesture that means "extend".
let index = self.byte_index_at_x(pos.x);
self.press_at(index, crate::shortcut::Modifiers::from_event_bits(*modifiers));
}
// A double click selects the word under the pointer; a third click in the same streak
// selects the whole value, which is the convention for single-line fields.
Event::MouseDoubleClick { pos, button }
if *button == 1 && self.field_rect().contains_point(*pos) =>
{
let index = self.byte_index_at_x(pos.x);
if self.press_streak >= 3 {
self.select_all();
} else {
let before_cursor = self.cursor_position;
let before_selection = self.selection_start;
let (start, end) = self.word_range_at(index);
self.selection_start = Some(start);
self.cursor_position = end;
self.dragging_selection = false;
self.notify_caret_change(before_cursor, before_selection);
self.base.request_redraw();
}
}
// A drag extends the selection the press began, and only then — see `drag_to`.
Event::MouseMove { pos } => {
if self.dragging_selection {
let index = self.byte_index_at_x(pos.x);
self.drag_to(index);
}
}
// A release anywhere ends the gesture, including outside the field: the anchor
// stays where the press put it so the selection the user made is kept.
Event::MouseRelease { button, .. } if *button == 1 => {
self.end_drag();
}
_ => { /* Other events are not relevant */ }
}
}
}
/// A selected value is the field's drag payload.
///
/// The payload uses the `text/plain` type so it can land in any other text control without an
/// adapter, and a masked field contributes the mask rather than the plaintext — the same rule
/// its copy path follows.
impl DragSource for LineEdit {
fn drag_payload(&self, pos: Point) -> Option<DragPayload> {
// The switch is consulted before anything is measured, so a field that did not opt in
// pays nothing for a gesture it will refuse.
if !self.drag_enabled || !self.field_rect().contains_point(pos) {
return None;
}
let selected = self.selected_text();
if selected.is_empty() {
return None;
}
let carried = match self.echo_mode {
EchoMode::Normal => selected.clone(),
EchoMode::Password => Self::mask_text(&selected),
EchoMode::NoEcho => return None,
};
Some(DragPayload::new("text/plain", carried.clone()).with_label(carried).with_origin(pos))
}
/// A `Move` drop removes the source selection; every other effect keeps it.
fn on_drag_finished(&mut self, effect: DropEffect) {
if !effect.consumes_source() || self.read_only {
return;
}
if !self.selected_text().is_empty() {
let revision = self.text_revision;
self.backspace();
self.modified = true;
self.emit_text_edited_if_revision_moved(revision);
}
}
}
/// The field accepts plain text and inserts it at the drop point.
impl DropTarget for LineEdit {
fn can_accept(&self, payload: &DragPayload) -> bool {
!self.read_only && payload.is_type("text/plain")
}
fn on_drop(&mut self, payload: &DragPayload, pos: Point) -> DropEffect {
if !self.can_accept(payload) || !self.field_rect().contains_point(pos) {
return DropEffect::None;
}
let text =
if payload.label.is_empty() { payload.item_id.clone() } else { payload.label.clone() };
if text.is_empty() {
return DropEffect::None;
}
self.press_at(self.byte_index_at_x(pos.x), crate::shortcut::Modifiers::empty());
self.end_drag();
let revision = self.text_revision;
self.insert_str(&text);
self.modified = true;
self.emit_text_edited_if_revision_moved(revision);
self.base.request_redraw();
DropEffect::Copy
}
}
impl Draw for LineEdit {
fn draw(&mut self, context: &mut RenderContext) {
// Draw base widget
//
// The **field**, not the control's rectangle: see `field_rect`. Every measurement
// below — the fill, the border, the text's line box and the caret's top and bottom
// — is taken from this one box, so they cannot disagree about where the field is.
let rect = self.field_rect();
let style = self.style();
// ── The decorated layout ──
//
// Every box below comes from **one** derivation, measured against the renderer's own font. The
// value's origin, the caret, the two slots and the support row cannot disagree, because they
// are the same answer read for different purposes. The value's origin used to be
// `rect.x + padding` regardless of any slot, so a `$` would have been drawn *over* the value
// it marks; and the caret measured from that same fixed inset, so it sat at the wrong end of
// a centred or right-aligned field.
let layout = self.decoration_layout(context);
// Draw background
let bg = style.background_color.unwrap_or(Color::rgb(255, 255, 255));
context.face_with_gradient(
Rect::new(rect.x, rect.y, rect.width, rect.height),
bg,
self.style().background_gradient.as_ref(),
self.style().surface.unwrap_or_default(),
self.style().border_radius.unwrap_or(0),
Color::BLACK,
);
// Draw border
//
// The **border** answers to the meaning channel, the fill above to the interaction one.
// A refusal therefore keeps its outline while the pointer is over the field, which is the
// one moment the outline is what the user is looking for. When the control carries no
// meaning the border falls back to the interaction style's own colour, so a control with
// `semantic_state() == None` draws exactly as it did before the two channels were split.
let semantic_border =
crate::style::resolved_semantic_border("line_edit", self.semantic_state());
if let Some(border_color) = semantic_border.or(style.border_color) {
let bw = style.border_width.unwrap_or(0);
// STY-01: the outline follows the fill's corner radius. A square rule around a
// rounded field left the four corners showing the backdrop.
crate::widget::draw::stroke_surface_border(
context,
Rect::new(rect.x, rect.y, rect.width, rect.height),
style.border_radius.unwrap_or(0),
border_color,
bw,
);
}
// Draw text or placeholder
//
// The value is **borrowed** when the echo mode allows it. `display_text()` returns an owned
// `String`, so the ordinary case — normal echo, painting the field's own text — cloned the
// whole value once per frame on the crate's highest-traffic control. Only the password mask
// genuinely derives a string, and it is held in `masked` so the borrow can outlive the match.
let masked: String;
let revealed = self.reveals_value();
let display_text: &str = if self.text.is_empty() && !self.placeholder_text.is_empty() {
&self.placeholder_text
} else {
match self.echo_mode {
EchoMode::Normal => &self.text,
EchoMode::NoEcho => "",
EchoMode::Password if revealed => &self.text,
EchoMode::Password => {
masked = Self::mask_text(&self.text);
&masked
}
}
};
let font = effective_font(style);
// Whether the painted string is the field's own value (normal echo, or a revealed
// password) rather than a derived one. The caret measures its prefix from that same
// string when it can, so the two share one memoised advance instead of measuring two
// copies of it.
let display_is_value = !(self.text.is_empty() && !self.placeholder_text.is_empty())
&& match self.echo_mode {
EchoMode::Normal => true,
EchoMode::NoEcho => false,
EchoMode::Password => revealed,
};
let value_line = context.text_line(rect, font);
let text_color = style.text_color.unwrap_or(Color::rgb(0, 0, 0));
// The box the value is laid out in, and the alignment it uses within that box.
//
// Resolved **once**, outside the `if` that draws the string, because the caret below needs
// the exact same two facts: it rides with the glyphs, so it must be placed from the origin
// the glyphs were placed from. Computing them in two places is how the caret and the value
// drifted apart in the first place.
//
// `draw_text_fitted` insets its box by `TEXT_FIT_MARGIN` at each end, which is right for
// a label that must not touch its frame but wrong for a field value: left-aligned ink
// would then begin `TEXT_FIT_MARGIN` past the field's own padding. Handing it a box
// widened by that same inset on both sides puts the left edge back on the padding, so
// `Left` is byte-identical to the pre-alignment `draw_text` and the other two alignments
// measure from the same true box.
let fit = crate::render::TEXT_FIT_MARGIN as i32;
let value_box = Rect::new(
layout.value.x - fit,
value_line.y,
layout.value.width + (fit * 2) as u32,
value_line.height,
);
let value_align = self.alignment.to_horizontal().unwrap_or(HorizontalAlignment::Left);
let value_advance = self.cached_advance(
context,
AdvanceSource::Display,
display_text,
font,
0,
display_text.len(),
);
let value_origin = crate::render::fitted_origin(value_box, value_advance, value_align);
// ── Selection band ──
//
// Painted under the glyphs so the value stays readable while selected. The two offsets are
// measured through the renderer's shaper, the same ruler the caret uses, and clipped to the
// value's own box so a selection cannot spill over the prefix, the suffix or the border.
if let Some((start, end)) = self.selection_range() {
let start = start.min(display_text.len());
let end = end.min(display_text.len());
if start < end {
let selection_color = text_color.blend(&bg, 0.3).blend(&bg, 0.25);
let left_edge = layout.value.x;
let right_edge = layout.value.x + layout.value.width as i32;
let start_advance = self.cached_advance(
context,
AdvanceSource::Display,
display_text,
font,
0,
start,
);
let end_advance = self.cached_advance(
context,
AdvanceSource::Display,
display_text,
font,
0,
end,
);
let x0 =
(value_origin.x + start_advance - self.scroll_x).clamp(left_edge, right_edge);
let x1 =
(value_origin.x + end_advance - self.scroll_x).clamp(left_edge, right_edge);
if x1 > x0 {
context.draw_rect(
Rect::new(x0, value_line.y, (x1 - x0) as u32, value_line.height.max(1)),
selection_color,
);
}
}
}
if !display_text.is_empty() {
if self.scroll_x == 0 {
// The field's own line box. A glyph origin is the box's top-left edge, so the
// previous `rect.y + rect.height / 2` placed that edge on the field's middle line
// and drew the value half a line low.
context.draw_text_fitted_cow(
value_box,
display_text,
font,
text_color,
value_align,
);
} else {
// Scrolled: the value's origin moves left with the caret and the paint is clipped
// to the value box, so the leading characters leave the field instead of being
// elided. A value that fits never takes this path (`scroll_x` stays zero).
context.push_clip(
layout.value.x,
value_line.y,
layout.value.width,
value_line.height,
);
context.draw_text(
Point::new(value_origin.x - self.scroll_x, value_line.y),
display_text,
font,
text_color,
HorizontalAlignment::Left,
);
context.pop_clip();
}
}
// ── The in-field slots ──
//
// Drawn in their **own** boxes, in a muted tone of the field's ink so they read as unit marks
// rather than as content. They are deliberately not folded into `display_text`: the caret below
// is measured against `self.text` alone, so a prefix in the string would put `cursor_position
// == 0` after the `$` and make the start of the value unreachable.
let slot_color = text_color.blend(&bg, 0.35);
if let Some(prefix_box) = layout.prefix {
context.draw_text(
Point::new(prefix_box.x, value_line.y),
&self.decorations.prefix,
font,
slot_color,
HorizontalAlignment::Left,
);
}
if let Some(suffix_box) = layout.suffix {
context.draw_text(
Point::new(suffix_box.x, value_line.y),
&self.decorations.suffix,
font,
slot_color,
HorizontalAlignment::Left,
);
}
// ── The support row ──
//
// Message on the leading edge, counter on the trailing one. The error takes the theme's error
// colour, because a refusal that is painted in the same ink as a hint is a refusal the user has
// to read to notice.
if let Some(row) = layout.support {
// The validation colour is the theme's error token, not a literal red: a theme with a
// different error hue (or a high-contrast palette) must see a consistent error state.
let error_color = crate::style::semantic_color(crate::style::SemanticColor::Error)
.unwrap_or(Color::rgb(200, 40, 40));
let message = self.decorations.support_message();
if !message.is_empty() {
let message_color =
if self.decorations.has_error() { error_color } else { slot_color };
let row_line = context.text_line(row, font);
// Fitted to the band before the counter: a long support message used to paint
// straight over the trailing `n/max` reading.
let message_width = layout
.counter
.map_or(row.width, |counter| (counter.x - row.x - 4).max(0) as u32);
context.draw_text_fitted_cow(
Rect::new(row.x, row_line.y, message_width, row_line.height.max(1)),
message,
font,
message_color,
HorizontalAlignment::Left,
);
}
if let Some(counter_box) = layout.counter {
let counter_line = context.text_line(counter_box, font);
// The counter is a *budget* reading, so it turns to the error colour once the value
// exceeds the limit — the one moment it has something to warn about.
let counter_color = if self.is_over_limit() { error_color } else { slot_color };
if let Some(counter) = self.counter_text() {
context.draw_text(
Point::new(counter_box.x, counter_line.y),
&counter,
font,
counter_color,
HorizontalAlignment::Right,
);
}
}
}
// Draw the caret for whichever field owns keyboard focus.
if self.focused && !self.read_only && self.cursor_blink.is_visible() {
// The caret sits at **`cursor_position`**, not at the end of the value.
//
// This measured the whole string, so the marker was always drawn after the last
// glyph however the control was positioned: with `text == "Sample"` and
// `cursor_position == 0`, the caret rendered past the `e`. The field answers
// `cursor_position`, `set_cursor_position` clamps it, and `backspace`/`delete`
// both act on it — so the cursor was the one thing in the field that ignored the
// very field that defines it, and every editing affordance appeared to work at the
// wrong end of the text.
//
// The slice is taken through `floor_char_boundary` because `cursor_position` indexes
// bytes and the value may be multi-byte; slicing mid-character would panic, which is
// why the import for it was already present in this file.
//
// # Why the origin is the same `fitted_origin` the value was drawn with
//
// A centred or right-aligned value does **not** start at `text_x`: the fit path lays it
// out from `fitted_origin(value_box, advance, alignment)`. Measuring the caret from
// `text_x` therefore put the marker at the left edge of a right-aligned field while its
// own text sat at the right edge. Rather than duplicate that arithmetic here — the two
// would drift exactly as the value's origin and the caret's once did — the whole value's
// advance is measured and run through the same origin function, so the caret rides with
// the glyphs it belongs to.
let caret_byte = floor_char_boundary(self.text.as_str(), self.cursor_position);
// The value's own advance and its fitted origin were resolved once above, for the
// painted value; the caret rides on the same two facts instead of re-deriving them.
// The prefix is measured from the same string the caret belongs to: the painted one
// when it is the field's value, otherwise the value itself.
let prefix_advance = if display_is_value {
self.cached_advance(
context,
AdvanceSource::Display,
display_text,
font,
0,
caret_byte,
)
} else {
self.cached_advance(
context,
AdvanceSource::Value,
self.text.as_str(),
font,
0,
caret_byte,
)
};
let caret_x = value_origin.x + prefix_advance - self.scroll_x;
// The marker is clipped to the **value's** box. A caret beyond the visible text (a value
// wider than the room it has) belongs at the last pixel a user can see, not outside the
// control and not under the suffix. Clipping to the whole field instead would let the caret
// sit on top of a `%` and read as if the unit were part of the value.
let caret_x = caret_x.min(layout.value.x + layout.value.width as i32);
let caret_x = caret_x.max(layout.value.x);
// The caret spans the field's own content band, inset so it does not touch the
// border. The band is the field's, not the control's: with the field centred in
// a tall cell, `rect` alone would have drawn a caret taller than the field it
// belongs to.
let caret_top = rect.y + 2;
let caret_bottom = rect.y + rect.height as i32 - 2;
let caret_color = style.text_color.unwrap_or(Color::rgb(0, 0, 0));
context.draw_line(
Point::new(caret_x, caret_top),
Point::new(caret_x, caret_bottom),
caret_color,
);
// The uncommitted composition is drawn **after the caret**, where it will land when it is
// committed, with an underline marking it as preedit.
//
// # Why the field draws this and not only `ImePreedit`
//
// `ImePreedit` is an overlay: a host that mounts one gets a composition string with an
// underline, in a box of its own. But a user typing into a field expects the composition
// **inline**, at the caret, growing as they type — that is what makes an input method
// legible. Drawing it here is possible only because the preedit is now part of the
// field's model (`composition`); the overlay could never place it, because it does not
// know where this field's caret is.
//
// The advance is measured from the **same** `prefix` the caret uses, so the underline
// begins exactly at the caret and cannot drift from it.
if let Some(preedit) = self.composition.as_deref() {
let preedit_x = caret_x;
let preedit_width = context.measure_text(preedit, font).width as i32;
context.push_clip(
layout.value.x,
value_line.y,
layout.value.width,
value_line.height,
);
context.draw_text(
Point::new(preedit_x, value_line.y),
preedit,
font,
caret_color,
crate::core::HorizontalAlignment::Left,
);
// The underline is one pixel below the glyph box, over the preedit's own width.
// The line box above already carries the font's measured height (it is derived
// from the same `"M"` measurement), so it is read instead of measured again.
let underline_y = value_line.y + value_line.height as i32 + 1;
context.draw_line(
Point::new(preedit_x, underline_y),
Point::new(preedit_x + preedit_width, underline_y),
caret_color,
);
context.pop_clip();
}
}
// ── The opt-in clear button ──
//
// Drawn only when the field holds text, so an empty field keeps its plain corner. The
// glyph is a cross built from two lines, which needs no icon registry and reads at any
// scale the field's own font takes.
if self.clear_button_enabled && !self.text.is_empty() {
let button = self.clear_button_rect();
let ink = slot_color;
let inset = 4;
let cx = button.x + button.width as i32 / 2;
let cy = button.y + button.height as i32 / 2;
let arm = (button.width as i32 - inset * 2).max(2) / 2;
context.draw_line(Point::new(cx - arm, cy - arm), Point::new(cx + arm, cy + arm), ink);
context.draw_line(Point::new(cx - arm, cy + arm), Point::new(cx + arm, cy - arm), ink);
}
// ── Focus ring ──
//
// Only a keyboard focus draws it — a pointer press focuses without claiming visual
// focus, which is the rule every other control in the crate follows.
if self.base.draws_focus_ring() {
let ring = crate::widget::metrics::FocusRing::for_control(
rect,
style.border_radius.unwrap_or(0),
);
if ring.is_drawable() {
context.draw_rounded_rect_stroke(
ring.rect,
ring.radius,
crate::widget::metrics::focus_ring_color(bg.contrast_color()),
crate::widget::metrics::FOCUS_RING_WIDTH,
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compat::{MiniToString, Vec};
use crate::core::Rect;
/// A context-menu request is emitted with the point it asked about, and the field
/// reports that it handled it. The host supplies the menu; the field supplies the
/// request.
#[test]
fn a_context_menu_request_emits_the_requested_point() {
let mut field = LineEdit::new(Rect::new(0, 0, 160, 32));
let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
let sink = std::sync::Arc::clone(&seen);
field.context_menu_requested.connect_ref(move |pos: &Point| {
*sink.lock().unwrap() = Some(*pos);
});
assert!(field.context_menu_event(Point::new(18, 6)));
assert_eq!(*seen.lock().unwrap(), Some(Point::new(18, 6)));
}
/// The bitmap face fills its glyph box, so its ink left *is* the box left. An outline face draws
/// a real glyph whose ink is inset, so the ink's left edge sits one or two pixels right of the
/// box edge at these sizes. Pinning the two equal encoded a property of the bitmap face, not of
/// the layout.
const INK_INSET_TOLERANCE: i32 = 3;
#[test]
fn lineedit_creation_defaults() {
let le = LineEdit::new(Rect::new(0, 0, 200, 24));
assert!(le.text().is_empty());
assert!(le.placeholder_text().is_empty());
assert_eq!(le.max_length(), None);
assert_eq!(le.echo_mode(), EchoMode::Normal);
assert_eq!(le.cursor_position(), 0);
assert!(le.selection_start().is_none());
assert!(!le.is_focused(), "a fresh field is not focused");
}
/// The caret blinks only while the field holds focus, and it stops asking for frames when it
/// does not.
///
/// The caret was a solid line for the whole life of the field, so `tick` did not exist and a
/// host had no signal about whether more frames were owed. This pins the contract in both
/// directions: a blurred field is inert, and a focused one keeps reporting work until it
/// loses focus again.
#[test]
fn the_caret_blinks_while_focused_and_is_inert_while_blurred() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
// Blurred: no frames owed, whatever the delta.
assert!(!le.tick(10_000), "a blurred field owes no frame");
// Focused: it reports work, and keeps doing so because a blink never settles.
le.set_focused(true);
assert!(le.tick(0), "a focused field is blinking");
for _ in 0..10 {
assert!(le.tick(500), "a blink is periodic, so it never reports settled");
}
// A read-only field shows no caret, so it must not animate one either.
le.set_focused(false);
assert!(!le.tick(500));
}
/// The field must learn about focus from the events the runtime sends, since
/// that is what gates the caret. Before this the field had no focus state, so
/// `FocusGained` was ignored and the caret was never drawn.
#[test]
fn lineedit_tracks_focus_from_events() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.handle_event(&Event::FocusGained { reason: FocusReason::Programmatic });
assert!(le.is_focused(), "FocusGained must mark the field focused");
le.handle_event(&Event::FocusLost);
assert!(!le.is_focused(), "FocusLost must clear it");
}
/// Setting focus directly must be idempotent in effect: the flag is a boolean,
/// so a repeated set cannot leave it in a contradictory state.
#[test]
fn lineedit_set_focused_round_trips() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_focused(true);
assert!(le.is_focused());
le.set_focused(true);
assert!(le.is_focused());
le.set_focused(false);
assert!(!le.is_focused());
}
/// A focused field must actually paint a caret. The previous code drew nothing,
/// and the comment said why — there was no focus state to read.
#[test]
fn focused_lineedit_draws_a_caret() {
let rect = Rect::new(0, 0, 200, 24);
let mut focused = LineEdit::new(rect);
focused.set_text("ab");
focused.set_focused(true);
let mut unfocused = LineEdit::new(rect);
unfocused.set_text("ab");
let focused_frame = render(&mut focused, rect);
let unfocused_frame = render(&mut unfocused, rect);
assert_ne!(
focused_frame, unfocused_frame,
"focusing must change what is painted, because it draws the caret"
);
}
/// Renders a widget into an RGBA frame for comparison.
fn render(widget: &mut LineEdit, rect: Rect) -> Vec<u8> {
use crate::core::{Color, Size};
use crate::render::{PaintBackend, RenderContext, SoftwarePaintBackend};
use crate::widget::Draw;
let mut surface = SoftwarePaintBackend::new(Size::new(rect.width, rect.height), 1.0);
surface.begin_frame(Color::WHITE);
{
let mut context = RenderContext::new(&mut surface);
widget.draw(&mut context);
}
surface.end_frame();
surface.frame_rgba().to_vec()
}
#[test]
fn lineedit_set_text() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello".to_string());
assert_eq!(le.text(), "Hello");
assert_eq!(le.cursor_position(), 5);
}
#[test]
fn lineedit_set_text_empty() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello".to_string());
le.set_text(String::new());
assert!(le.text().is_empty());
assert_eq!(le.cursor_position(), 0);
}
#[test]
fn lineedit_undo_redo_restores_text() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
// A programmatic `set_text` is the saved state and records no history, so the two values
// are produced through the user edit path (see I-04).
le.insert_str("one");
le.select_all();
le.insert_str("two");
assert!(le.can_undo());
assert!(le.undo());
assert_eq!(le.text(), "one");
assert!(le.can_redo());
assert!(le.redo());
assert_eq!(le.text(), "two");
}
#[test]
fn lineedit_control_z_and_control_y_drive_history() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
// Programmatic writes are pristine (I-04), so the history is built by real edits.
le.insert_str("before");
le.select_all();
le.insert_str("after");
// Bit 3 is the event's Meta/Command bit, i.e. the portable "primary accelerator"
// (`Modifiers::from_event_bits`). The physical-Control bit is bit 1 and means Control.
le.handle_event(&Event::key_press(90, 0b1000));
assert_eq!(le.text(), "before");
le.handle_event(&Event::key_press(89, 0b1000));
assert_eq!(le.text(), "after");
}
#[test]
fn primary_shift_z_is_the_other_redo_chord() {
// `Ctrl+Shift+Z` / `Cmd+Shift+Z` used to fall into the undo arm and undo the edit the
// user meant to redo (I-01).
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.insert_str("before");
le.select_all();
le.insert_str("after");
le.handle_event(&Event::key_press(90, 0b1000));
assert_eq!(le.text(), "before");
// Bit 0 is the Shift bit beside the primary accelerator.
le.handle_event(&Event::key_press(90, 0b1001));
assert_eq!(le.text(), "after");
}
#[test]
fn a_multi_byte_password_produces_one_star_per_character() {
// `mask_text` repeated by byte length, so `héllo` (5 characters, 6 bytes) painted six
// stars and the mask disagreed with the value it hid (I-02).
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_echo_mode(EchoMode::Password);
le.set_text("héllo");
assert_eq!(LineEdit::mask_text(le.text()), "*****");
}
#[test]
fn lineedit_placeholder() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
assert!(le.placeholder_text().is_empty());
le.set_placeholder_text("Enter name".to_string());
assert_eq!(le.placeholder_text(), "Enter name");
le.set_placeholder_text(String::new());
assert!(le.placeholder_text().is_empty());
}
#[test]
fn lineedit_max_length() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
assert_eq!(le.max_length(), None);
le.set_max_length(Some(5));
assert_eq!(le.max_length(), Some(5));
le.set_max_length(None);
assert_eq!(le.max_length(), None);
}
#[test]
fn lineedit_max_length_truncates() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello World".to_string());
le.set_max_length(Some(5));
assert_eq!(le.text(), "Hello");
}
/// Reducing the limit truncates the value *and* invalidates the history that
/// could restore the over-limit string.
#[test]
fn max_length_change_keeps_undo_within_the_limit() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("abcdef");
le.set_max_length(Some(3));
assert_eq!(le.text(), "abc", "the value is truncated to the limit");
assert!(!le.can_undo(), "an over-limit value must not be undoable");
assert!(!le.undo());
assert_eq!(le.text(), "abc");
assert!(!le.redo());
assert_eq!(le.text(), "abc");
}
#[test]
fn lineedit_cursor_position() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello".to_string());
le.set_cursor_position(3);
assert_eq!(le.cursor_position(), 3);
le.set_cursor_position(100); // clamps to text len
assert_eq!(le.cursor_position(), 5);
}
#[test]
fn lineedit_echo_mode() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
assert_eq!(le.echo_mode(), EchoMode::Normal);
le.set_echo_mode(EchoMode::Password);
assert_eq!(le.echo_mode(), EchoMode::Password);
le.set_echo_mode(EchoMode::NoEcho);
assert_eq!(le.echo_mode(), EchoMode::NoEcho);
le.set_echo_mode(EchoMode::Normal);
assert_eq!(le.echo_mode(), EchoMode::Normal);
}
/// A masked field must not hand its plaintext to the process-global clipboard.
///
/// `selected_text` keeps returning the real value — the host needs it to store a
/// credential — but the clipboard path is a *different* reader, and the clipboard is
/// readable by every other process. In `Password` mode it must therefore receive the
/// same `*` mask the field paints; in `NoEcho` mode, which paints nothing, nothing may
/// be copied at all.
#[cfg(not(alloc_frugal))]
#[test]
fn lineedit_masked_selection_copies_the_mask_not_the_plaintext() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("s3cret".to_string());
le.select_all();
// The host's own read still sees the real value.
assert_eq!(le.selected_text(), "s3cret");
le.set_echo_mode(EchoMode::Password);
assert_eq!(le.clipboard_selection().as_deref(), Some("******"));
le.set_echo_mode(EchoMode::NoEcho);
assert_eq!(le.clipboard_selection(), None);
le.set_echo_mode(EchoMode::Normal);
assert_eq!(le.clipboard_selection().as_deref(), Some("s3cret"));
}
/// An empty selection is not a copy, whatever the echo mode.
#[cfg(not(alloc_frugal))]
#[test]
fn lineedit_no_selection_copies_nothing() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("s3cret".to_string());
le.clear_selection();
assert_eq!(le.clipboard_selection(), None);
}
/// The widget layer and the platform layer must name the **same** echo-mode
/// enum, so a mode read back from a native control can be handed straight to
/// this widget. Distinct types would make the assignment below ill-typed.
#[test]
fn lineedit_shares_the_canonical_echo_mode_type() {
let canonical: crate::platform::EchoMode = crate::platform::EchoMode::Password;
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_echo_mode(canonical);
assert_eq!(le.echo_mode(), canonical);
}
#[test]
fn lineedit_select_all() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello World".to_string());
le.select_all();
assert_eq!(le.selection_start(), Some(0));
assert_eq!(le.cursor_position(), 11);
assert_eq!(le.selected_text(), "Hello World");
}
#[test]
fn lineedit_clear_selection() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello".to_string());
le.select_all();
le.clear_selection();
assert!(le.selection_start().is_none());
}
// ─── Shift-arrow selection (BLUE24 §12 U-6) ───
/// A Shift-arrow **extends** the selection; a plain arrow replaces it.
///
/// # The defect this pins
///
/// The anchor rule was written out once per arrow key, six copies of one decision. Beyond the
/// duplication, the copies meant "Shift extends" lived only in the event loop — nothing else
/// could reach it, so the pointer gesture and the entry point a host calls had no way to
/// express a range. The assertions are on the *range*, not on the anchor, because a range is
/// what the user sees selected: an implementation that moved the caret and forgot the anchor
/// would still satisfy `cursor_position` and silently select nothing.
///
/// The modifiers are spelled as the **event bitmask** (see
/// [`crate::shortcut::Modifiers`]), not as `Modifiers` bits: an `Event` carries the framework's
/// wire convention, and the field translates it with `from_event_bits`.
#[test]
fn a_shift_arrow_extends_and_a_plain_arrow_replaces() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("abcdef".to_string()); // caret at the end
// Shift+Left twice grows a two-character selection, without collapsing to a caret.
le.handle_event(&Event::key_press(37, SHIFT_BIT));
assert_eq!(le.selected_text(), "f", "the first Shift+Left selects the character behind");
le.handle_event(&Event::key_press(37, SHIFT_BIT));
assert_eq!(le.selected_text(), "ef", "the second extends the same range");
// A plain Left keeps the caret where it is and drops the selection entirely.
le.handle_event(&Event::key_press(37, 0));
assert_eq!(le.selection_start(), None, "a plain arrow is not an extend");
assert_eq!(le.cursor_position(), 3, "and the caret is unmoved by the deselect");
}
/// Shift+Home and Shift+End select from the caret to the ends of the value.
#[test]
fn a_shift_home_and_end_select_to_the_ends_of_the_value() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("abcdef".to_string());
le.set_cursor_position(2);
le.handle_event(&Event::key_press(35, SHIFT_BIT));
assert_eq!(le.selected_text(), "cdef", "Shift+End runs from the anchor to the end");
// Shift+Home extends from the *same* anchor at 2, back past the caret to the start: the
// range becomes 0..=2, the other side of the same anchor rather than a rewrite of it.
le.handle_event(&Event::key_press(36, SHIFT_BIT));
assert_eq!(le.cursor_position(), 0, "the caret walks to the start");
assert_eq!(le.selection_start(), Some(2), "the anchor is unchanged by the second key");
assert_eq!(le.selected_text(), "ab", "so the selection flips to the other side of it");
// Home with no modifier collapses the range, the same as any plain movement.
le.handle_event(&Event::key_press(36, 0));
assert_eq!(le.selection_start(), None);
assert_eq!(le.cursor_position(), 0);
}
/// Shift+Home on a field that has never been selected anchors at the live caret.
///
/// The anchor is adopted from the caret when there is none, rather than assumed to be 0. A
/// field whose caret sits at the end would otherwise select the whole value for a gesture the
/// user aimed at the start of the line they were on.
#[test]
fn a_shift_move_with_no_anchor_anchors_at_the_caret() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("abcdef".to_string());
le.set_cursor_position(3);
assert_eq!(le.selection_start(), None, "a fresh caret is not an anchor");
le.handle_event(&Event::key_press(36, SHIFT_BIT));
assert_eq!(le.cursor_position(), 0, "Shift+Home walks the caret to the start");
assert_eq!(le.selection_start(), Some(3), "adopting the caret as the anchor, not 0");
assert_eq!(le.selected_text(), "abc", "so the range is the caret's own line prefix");
}
/// A Shift-arrow does not move the anchor once a selection exists, so the range grows from a
/// fixed point instead of sliding along with the caret.
#[test]
fn an_extended_range_grows_from_a_fixed_anchor() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("abcdef".to_string());
le.set_cursor_position(3);
// The caret steps back one *character per press*, so the anchor stays at 3 while the
// caret walks 3 -> 2 -> 1 and the range grows `"c"`, `"bc"`.
le.handle_event(&Event::key_press(37, SHIFT_BIT));
assert_eq!(le.cursor_position(), 2, "one press is one character");
assert_eq!(le.selection_start(), Some(3), "the anchor is where the gesture began");
assert_eq!(le.selected_text(), "c", "so the first step selects one character");
le.handle_event(&Event::key_press(37, SHIFT_BIT));
assert_eq!(le.selection_start(), Some(3), "and it does not slide with the caret");
assert_eq!(le.selected_text(), "bc", "so the range is anchor-to-caret");
assert_eq!(le.cursor_position(), 1);
}
/// An extension is **reversible**: Shift+Home then Shift+End returns the range to the anchor.
///
/// # The defect this pins
///
/// Home and End re-anchored at the caret before moving, so a second extension grew from the
/// wrong end: Shift+Home on a caret at 5 selected 0..=5 and moved the anchor to 5; the following
/// Shift+End then selected 5..=len instead of 0..=len. The anchor belongs to the *gesture*, and
/// only a press that begins one may move it.
#[test]
fn extending_back_and_forth_returns_to_the_anchor() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("abcdefgh".to_string());
le.set_cursor_position(5);
le.handle_event(&Event::key_press(36, SHIFT_BIT));
assert_eq!(le.cursor_position(), 0, "Shift+Home walks the caret to the start");
assert_eq!(le.selected_text(), "abcde", "the range is anchor(5)-to-caret(0)");
assert_eq!(le.selection_start(), Some(5), "the anchor is still where it began");
// The gesture is reversible: Shift+End **extends** from the same anchor, so the range
// flips to the other side of it rather than being replaced with 5..=len. This is the
// assertion that fails if Home/End copy the old `selection_start = Some(cursor)` rule.
le.handle_event(&Event::key_press(35, SHIFT_BIT));
assert_eq!(le.cursor_position(), 8, "Shift+End walks the caret to the end");
assert_eq!(le.selection_start(), Some(5), "the anchor never moved");
assert_eq!(le.selected_text(), "fgh", "so the range is anchor(5)-to-caret(8)");
}
/// Movement saturates rather than running off either end of the value.
///
/// # The defect this pins
///
/// The arrows used to be guarded by `if cursor > 0` / `if cursor < len`, so at an end the key was
/// *dropped* — including the deselect a plain press owes the user. A ragged selection then
/// survived an arrow press that plainly meant "just move". Saturation keeps the caret in range
/// and keeps the plain-press contract intact.
#[test]
fn movement_at_an_end_still_drops_the_selection() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("abc".to_string());
// Caret already at the end: Right cannot move, but it still ends the selection.
le.select_all();
assert_eq!(le.selection_start(), Some(0));
le.handle_event(&Event::key_press(39, 0));
assert_eq!(le.cursor_position(), 3, "the caret stays inside the value");
assert_eq!(le.selection_start(), None, "a plain press at the end still deselects");
// Caret already at the start with a range straddling it: Left cannot move, but the same
// deselect is owed. The range is built the way a shift-click does — press at the end,
// then shift-press at the start — so the caret lands on 0 with the anchor at 3.
le.select_all();
le.press_at(3, crate::shortcut::Modifiers::NONE);
le.press_at(0, crate::shortcut::Modifiers::SHIFT);
assert_eq!(le.cursor_position(), 0);
assert_eq!(le.selection_start(), Some(3), "a real range straddling the start");
assert_eq!(le.selected_text(), "abc");
le.handle_event(&Event::key_press(37, 0));
assert_eq!(le.cursor_position(), 0, "Left cannot move past the start");
assert_eq!(le.selection_start(), None, "but it still drops the stale range");
assert_eq!(le.selected_text(), "", "so nothing is left selected");
}
/// A control chord is not text: `Ctrl+B` must not insert a literal `b`.
///
/// # The defect this pins
///
/// The catch-all arm treated every unmapped key as a character and only excluded the chords it
/// happened to list (copy, paste, cut, undo, redo). So Ctrl+B, Ctrl+Q, Alt+1 and every other
/// shortcut the host may own were typed into the field as their bare key. A field that swallows
/// the application's own accelerators is unusable as a text input in a real form.
///
/// The comment describes Ctrl/Alt/Meta, and the event convention says the Meta bit is the
/// primary accelerator — so those are the bits asserted, not `Modifiers` bits.
#[test]
fn a_control_chord_is_not_typed_into_the_field() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
// Bit 1 is physical Control, bit 2 is Alt, bit 3 is the primary accelerator (Command on
// macOS). `from_event_bits` folds bit 3 into *both* PRIMARY and CTRL, and `contains`
// compares the mask's value rather than testing a bit, so the guard must ask about the
// three modifiers separately — a combined `contains(CTRL|ALT|META)` would only fire when
// all three were held, letting a plain Ctrl chord through.
for (name, bits) in [("Ctrl", 0b0010u32), ("Alt", 0b0100), ("Primary", 0b1000)] {
le.handle_event(&Event::key_press(98, bits));
assert!(le.text().is_empty(), "{name}+B must not insert a `b`");
}
// And a control code with no modifier at all is not content either: `key: 9` is Tab.
le.handle_event(&Event::key_press(9, 0));
assert!(le.text().is_empty(), "a bare Tab is not text");
// The unmodified key is still text, so the guard did not disable typing. The key codes
// are ASCII, so 66 is the uppercase `B` and 98 the lowercase `b`.
le.handle_event(&Event::key_press(98, 0));
assert_eq!(le.text(), "b", "a plain `b` is content");
}
/// The framework's Shift bit on an event mask.
const SHIFT_BIT: u32 = 0b0001;
// ─── Pointer selection ───
/// A press puts the caret where the user aimed and anchors a selection there.
///
/// # The defect this pins
///
/// A press used to *only* focus the field. `set_text` leaves the caret at the end, so clicking
/// into the middle of an existing value and typing appended to it rather than inserting at the
/// click — and there was no pointer selection at all, because nothing computed an index from `x`.
/// This bites the common case first: opening a form, clicking a prefilled field to correct one
/// word, and finding every keystroke going to the end of the line.
#[cfg(not(alloc_frugal))]
#[cfg(device_profile)]
#[test]
fn a_press_places_the_caret_where_the_pointer_landed() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("abcdefgh".to_string());
assert_eq!(le.cursor_position(), 8, "`set_text` leaves the caret at the end");
let field = le.field_rect();
// One character cell past the value's origin is the boundary after character 1.
let cell = cell_width();
let origin = value_origin(&mut le);
le.handle_event(&Event::mouse_press(
origin + cell + cell / 2,
field.y + field.height as i32 / 2,
1,
));
assert_eq!(le.cursor_position(), 1, "the caret lands on the character clicked");
assert_eq!(le.selection_start(), Some(1), "and it is the anchor for a drag");
}
/// A drag extends that selection; a hover that was never pressed does not move the caret.
///
/// Both halves matter. The first is the gesture: press on character 1, drag to character 4,
/// release leaves `"bcd"` selected. The second is the guard — `MouseMove` is delivered on every
/// pointer step over the control, so a field that acted on it unconditionally would have its
/// caret follow the mouse whenever the pointer crossed it, with no button pressed at all.
#[cfg(not(alloc_frugal))]
#[cfg(device_profile)]
#[test]
fn a_drag_extends_the_selection_but_a_bare_hover_does_not() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("abcdefgh".to_string());
let field = le.field_rect();
let mid = field.y + field.height as i32 / 2;
let cell = cell_width();
let origin = value_origin(&mut le);
// A hover with no press ever delivered leaves the caret exactly where it was.
le.handle_event(&Event::mouse_move(field.x + 4 * cell, mid));
assert_eq!(le.cursor_position(), 8, "an unpressed hover must not move the caret");
assert_eq!(le.selection_start(), None);
// Press on character 1, drag to character 4: `"bcd"` is selected.
le.handle_event(&Event::mouse_press(origin + cell + cell / 2, mid, 1));
assert_eq!(le.selection_start(), Some(1), "the press anchors where it landed");
le.handle_event(&Event::mouse_move(origin + 4 * cell + cell / 2, mid));
assert_eq!(le.selected_text(), "bcd", "the drag selected the span between the two points");
// The release ends the gesture, so a later hover is inert again.
le.handle_event(&Event::mouse_release(origin + 4 * cell, mid, 1));
le.handle_event(&Event::mouse_move(field.x + 7 * cell, mid));
assert_eq!(le.cursor_position(), 4, "a hover after the release does not extend");
assert_eq!(le.selected_text(), "bcd", "and the selection the user made is kept");
}
/// A press past the end of the value anchors at the end and readies a backward drag.
#[cfg(not(alloc_frugal))]
#[test]
fn a_press_beyond_the_value_anchors_at_its_end() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("ab".to_string());
let field = le.field_rect();
let mid = field.y + field.height as i32 / 2;
// Well past the two characters that exist: the caret saturates at the end. The press must
// land **inside the painted band** to be delivered, so it is taken from `field`, not from
// the control's rectangle — on a tall cell the two are different boxes.
le.handle_event(&Event::mouse_press(field.x + field.width as i32 - 2, mid, 1));
assert_eq!(
le.cursor_position(),
1,
"a press past the two-character value clamps to its own box, i.e. onto the last one"
);
assert_eq!(le.selection_start(), Some(1), "and that clamped character is the anchor");
// Dragging back over the value selects it, which is the gesture this enables.
let origin = value_origin(&mut le);
le.handle_event(&Event::mouse_move(origin, mid));
assert_eq!(le.cursor_position(), 0, "the drag reaches the value's leading edge");
assert_eq!(le.selected_text(), "a", "so the range is anchor(1)-to-caret(0)");
}
/// The click-to-index map and the painted value agree about where character zero is.
///
/// Read off the ink rather than off the same helper the hit test calls: a test that asked
/// `decoration_layout` where the value starts would agree with a bug in it. The pen that draws
/// the string is at `field.x + TEXT_FIELD_PADDING_H` (see `the_value_starts_at_the_fields_horizontal_padding`),
/// so clicking that pixel must resolve to index 0.
#[cfg(not(alloc_frugal))]
#[test]
fn a_click_on_the_first_glyph_resolves_to_index_zero() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("Sample".to_string());
let field = le.field_rect();
let pen = field.x + dimensions::TEXT_FIELD_PADDING_H as i32;
le.handle_event(&Event::mouse_press(pen, field.y + field.height as i32 / 2, 1));
assert_eq!(le.cursor_position(), 0, "the first pixel of the value is index 0");
}
/// The pixel-to-index map is total on multi-byte values: no click can split a character.
///
/// A byte-counting map lands inside `é` or a CJK glyph and the next `&text[..caret]` panics.
#[cfg(not(alloc_frugal))]
#[test]
fn a_click_never_lands_inside_a_multi_byte_character() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("héllo wörld 中文".to_string());
let field = le.field_rect();
let mid = field.y + field.height as i32 / 2;
for dx in 0..field.width as i32 {
le.handle_event(&Event::mouse_press(field.x + dx, mid, 1));
let caret = le.cursor_position();
assert!(caret <= le.text().len(), "the caret is inside the value at +{dx}");
assert!(
le.text().is_char_boundary(caret),
"the caret at +{dx} split a character: {caret} in {:?}",
le.text()
);
}
}
/// The width of one character cell in the field's shipped face, as the shaper computes it.
///
/// Kept in the test module rather than as a private method on the control: it is the fixture's
/// model of the metrics, and a control method for it would be dead code the gate would flag.
///
/// Gated with its only consumers: they drive the pointer path, so they are
/// `#[cfg(not(alloc_frugal))]`, and they need a device profile for the text metrics the
/// measurement rests on. An ungated helper became dead code under `mini` (which *is*
/// `alloc_frugal`) and again under a stripped-but-not-frugal profile (`embedded`), where
/// `clippy -D warnings` reported it while the device profiles stayed green.
#[cfg(all(not(alloc_frugal), device_profile))]
fn cell_width() -> i32 {
(crate::core::Font::default().size() * 0.6).round().max(1.0) as i32
}
/// The x the value's glyphs are laid out from, read from the field's own layout.
#[cfg(not(alloc_frugal))]
fn value_origin(le: &mut LineEdit) -> i32 {
let mut measurement =
crate::render::SoftwarePaintBackend::new(crate::core::Size::new(0, 0), 1.0);
let mut context = RenderContext::new(&mut measurement);
le.decoration_layout(&mut context).value.x
}
#[test]
fn lineedit_insert_text() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.insert_str("Hello");
assert_eq!(le.text(), "Hello");
}
#[test]
fn lineedit_backspace() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello".to_string());
le.backspace();
assert_eq!(le.text(), "Hell");
}
#[test]
fn lineedit_delete() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello".to_string());
le.set_cursor_position(0);
le.delete();
assert_eq!(le.text(), "ello");
}
#[test]
fn lineedit_clear() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("Hello".to_string());
le.clear();
assert!(le.text().is_empty());
}
#[test]
fn lineedit_geometry_delegation() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_geometry(Rect::new(10, 10, 150, 30));
assert_eq!(le.geometry(), Rect::new(10, 10, 150, 30));
}
/// The field is a full-width band one text-field height tall, centred in the control.
///
/// The control used to paint its whole rectangle, so a 240x120 census cell drew a
/// 240x120 white slab — a panel, not a field — and the drawn height disagreed with
/// `size_hint`'s 24 by a factor of five. This pins the shared `full_width_band`
/// derivation in both directions: the height is the table's constant whatever the
/// cell, and a control smaller than the field clamps rather than painting outside.
#[cfg(device_profile)]
#[test]
fn the_field_is_a_text_field_height_in_any_rectangle() {
// The assertion is the Material height, so a concurrent test that activates the Macos
// profile must not change what this control measures.
let _theme_guard = crate::style::theme_test_guard();
assert!(crate::theme::global_theme_manager().set_theme("default"));
for height in [48u32, 120, 300] {
let le = LineEdit::new(Rect::new(0, 0, 240, height));
let field = le.field_rect();
assert_eq!(
field.height,
dimensions::TEXT_FIELD_MIN_HEIGHT,
"at control height {height}"
);
assert_eq!(field.width, 240, "the field spans the control's width");
assert_eq!(field.y, (height - field.height) as i32 / 2, "at control height {height}");
}
let short = LineEdit::new(Rect::new(0, 0, 240, 20));
assert_eq!(short.field_rect().height, 20, "a short control clamps the field");
}
/// A Macos-profile theme paints and hit-tests macOS's 22 px field band.
///
/// The field is the single derivation both the paint path and the pointer use, so asserting
/// its height pins the whole control rather than one call site.
#[cfg(device_profile)]
#[test]
fn a_macos_profile_theme_uses_the_compact_field_height() {
let _theme_guard = crate::style::theme_test_guard();
let mut theme = crate::theme::Theme::default();
theme.name = "p2-6-lineedit-macos".to_string();
theme.metrics_profile = crate::widget::metrics::ControlMetricsProfile::Macos;
{
let mut manager = crate::theme::global_theme_manager();
manager.register_theme(theme);
assert!(manager.set_theme("p2-6-lineedit-macos"));
}
let le = LineEdit::new(Rect::new(0, 0, 240, 120));
let field = le.field_rect();
assert!(crate::theme::global_theme_manager().set_theme("default"));
assert_eq!(field.height, 22, "macOS's text field is 22 px tall: {field:?}");
assert_eq!(field.y, (120 - 22) / 2, "the compact band is still centred: {field:?}");
assert_eq!(field.width, 240, "and still spans the control");
}
/// The Cupertino profile keeps the Material text-field band unchanged.
#[cfg(device_profile)]
#[test]
fn the_cupertino_profile_keeps_the_material_field_height() {
let _theme_guard = crate::style::theme_test_guard();
let mut theme = crate::theme::Theme::default();
theme.name = "p2-6-lineedit-cupertino".to_string();
theme.metrics_profile = crate::widget::metrics::ControlMetricsProfile::Cupertino;
{
let mut manager = crate::theme::global_theme_manager();
manager.register_theme(theme);
assert!(manager.set_theme("p2-6-lineedit-cupertino"));
}
let field = LineEdit::new(Rect::new(0, 0, 240, 120)).field_rect();
assert!(crate::theme::global_theme_manager().set_theme("default"));
assert_eq!(field.height, dimensions::TEXT_FIELD_MIN_HEIGHT);
}
/// Hit-testing follows the ink: a press below the field does not focus it.
///
/// With the field centred in a 120 px cell, a press on the control's rectangle but
/// 60 px below the drawn band belongs to the window background. The control must not
/// claim it — the clickable area has to be the one a user can see.
#[test]
fn a_press_outside_the_drawn_band_does_not_focus_the_field() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
let field = le.field_rect();
// Inside the band focuses.
le.handle_event(&Event::MousePress {
pos: Point::new(field.x + 10, field.y + field.height as i32 / 2),
button: 1,
modifiers: 0,
});
assert!(le.is_focused(), "a press on the drawn field focuses it");
// Below the band, inside the control's rectangle, does not.
le.set_focused(false);
le.handle_event(&Event::MousePress {
pos: Point::new(field.x + 10, field.y + field.height as i32 + 40),
button: 1,
modifiers: 0,
});
assert!(!le.is_focused(), "a press below the drawn field must not focus it");
}
/// The value is drawn on the field's own middle line.
///
/// The origin of a text run is its glyph box's top-left corner, so the old
/// `rect.y + rect.height / 2` put that corner on the field's middle line and drew the
/// value half a line low. Pinning the drawn line box — not the origin — to the centre is
/// what keeps the two from agreeing by accident.
///
/// # Why the check reads the ink
///
/// The value is no longer a `<text>` element carrying a `y`: the backend emits the same
/// `font8x8` rectangles the software rasteriser fills, as subpaths of one `<path>` (see
/// `crate::widget::svg::text_ink_box`). The ink box is also the better witness, because it
/// is where the glyphs actually landed rather than what an element claimed.
#[cfg(not(alloc_frugal))]
#[test]
fn the_value_sits_on_the_fields_middle_line() {
// 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 le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("Sample");
let svg = crate::widget::svg::render_to_svg(&mut le);
let field = le.field_rect();
let (_, top, _, bottom) = crate::widget::svg::text_ink_box(&svg)
.expect("a field with a value draws it as glyph geometry");
assert!(top >= field.y, "the value starts inside the field: y={top}");
assert!(
bottom <= field.y + field.height as i32,
"and above its bottom edge: y={bottom}, field={field:?}"
);
// And it is *centred*, not merely contained: the field's own line box is the reference
// the value was moved onto, so its ink shares that box's middle line. A value left on
// the old `rect.y + rect.height / 2` anchor sits a whole half line below it.
let mut backend = crate::render::SvgPaintBackend::new(crate::core::Size::new(240, 120));
let context = RenderContext::new(&mut backend);
let font = crate::core::Font::default();
let line = context.text_line(field, &font);
assert_eq!(
top + bottom,
line.y * 2 + line.height as i32,
"the value hangs on the field's own line box middle line"
);
}
/// The value's horizontal origin is the field's own padding.
///
/// A field's text is inset from its edge by [`dimensions::TEXT_FIELD_PADDING_H`]; the
/// origin was a local literal `4`, which is a different fact written in a second place.
///
/// # Why the edge is read off the ink
///
/// There is no `x` attribute to read any more: the backend emits the string as `font8x8`
/// glyph rectangles inside one `<path>` (see `crate::widget::svg::text_ink_box`), so the
/// run's left edge is where the pen actually put its first set bit. `context.text_line`
/// centres the line box's *height*, not each cluster, so the pen itself is `field.x +
/// TEXT_FIELD_PADDING_H` exactly; what is left over is the first glyph's own blank lead
/// column, which the `font8x8` table gives as 0 for `S`. The assertion is still a real
/// constraint on the padding: the pen is what the padding places, and the test would read
/// `padding + 20` (or any other literal) instead of `padding` if the draw site stopped
/// reading [`dimensions::TEXT_FIELD_PADDING_H`].
#[cfg(not(alloc_frugal))]
#[test]
fn the_value_starts_at_the_fields_horizontal_padding() {
// 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 le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("Sample");
let svg = crate::widget::svg::render_to_svg(&mut le);
// The fixture paints only the field's own chrome — a fill and a border — so what is
// left is the value's ink, which no other string in this control can supply.
assert_eq!(svg.matches("<rect").count(), 2, "only the field's fill and border are rects");
let field = le.field_rect();
let (left, _, _, _) = crate::widget::svg::text_ink_box(&svg)
.expect("a field with a value draws it as glyph geometry");
assert_eq!(
left,
field.x + dimensions::TEXT_FIELD_PADDING_H as i32,
"the value starts at the field's own padding: field={field:?}"
);
}
// ─── Decoration slots (F-12) ───
/// A field that never sets a slot must paint exactly as it did, and reserve nothing extra.
///
/// This is the non-change guarantee: the slots are additive, so every existing caller keeps its
/// pixels and its height.
#[test]
fn a_field_with_no_slots_is_unchanged() {
// 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 le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_text("Sample");
assert!(le.decorations().is_empty());
assert_eq!(le.get("prefix").unwrap().as_str(), Some(""));
assert_eq!(le.get("counter").unwrap(), CapabilityValue::Null, "no limit means no counter");
let svg = crate::widget::svg::render_to_svg(&mut le);
// The value is still the only ink, and it still starts at the field's padding.
let (left, _, _, _) = crate::widget::svg::text_ink_box(&svg).expect("the value is drawn");
assert_eq!(left, le.field_rect().x + dimensions::TEXT_FIELD_PADDING_H as i32);
}
/// A prefix is drawn **before** the value, and the value moves right to make room.
///
/// # The defect this pins
///
/// The shortcut is to concatenate `prefix + value` into one string. That draws nearly the same
/// glyphs in nearly the same place, so it looks right — while it also (a) makes `cursor_position ==
/// 0` render after the `$`, and (b) makes a select-all copy the `$`. The distinguishing fact is that
/// the two are **separate ink runs** with the prefix to the left of the value, so the test reads all
/// runs and orders them rather than trusting which one was painted first.
#[test]
fn a_prefix_is_drawn_before_the_value_and_shifts_it() {
// 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 plain = LineEdit::new(Rect::new(0, 0, 240, 120));
plain.set_text("12");
let plain_svg = crate::widget::svg::render_to_svg(&mut plain);
let plain_runs = crate::widget::svg::text_ink_boxes(&plain_svg);
assert_eq!(plain_runs.len(), 1, "a plain field draws its value as one run");
let (plain_left, _, plain_right, _) = plain_runs[0];
let mut prefixed = LineEdit::new(Rect::new(0, 0, 240, 120));
prefixed.set_text("12");
prefixed.set_prefix("$");
let prefixed_svg = crate::widget::svg::render_to_svg(&mut prefixed);
let mut runs = crate::widget::svg::text_ink_boxes(&prefixed_svg);
assert_eq!(
runs.len(),
2,
"the prefix and the value are two runs, not one concatenated string"
);
runs.sort_by_key(|b| b.0);
let (prefix_left, prefix_right) = (runs[0].0, runs[0].2);
let (value_left, value_right) = (runs[1].0, runs[1].2);
// The `$` takes the field's leading padding. The run's left edge is the *ink*, and neither
// face's ink starts exactly at the origin — the `$` bitmap has no set bit in its leftmost
// column, and an outline `$` is inset by its own shape — so the assertion allows the ink
// inset and nothing more. It is still a comparison against where a *value with no prefix*
// starts, so a prefix that ignored the padding and began on the border (or after the
// value) is a whole glyph away and fails.
assert!(
(prefix_left - plain_left).abs() <= INK_INSET_TOLERANCE,
"the prefix starts where a value with no prefix starts: it begins at {prefix_left}, \
the field's leading padding puts a run at {plain_left}"
);
// …and the value is pushed clear of it rather than starting there too.
assert!(
value_left > prefix_right,
"the value must begin past the prefix: prefix ends at {prefix_right}, value at {value_left}"
);
assert!(
value_left > plain_left,
"and further right than it sat without a prefix ({plain_left})"
);
// The value's own ink is the same width as before — only its origin moved, so the prefix did not
// disturb the glyphs it marks.
assert_eq!(
value_right - value_left,
plain_right - plain_left,
"the prefix shifted the value without reshaping it"
);
assert_eq!(prefixed.get("prefix").unwrap().as_str(), Some("$"));
assert!(
plain_left >= plain.field_rect().x + dimensions::TEXT_FIELD_PADDING_H as i32,
"the value is inset by the field's padding, not on the border"
);
}
/// The caret is measured against the **value**, so at `cursor_position == 0` it sits at the value's
/// origin — after a prefix, not after the `$`'s own box.
///
/// This is the property that makes keeping the slots separate worth the trouble: with the prefix
/// folded into the text, `cursor_position == 0` would place the caret to the right of the `$` and
/// the start of the value would be unreachable.
#[test]
fn the_caret_at_position_zero_sits_at_the_values_origin_not_after_the_prefix() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_prefix("$");
le.set_text("12");
le.set_cursor_position(0);
le.set_focused(true);
// The layout is computed against the **real** SVG backend's metrics — the same backend the
// painter uses — and then read for the two facts that matter: the prefix has a box, and the
// value begins past it.
let mut backend = crate::render::svg::SvgPaintBackend::new(le.geometry().size());
let layout = {
let mut context = crate::render::RenderContext::new(&mut backend);
le.decoration_layout(&mut context)
};
let prefix = layout.prefix.expect("the prefix has a box of its own");
assert!(
layout.value.x >= prefix.right(),
"the value must begin at or past the prefix's trailing edge: {layout:?}"
);
assert!(layout.value.width > 0, "and it must keep some room: {layout:?}");
}
/// An error displaces the helper and paints on its own row; the counter shares that row and is
/// derived from the value and the limit.
#[test]
fn the_support_row_shows_the_error_and_a_derived_counter() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set_max_length(Some(5));
le.set_text("abc");
assert_eq!(le.get("counter").unwrap().as_str(), Some("3/5"));
assert_eq!(le.get("over_limit").unwrap().as_bool(), Some(false));
// The helper shows while there is no error…
le.set_helper_text("Up to five characters");
assert_eq!(le.decorations().support_message(), "Up to five characters");
assert!(le.decorations().needs_support_row());
// …and the error displaces it rather than joining it.
le.set_error_text("Too long");
assert_eq!(le.decorations().support_message(), "Too long");
assert!(le.decorations().has_error());
assert_eq!(le.get("error").unwrap().as_str(), Some("Too long"));
assert_eq!(
le.get("helper").unwrap().as_str(),
Some("Up to five characters"),
"the helper is displaced, not deleted"
);
// Over the limit is reported, and the counter says how far. `set_text` enforces the limit too —
// a limit the control honours only while typing is a hint, not a limit — so the value is clamped
// and the pair stays consistent.
le.set_text("abcdefgh");
assert_eq!(le.text(), "abcde", "`set_text` must honour `max_length` like typing does");
assert_eq!(le.get("counter").unwrap().as_str(), Some("5/5"));
assert_eq!(
le.get("over_limit").unwrap().as_bool(),
Some(false),
"the stored value cannot exceed a limit it was clamped to"
);
// Clearing the error restores the helper without the caller having to re-set it.
le.set_error_text("");
assert_eq!(le.decorations().support_message(), "Up to five characters");
}
/// The counter is read-only, and the two in-field slots round-trip through the contract.
#[test]
fn the_slots_round_trip_through_the_property_api() {
let mut le = LineEdit::new(Rect::new(0, 0, 240, 120));
le.set("prefix", CapabilityValue::String("$".to_string())).unwrap();
le.set("suffix", CapabilityValue::String("%".to_string())).unwrap();
le.set("helper", CapabilityValue::String("Hint".to_string())).unwrap();
le.set("error", CapabilityValue::String("Bad".to_string())).unwrap();
assert_eq!(le.get("prefix").unwrap().as_str(), Some("$"));
assert_eq!(le.get("suffix").unwrap().as_str(), Some("%"));
assert_eq!(le.get("helper").unwrap().as_str(), Some("Hint"));
assert_eq!(le.get("error").unwrap().as_str(), Some("Bad"));
// The two derived names are refused, so there is no second writer to disagree with.
assert!(le.set("counter", CapabilityValue::String("1/1".to_string())).is_err());
assert!(le.set("over_limit", CapabilityValue::Bool(true)).is_err());
}
/// A field too narrow for its slots still draws its field chrome and does not panic.
#[test]
fn a_field_squeezed_by_its_slots_still_paints() {
let mut le = LineEdit::new(Rect::new(0, 0, 40, 120));
le.set_prefix("verylongprefix");
le.set_suffix("verylongsuffix");
le.set_text("value");
let svg = crate::widget::svg::render_to_svg(&mut le);
assert!(svg.starts_with("<svg"));
assert!(svg.ends_with("</svg>"));
}
#[test]
fn lineedit_visibility() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
assert!(le.is_visible());
le.hide();
assert!(!le.is_visible());
le.show();
assert!(le.is_visible());
}
#[test]
fn lineedit_enabled() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
assert!(le.is_enabled());
le.set_enabled(false);
assert!(!le.is_enabled());
le.set_enabled(true);
assert!(le.is_enabled());
}
#[test]
fn lineedit_id_kind() {
let le_a = LineEdit::new(Rect::new(0, 0, 100, 24));
let le_b = LineEdit::new(Rect::new(0, 0, 100, 24));
assert_ne!(le_a.id(), le_b.id());
assert_eq!(le_a.kind(), WidgetKind::LineEdit);
assert_eq!(le_b.kind(), WidgetKind::LineEdit);
}
#[test]
fn lineedit_signal_accessors() {
let le = LineEdit::new(Rect::new(0, 0, 100, 24));
let _text_changed = &le.text_changed;
let _editing_finished = &le.editing_finished;
let _return_pressed = &le.return_pressed;
}
#[cfg(not(alloc_frugal))]
#[test]
fn the_caret_is_drawn_at_cursor_position_not_at_the_end() {
// 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();
// The caret used to be measured against the **whole** value, so it was always drawn
// after the last glyph however the control was positioned: with `cursor_position = 0` it
// still sat past the `e` of "Sample". The field answers `cursor_position`, clamps it on
// every write, and acts on it in `backspace`/`delete`, so the marker was the one part of
// the field ignoring the field's own cursor.
//
// The assertion reads the drawn geometry out of the SVG, because the defect is entirely
// about where the ink lands — asserting the stored index would have passed before the fix
// too, which is why it survived.
fn caret_x(cursor_position: usize) -> i32 {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_text("Sample".to_string());
// `focus()` places the caret at the end for the autofocus case, so the requested
// position is applied *after* it — the same order a caller that positions a caret
// uses.
field.set_focused(true);
field.set_cursor_position(cursor_position);
let svg = crate::widget::svg::render_to_svg(&mut field);
// The caret is the only vertical line the control draws, emitted as a `<line>` with
// `x1 == x2`.
svg.lines()
.filter(|line| line.contains("<line"))
.find_map(|line| {
let x1 = line.split("x1=\"").nth(1)?.split('"').next()?;
let x2 = line.split("x2=\"").nth(1)?.split('"').next()?;
if x1 != x2 {
return None;
}
x1.parse::<i32>().ok()
})
.expect("a focused, editable field must draw its caret as a vertical line")
}
let at_start = caret_x(0);
let at_three = caret_x(3);
let at_end = caret_x(6);
// This assertion used to pin the literal `4`, which was a local padding constant
// written at the draw site. The origin is now [`dimensions::TEXT_FIELD_PADDING_H`],
// the same table value every other field insets its content by, so what this pins is
// "the caret starts at the field's own horizontal padding" — the fact the old
// literal was an unshared spelling of, not a different fact.
assert_eq!(
at_start,
dimensions::TEXT_FIELD_PADDING_H as i32,
"a caret at position 0 sits at the text origin (the field's padding inset)"
);
assert!(
at_start < at_three && at_three < at_end,
"the caret must advance with the cursor position, not jump to the end \
({at_start}, {at_three}, {at_end})"
);
}
/// `max_length` is a **character** budget, so truncating at it must count characters.
///
/// The limit is what the user sees and what `counter_text` reports, but an earlier revision
/// truncated with `String::truncate(max)` — a **byte** index. On `"héllo"` (five characters,
/// six bytes) a limit of three cut to `"hé"`, dropping a legal character; and a limit that
/// landed inside a multi-byte character split it, which `String::truncate` panics on rather
/// than permitting.
#[test]
fn max_length_truncates_whole_characters_not_bytes() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("héllo");
assert_eq!(le.text().chars().count(), 5);
le.set_max_length(Some(3));
assert_eq!(le.text(), "hél", "three *characters* are kept, not three bytes");
assert!(le.text().is_char_boundary(le.cursor_position()));
// A limit that falls inside a character must not panic and must not split it.
let mut wide = LineEdit::new(Rect::new(0, 0, 200, 24));
wide.set_text("éééé");
wide.set_max_length(Some(2));
assert_eq!(wide.text(), "éé");
}
/// The limit is compared against the value in the *same* frame it is expressed in.
///
/// `insert_text` computed its remaining room as `max - self.text.len()`, mixing a character
/// budget with a byte length: on `"héllo"` a limit of eight left `8 - 6 == 2` characters of
/// room instead of three, and a limit of six — which the counter shows as "5/6", i.e. one
/// character free — left **zero**, so the field refused every further keystroke.
#[test]
fn insert_text_measures_the_remaining_room_in_characters() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("héllo");
le.set_max_length(Some(6));
le.insert_str("z");
assert_eq!(le.text(), "hélloz", "the counter said 5/6, so one more character fits");
assert_eq!(le.text().chars().count(), 6);
// A multi-character insert is clipped to the room that remains, by character.
let mut clipped = LineEdit::new(Rect::new(0, 0, 200, 24));
clipped.set_text("éé");
clipped.set_max_length(Some(4));
clipped.insert_str("wxyz");
assert_eq!(clipped.text(), "ééwx");
}
/// `selection_range` and `insert_str` are the spellings the other text fields publish
/// (WDGT-14); this pins that they describe and edit the same selection.
#[test]
fn selection_range_and_insert_str_share_the_fields_selection() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("hello world");
assert_eq!(le.selection_range(), None, "no anchor means no range");
le.select_all();
assert_eq!(le.selection_range(), Some((0, 11)));
assert_eq!(le.selected_text(), "hello world", "the range and the text agree");
le.insert_str("bye");
assert_eq!(le.text(), "bye", "the canonical insert replaced the selection");
assert_eq!(le.selection_range(), None);
}
/// The widget layer's half of IME: a preedit updates the preview without touching the value,
/// and a commit replaces the preview with text through the ordinary edit path.
#[test]
fn ime_preedit_and_commit_update_the_model() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.handle_event(&Event::ime_preedit("に", 1));
assert_eq!(field.text(), "", "an uncommitted composition is not the value");
assert_eq!(field.composition(), Some("に"));
field.handle_event(&Event::ime_commit("你好"));
assert_eq!(field.text(), "你好", "the commit enters the model");
assert!(!field.has_composition(), "and ends the composition");
}
/// The IME query reports a real caret rectangle, and it moves with the caret.
///
/// A non-zero rectangle is the whole point: a native candidate window anchored to a zero-sized
/// or off-field box has no insertion point to sit beside. The x advance also has to follow the
/// measured prefix, so the anchor lands on the character the user is inserting at.
#[test]
fn input_method_query_reports_the_caret_rectangle() {
let mut field = LineEdit::new(Rect::new(10, 20, 200, 24));
field.set_text("abc");
field.set_cursor_position(0);
let at_start = field
.input_method_query()
.expect("an editable text field always has an insertion point");
assert!(at_start.caret_rect.width > 0, "the caret must have a width: {at_start:?}");
assert!(at_start.caret_rect.height > 0, "the caret must have a height: {at_start:?}");
assert_eq!(at_start.caret_byte, Some(0));
field.set_cursor_position(3);
let at_end = field.input_method_query().expect("query after moving the caret");
assert_eq!(at_end.caret_byte, Some(3));
assert!(
at_end.caret_rect.x > at_start.caret_rect.x,
"the caret must advance with the measured prefix ({} -> {})",
at_start.caret_rect.x,
at_end.caret_rect.x
);
assert_eq!(at_end.caret_rect.height, at_start.caret_rect.height);
}
/// The caret and the edit keys step by **character**, not by byte.
///
/// A bare `cursor_position += 1` landed inside a multi-byte character, so `insert_text`'s
/// `floor_char_boundary` then rounded forward to the end of the value: on `"éé"` a single
/// Right followed by a keystroke appended instead of inserting one character in. The same
/// arithmetic made `backspace`/`delete` slice mid-character.
#[test]
fn caret_and_edit_keys_step_by_character() {
let mut le = LineEdit::new(Rect::new(0, 0, 200, 24));
le.set_text("éé");
le.set_cursor_position(0);
le.handle_event(&Event::key_press(39, 0)); // Right
assert_eq!(le.cursor_position(), 2, "one character forward is two bytes for 'é'");
le.insert_str("x");
assert_eq!(le.text(), "éxé", "the insert lands at the caret, not at the end");
// Backspace removes the whole character before the caret.
let mut back = LineEdit::new(Rect::new(0, 0, 200, 24));
back.set_text("aé");
back.set_cursor_position(back.text().len());
back.backspace();
assert_eq!(back.text(), "a");
// Delete removes the whole character after the caret.
let mut fwd = LineEdit::new(Rect::new(0, 0, 200, 24));
fwd.set_text("éa");
fwd.set_cursor_position(0);
fwd.delete();
assert_eq!(fwd.text(), "a");
}
/// The caret rides with the glyphs of a centred or right-aligned value.
///
/// The value is laid out from `fitted_origin(value_box, advance, alignment)`; the caret was
/// measured from the field's fixed leading inset instead, so on a right-aligned field the
/// marker sat at the left edge while its own text sat at the right edge. The two now read the
/// same origin function, which is what keeps them together.
#[test]
fn the_caret_follows_a_non_left_aligned_value() {
let _theme_guard = crate::style::theme_test_guard();
fn caret_x(alignment: crate::core::Alignment) -> i32 {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_text("Sample".to_string());
field.set_alignment(alignment);
field.set_focused(true);
field.set_cursor_position(0);
let svg = crate::widget::svg::render_to_svg(&mut field);
svg.lines()
.filter(|line| line.contains("<line"))
.find_map(|line| {
let x1 = line.split("x1=\"").nth(1)?.split('"').next()?;
let x2 = line.split("x2=\"").nth(1)?.split('"').next()?;
(x1 == x2).then(|| x1.parse::<i32>().ok())?
})
.expect("a focused, editable field must draw its caret as a vertical line")
}
let left = caret_x(crate::core::Alignment::Left);
let centre = caret_x(crate::core::Alignment::Center);
let right = caret_x(crate::core::Alignment::Right);
assert!(
left < centre && centre < right,
"a caret at position 0 must follow the value's own alignment \
(left={left}, centre={centre}, right={right})"
);
}
#[cfg(not(alloc_frugal))]
#[test]
fn lineedit_clipboard_copy_paste_cut() {
use crate::event::Event::KeyPress;
// The clipboard is process-wide, so this test must not run concurrently with any
// other test that copies or pastes. Without the guard it failed intermittently
// under the parallel harness while passing on its own.
let _clipboard = crate::clipboard::clipboard_test_guard();
let mut source = LineEdit::new(Rect::new(0, 0, 200, 24));
source.set_text("hello world");
source.select_all();
// Ctrl+C copies the selection to the platform clipboard.
source.handle_event(&KeyPress { key: 67, modifiers: 0b1000 });
assert_eq!(crate::get_clipboard_text(), "hello world");
// Ctrl+V pastes into another field.
let mut target = LineEdit::new(Rect::new(0, 0, 200, 24));
target.handle_event(&KeyPress { key: 86, modifiers: 0b1000 });
assert_eq!(target.text(), "hello world");
// Ctrl+X on a selected field copies then removes the selection.
source.select_all();
source.handle_event(&KeyPress { key: 88, modifiers: 0b1000 });
assert_eq!(source.text(), "");
assert_eq!(crate::get_clipboard_text(), "hello world");
// Read-only fields still copy via Ctrl+C.
let mut read_only = LineEdit::new(Rect::new(0, 0, 200, 24));
read_only.set_text("secret");
read_only.set_read_only(true);
read_only.select_all();
read_only.handle_event(&KeyPress { key: 67, modifiers: 2 });
assert_eq!(crate::get_clipboard_text(), "secret");
// …but editing stays blocked.
assert_eq!(read_only.text(), "secret");
}
/// A refusal travels the **meaning** channel, so it never competes with the interaction one.
///
/// # The defect this pins
///
/// The preset themes declare ten `"<kind>:error"` overrides, and the meaning used to be
/// reported from `widget_state()` — a single-valued chain the interaction also wanted. The
/// interaction won whenever the pointer was over the field, so `"line_edit:error"` stopped
/// applying exactly when the user moved onto the field to read the refusal. The meaning is now
/// orthogonal (`semantic_state`), so the first half of this test proves the control still asks
/// the question, and the second proves the theme's answer arrives on a border.
///
/// # Why this is gated on `full_widgets`
///
/// It installs the preset appearances through `widget::census`, which is the module that owns
/// them and exists only where the widget set is unstripped. On a stripped profile the theme is
/// absent entirely, so there is no preset to install and no `:error` override to read — the
/// subject of the test does not exist there, which is what a profile gate has to say.
#[cfg(full_widgets)]
#[test]
fn a_refused_field_reports_the_error_meaning_and_takes_the_override() {
use crate::style::{SemanticState, WidgetState};
let _theme_guard = crate::style::theme_test_guard();
crate::widget::census::install_preset_appearances();
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
assert_eq!(field.widget_state(), WidgetState::Normal, "a fresh field is at rest");
assert_eq!(field.semantic_state(), SemanticState::None, "and carries no meaning");
field.set_error_text("Too long");
assert_eq!(
field.semantic_state(),
SemanticState::Error,
"a field with a refusal message must say so, or the `:error` override is unreachable"
);
assert_eq!(
field.widget_state(),
WidgetState::Normal,
"but the interaction channel stays at rest: the refusal is not an interaction"
);
// The theme resolves a border for that meaning — the whole point of reporting it.
let border = crate::style::resolved_semantic_border("line_edit", field.semantic_state());
assert!(border.is_some(), "the preset must define a border on `line_edit:error`");
// Clearing the message returns the field to no meaning, so it is not latched.
field.set_error_text("");
assert_eq!(
field.semantic_state(),
SemanticState::None,
"clearing the error restores no meaning"
);
}
/// BLUE24 §3.3 criterion 1: a hovered refusal keeps **both** channels at once.
///
/// This is the assertion the single-valued chain could not satisfy: `widget_state()` was the
/// only way to say "error", so a hovered field could report either the hover or the error but
/// never both. With the channels split, the fill follows the hover and the border follows the
/// meaning in the same frame.
#[cfg(full_widgets)]
#[test]
fn a_hovered_refusal_keeps_hover_fill_and_error_border() {
use crate::event::Event;
use crate::style::{SemanticState, WidgetState};
let _theme_guard = crate::style::theme_test_guard();
crate::widget::census::install_preset_appearances();
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_error_text("Too long");
field.handle_event(&Event::MouseEnter { pos: crate::core::Point::new(10, 10) });
assert_eq!(
field.widget_state(),
WidgetState::Hover,
"the fill answers to the interaction, so a hovered field reports hover"
);
assert_eq!(
field.semantic_state(),
SemanticState::Error,
"and the meaning survives the hover, which is the defect being pinned"
);
// Both channels reach the theme in the same frame: the hover fill and the error border.
let hover_style =
crate::theme::resolved_theme_style_for_state("line_edit", WidgetState::Hover);
assert!(hover_style.is_some(), "the preset defines `line_edit:hover`");
assert!(
crate::style::resolved_semantic_border("line_edit", field.semantic_state()).is_some(),
"and a border for `line_edit:error` at the same time"
);
}
/// The interaction channel still reports `Disabled` for an inert field, refusal or not.
#[test]
fn a_disabled_field_reports_disabled_even_with_a_refusal_message() {
use crate::style::{SemanticState, WidgetState};
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_error_text("Too long");
field.set_enabled(false);
assert_eq!(
field.widget_state(),
WidgetState::Disabled,
"a disabled field cannot be acted on, so its state must say disabled"
);
assert_eq!(
field.semantic_state(),
SemanticState::Error,
"while the meaning is still reported on its own channel"
);
}
}
#[cfg(test)]
mod composition_tests {
use super::*;
use crate::compat::Vec;
fn field() -> LineEdit {
LineEdit::new(Rect::new(0, 0, 200, 24))
}
/// Renders the field into an RGBA frame, for pixel-level assertions.
fn render(widget: &mut LineEdit, rect: Rect) -> Vec<u8> {
use crate::core::{Color, Size};
use crate::render::{PaintBackend, RenderContext, SoftwarePaintBackend};
use crate::widget::Draw;
let mut surface = SoftwarePaintBackend::new(Size::new(rect.width, rect.height), 1.0);
surface.begin_frame(Color::WHITE);
{
let mut context = RenderContext::new(&mut surface);
widget.draw(&mut context);
}
surface.end_frame();
surface.frame_rgba().to_vec()
}
/// A composition does **not** change the field's value.
///
/// # The defect this pins (BLUE24 §12 U-5)
///
/// A platform input method reports the preedit one keystroke at a time. If that went through
/// `insert_text`, the field's value would change on every partial character and `text_changed`
/// would fire for a word the user has not finished — so a form's validation would run against
/// text nobody committed. Holding the composition apart is what makes the value stable until the
/// commit.
#[test]
fn a_composition_does_not_change_the_value() {
let mut field = field();
field.set_text("ab");
field.set_composition("し");
assert_eq!(field.text(), "ab", "the value is untouched while composing");
assert_eq!(field.composition(), Some("し"));
assert!(field.has_composition());
}
/// Committing puts the preedit into the model, at the caret, through the ordinary insert path.
#[test]
fn committing_inserts_the_preedit_as_text() {
let mut field = field();
field.set_text("ab");
field.set_cursor_position(1);
field.set_composition("X");
assert!(field.commit_composition());
assert_eq!(field.text(), "aXb", "a commit is an insert, not a replacement");
assert!(!field.has_composition(), "and the session is over");
assert!(!field.commit_composition(), "a second commit has nothing to accept");
}
/// Cancelling restores nothing, because nothing was changed.
#[test]
fn cancelling_leaves_the_value_exactly_as_it_was() {
let mut field = field();
field.set_text("keep");
field.set_composition("discard me");
assert!(field.cancel_composition());
assert_eq!(field.text(), "keep");
assert!(!field.has_composition());
assert!(!field.cancel_composition(), "there was nothing left to cancel");
}
/// Committing a composition respects `max_length`, exactly as typing does.
///
/// This is the reason the commit goes through `insert_text` rather than writing `text` directly:
/// a shortcut would have been the one edit path in the control that ignores the limit.
#[test]
fn committing_respects_the_max_length() {
let mut field = field();
field.set_max_length(Some(4));
field.set_text("ab");
field.set_composition("cdef");
field.commit_composition();
assert!(field.text().len() <= 4, "the limit applies: got {:?}", field.text());
}
/// A composition can replace a selection, like any other insertion.
#[test]
fn committing_replaces_a_selection() {
let mut field = field();
field.set_text("abc");
field.select_all();
field.set_composition("Z");
field.commit_composition();
assert_eq!(field.text(), "Z", "the commit replaced the selected range");
}
/// An empty preedit withdraws the session without committing anything.
#[test]
fn an_empty_preedit_withdraws_the_session() {
let mut field = field();
field.set_text("ab");
field.set_composition("x");
field.set_composition("");
assert!(!field.has_composition());
assert_eq!(field.text(), "ab", "withdrawing is not committing");
}
/// The preedit is drawn **inline at the caret**, with an underline.
///
/// # The gap this pins (BLUE24 §12 U-5)
///
/// `ImePreedit` is an overlay in a box of its own; it cannot place a composition at a field's
/// caret, because it does not know where that is. The field can, and this asserts it does: the
/// preedit appears after the value's own ink and a horizontal rule is drawn beneath it.
#[test]
fn the_preedit_is_painted_at_the_caret_with_an_underline() {
let bounds = Rect::new(0, 0, 200, 24);
let mut field = LineEdit::new(bounds);
field.set_text("ab");
field.set_cursor_position(2);
field.set_focused(true);
let without = crate::widget::svg::render_widget_to_svg(&mut field, bounds);
field.set_composition("し");
let with = crate::widget::svg::render_widget_to_svg(&mut field, bounds);
assert_ne!(with, without, "an active composition must change what is painted");
// A horizontal rule is a `<line>` with `y1 == y2`; the caret is a vertical one. The underline
// is the only horizontal line this change adds.
let horizontal_lines = |svg: &str| {
svg.lines()
.filter(|line| line.contains("<line "))
.filter(|line| {
let get = |name: &str| -> Option<i32> {
line.split(&format!("{name}=\"")).nth(1)?.split('"').next()?.parse().ok()
};
get("y1").is_some() && get("y1") == get("y2")
})
.count()
};
assert!(
horizontal_lines(&with) > horizontal_lines(&without),
"the preedit must be underlined, or a user cannot see it is uncommitted"
);
// And cancelling removes it again, so the picture is tied to the session.
field.cancel_composition();
let after = crate::widget::svg::render_widget_to_svg(&mut field, bounds);
assert_eq!(horizontal_lines(&after), horizontal_lines(&without));
}
// ── D09-STYLE-02: the hint measures with the font the paint uses ──
/// A caller-authored `style.font` must widen the field's hint and its drawn value.
///
/// # The defect this pins
///
/// `size_hint()` measured the value with `Font::default()` while `draw()` used `style.font`,
/// so a custom face or a scaled theme font left the field asking for less room than its ink
/// needed.
#[test]
fn a_custom_font_grows_the_line_edit_hint_and_the_drawn_value() {
let _theme_guard = crate::style::theme_test_guard();
let mut baseline = LineEdit::new(Rect::new(0, 0, 400, 24));
baseline.set_text("A longer value");
let base_hint = baseline.size_hint();
let base_ink = value_ink_width(&mut baseline);
let mut big = LineEdit::new(Rect::new(0, 0, 400, 24));
big.set_text("A longer value");
big.set_style(
crate::style::WidgetStyle::default().with_font(crate::core::Font::simple("Test", 30.0)),
);
let big_hint = big.size_hint();
let big_ink = value_ink_width(&mut big);
assert!(
big_hint.width > base_hint.width,
"a larger font must widen the field hint: {} vs {}",
big_hint.width,
base_hint.width
);
assert!(
big_ink > base_ink,
"a larger font must widen the drawn value: {big_ink} vs {base_ink}"
);
}
/// A text scale above 1.0, resolved through the theme, must widen the hint.
#[test]
#[cfg(device_profile)]
fn a_theme_text_scale_above_one_grows_the_line_edit_hint() {
use crate::style::environment::{
install_environment, uninstall_environment, EnvironmentProvider,
};
use crate::style::MotionPreference;
struct Scaled(f32);
impl EnvironmentProvider for Scaled {
fn text_scale(&self) -> f32 {
self.0
}
fn motion_preference(&self) -> MotionPreference {
MotionPreference::NoPreference
}
}
let _guard = crate::style::theme_test_guard();
let previous = install_environment(Box::new(Scaled(1.0)));
{
let mut manager = crate::theme::global_theme_manager();
manager.register_theme(crate::theme::Theme::default());
manager.set_appearance(crate::theme::AppearanceMode::Light);
}
let mut at_one = LineEdit::new(Rect::new(0, 0, 400, 24));
at_one.set_text("Scaled value");
crate::theme::apply_active_theme(&mut at_one);
let hint_one = at_one.size_hint();
install_environment(Box::new(Scaled(1.5)));
let mut scaled = LineEdit::new(Rect::new(0, 0, 400, 24));
scaled.set_text("Scaled value");
crate::theme::apply_active_theme(&mut scaled);
let hint_large = scaled.size_hint();
let _ = uninstall_environment();
if let Some(previous) = previous {
install_environment(previous);
}
assert!(
hint_large.width > hint_one.width,
"a text scale above 1.0 must widen the field hint: {} vs {}",
hint_large.width,
hint_one.width
);
}
/// The ink width of the value a field paints, read back from an SVG render.
fn value_ink_width(field: &mut LineEdit) -> i32 {
let svg = crate::widget::svg::render_to_svg(field);
crate::widget::svg::text_ink_box(&svg).map(|(x, _, right, _)| right - x).unwrap_or(0)
}
// ── D09-INPUT-01: platform-committed text reaches the value ──
/// A `TextInput` from the platform must enter the field's value.
///
/// # The defect this pins (D09-INPUT-01)
///
/// The desktop backends deliver a printable character or an IME commit as
/// `Event::TextInput`, not as a `KeyPress`. This handler only matched `KeyPress`, so the text
/// the platform committed was dropped and a focused field never changed. The test feeds
/// `TextInput` (never `KeyPress`) to prove the committed-text path itself is wired.
#[test]
fn text_input_enters_the_value() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_focused(true);
field.handle_event(&Event::TextInput { text: "hé".to_string() });
assert_eq!(field.text(), "hé", "committed text must reach the value");
}
/// An IME commit is committed text and enters the value the same way.
#[test]
fn ime_commit_enters_the_value() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_focused(true);
field.handle_event(&Event::ime_commit("你好"));
assert_eq!(field.text(), "你好");
}
/// A `TextInput` replacing a selection must replace the range, not append to it.
#[test]
fn text_input_replaces_the_selection() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_focused(true);
field.set_text("abcdef".to_string());
field.select_all();
field.handle_event(&Event::TextInput { text: "Z".to_string() });
assert_eq!(field.text(), "Z", "the committed text replaced the selected range");
}
/// Committed text respects `max_length`, exactly as a typed character does.
#[test]
fn text_input_respects_the_max_length() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_focused(true);
field.set_max_length(Some(3));
field.handle_event(&Event::TextInput { text: "abcdef".to_string() });
assert_eq!(field.text().chars().count(), 3, "the limit applies to a commit too");
}
/// A read-only field ignores committed text.
#[test]
fn read_only_ignores_text_input() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_focused(true);
field.set_text("locked".to_string());
field.set_read_only(true);
field.handle_event(&Event::TextInput { text: "X".to_string() });
assert_eq!(field.text(), "locked", "a read-only field must not accept committed text");
}
/// A disabled field ignores committed text.
#[test]
fn disabled_ignores_text_input() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_enabled(false);
field.set_focused(true);
field.handle_event(&Event::TextInput { text: "X".to_string() });
assert_eq!(field.text(), "", "a disabled field must not accept committed text");
}
/// Committed text emits `text_changed` once with the new value, and the edit is undoable.
#[test]
fn text_input_emits_changed_and_is_undoable() {
use crate::compat::Vec;
use std::sync::{Arc, Mutex};
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_focused(true);
let seen = Arc::new(Mutex::new(Vec::<String>::new()));
let seen_clone = seen.clone();
field.text_changed.connect(move |text| seen_clone.lock().unwrap().push(text.to_string()));
field.handle_event(&Event::TextInput { text: "hi".to_string() });
assert_eq!(field.text(), "hi");
assert_eq!(*seen.lock().unwrap(), vec!["hi".to_string()]);
assert!(field.undo(), "committed text is on the undo stack like any other edit");
assert_eq!(field.text(), "");
}
/// The phone grammar filters what may enter the model and reports the digit span.
#[test]
fn the_phone_grammar_filters_and_reports() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_validator(Some(InputValidator::Phone));
// Letters are refused at the insertion path; the separators and digits survive.
field.insert_str("1 (555) 123-4567 x9");
assert_eq!(field.text(), "1 (555) 123-4567 9");
assert!(field.is_valid(), "twelve digits is a valid phone number");
// A programmatic write is trimmed and filtered too.
field.set_text(" +44 20 7946 0958 ");
assert_eq!(field.text(), "+44 20 7946 0958");
assert!(field.is_valid());
// Too few digits is reported, with the message in the error decoration.
field.set_text("123");
assert!(!field.is_valid());
assert!(!field.validation_message().is_empty());
assert_eq!(field.error_text(), field.validation_message());
// Nothing typed is not an error, and the validator's message is cleared.
field.set_text("");
assert!(field.is_valid());
assert_eq!(field.error_text(), "");
}
/// The e-mail grammar refuses whitespace and checks the `local@domain.tld` shape.
#[test]
fn the_email_grammar_validates_shape() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_validator(Some(InputValidator::Email));
field.insert_str("name @domain");
assert_eq!(field.text(), "name@domain", "whitespace never enters the model");
assert!(!field.is_valid(), "a domain without a dot is not an address");
field.set_text("name@domain.com");
assert!(field.is_valid());
assert_eq!(field.validation_message(), "");
// One '@' and non-empty labels are part of the rule.
for invalid in ["@domain.com", "name@.com", "name@domain.", "a@b@c.com"] {
field.set_text(invalid);
assert!(!field.is_valid(), "{invalid} must be rejected");
}
}
/// A caller's own refusal message survives a value that satisfies the grammar.
#[test]
fn the_validator_only_clears_its_own_error() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_validator(Some(InputValidator::Email));
field.set_text("not-an-address");
assert_eq!(field.error_text(), field.validation_message());
field.set_text("name@domain.com");
assert_eq!(field.error_text(), "", "the validator clears the message it wrote");
field.set_error_text("This address is already registered");
assert!(field.is_valid());
assert_eq!(
field.error_text(),
"This address is already registered",
"a caller's refusal must not be cleared by the field's own grammar"
);
}
/// A host rule is consulted through the trait, and its three-way state is published.
///
/// # What this pins
///
/// The field used to hold a closed enum of two grammars, so a caller with its own domain
/// rule had no way to install it. It now holds `Box<dyn Validator>`, and the state is
/// three-way: an empty value is *intermediate* — not yet acceptable, but not an error
/// either — so a form can keep submit disabled without painting the field red.
#[test]
fn a_host_rule_can_be_installed_behind_the_trait() {
#[derive(Debug)]
struct DigitsOnly;
impl Validator for DigitsOnly {
fn state(&self, text: &str) -> ValidationState {
if text.is_empty() {
ValidationState::Intermediate
} else if text.chars().all(|ch| ch.is_ascii_digit()) {
ValidationState::Acceptable
} else {
ValidationState::Invalid
}
}
fn message(&self) -> &'static str {
"Enter digits only"
}
fn filter(&self, text: &str) -> String {
text.chars().filter(|ch| ch.is_ascii_digit()).collect()
}
fn fixup(&self, text: &str) -> Option<String> {
text.is_empty().then(|| "0".to_string())
}
}
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_dyn_validator(Some(Box::new(DigitsOnly)));
assert_eq!(field.validation_state(), ValidationState::Intermediate);
assert!(!field.is_valid(), "intermediate is not acceptable for submission");
assert_eq!(field.error_text(), "", "an incomplete value is not an accusation");
assert_eq!(
field.get("validation_state").unwrap(),
CapabilityValue::String("intermediate".to_string())
);
// The rule's own filter runs on the insertion path.
field.insert_str("a1b2");
assert_eq!(field.text(), "12");
assert_eq!(field.validation_state(), ValidationState::Acceptable);
assert!(field.is_valid());
assert_eq!(
field.get("validation_state").unwrap(),
CapabilityValue::String("acceptable".to_string())
);
assert_eq!(
field.set("validation_state", CapabilityValue::String("invalid".to_string())),
Err(CapabilityAccessError::ReadOnlyProperty),
"the state follows the value and cannot be assigned"
);
// Removing the rule returns the field to its free-form, always-acceptable behaviour.
field.set_dyn_validator(None);
assert_eq!(field.validation_state(), ValidationState::Acceptable);
assert!(field.is_valid());
}
/// A repairable value is fixed up through the rule's own nearest form.
#[test]
fn a_repairable_value_can_be_fixed_up() {
#[derive(Debug)]
struct DomainSuffix;
impl Validator for DomainSuffix {
fn state(&self, text: &str) -> ValidationState {
if text.ends_with("@example.com") {
ValidationState::Acceptable
} else if text.contains('@') {
ValidationState::Invalid
} else {
ValidationState::Intermediate
}
}
fn message(&self) -> &'static str {
"Enter a name@example.com address"
}
fn fixup(&self, text: &str) -> Option<String> {
let name = text.trim();
if name.is_empty() || name.contains('@') {
None
} else {
Some(format!("{name}@example.com"))
}
}
}
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
field.set_dyn_validator(Some(Box::new(DomainSuffix)));
field.insert_str("ada");
assert_eq!(field.validation_state(), ValidationState::Intermediate);
assert!(field.fixup(), "the rule completes the name");
assert_eq!(field.text(), "ada@example.com");
assert!(field.is_valid());
assert!(!field.fixup(), "a value already in its nearest form is not rewritten");
assert!(field.undo(), "the repair goes through the undoable path");
assert_eq!(field.text(), "ada");
}
/// A user edit marks the field dirty; a programmatic write clears the flag.
#[test]
fn the_modified_flag_tracks_user_edits_only() {
let mut field = LineEdit::new(Rect::new(0, 0, 200, 24));
assert!(!field.is_modified());
field.set_text("saved");
assert!(!field.is_modified(), "a programmatic write is the saved state");
field.handle_event(&Event::TextInput { text: "!".to_string() });
assert!(field.is_modified(), "typing must mark the value dirty");
field.set_text("saved");
assert!(!field.is_modified(), "rewriting the value clears the flag");
}
/// The clear button is opt-in, and a press on it erases the value.
#[test]
fn the_optional_clear_button_erases_on_press() {
let rect = Rect::new(0, 0, 200, 48);
let mut plain = LineEdit::new(rect);
plain.set_text("gone");
let mut button = LineEdit::new(rect);
button.set_clear_button_enabled(true);
button.set_text("gone");
assert_ne!(
render(&mut plain, rect),
render(&mut button, rect),
"enabling the button must paint it"
);
let hit = button.clear_button_rect();
button.handle_event(&Event::MousePress {
pos: Point::new(hit.x + 2, hit.y + 2),
button: 1,
modifiers: 0,
});
assert_eq!(button.text(), "", "a press on the clear button empties the field");
}
/// Password echo on edit reveals the value only while the field owns focus.
#[test]
fn password_echo_on_edit_reveals_only_while_focused() {
let rect = Rect::new(0, 0, 200, 48);
let mut field = LineEdit::new(rect);
field.set_echo_mode(EchoMode::Password);
field.set_password_echo_on_edit(true);
field.set_text("secret");
let masked = render(&mut field, rect);
field.set_focused(true);
let revealed = render(&mut field, rect);
assert_ne!(masked, revealed, "focus must reveal the value");
let mut plain = LineEdit::new(rect);
plain.set_echo_mode(EchoMode::Password);
plain.set_text("secret");
assert_eq!(
masked,
render(&mut plain, rect),
"a blurred echo-on-edit field paints the same mask as a plain password field"
);
}
/// A double click selects the word the pointer landed on.
#[test]
fn a_double_click_selects_the_word() {
let mut field = LineEdit::new(Rect::new(0, 0, 240, 48));
field.set_text("alpha beta");
// `alpha` occupies the leading cells; a press inside it selects that word.
field.handle_event(&Event::MouseDoubleClick { pos: Point::new(3, 10), button: 1 });
assert_eq!(field.selected_text(), "alpha");
}
/// A selection paints a band behind the value.
#[test]
fn a_selection_paints_a_band() {
let rect = Rect::new(0, 0, 200, 48);
let mut plain = LineEdit::new(rect);
plain.set_text("selected");
let mut selected = LineEdit::new(rect);
selected.set_text("selected");
selected.select_all();
assert_ne!(
render(&mut plain, rect),
render(&mut selected, rect),
"a selection must change the pixels, or the range is invisible"
);
}
/// A value wider than the field scrolls so the caret stays visible.
#[test]
fn a_long_value_scrolls_to_reveal_the_caret() {
let mut field = LineEdit::new(Rect::new(0, 0, 90, 48));
field.set_text("a very long value that cannot fit");
assert_eq!(field.cursor_position(), field.text().len());
assert!(field.scroll_x() > 0, "the caret at the end needs the value scrolled");
field.set_cursor_position(0);
assert_eq!(field.scroll_x(), 0, "the start of the value needs no scroll");
}
/// Primary+Left/Right step by word instead of by character.
#[test]
fn primary_arrows_step_by_word() {
let mut field = LineEdit::new(Rect::new(0, 0, 240, 24));
field.set_text("one two three");
let end = field.text().len();
field.handle_event(&Event::KeyPress { key: 37, modifiers: 0b1000 });
assert_eq!(field.cursor_position(), 8, "the caret moves to the start of `three`");
field.handle_event(&Event::KeyPress { key: 39, modifiers: 0b1000 });
assert_eq!(field.cursor_position(), end, "and back to the end");
}
/// A selected value is exported as a `text/plain` drag payload.
#[test]
fn a_selection_is_a_drag_payload() {
use crate::event::dnd::DragSource;
let mut field = LineEdit::new(Rect::new(0, 0, 240, 48));
field.set_text("dragged");
field.select_all();
let payload =
field.drag_payload(Point::new(10, 10)).expect("a selected value must be draggable");
assert_eq!(payload.label, "dragged");
assert!(payload.is_type("text/plain"));
}
/// Keyboard focus draws the focus ring; a pointer press does not.
#[test]
fn keyboard_focus_draws_the_focus_ring() {
let rect = Rect::new(0, 0, 200, 48);
let mut blurred = LineEdit::new(rect);
blurred.set_text("x");
let mut focused = LineEdit::new(rect);
focused.set_text("x");
focused.handle_event(&Event::FocusGained { reason: FocusReason::Tab });
assert!(focused.base().draws_focus_ring());
assert_ne!(render(&mut blurred, rect), render(&mut focused, rect));
}
/// The selection and caret signals report a pointer selection once per real change.
#[test]
fn selection_and_caret_signals_report_moves() {
use crate::compat::Vec;
use std::sync::{Arc, Mutex};
let mut field = LineEdit::new(Rect::new(0, 0, 240, 48));
field.set_text("abcdef");
field.set_cursor_position(0);
let carets = Arc::new(Mutex::new(Vec::<usize>::new()));
let carets_clone = carets.clone();
field.cursor_position_changed.connect(move |value| {
carets_clone.lock().unwrap().push(*value);
});
let selections = Arc::new(Mutex::new(0usize));
let selections_clone = selections.clone();
field.selection_changed.connect(move || {
*selections_clone.lock().unwrap() += 1;
});
field.select_all();
assert!(!carets.lock().unwrap().is_empty(), "the caret moved to the end");
assert_eq!(*selections.lock().unwrap(), 1);
}
}