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
//! Single-line text editing: [`text_input`] and [`password_input`].
//!
//! The two are one widget, [`TextInput<C>`], over two answers to where the
//! text lives. [`Plain`] mirrors an `RwSignal<String>`, which is what any field
//! wants. [`Masked`] keeps it in the [`Secret`](crate::Secret) behind a [`Password`] and edits
//! it there, in place: nothing about a password is copied, kept for undo, or
//! allowed out through the clipboard. Everything else — the caret, selection,
//! scrolling, styling, focus — is the same code for both, so a password field
//! cannot fall behind the text field it looks like.
//!
//! Styling (background, borders, etc.) should be handled by wrapping in a Container.
use std::cell::Cell;
use std::collections::VecDeque;
use std::ops::Range;
use std::time::{Duration, Instant};
use unicode_segmentation::GraphemeCursor;
use zeroize::Zeroizing;
use crate::clock::{EventInstant, FrameInstant};
use crate::default_font_family;
use crate::jobs::{JobRequest, RequiredJob, request_job, request_job_at};
use crate::layout::{Constraints, Size};
use crate::reactive::focus::{has_focus_with_keyboard, offer_autofocus};
use crate::reactive::{
CursorIcon, IntoSignal, Password, Prop, RwSignal, SelectionKind, clipboard_copy, has_focus,
paste_into, primary_copy, request_focus,
};
use crate::renderer::{PaintContext, char_index_from_x_styled};
use crate::tree::{LayoutCtx, Tree, WidgetId};
use crate::widget_ref::{WidgetRef, register_widget_ref};
use super::control::Control;
use super::font::{FontFamily, FontWeight, LineHeight};
use super::state_layer::{StateWhen, Stateful};
use super::text_style::{DEFAULT_FONT_SIZE, TextStyle};
use super::widget::{Color, Event, EventResponse, Key, MouseButton, Rect, Widget};
/// The caret, selection band and placeholder colours a field declares for
/// itself.
///
/// These three are not text style. A [`Text`](crate::widgets::Text) draws
/// glyphs and nothing else; only a field draws a caret, a band or a
/// placeholder, so only a field is asked about them. They lived in
/// [`TextStyle`] for a while, each with a doc comment admitting that one
/// widget ever read it, which is the shape of a property in the wrong struct.
///
/// Every field is optional and independent, so declaring only the caret colour
/// leaves the selection at its default.
#[derive(Clone, Copy, Default, PartialEq)]
pub(crate) struct InputStyle {
/// Colour of the caret. Defaults to the resolved text colour — a field
/// that only sets its text colour should not sprout a blue cursor.
pub(crate) cursor_color: Prop<Color>,
/// Colour of the selection band drawn behind the selected glyphs.
pub(crate) selection_color: Prop<Color>,
/// Colour of the placeholder. Defaults to the text colour at reduced
/// alpha — a placeholder is the same text, quieter.
pub(crate) placeholder_color: Prop<Color>,
}
/// Cursor blink interval in milliseconds
const CURSOR_BLINK_MS: u64 = 530;
/// How much of the text colour a placeholder keeps when nothing overrides it.
/// A placeholder is the same text, quieter — not a different colour to pick.
const PLACEHOLDER_ALPHA: f32 = 0.45;
/// Maximum number of undo history entries
const MAX_HISTORY_SIZE: usize = 100;
/// Padding from edges before scrolling starts
const SCROLL_PADDING: f32 = 2.0;
/// Time window for coalescing similar edits (in milliseconds)
const HISTORY_COALESCE_MS: u64 = 500;
/// The ambient facts of one edit: the width the caret has to stay inside, and
/// when the event that caused it happened.
///
/// Built once in `event` and carried down, the way `Container` carries a
/// `HitContext`. They travelled as two positional parameters through thirteen
/// private methods, of which two actually read the instant — and the next
/// ambient fact would have been a fourteenth.
#[derive(Clone, Copy)]
struct Edit {
width: f32,
at: EventInstant,
}
/// Type alias for text input callbacks
type TextCallback = Box<dyn Fn(&str)>;
/// A snapshot of text input state for undo/redo
#[derive(Clone, Debug)]
struct HistoryEntry {
/// The text content
text: String,
/// Cursor position
cursor: usize,
/// Selection anchor
anchor: usize,
}
/// Type of edit operation for history coalescing
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EditType {
Insert,
Delete,
}
/// Undo/redo history manager
struct History {
/// Stack of past states (most recent at end)
undo_stack: VecDeque<HistoryEntry>,
/// Stack of undone states for redo
redo_stack: VecDeque<HistoryEntry>,
/// Time of last edit (for coalescing)
last_edit_time: EventInstant,
/// Type of last edit (for coalescing)
last_edit_type: Option<EditType>,
}
impl History {
fn new() -> Self {
Self {
undo_stack: VecDeque::new(),
redo_stack: VecDeque::new(),
last_edit_time: Instant::now().into(),
last_edit_type: None,
}
}
/// Push a new state to history (clears redo stack)
/// Uses coalescing to merge similar edits within a time window
fn push(&mut self, entry: HistoryEntry, edit_type: EditType, at: EventInstant) {
let since_last = at.duration_since(self.last_edit_time);
// Coalesce similar edits within the time window
let should_coalesce = self.last_edit_type == Some(edit_type)
&& since_last < Duration::from_millis(HISTORY_COALESCE_MS)
&& !self.undo_stack.is_empty();
if !should_coalesce {
self.undo_stack.push_back(entry);
self.redo_stack.clear();
// Limit history size
if self.undo_stack.len() > MAX_HISTORY_SIZE {
self.undo_stack.pop_front();
}
}
self.last_edit_time = at;
self.last_edit_type = Some(edit_type);
}
/// Reset coalescing state (call after non-edit operations like undo/redo)
fn reset_coalescing(&mut self) {
self.last_edit_type = None;
}
/// Undo: pop from undo stack, push current to redo stack
fn undo(&mut self, current: HistoryEntry) -> Option<HistoryEntry> {
if let Some(previous) = self.undo_stack.pop_back() {
self.redo_stack.push_back(current);
Some(previous)
} else {
None
}
}
/// Redo: pop from redo stack, push current to undo stack
fn redo(&mut self, current: HistoryEntry) -> Option<HistoryEntry> {
if let Some(next) = self.redo_stack.pop_back() {
self.undo_stack.push_back(current);
Some(next)
} else {
None
}
}
}
/// Selection state tracking anchor and cursor positions
#[derive(Clone, Copy, Debug, Default)]
pub struct Selection {
/// Where selection started (anchor point)
pub anchor: usize,
/// Current cursor position
pub cursor: usize,
}
impl Selection {
/// Create a new selection with cursor at given position (no selection)
pub fn new(pos: usize) -> Self {
Self {
anchor: pos,
cursor: pos,
}
}
/// Check if there is an active selection (anchor != cursor)
pub fn has_selection(&self) -> bool {
self.anchor != self.cursor
}
/// Get the start and end of the selection (min, max)
pub fn range(&self) -> (usize, usize) {
if self.anchor <= self.cursor {
(self.anchor, self.cursor)
} else {
(self.cursor, self.anchor)
}
}
/// Collapse selection to cursor position
pub fn collapse(&mut self) {
self.anchor = self.cursor;
}
}
/// Where a field's text lives, and what may be done with it.
///
/// Public so that [`TextInput<C>`] can name it, and in a private module so that
/// nothing outside the crate can implement it: the two answers are [`Plain`]
/// and [`Masked`], and a third would be a field the rules above were never
/// asked about.
mod content {
use std::ops::Range;
pub trait Content: 'static {
/// Whether the text is hidden: never copied out, and a Ctrl+arrow
/// does not reveal where its words end.
const HIDDEN: bool;
/// Lend the text, untracked: the editing below runs from events. For
/// finding positions in it, never for copying it out — that is
/// [`snapshot`](Self::snapshot)'s to allow.
fn with_text<R>(&self, f: impl FnOnce(&str) -> R) -> R;
/// A copy for the undo history, or `None` where there may be no
/// copy — which is also what turns undo off.
fn snapshot(&self) -> Option<String>;
/// Replace a byte range, in place, and tell whoever is listening.
/// `Some` with the new character count when what they did with it
/// replaced the text.
fn replace(&mut self, range: Range<usize>, with: &str) -> Option<usize>;
/// Read the text back in layout, tracked. `Some` with the new character
/// count when what is displayed differs from `char_count` characters
/// of what was displayed before.
fn refresh(&mut self, char_count: usize) -> Option<usize>;
/// What is drawn for `char_count` characters.
fn display(&self, char_count: usize) -> String;
/// Enter. `Some` with the new character count when what the submit
/// did replaced the text.
fn submit(&mut self) -> Option<usize>;
}
}
use content::Content;
/// A field's text as an ordinary `String`, mirrored from an `RwSignal`.
///
/// What [`text_input`] builds. The signal is the application's, and the
/// field writes every edit back to it.
pub struct Plain {
value: RwSignal<String>,
text: String,
on_change: Option<TextCallback>,
on_submit: Option<TextCallback>,
}
impl Plain {
/// Make `value` the text, if it is not already. `Some` with the new
/// character count when it was not.
fn adopt(&mut self, value: &str) -> Option<usize> {
if self.text == value {
return None;
}
self.text.clear();
self.text.push_str(value);
Some(self.text.chars().count())
}
/// What a callback just wrote to the signal, read now rather than at the
/// next layout: the loop hands a surface every queued event before laying
/// it out, and the next key in the batch must edit the text as the
/// callback left it (#725).
fn written_back(&mut self) -> Option<usize> {
let value = self.value;
value.with_untracked(|value| self.adopt(value))
}
}
impl Content for Plain {
const HIDDEN: bool = false;
fn with_text<R>(&self, f: impl FnOnce(&str) -> R) -> R {
f(&self.text)
}
fn snapshot(&self) -> Option<String> {
Some(self.text.clone())
}
fn replace(&mut self, range: Range<usize>, with: &str) -> Option<usize> {
self.text.replace_range(range, with);
self.value.set(self.text.clone());
let callback = self.on_change.as_ref()?;
callback(&self.text);
self.written_back()
}
fn refresh(&mut self, _char_count: usize) -> Option<usize> {
let value = self.value;
value.with(|value| self.adopt(value))
}
fn display(&self, _char_count: usize) -> String {
self.text.clone()
}
fn submit(&mut self) -> Option<usize> {
let callback = self.on_submit.as_ref()?;
callback(&self.text);
self.written_back()
}
}
/// A field's text as a [`Secret`](crate::Secret), behind a [`Password`].
///
/// What [`password_input`] builds. The field edits the secret where it lies,
/// and draws [`mask_char`](TextInput::mask_char) once per character without
/// ever reading what the characters are — unless it is told to
/// [`reveal`](TextInput::reveal) them.
pub struct Masked {
password: Password,
mask_char: Prop<char>,
cached_mask_char: char,
reveal: Prop<bool>,
cached_reveal: bool,
on_submit: Option<Box<dyn Fn()>>,
}
impl Content for Masked {
const HIDDEN: bool = true;
fn with_text<R>(&self, f: impl FnOnce(&str) -> R) -> R {
self.password.with_untracked(|secret| f(secret.expose()))
}
fn snapshot(&self) -> Option<String> {
// A history of a password is copies of it. GTK turns undo off for
// invisible text for the same reason.
None
}
fn replace(&mut self, range: Range<usize>, with: &str) -> Option<usize> {
self.password
.edit(|secret| secret.replace_range(range, with));
None
}
fn refresh(&mut self, char_count: usize) -> Option<usize> {
// The count, not the text: counting borrows the secret and keeps
// nothing, and the count is all the display is made of.
let now = self.password.with(|secret| secret.expose().chars().count());
let mask_char = self.mask_char.get_or('•');
let reveal = self.reveal.get_or(false);
let changed = now != char_count
|| mask_char != self.cached_mask_char
|| reveal != self.cached_reveal
// What is drawn while revealed is the text itself, which can change
// without its length changing.
|| reveal;
self.cached_mask_char = mask_char;
self.cached_reveal = reveal;
changed.then_some(now)
}
fn display(&self, char_count: usize) -> String {
if self.cached_reveal {
return self.with_text(str::to_owned);
}
std::iter::repeat_n(self.cached_mask_char, char_count).collect()
}
fn submit(&mut self) -> Option<usize> {
// Enter only says so. Whether the text leaves the field — `take`, and
// it is empty — or stays while a duplicate is checked is the
// application's to decide, and the answer is read back here.
let callback = self.on_submit.as_ref()?;
callback();
Some(self.with_text(|text| text.chars().count()))
}
}
/// A single-line text field, over where its text lives.
///
/// `TextInput` is the plain one, bound to an `RwSignal<String>` by
/// [`text_input`]; [`PasswordInput`] keeps its text in a [`Password`] and is
/// built by [`password_input`].
pub struct TextInput<C = Plain> {
content: C,
cached_char_count: usize,
/// Wiped whenever it is replaced or dropped: for a revealed password it is
/// the text itself.
cached_display_text: Zeroizing<String>,
display_text_dirty: bool,
// Measurement cache (avoid repeated text shaping in paint)
/// Total width of display text
cached_text_width: f32,
/// Cumulative width at each character index (length = char_count + 1)
/// cached_glyph_positions[i] = width of text[0..i]
cached_glyph_positions: Vec<f32>,
/// Whether measurements need to be recalculated
measurements_dirty: bool,
// Metrics resolved from the enclosing container's style. Cached because a
// change to any of them invalidates the glyph measurements below.
cached_font_size: f32,
cached_font_family: FontFamily,
cached_font_weight: FontWeight,
cached_line_height: LineHeight,
cached_letter_spacing: f32,
/// The height of one line of this style, which is the field's height.
cached_line_box: f32,
/// Whether the text refuses to change. Not the same as disabled: a
/// read-only field still takes the focus, still says so, and still lets a
/// selection be made and copied — it only refuses the edit.
readonly: Prop<bool>,
/// Whether a caret is drawn at all. Off costs nothing: no caret, no blink,
/// nothing to wake the loop for.
caret: Prop<bool>,
cached_caret: bool,
/// See [`cursor`](Self::cursor).
cursor: Prop<CursorIcon>,
/// Handle for application code to reach this input — to focus it, mostly.
widget_ref: Option<WidgetRef>,
/// Shown while the value is empty. Reactive: a prompt that changes — PAM
/// asking a different question — changes what the empty field says.
placeholder: Prop<String>,
/// An unmade offer of the initial focus. Cleared once made, so autofocus is
/// a *first layout* behaviour rather than something that fights the user on
/// every relayout.
autofocus_pending: bool,
// Selection state
selection: Selection,
// Cursor blinking
cursor_visible: bool,
last_cursor_toggle: FrameInstant,
// Mouse drag selection
is_dragging: bool,
// Mouse hover state (for cursor icon)
is_hovered: bool,
/// The same fact behind a signal, so a state override resolving it
/// subscribes. Written next to `is_hovered`, never instead of it: the
/// cursor logic reads a bool on the event path, where a subscription
/// would be noise.
hover: RwSignal<bool>,
// Undo/redo history
history: History,
// Horizontal scroll offset for text overflow
scroll_offset: f32,
/// A replaced text whose scroll is still to be fitted to the field's
/// width. Every layout fits it until the field is painted, because a
/// parent can lay the field out again, narrower, after the layout that
/// read the text back: a row that overflows does. Cleared when the field
/// is next painted; a field the frame does not paint keeps fitting.
scroll_fit_pending: Cell<bool>,
/// What this input declares about its own text, and about the furniture
/// only it draws. Boxed and absent by default.
text_style: Option<Box<TextStyle>>,
/// How the declared colour and size move, when declared with a motion.
text_anims: Option<Box<crate::widgets::text_style::TextAnims>>,
input_style: Option<Box<InputStyle>>,
/// Overrides that apply while this field's control is in a state, in
/// declaration order.
states: Vec<(StateWhen, TextStyle)>,
}
/// A field whose text is a [`Secret`](crate::Secret) behind a [`Password`].
pub type PasswordInput = TextInput<Masked>;
impl TextInput<Plain> {
/// Create a TextInput with a Signal for two-way binding.
/// Changes made in the TextInput will be written back to the signal.
pub fn new(signal: RwSignal<String>) -> Self {
// Use get_untracked() to avoid registering layout dependencies during widget creation.
// Layout dependencies should only be registered during the widget's own layout phase.
let text = signal.get_untracked();
let char_count = text.chars().count();
Self::with_content(
Plain {
value: signal,
text,
on_change: None,
on_submit: None,
},
char_count,
)
}
/// Set callback for text changes
pub fn on_change<F: Fn(&str) + 'static>(mut self, callback: F) -> Self {
self.content.on_change = Some(Box::new(callback));
self
}
/// Set callback for submit (Enter key)
pub fn on_submit<F: Fn(&str) + 'static>(mut self, callback: F) -> Self {
self.content.on_submit = Some(Box::new(callback));
self
}
}
impl TextInput<Masked> {
/// A field over `password`, which it reads and edits in place.
pub fn new_password(password: Password) -> Self {
let char_count = password.with_untracked(|secret| secret.expose().chars().count());
Self::with_content(
Masked {
password,
mask_char: Prop::Unset,
cached_mask_char: '•',
reveal: Prop::Unset,
cached_reveal: false,
on_submit: None,
},
char_count,
)
}
/// The character drawn for each one typed (default: '•').
pub fn mask_char<M>(mut self, c: impl IntoSignal<char, M>) -> Self {
self.content.mask_char = c.into_prop();
self
}
/// Draw the text itself rather than its mask, while this says so — the
/// eye button beside a password box.
///
/// Declared rather than rebuilt, so the caret, the selection and the focus
/// stay where they were. What stays hidden is everything else: nothing is
/// copied or cut out, and there is no undo.
///
/// **Drawing the text puts copies of it where drawing any text does.**
/// Shaping makes temporary copies of what it shapes and frees them
/// unwiped, and the measurement and render caches keep what they shaped —
/// all ordinary memory, none of it guido's to wipe. The secret itself
/// stays where it was, and the field's own copy of what it drew is wiped
/// when it is replaced. GTK 4's peek icon makes the same trade: while the
/// text is shown, it is laid out like any other.
pub fn reveal<M>(mut self, reveal: impl IntoSignal<bool, M>) -> Self {
self.content.reveal = reveal.into_prop();
self
}
/// Called on Enter.
///
/// The text is not handed over: the callback reaches it through the
/// [`Password`], as a button beside the field would, and chooses —
/// [`take`](Password::take) moves it out and empties the field,
/// [`duplicate`](crate::Secret::duplicate) keeps the field as it is while a copy
/// is checked. Either way it stays a [`Secret`](crate::Secret), which is `Send`, so PAM
/// can have it on another thread.
pub fn on_submit<F: Fn() + 'static>(mut self, callback: F) -> Self {
self.content.on_submit = Some(Box::new(callback));
self
}
}
impl<C: Content> TextInput<C> {
fn with_content(content: C, cached_char_count: usize) -> Self {
let default_family = default_font_family();
Self {
content,
cached_char_count,
cached_display_text: Zeroizing::new(String::new()),
display_text_dirty: true,
cached_text_width: 0.0,
cached_glyph_positions: Vec::new(),
measurements_dirty: true,
cached_font_size: DEFAULT_FONT_SIZE,
cached_font_family: default_family,
cached_font_weight: FontWeight::NORMAL,
cached_line_height: LineHeight::Normal,
cached_letter_spacing: 0.0,
cached_line_box: 0.0,
readonly: Prop::Unset,
caret: Prop::Unset,
cached_caret: true,
cursor: Prop::Const(CursorIcon::Text),
widget_ref: None,
placeholder: Prop::Unset,
autofocus_pending: false,
selection: Selection::new(0),
cursor_visible: true,
last_cursor_toggle: Instant::now().into(),
is_dragging: false,
is_hovered: false,
hover: crate::reactive::signal::create_signal(false),
history: History::new(),
scroll_offset: 0.0,
scroll_fit_pending: Cell::new(false),
text_style: None,
text_anims: None,
input_style: None,
states: Vec::new(),
}
}
/// Give up the hover.
///
/// Two events mean the same thing — the pointer moved out of the bounds, or
/// it left the surface — and both used to spell it out. The
/// guard lives here rather than at the call sites so that neither can
/// forget it: an unchanged pointer move must not cost a signal write.
fn release_pointer(&mut self) {
if self.is_hovered {
self.is_hovered = false;
self.hover.set(false);
}
}
/// Whether an override applies. Reading the answer subscribes the field to
/// its control, so it is asked only for a state it declares.
fn is_state_active(&self, id: WidgetId, control: Option<&Control>, when: &StateWhen) -> bool {
match (when, control) {
(StateWhen::When(condition), _) => condition.get(),
(_, Some(control)) => control.is_active(when),
// No control above: the field is its own unit. It already tracks
// the pointer for its cursor, and it is the thing that holds the
// focus, so both answers are its own.
(StateWhen::Hovered, None) => self.hover.get(),
(StateWhen::Focused, None) => crate::reactive::focus::focus_path().contains(id),
// Nothing above it declared `enabled`, so nothing switched it off —
// and being read-only is not being disabled.
(StateWhen::Pressed | StateWhen::Disabled, None) => false,
}
}
fn resolved_input_style(&self) -> InputStyle {
self.input_style.as_deref().copied().unwrap_or_default()
}
/// Refuse edits, and nothing else.
///
/// For the field whose answer is already in flight: a lock screen that has
/// sent the password to PAM must stop taking the characters typed while it
/// waits, because they can never be sent and are thrown away when the
/// answer arrives.
///
/// **It keeps the focus, and the ring that says so.** That is the whole
/// reason this is not
/// [`Container::enabled`](crate::widgets::Container::enabled): a disabled
/// thing is not available and gives the keyboard up, while a read-only one
/// is still where your typing is aimed — on a multi-monitor lock screen the
/// `when_focused` ring is the only thing naming the screen. Every toolkit
/// keeps these two apart for exactly this reason: `readonly` beside
/// `disabled` on the web, `setReadOnly` beside `setEnabled` in Qt,
/// `readOnly` beside `enabled` in Flutter.
///
/// The caret is not part of it. A field that should stop blinking while it
/// waits says so with the property that owns that —
/// [`caret`](Self::caret) — driven by the same signal.
///
/// ```
/// use guido::prelude::*;
///
/// let value = create_signal(String::new());
/// let busy = create_signal(false);
/// let _ = text_input(value).readonly(busy).caret(move || !busy.get());
/// ```
///
/// What it refuses is every *edit*: typing, backspace, delete, paste, cut
/// and undo. What it keeps is everything that only reads — the caret moves,
/// a selection can be made and copied, and `Enter` still reaches
/// [`on_submit`](Self::on_submit), which is Qt's line and the one a caller
/// can put its own guard behind.
pub fn readonly<M>(mut self, readonly: impl IntoSignal<bool, M>) -> Self {
self.readonly = readonly.into_prop();
self
}
/// Attach a handle, so application code can move the keyboard here.
///
/// The container has the same builder; put the ref on the *input* when what
/// you mean is "focus this field", since a container around it given the
/// focus keeps it, and the field never hears the keys.
///
/// ```no_run
/// # use guido::prelude::*;
/// let field = create_widget_ref();
/// // ...
/// container().on_click(move || field.focus());
/// ```
pub fn widget_ref(mut self, widget_ref: WidgetRef) -> Self {
self.widget_ref = Some(widget_ref);
self
}
/// Text to show while the field is empty.
///
/// Drawn in the placeholder colour — this field's text colour at reduced
/// alpha unless it declares
/// [`placeholder_color`](Self::placeholder_color) — and
/// never masked, since it is a label rather than a value: a password field
/// with a placeholder shows the word, not bullets.
///
/// Reactive, so a prompt that changes changes the empty field with it.
pub fn placeholder<M>(mut self, text: impl IntoSignal<String, M>) -> Self {
self.placeholder = text.into_prop();
self
}
/// Draw no caret, keeping the focus and everything it carries — click to
/// position, drag to select, the keyboard.
///
/// For a field where the caret says nothing: a masked one, where every
/// character looks the same and you are always at the end. swaylock draws no
/// caret for that reason.
///
/// It is also the cheapest field there is. A blinking caret is the one thing
/// a still screen redraws on its own, twice a second, forever; without it an
/// idle surface wakes the loop for nothing at all.
pub fn no_caret(self) -> Self {
self.caret(false)
}
/// Whether a caret is drawn at all.
///
/// The property [`no_caret`](Self::no_caret) is the shorthand for. Read
/// where the rest of the declared values are read, so a field can be told
/// to stop drawing one without being rebuilt and losing its focus.
pub fn caret<M>(mut self, caret: impl IntoSignal<bool, M>) -> Self {
self.caret = caret.into_prop();
self
}
/// The shape the pointer takes over the field: the I-beam unless said
/// otherwise.
///
/// It is claimed on every pointer event inside the field, a press as well
/// as a move, and the field is inside whatever declared a shape around it,
/// so this is the one place a field's shape can be changed. A masked field
/// with no caret has nothing a click could place, and on a surface with no
/// pointer it should not bring one back:
///
/// ```
/// # use guido::prelude::*;
/// # let secret = create_password();
/// password_input(secret)
/// .no_caret()
/// .cursor(CursorIcon::Hidden);
/// ```
///
/// It takes a signal, as [`Container::cursor`](crate::widgets::Container::cursor)
/// does, and a shape that changes under a still pointer goes out without
/// waiting for it to move.
pub fn cursor<M>(mut self, cursor: impl IntoSignal<CursorIcon, M>) -> Self {
self.cursor = cursor.into_prop();
self
}
/// Take keyboard focus when this input first appears, unless a widget on
/// its own surface has it.
///
/// For a screen that exists to be typed into — a lock screen, a search
/// overlay, a dialog with one field — where making the user click first is
/// the wrong answer, and where there is no cursor to click *with* on a
/// surface that has no pointer.
///
/// The offer is made once, at the input's first layout. Three things
/// shape it:
///
/// - *once*, so a relayout does not drag focus back from wherever the user
/// has since put it
/// - *never from its own surface*, so two autofocusing inputs side by side do
/// not fight — the first laid out wins
/// - *with the keyboard*, when the focus is on another surface: the input
/// takes it only once the keyboard is on its own surface. A popup opened
/// from a focused field gets its focus when the keyboard reaches it,
/// and the field below gets it back when the popup closes. A lock screen
/// built for a monitor plugged in mid-lock does not pull the focus off
/// the one being typed into, and has it if the keyboard comes to it.
///
/// The equivalent elsewhere: Flutter's `autofocus: true`, Floem's
/// `autofocus` focus-nav flag, `forward-focus` on a Slint window.
pub fn autofocus(mut self) -> Self {
self.autofocus_pending = true;
self
}
/// Get the display text (masked for a password), using cache when clean
fn display_text(&mut self) -> &str {
if self.display_text_dirty {
self.cached_display_text = Zeroizing::new(self.content.display(self.cached_char_count));
self.display_text_dirty = false;
}
&self.cached_display_text
}
/// Get the display text for immutable contexts (for paint)
fn display_text_cached(&self) -> &str {
&self.cached_display_text
}
/// Update cached glyph positions if measurements are dirty.
/// Call this from layout() to ensure measurements are ready for paint().
fn update_measurements(&mut self) {
if !self.measurements_dirty {
return;
}
// Ensure display text is current
let _ = self.display_text();
let display = &self.cached_display_text;
let font_size = self.cached_font_size;
let font_family = &self.cached_font_family;
let font_weight = self.cached_font_weight;
let letter_spacing = self.cached_letter_spacing;
// Build cumulative position array (positions[i] = x of the boundary
// before character i) by shaping the text ONCE. The previous
// implementation measured every prefix — O(n) shaping passes of
// O(n) text per keystroke — and flooded the measurement cache with
// one entry per prefix.
self.cached_glyph_positions = crate::renderer::measure_char_positions_styled(
display,
font_size,
*font_family,
font_weight,
letter_spacing,
);
self.cached_text_width = self
.cached_glyph_positions
.last()
.copied()
.unwrap_or_default();
self.cached_line_box = crate::renderer::measure_line_height(
font_size,
*font_family,
font_weight,
self.cached_line_height,
);
self.measurements_dirty = false;
}
/// Get cached width at a character index (0 to char_count inclusive)
fn cached_width_at_char(&self, char_index: usize) -> f32 {
self.cached_glyph_positions
.get(char_index)
.copied()
.unwrap_or(self.cached_text_width)
}
/// Convert a character index to a byte index in the text
fn char_to_byte_index(&self, char_index: usize) -> usize {
self.content.with_text(|text| {
text.char_indices()
.nth(char_index)
.map(|(i, _)| i)
.unwrap_or(text.len())
})
}
/// Convert a character range to a byte range in the cached value
fn char_range_to_byte_range(&self, start: usize, end: usize) -> (usize, usize) {
let byte_start = self.char_to_byte_index(start);
let byte_end = self.char_to_byte_index(end);
(byte_start, byte_end)
}
/// Refresh cached values from the bound signal and this field's style.
///
/// The reads belong to this input because the call its layout is made
/// inside does — see `LayoutCtx::layout_child` — so a change to a declared
/// metric re-lays-out this input and nothing else.
fn refresh(&mut self, ctx: &mut LayoutCtx, id: WidgetId) -> f32 {
let (
new_font_size,
new_font_family,
new_font_weight,
new_line_height,
new_letter_spacing,
overflow,
new_color,
) = {
let style = self.resolved_text_style(ctx.tree_ref(), id);
// Assigned here rather than returned, as the font metrics are:
// the rule in this function is that a value comes back through
// the tuple only when it is compared against its cache below to
// raise a dirty flag.
self.cached_caret = self.caret.get_or(true);
(
style.font_size(id),
style.font_family(),
style.font_weight(),
style.line_height(),
style.letter_spacing(id),
crate::widgets::text::decoration_overflow(style.stroke(), style.shadow()),
self.animates_text_color().then(|| style.color(id)),
)
};
// Compared against what the field holds, in place: a read that
// copied the value out would be a copy per layout.
if let Some(char_count) = self.content.refresh(self.cached_char_count) {
self.text_replaced(char_count);
}
// The declared motions, pointed at what the style now resolves to. The
// same two properties `Text` animates, from the same list — see
// `declares_text_style`.
let new_font_size =
self.retarget_text_anims(ctx, id, new_color.unwrap_or(Color::WHITE), new_font_size);
// Check font properties - only set dirty flag if changed
if (new_font_size - self.cached_font_size).abs() > f32::EPSILON {
self.cached_font_size = new_font_size;
self.measurements_dirty = true;
}
if new_font_family != self.cached_font_family {
self.cached_font_family = new_font_family;
self.measurements_dirty = true;
}
if new_font_weight != self.cached_font_weight {
self.cached_font_weight = new_font_weight;
self.measurements_dirty = true;
}
if new_line_height.key() != self.cached_line_height.key() {
self.cached_line_height = new_line_height;
self.measurements_dirty = true;
}
if new_letter_spacing.to_bits() != self.cached_letter_spacing.to_bits() {
self.cached_letter_spacing = new_letter_spacing;
self.measurements_dirty = true;
}
overflow
}
/// Advance the blink, and ask to be woken when it next changes.
///
/// Returns whether the caret is drawn at all.
///
/// The wake is *scheduled*, not animated. Asking for an animation frame —
/// which is what this did — pins the loop at 60 fps for a square wave that
/// changes twice a second, so 113 frames out of 114 repaint the same pixels.
/// A focused field is the normal state of a lock screen, and that ran all
/// night.
fn update_cursor_blink(&mut self, tree: &Tree, id: WidgetId) -> bool {
if !self.cached_caret || !has_focus_with_keyboard(tree, id) {
return false;
}
let now = tree.frame_instant();
let period = Duration::from_millis(CURSOR_BLINK_MS);
if now.duration_since(self.last_cursor_toggle) >= period {
self.cursor_visible = !self.cursor_visible;
self.last_cursor_toggle = now;
}
true
}
/// Reset cursor to visible (called on input)
/// Restart the caret's blink from the edit that moved it.
///
/// The blink runs on frames and the edit happened on an event, so the
/// phase starts a loop's input latency earlier than the frame that will
/// draw it — which shifts the first blink and nothing else. That is the
/// crossing, made here rather than at each of the callers, which is the
/// only reason this takes an [`EventInstant`] and not the clock it
/// measures against.
fn reset_cursor_blink(&mut self, at: EventInstant) {
let at = at.as_frame_start();
self.cursor_visible = true;
self.last_cursor_toggle = at;
}
/// Where a press at `x` puts the cursor: the nearest boundary, moved out
/// of any cluster it falls inside.
fn char_index_at_x(&self, x: f32, bounds: Rect) -> usize {
self.cluster_start(self.nearest_char_index_at_x(x, bounds))
}
/// Get character index from x coordinate relative to text start.
/// Uses cached glyph positions for O(log n) binary search.
fn nearest_char_index_at_x(&self, x: f32, bounds: Rect) -> usize {
let text_x = bounds.x;
// Account for scroll offset
let relative_x = x - text_x + self.scroll_offset;
if relative_x <= 0.0 {
return 0;
}
if relative_x >= self.cached_text_width {
return self.cached_char_count;
}
// Binary search on cached glyph positions
let positions = &self.cached_glyph_positions;
if positions.is_empty() {
// Fallback if cache not populated (shouldn't happen after layout)
let display = self.display_text_cached();
return char_index_from_x_styled(
display,
self.cached_font_size,
relative_x,
self.cached_font_family,
self.cached_font_weight,
self.cached_letter_spacing,
);
}
// Find the insertion point using binary search
let mut left = 0;
let mut right = positions.len();
while left < right {
let mid = (left + right) / 2;
if positions[mid] < relative_x {
left = mid + 1;
} else {
right = mid;
}
}
// left now points to first position >= relative_x
// Check if click is closer to the previous character
if left > 0 && left < positions.len() {
let prev_x = positions[left - 1];
let curr_x = positions[left];
if (relative_x - prev_x) < (curr_x - relative_x) {
return left - 1;
}
}
left.min(self.cached_char_count)
}
/// Keep the scroll within a text that was replaced wholesale: never past
/// its end, and with its caret in view. Kept as the old text had it, an
/// emptied field drew its caret and placeholder out of sight (#723). A
/// scroll already within the text moves no further than the caret needs.
fn scroll_within_text(&mut self, width: f32) {
self.update_measurements();
let visible_width = width - SCROLL_PADDING * 2.0;
let furthest = (self.cached_text_width - visible_width).max(0.0);
self.scroll_offset = self.scroll_offset.min(furthest);
self.ensure_cursor_visible(width);
}
/// Ensure the cursor is visible by adjusting scroll offset
fn ensure_cursor_visible(&mut self, width: f32) {
// Ensure measurements are up to date
self.update_measurements();
let cursor_x = self.cached_width_at_char(self.selection.cursor);
let visible_width = width - SCROLL_PADDING * 2.0;
if visible_width <= 0.0 {
return;
}
// If cursor is to the left of visible area, scroll left
if cursor_x < self.scroll_offset + SCROLL_PADDING {
self.scroll_offset = (cursor_x - SCROLL_PADDING).max(0.0);
}
// If cursor is to the right of visible area, scroll right
else if cursor_x > self.scroll_offset + visible_width {
self.scroll_offset = cursor_x - visible_width;
}
// Don't scroll past the start
self.scroll_offset = self.scroll_offset.max(0.0);
}
/// Whether the field is refusing edits right now.
///
/// Asked by each of the four functions that write the text, rather than at
/// the entrance: a keystroke is not the only way in — a middle click pastes
/// the primary selection straight into `insert_text` — and a guard at one
/// entrance is a guard the next one does not have. Untracked for the same
/// reason the clipboard guards are: an event does not wait for a layout, so
/// a field told to freeze must be frozen for the very next key rather than
/// for the frame after the next pass.
fn refuses_edits(&self) -> bool {
self.readonly.get_or_untracked(false)
}
/// Insert text at cursor, replacing any selection
fn insert_text(&mut self, text: &str, edit: Edit) {
if self.refuses_edits() {
return;
}
// The field is one line, and a line copied from a terminal brings its
// line break: removed, as HTML strips newlines from an `<input
// type=text>`'s value. Wiped, because a paste is often a password, and
// sized up front so no regrowth frees an unwiped buffer.
const LINE_BREAKS: [char; 2] = ['\n', '\r'];
let mut one_line;
let text = if text.contains(LINE_BREAKS) {
one_line = Zeroizing::new(String::with_capacity(text.len()));
one_line.extend(text.split(LINE_BREAKS));
&one_line
} else {
text
};
// Nothing to insert over nothing selected is no edit, as in `delete`.
if text.is_empty() && !self.selection.has_selection() {
return;
}
// Save state before modification
self.save_to_history(EditType::Insert, edit.at);
let (start, end) = self.selection.range();
let rewritten = self.splice(start, end, text);
self.reset_cursor_blink(edit.at);
self.follow_edit(rewritten, edit.width);
}
/// Delete selected text or character before/after cursor
fn delete(&mut self, forward: bool, edit: Edit) {
if self.refuses_edits() {
return;
}
let cursor = self.selection.cursor;
let (start, end) = if self.selection.has_selection() {
self.selection.range()
} else if forward {
(cursor, self.step(cursor, true))
} else {
(self.step(cursor, false), cursor)
};
// Nothing to delete is no edit: no history entry, and nothing for
// `on_change` to hear.
let mut rewritten = false;
if start < end {
self.save_to_history(EditType::Delete, edit.at);
rewritten = self.splice(start, end, "");
}
self.reset_cursor_blink(edit.at);
self.follow_edit(rewritten, edit.width);
}
/// Replace the characters `start..end` with `text`, and put the cursor
/// after it — or wherever is left of it, when a callback that heard the
/// edit rewrote the text. Says whether one did.
fn splice(&mut self, start: usize, end: usize, text: &str) -> bool {
let (byte_start, byte_end) = self.char_range_to_byte_range(start, end);
let inserted_char_count = text.chars().count();
let replaced = self.content.replace(byte_start..byte_end, text);
// Update cached char count: old - deleted + inserted
self.cached_char_count = self.cached_char_count - (end - start) + inserted_char_count;
self.display_text_dirty = true;
self.measurements_dirty = true;
self.selection = Selection::new(start + inserted_char_count);
if let Some(char_count) = replaced {
self.text_replaced(char_count);
}
replaced.is_some()
}
/// Bring the caret into view after an edit: within the text as well, when
/// a callback replaced it, since the text the scroll was for is gone.
fn follow_edit(&mut self, rewritten: bool, width: f32) {
if rewritten {
self.scroll_within_text(width);
} else {
self.ensure_cursor_visible(width);
}
}
/// The text was replaced wholesale — read back in layout, restored by an
/// undo, or rewritten by a callback — and is now `char_count` characters
/// long.
fn text_replaced(&mut self, char_count: usize) {
self.cached_char_count = char_count;
self.display_text_dirty = true;
self.measurements_dirty = true;
// Clamp selection to valid range, and out of any cluster the new
// text put it inside
self.selection.cursor = self.cluster_start(self.selection.cursor.min(char_count));
self.selection.anchor = self.cluster_start(self.selection.anchor.min(char_count));
self.scroll_fit_pending.set(true);
}
/// Move cursor left/right, optionally extending selection
fn move_cursor(&mut self, direction: i32, extend_selection: bool, word: bool, edit: Edit) {
let new_pos = if word {
self.find_word_boundary(self.selection.cursor, direction)
} else {
self.step(self.selection.cursor, direction > 0)
};
self.selection.cursor = new_pos;
if !extend_selection {
self.selection.collapse();
}
self.reset_cursor_blink(edit.at);
self.ensure_cursor_visible(edit.width);
}
/// The position one character on from `from`, where a character is what
/// is drawn as one: an `e` and its combining accent, a flag of two code
/// points. The arrows, Delete and Backspace all step by it.
///
/// A hidden text steps one `char` at a time, because its mask draws a
/// bullet for each.
fn step(&self, from: usize, forward: bool) -> usize {
if C::HIDDEN {
return if forward {
(from + 1).min(self.cached_char_count)
} else {
from.saturating_sub(1)
};
}
let byte = self.char_to_byte_index(from);
self.content.with_text(|text| {
let mut cursor = GraphemeCursor::new(byte, text.len(), true);
let boundary = if forward {
cursor.next_boundary(text, 0)
} else {
cursor.prev_boundary(text, 0)
};
match boundary {
Ok(Some(to)) if forward => from + text[byte..to].chars().count(),
Ok(Some(to)) => from - text[to..byte].chars().count(),
_ => from,
}
})
}
/// `at`, or the start of the character as drawn that it falls inside.
fn cluster_start(&self, at: usize) -> usize {
if C::HIDDEN {
return at;
}
let byte = self.char_to_byte_index(at);
let inside = self.content.with_text(|text| {
GraphemeCursor::new(byte, text.len(), true).is_boundary(text, 0) == Ok(false)
});
if inside { self.step(at, false) } else { at }
}
/// Find word boundary in given direction
fn find_word_boundary(&self, start: usize, direction: i32) -> usize {
let len = self.cached_char_count;
// Where a hidden text's words end is part of what is hidden, so a
// word jump goes to the edge, as GTK's password entry does.
if C::HIDDEN {
return if direction < 0 { 0 } else { len };
}
if direction < 0 {
// Move left - collect only the prefix up to cursor (not entire string)
if start == 0 {
return 0;
}
// Collect characters before cursor position
let prefix: Vec<char> = self.content.with_text(|t| t.chars().take(start).collect());
let mut pos = prefix.len() - 1;
// Skip whitespace going backwards
while pos > 0 && prefix[pos].is_whitespace() {
pos -= 1;
}
// Skip word characters going backwards
while pos > 0 && !prefix[pos - 1].is_whitespace() {
pos -= 1;
}
pos
} else {
// Move right - use iterator directly, no allocation
if start >= len {
return len;
}
self.content.with_text(|text| {
let mut pos = start;
let mut chars = text.chars().skip(start).peekable();
// Skip word characters
while let Some(&c) = chars.peek() {
if c.is_whitespace() {
break;
}
chars.next();
pos += 1;
}
// Skip whitespace
for c in chars {
if !c.is_whitespace() {
break;
}
pos += 1;
}
pos.min(len)
})
}
}
/// Move cursor to start/end
fn move_to_edge(&mut self, to_start: bool, extend_selection: bool, edit: Edit) {
self.selection.cursor = if to_start { 0 } else { self.cached_char_count };
if !extend_selection {
self.selection.collapse();
}
self.reset_cursor_blink(edit.at);
self.ensure_cursor_visible(edit.width);
}
/// Select all text
fn select_all(&mut self, edit: Edit) {
self.selection.anchor = 0;
self.selection.cursor = self.cached_char_count;
self.reset_cursor_blink(edit.at);
self.ensure_cursor_visible(edit.width);
}
/// Get selected text
fn get_selected_text(&self) -> Option<String> {
if self.selection.has_selection() {
let (start, end) = self.selection.range();
let (byte_start, byte_end) = self.char_range_to_byte_range(start, end);
Some(
self.content
.with_text(|text| text[byte_start..byte_end].to_string()),
)
} else {
None
}
}
/// The selection, when it is allowed to leave the widget.
///
/// `None` for a password. What a masked field holds must not reach the
/// clipboard or the primary selection, and the leak that matters is not
/// Ctrl+C — it is the primary selection, which an ordinary mouse drag fills
/// with no keystroke at all, ready for a middle-click anywhere else. GTK4's
/// `GtkPasswordEntry` refuses to export for the same reason; GTK3 exported
/// the mask instead, which is a row of bullets that is no use to paste.
///
/// Pasting *into* the field stays allowed. Blocking that is the security
/// theatre banking sites are mocked for: it stops password managers, not
/// attackers, and pushes people towards passwords they can type.
fn exportable_selection(&self) -> Option<String> {
if C::HIDDEN {
return None;
}
self.get_selected_text()
}
/// Copy selected text to clipboard
fn copy_selection(&self) {
if let Some(text) = self.exportable_selection() {
clipboard_copy(&text);
}
}
/// Cut selected text (copy and delete)
fn cut_selection(&mut self, edit: Edit) {
// A cut that cannot copy is not a cut. Refusing the gesture outright is
// what GtkPasswordEntry does, and it keeps Ctrl+X from quietly becoming
// a delete while the user believes the clipboard was filled.
if C::HIDDEN {
return;
}
if self.selection.has_selection() {
self.copy_selection();
self.delete(false, edit); // Delete the selection
}
}
/// Ask for a paste. The text comes back as `Event::Pasted`, once the
/// application that owns the selection has answered.
fn paste(&self, kind: SelectionKind, id: WidgetId) {
if !self.refuses_edits() {
paste_into(kind, id);
}
}
/// Save current state to history (call before making changes)
fn save_to_history(&mut self, edit_type: EditType, at: EventInstant) {
if let Some(entry) = self.current_history_entry() {
self.history.push(entry, edit_type, at);
}
}
/// Get current state as a history entry, where the text allows one.
fn current_history_entry(&self) -> Option<HistoryEntry> {
Some(HistoryEntry {
text: self.content.snapshot()?,
cursor: self.selection.cursor,
anchor: self.selection.anchor,
})
}
/// Undo the last change
fn undo(&mut self, edit: Edit) {
if self.refuses_edits() {
return;
}
let Some(current) = self.current_history_entry() else {
return;
};
if let Some(previous) = self.history.undo(current) {
self.restore(previous, edit);
}
}
/// Redo the last undone change
fn redo(&mut self, edit: Edit) {
if self.refuses_edits() {
return;
}
let Some(current) = self.current_history_entry() else {
return;
};
if let Some(next) = self.history.redo(current) {
self.restore(next, edit);
}
}
/// Put back a state from the history.
fn restore(&mut self, entry: HistoryEntry, edit: Edit) {
let whole = self.content.with_text(str::len);
let replaced = self.content.replace(0..whole, &entry.text);
self.selection.cursor = entry.cursor;
self.selection.anchor = entry.anchor;
self.text_replaced(replaced.unwrap_or_else(|| entry.text.chars().count()));
self.history.reset_coalescing();
self.reset_cursor_blink(edit.at);
self.scroll_within_text(edit.width);
}
/// Handle key down event
fn handle_key(
&mut self,
id: WidgetId,
key: &Key,
ctrl: bool,
shift: bool,
edit: Edit,
) -> EventResponse {
// What the *answer* is for a key a read-only field will not use — the
// refusal itself is at the four writers, which is what makes it hold
// for the middle-click paste as well. `Ignored` rather than `Handled`,
// because a keystroke this field will not use is a keystroke somebody
// else may: Qt's read-only line edit ignores them for the same reason.
if mutates(key, ctrl) && self.refuses_edits() {
return EventResponse::Ignored;
}
match key {
Key::Backspace => {
self.delete(false, edit);
EventResponse::Handled
}
Key::Delete => {
self.delete(true, edit);
EventResponse::Handled
}
Key::Enter => {
if let Some(char_count) = self.content.submit() {
self.text_replaced(char_count);
self.scroll_within_text(edit.width);
}
EventResponse::Handled
}
Key::Left => {
if !shift && self.selection.has_selection() {
// Collapse to start of selection
let (start, _) = self.selection.range();
self.selection = Selection::new(start);
self.reset_cursor_blink(edit.at);
} else {
self.move_cursor(-1, shift, ctrl, edit);
}
EventResponse::Handled
}
Key::Right => {
if !shift && self.selection.has_selection() {
// Collapse to end of selection
let (_, end) = self.selection.range();
self.selection = Selection::new(end);
self.reset_cursor_blink(edit.at);
} else {
self.move_cursor(1, shift, ctrl, edit);
}
EventResponse::Handled
}
Key::Home => {
self.move_to_edge(true, shift, edit);
EventResponse::Handled
}
Key::End => {
self.move_to_edge(false, shift, edit);
EventResponse::Handled
}
Key::Char(c) => {
if ctrl {
match c.to_ascii_lowercase() {
'a' => {
self.select_all(edit);
EventResponse::Handled
}
'c' => {
self.copy_selection();
EventResponse::Handled
}
'x' => {
self.cut_selection(edit);
EventResponse::Handled
}
'v' => {
self.paste(SelectionKind::Clipboard, id);
EventResponse::Handled
}
'z' => {
// Ctrl+Shift+Z = redo, Ctrl+Z = undo
if shift {
self.redo(edit);
} else {
self.undo(edit);
}
EventResponse::Handled
}
'y' => {
// Ctrl+Y = redo
self.redo(edit);
EventResponse::Handled
}
_ => EventResponse::Ignored,
}
} else if !c.is_control() {
// Encoded on the stack: a `String` per keystroke is a
// heap copy of every character of a password.
self.insert_text(c.encode_utf8(&mut [0; 4]), edit);
EventResponse::Handled
} else {
EventResponse::Ignored
}
}
_ => EventResponse::Ignored,
}
}
}
/// Whether this keystroke would change the text.
///
/// Only decides what a read-only field *answers* — the edit is already refused
/// at the writers — so a key missing from this list is a key answered
/// `Handled` that changes nothing, rather than a hole.
fn mutates(key: &Key, ctrl: bool) -> bool {
match key {
Key::Backspace | Key::Delete => true,
Key::Char(c) if ctrl => matches!(c.to_ascii_lowercase(), 'x' | 'v' | 'z' | 'y'),
Key::Char(c) => !c.is_control(),
_ => false,
}
}
impl<C: Content> Stateful for TextInput<C> {
type Style = TextStyle;
fn push_state_style(&mut self, when: StateWhen, style: TextStyle) {
self.states.push((when, style));
}
}
crate::widgets::text_style::declares_text_style!(impl[C: Content] TextInput<C>, text_style, text_anims);
/// The field's own furniture: the caret, the selection band and the
/// placeholder.
///
/// Inherent, and only here, because a field is the only widget that draws any
/// of it. A caret colour on a `Text` would be a property nothing reads, and a
/// container declares nothing about the text inside it.
impl<C: Content> TextInput<C> {
fn input_style_mut(&mut self) -> &mut InputStyle {
self.input_style.get_or_insert_with(Box::default)
}
/// Colour of the caret.
pub fn cursor_color<M>(mut self, color: impl IntoSignal<Color, M>) -> Self {
self.input_style_mut().cursor_color = color.into_prop();
self
}
/// Colour of the selection band behind the selected glyphs.
pub fn selection_color<M>(mut self, color: impl IntoSignal<Color, M>) -> Self {
self.input_style_mut().selection_color = color.into_prop();
self
}
/// Colour of the placeholder.
pub fn placeholder_color<M>(mut self, color: impl IntoSignal<Color, M>) -> Self {
self.input_style_mut().placeholder_color = color.into_prop();
self
}
}
impl<C: Content> Widget for TextInput<C> {
/// A field is a place Tab stops at. It has no children to register.
fn register_children(&mut self, tree: &mut Tree, id: WidgetId) {
tree.make_tab_stop(id);
}
fn advance_animations(&mut self, tree: &mut Tree, id: WidgetId) -> bool {
let blinking = self.update_cursor_blink(tree, id);
let animating = self.advance_text_anims(tree, id);
blinking || animating
}
fn layout(&mut self, ctx: &mut LayoutCtx, constraints: Constraints) -> Size {
let id = ctx.id();
// Text inputs are never relayout boundaries
ctx.tree().set_relayout_boundary(id, false);
// Refresh cached values from reactive properties. The reads belong to
// this layout, which is the scope the call was made inside.
let overflow = self.refresh(ctx, id);
ctx.tree().set_own_paint_reach(id, overflow);
// Update measurement cache (has internal dirty check)
self.update_measurements();
// Use cached text width for sizing (TextMeasurer caches the actual measurement)
// Use previous height from tree to maintain stable sizing
let prev_height = ctx
.tree_ref()
.cached_size(id)
.map(|s| s.height)
.unwrap_or(0.0);
let height = self.cached_line_box.max(prev_height);
// Text inputs should fill available width (like HTML input elements)
// Use max_width if available, otherwise fall back to measured width
let width = if constraints.max_width.is_finite() && constraints.max_width > 0.0 {
constraints.max_width
} else {
self.cached_text_width.max(100.0) // Minimum 100px if unconstrained
};
let size = Size::new(
width.max(constraints.min_width).min(constraints.max_width),
height
.max(constraints.min_height)
.min(constraints.max_height),
);
// Measured now that the width is known, against the text it holds now.
if self.scroll_fit_pending.get() {
self.scroll_within_text(size.width);
}
if let Some(widget_ref) = self.widget_ref {
register_widget_ref(id, widget_ref);
}
// Here rather than at construction because focus needs the tree, and
// this is the first moment the input is in one — the same reason Flutter
// makes you wait for a post-frame callback to request focus by hand.
if self.autofocus_pending {
self.autofocus_pending = false;
offer_autofocus(ctx.tree(), id);
}
size
}
fn paint(&self, ctx: &mut PaintContext) {
let (tree, id) = (ctx.tree(), ctx.id());
// Draw in LOCAL coordinates (0,0 is widget origin)
// Parent Container sets position transform
let bounds = tree.get_bounds(id).unwrap_or_default();
// Every layout of this pass has fitted the scroll by now; the last
// one, at the width drawn here, is the one that holds.
self.scroll_fit_pending.set(false);
let display = self.display_text_cached();
let is_focused = has_focus(id);
// Read inside the scope the framework opened around this call, so a
// change to one repaints this input and nothing else.
let (text_color, selection_color, cursor_color, stroke, shadow, placeholder) = {
let style = self.resolved_text_style(tree, id);
let input = self.resolved_input_style();
let text_color = crate::widgets::container::get_animated_value(
self.text_anims.as_ref().and_then(|a| a.color.as_ref()),
|| style.color(id),
);
// Only when there is nothing to show instead. Read inside the
// tracking scope like every other paint input, so a prompt that
// changes repaints the field.
// The emptiness test first: reading the prop clones the prompt out
// and subscribes to it, and a field with content shows no prompt —
// so doing it the other way round allocates a `String` per paint
// and repaints a field for a prompt it is not displaying.
let placeholder = (self.cached_char_count == 0)
.then(|| self.placeholder.get())
.flatten()
.map(|placeholder| {
let color = input.placeholder_color.get_or(Color::rgba(
text_color.r,
text_color.g,
text_color.b,
text_color.a * PLACEHOLDER_ALPHA,
));
(placeholder, color)
});
(
text_color,
input
.selection_color
.get_or(Color::rgba(0.4, 0.6, 1.0, 0.4)),
// The caret defaults to the text colour: an input that
// only sets `text_color` should not sprout a blue cursor.
input.cursor_color.get_or(text_color),
style.stroke(),
style.shadow(),
placeholder,
)
};
// The text scrolls horizontally under a fixed viewport, so whatever
// slid past either edge has to be cut at the widget's bounds.
//
// Horizontally only: the vertical axis never scrolls, and closing it
// would trim descenders and any glyph stroke or shadow, which the
// viewport is not meant to touch. One em of slack each way is past
// anything a single line can reach.
let slack = self.cached_font_size;
ctx.set_clip_rect(Rect::new(
0.0,
-slack,
bounds.width,
bounds.height + slack * 2.0,
));
// Draw selection highlight if focused and has selection (LOCAL coords)
if is_focused && self.selection.has_selection() {
let (start, end) = self.selection.range();
let start_x = self.cached_width_at_char(start) - self.scroll_offset;
let end_x = self.cached_width_at_char(end) - self.scroll_offset;
let selection_rect = Rect::new(start_x, 0.0, end_x - start_x, bounds.height);
ctx.draw_rounded_rect(selection_rect, selection_color, 0.0);
}
// Draw text with scroll offset (LOCAL coords)
let text_bounds = Rect::new(
-self.scroll_offset,
0.0,
self.cached_text_width.max(bounds.width),
bounds.height,
);
// The placeholder stands in for the text, never beside it: it is only
// resolved when the value is empty, so there is nothing to overlap.
let (drawn, drawn_color) = match &placeholder {
Some((text, color)) => (text.as_str(), *color),
None => (display, text_color),
};
ctx.draw_text_decorated(
drawn,
text_bounds,
drawn_color,
self.cached_font_size,
self.cached_font_family,
self.cached_font_weight,
self.cached_line_height,
self.cached_letter_spacing,
crate::widgets::TextAlign::Start,
stroke,
shadow,
// One line, laid out with no width: a field scrolls, it never wraps.
Some(crate::renderer::LineFit::wrapping(None)),
);
// The caret, and the wake that keeps it blinking.
//
// `self.caret` gates the *drawing*, not only the blink: stopping the blink
// leaves `cursor_visible` at whatever it last was — true, from the
// constructor — and a field asked for no caret got a permanent one.
// Not while the surface is without the keyboard: the field keeps the
// focus then, and a caret blinking in it would say keys go there.
if self.cached_caret && has_focus_with_keyboard(tree, id) {
// The toggle happens in `advance_animations`, and this is what asks
// for the wake that runs it. It has to be here, not at the moment
// focus arrives: focus comes from a click, from `autofocus`, or from
// `WidgetRef::focus()`, and all three only queue a repaint. Asking
// from the repaint covers every one of them, and covers the half of
// the cycle where the caret is hidden and there is nothing to draw.
request_job_at(
id,
JobRequest::Animation(RequiredJob::Paint),
// A deadline the loop compares against the wall clock, so it
// leaves the frame's sequence here.
(self.last_cursor_toggle + Duration::from_millis(CURSOR_BLINK_MS)).into_inner(),
);
if self.cursor_visible {
let cursor_x =
self.cached_width_at_char(self.selection.cursor) - self.scroll_offset;
let cursor_rect = Rect::new(
cursor_x,
0.0,
1.5, // cursor width
bounds.height,
);
ctx.draw_rounded_rect(cursor_rect, cursor_color, 0.0);
}
}
}
fn event(&mut self, tree: &mut Tree, id: WidgetId, event: &Event) -> EventResponse {
// When this event happened, which every edit below is timed against —
// the undo-coalescing window and the caret restarting on input.
let edit = Edit {
width: tree.get_bounds(id).unwrap_or_default().width,
at: tree.event_instant(),
};
// Get bounds from Tree for hit testing
let bounds = tree.get_bounds(id).unwrap_or_default();
let pointed_at = bounds.contains_at(event.coords());
if pointed_at {
tree.point_shows_cursor(self.cursor);
}
match event {
Event::MouseDown {
at: Some(at),
button,
..
} if bounds.contains(at.x, at.y) && *button == MouseButton::Left => {
// Focus, then repaint to show the caret where the click landed.
// The blink schedules its own next wake from `paint`.
request_focus(tree, id);
request_job(id, JobRequest::Paint);
// Set cursor position
let char_index = self.char_index_at_x(at.x, bounds);
self.selection = Selection::new(char_index);
self.is_dragging = true;
self.reset_cursor_blink(edit.at);
self.ensure_cursor_visible(bounds.width);
return EventResponse::Handled;
}
// Matched whether or not it has a position, because the two
// halves want different answers: a move with no position is over
// nothing, so the hover below has to fall — but it says nothing
// about where a selection has got to, so the drag keeps what it
// had rather than being dragged to the start of the line.
Event::MouseMove { at, .. } => {
if pointed_at && !self.is_hovered {
self.is_hovered = true;
self.hover.set(true);
} else if !pointed_at {
self.release_pointer();
}
if let Some(at) = at
&& self.is_dragging
{
// Extend selection while dragging
let char_index = self.char_index_at_x(at.x, bounds);
self.selection.cursor = char_index;
self.ensure_cursor_visible(bounds.width);
request_job(id, JobRequest::Paint);
return EventResponse::Handled;
}
}
Event::MouseUp { button, .. } if *button == MouseButton::Left && self.is_dragging => {
self.is_dragging = false;
// Select-to-copy: a completed mouse selection becomes the
// primary selection (middle-click paste elsewhere)
if let Some(text) = self.exportable_selection() {
primary_copy(&text);
}
return EventResponse::Handled;
}
Event::MouseDown {
at: Some(at),
button,
..
} if bounds.contains(at.x, at.y) && *button == MouseButton::Middle => {
// Middle-click paste from the primary selection
request_focus(tree, id);
let char_index = self.char_index_at_x(at.x, bounds);
self.selection = Selection::new(char_index);
self.paste(SelectionKind::Primary, id);
self.reset_cursor_blink(edit.at);
request_job(id, JobRequest::Paint);
return EventResponse::Handled;
}
// A press inside a field that holds the keyboard is the field's,
// whatever the button pressed. The dispatcher takes the focus off a
// press nobody claimed, and the arms above claim only left and
// middle — so a right press on the caret used to blur the very
// field it landed on.
//
// Said on the tree rather than by returning `Handled`, which also
// means consumed: a row wrapping the field declaring `on_right_click`
// never saw the press, and whether it fired depended on where the
// keyboard was. The same conflation as #308, one widget over.
Event::MouseDown { at: Some(at), .. }
if has_focus(id) && bounds.contains(at.x, at.y) =>
{
tree.keep_the_focus_this_press_landed_on();
}
// A key is only ever routed to the field with the focus.
Event::KeyDown { key, modifiers, .. } => {
let response = self.handle_key(id, key, modifiers.ctrl, modifiers.shift, edit);
if response == EventResponse::Handled {
request_job(id, JobRequest::Paint);
}
return response;
}
// Inserted at the caret as it is now, which is where it was asked
// for unless the user moved it while the answer was on its way.
Event::Pasted(text) => {
self.insert_text(text.as_str(), edit);
request_job(id, JobRequest::Paint);
return EventResponse::Handled;
}
// The surface losing the keyboard keeps the focus here, and the
// caret goes until it is back; see `has_focus_with_keyboard`.
Event::FocusOut if has_focus(id) => {
self.is_dragging = false;
request_job(id, JobRequest::Paint);
}
Event::FocusIn if has_focus(id) => {
self.reset_cursor_blink(edit.at);
request_job(id, JobRequest::Paint);
}
Event::MouseLeave => {
// A selection drag survives the pointer leaving the *field* —
// that is how you select past its edge, and `release_pointer`
// above is called for it. It must not survive the pointer
// leaving the *surface*, because nothing out there will ever
// deliver the release that ends it: the drag would then extend
// on the next move that arrived, with no button held. A touch
// gesture the compositor cancels is how that now happens.
self.is_dragging = false;
self.release_pointer();
}
_ => {}
}
// A point on the field that it did not take is still on the field:
// what it covers is not under the point, and the I-beam it showed
// must not be overwritten by a widget beneath it (#636).
if pointed_at {
EventResponse::Hit
} else {
EventResponse::Ignored
}
}
}
/// Create a text input widget with two-way signal binding.
///
/// Changes made in the text input will be written back to the signal.
/// ```no_run
/// # use guido::prelude::*;
/// let username = create_signal(String::new());
/// text_input(username);
/// ```
pub fn text_input(signal: RwSignal<String>) -> TextInput {
TextInput::new(signal)
}
/// Create a password field over `password`.
///
/// The field reads and edits the [`Secret`](crate::Secret) the [`Password`] holds, in place,
/// and draws one [`mask_char`](TextInput::mask_char) per character. Nothing
/// about the text is copied: there is no undo history, nothing can be copied
/// or cut out of it, and [`on_submit`](TextInput::<Masked>::on_submit) is told
/// of Enter and reaches the secret through the `Password`.
/// [`reveal`](TextInput::reveal) shows the text, at the cost it documents.
///
/// ```no_run
/// # use guido::prelude::*;
/// let password = create_password();
/// let busy = create_signal(false);
///
/// password_input(password)
/// .placeholder("Password")
/// .readonly(busy)
/// .on_submit(move || {
/// busy.set(true);
/// // Moved out, and the field is empty; dropping it wipes it.
/// let secret: Secret = password.take();
/// # let _ = secret;
/// });
///
/// // Wiped in place, for instance after an idle timeout.
/// password.clear();
/// ```
pub fn password_input(password: Password) -> PasswordInput {
TextInput::new_password(password)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Secret;
use crate::jobs::JobType;
use crate::jobs::{clear_pending_jobs, clear_scheduled_jobs, next_deadline, queued_job_types};
use crate::layout::Constraints;
use crate::reactive::create_signal;
use crate::widgets::PointerKind;
/// A move with no position says nothing about where a drag has got to.
///
/// A pointer event that has descended into a subtree collapsed to nothing
/// arrives without a position (#227), and the arm that extends a selection
/// has to leave it alone rather than read the absence as an origin — which
/// is what an earlier attempt's far-away sentinel did, putting the cursor
/// at index 0 for as long as the box was closed.
///
/// A guard rather than a fix: the shape that ships already holds this,
/// because the drag branch asks for a position before it moves anything.
/// What it guards against is somebody restoring the unwrap — the `None`
/// arriving here is indistinguishable from a click at the origin the
/// moment it is given a default.
#[test]
fn a_move_with_no_position_leaves_the_selection_where_it_was() {
let mut tree = crate::tree::Tree::new();
// An id with no bounds: the drag branch does not consult them — that
// is what lets a selection continue past the edge of the field — so
// the empty rect is exactly the right stand-in here.
let id = tree.register(Box::new(crate::widgets::container()));
let text = create_signal(String::from("hello world"));
let mut input = text_input(text);
input.selection = Selection {
anchor: 2,
cursor: 7,
};
input.is_dragging = true;
let moved_to = Event::mouse_move(60.0, 5.0);
Widget::event(&mut input, &mut tree, id, &moved_to);
let dragged = input.selection.cursor;
assert_ne!(
dragged, 7,
"a positioned move has to extend the selection, or this test is \
asserting against a drag that was never running"
);
Widget::event(
&mut input,
&mut tree,
id,
&Event::MouseMove {
at: None,
pointer: PointerKind::Mouse,
},
);
assert_eq!(
(input.selection.anchor, input.selection.cursor),
(2, dragged),
"and one with no position leaves it exactly where it was"
);
}
/// Two keystrokes inside the window are one undo, and two outside it are
/// two — which is what `HISTORY_COALESCE_MS` promises and nothing could
/// ask before.
///
/// The window is half a second. A test that wanted to stand on either side
/// of it had to sleep for real, so the far side cost five seconds of wall
/// clock and the near side was a race against how long the assertions took.
/// Both moments are named now.
#[test]
fn the_coalescing_window_has_two_sides_and_they_can_both_be_asked_about() {
let entry = |text: &str| HistoryEntry {
text: text.to_string(),
cursor: text.chars().count(),
anchor: text.chars().count(),
};
let inside = {
let t0: EventInstant = Instant::now().into();
let mut history = History::new();
history.push(entry("a"), EditType::Insert, t0);
history.push(
entry("ab"),
EditType::Insert,
t0 + Duration::from_millis(50),
);
history.undo_stack.len()
};
assert_eq!(
inside, 1,
"two keystrokes fifty milliseconds apart are one thing to undo"
);
let outside = {
let t0: EventInstant = Instant::now().into();
let mut history = History::new();
history.push(entry("a"), EditType::Insert, t0);
history.push(entry("ab"), EditType::Insert, t0 + Duration::from_secs(5));
history.undo_stack.len()
};
assert_eq!(
outside, 2,
"and five seconds apart they are two, because the sentence in \
between was a different thought"
);
}
/// A field inside a container, laid out from the container, focused.
///
/// The container is what makes these tests about *reactivity* rather than
/// about plumbing. A `TextInput` re-runs its own layout on every call, so a
/// value read without tracking still reaches a second direct `layout(..)`
/// and the test passes while nothing subscribes. A container takes its
/// unchanged-constraints early-out and never asks its children again, so
/// the second pass reaches the field only if the write marked it.
fn field_in_container(input: impl Widget + 'static) -> (Tree, WidgetId, WidgetId) {
clear_pending_jobs();
clear_scheduled_jobs();
crate::reactive::focus::clear_focus();
let mut tree = Tree::new();
let root = tree.register(Box::new(crate::widgets::container().child(input)));
tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));
let id = tree.get_children(root)[0];
relayout(&mut tree, root);
request_focus(&tree, id);
clear_pending_jobs();
(tree, root, id)
}
/// Re-lay out from `root` after draining the jobs a signal write queued.
///
/// The drain is what turns a write into `needs_layout` on the widget that
/// read it; without it the second pass measures the cache.
fn relayout(tree: &mut Tree, root: WidgetId) {
crate::jobs::pump_and_layout(tree, root, Constraints::new(0.0, 0.0, 200.0, 40.0));
}
/// Put the caret at the end, which is where its x becomes a measurement of
/// the displayed text rather than a constant zero.
fn caret_to_end(tree: &mut Tree, id: WidgetId) {
key(tree, id, Key::End, false);
}
/// Press one key on the field, with or without shift.
fn key(tree: &mut Tree, id: WidgetId, key: Key, shift: bool) {
tree.with_widget_mut(id, |w, wid, t| {
w.event(
t,
wid,
&Event::KeyDown {
key,
modifiers: crate::widgets::widget::Modifiers {
shift,
..Default::default()
},
repeat: false,
},
)
});
}
/// The colour and size the field drew its glyphs at, on a frame at a named
/// instant.
///
/// Named because an eased value is a function of how long it has been
/// running, and a test that let the clock decide would assert on whatever
/// the machine managed between two calls.
fn drawn_text(tree: &mut Tree, id: WidgetId, at: std::time::Instant) -> Option<(Color, f32)> {
fn find(node: &crate::renderer::RenderNode) -> Option<(Color, f32)> {
for cmd in &node.commands {
if let crate::renderer::DrawCommand::Text {
color, font_size, ..
} = &**cmd
{
return Some((*color, *font_size));
}
}
node.children.iter().find_map(|child| find(child))
}
tree.set_frame_instant(Some(at));
relayout(tree, id);
let node = paint_once(tree, id);
tree.set_frame_instant(None);
find(&node)
}
/// Every rectangle the field draws. Focused with no selection, the caret is
/// the only one there can be, and its x is where the displayed text ends.
fn drawn_rects(tree: &mut Tree, id: WidgetId) -> Vec<crate::widgets::Rect> {
fn collect(node: &crate::renderer::RenderNode, out: &mut Vec<crate::widgets::Rect>) {
for cmd in &node.commands {
if let crate::renderer::DrawCommand::RoundedRect { rect, .. } = &**cmd {
out.push(*rect);
}
}
for child in &node.children {
collect(child, out);
}
}
let mut out = Vec::new();
collect(&paint_once(tree, id), &mut out);
out
}
/// A password is drawn as its mask, never as its text.
///
/// Read off the caret's x, which sits at the end of the *displayed* text:
/// bullets and `iiii` are different widths in any font, so the assertion
/// does not depend on which one is installed — only that they differ.
#[test]
fn a_password_is_drawn_as_its_mask() {
let password = crate::reactive::create_password();
password.set(Secret::from("iiiiiiii".to_owned()));
let (mut tree, _, id) = field_in_container(password_input(password));
caret_to_end(&mut tree, id);
let masked = drawn_rects(&mut tree, id);
assert_eq!(masked.len(), 1, "the caret, and nothing else");
let (mut tree, _, id) =
field_in_container(text_input(create_signal("iiiiiiii".to_owned())));
caret_to_end(&mut tree, id);
let plain = drawn_rects(&mut tree, id);
assert_ne!(
masked[0].x, plain[0].x,
"the password field drew its text rather than its mask"
);
}
/// A field is one line however long its value: it draws its text with a
/// fit of no width, which never wraps. Drawn without a fit, a text wraps
/// at its box, and a value wider than the field would break onto lines.
#[test]
fn a_field_draws_its_value_on_one_line() {
let (mut tree, _, id) = field_in_container(text_input(create_signal(
"a value far longer than any narrow field could hold".to_owned(),
)));
fn fits(
node: &crate::renderer::RenderNode,
out: &mut Vec<Option<crate::renderer::LineFit>>,
) {
for cmd in &node.commands {
if let crate::renderer::DrawCommand::Text { fit, .. } = &**cmd {
out.push(*fit);
}
}
node.children.iter().for_each(|c| fits(c, out));
}
let mut drawn = Vec::new();
fits(&paint_once(&mut tree, id), &mut drawn);
assert!(!drawn.is_empty(), "the field drew its value");
for fit in drawn {
assert_eq!(
fit,
Some(crate::renderer::LineFit::wrapping(None)),
"a field never wraps"
);
}
}
/// Every text a subtree drew.
fn drawn_strings(tree: &mut Tree, id: WidgetId) -> Vec<String> {
fn collect(node: &crate::renderer::RenderNode, out: &mut Vec<String>) {
for cmd in &node.commands {
if let crate::renderer::DrawCommand::Text { text, .. } = &**cmd {
out.push(text.to_string());
}
}
for child in &node.children {
collect(child, out);
}
}
let mut out = Vec::new();
collect(&paint_once(tree, id), &mut out);
out
}
/// The application fills and wipes the field through the handle, outside
/// any event, and the field follows on its next layout — which the write
/// asks for, because the layout read the password.
#[test]
fn a_password_written_from_outside_reaches_the_field() {
let password = crate::reactive::create_password();
let (mut tree, root, id) = field_in_container(password_input(password).mask_char('*'));
password.set(Secret::from("abc".to_owned()));
relayout(&mut tree, root);
assert_eq!(drawn_strings(&mut tree, id), ["***"]);
password.clear();
relayout(&mut tree, root);
assert!(
drawn_strings(&mut tree, id).is_empty(),
"the mask outlived the text"
);
}
/// A write to the bound signal from outside reaches the field on its next
/// layout.
#[test]
fn a_plain_field_follows_its_signal() {
let value = create_signal("abc".to_owned());
let (mut tree, root, id) = field_in_container(text_input(value));
assert_eq!(drawn_strings(&mut tree, id), ["abc"]);
value.set("xyz".to_owned());
relayout(&mut tree, root);
assert_eq!(drawn_strings(&mut tree, id), ["xyz"]);
}
/// Enter takes the text with it, and the field says so.
#[test]
fn a_submit_empties_what_the_field_draws() {
let password = crate::reactive::create_password();
password.set(Secret::from("abc".to_owned()));
let (mut tree, root, id) = field_in_container(
password_input(password)
.mask_char('*')
.on_submit(move || drop(password.take())),
);
assert_eq!(drawn_strings(&mut tree, id), ["***"]);
tree.with_widget_mut(id, |w, wid, t| {
w.event(
t,
wid,
&Event::KeyDown {
key: Key::Enter,
modifiers: Default::default(),
repeat: false,
},
)
});
relayout(&mut tree, root);
assert!(
drawn_strings(&mut tree, id).is_empty(),
"the mask outlived the text"
);
}
/// Where the field drew each of its texts, the placeholder included.
fn drawn_text_x(tree: &mut Tree, id: WidgetId) -> Vec<(String, f32)> {
fn collect(node: &crate::renderer::RenderNode, out: &mut Vec<(String, f32)>) {
for cmd in &node.commands {
if let crate::renderer::DrawCommand::Text { text, rect, .. } = &**cmd {
out.push((text.to_string(), rect.x));
}
}
for child in &node.children {
collect(child, out);
}
}
let mut out = Vec::new();
collect(&paint_once(tree, id), &mut out);
out
}
/// A field typed past its width and then cleared by its own submit draws
/// its caret and its placeholder from its start, not where the old text
/// had scrolled them, out of sight (#723). The clear reaches the field on
/// the layout the write schedules, which only these tests can pump.
#[test]
fn a_field_cleared_by_its_submit_draws_its_caret_and_placeholder_in_view() {
let value = create_signal(String::new());
let (mut tree, root, id) = field_in_container(
text_input(value)
.placeholder("Search")
.on_submit(move |_| value.set(String::new())),
);
for _ in 0..80 {
key(&mut tree, id, Key::Char('a'), false);
}
assert!(
drawn_rects(&mut tree, id)[0].x > 100.0,
"typed past its width, the caret is at the right"
);
key(&mut tree, id, Key::Enter, false);
relayout(&mut tree, root);
assert_eq!(value.get_untracked(), "");
assert_eq!(drawn_text_x(&mut tree, id), [("Search".to_owned(), 0.0)]);
assert_eq!(drawn_rects(&mut tree, id)[0].x, 0.0, "the caret");
}
/// A text shortened from outside is shown from its start, not from where
/// the longer one had scrolled to (#723).
#[test]
fn a_field_shortened_from_outside_shows_its_text_from_the_start() {
let value = create_signal("a".repeat(80));
let (mut tree, root, id) = field_in_container(text_input(value));
caret_to_end(&mut tree, id);
value.set("abc".to_owned());
relayout(&mut tree, root);
assert_eq!(drawn_text_x(&mut tree, id), [("abc".to_owned(), 0.0)]);
}
/// A row that overflows lays a clipped box out a second time, narrower,
/// and the field in it with it, after the layout that read the field's
/// text back. The scroll is fitted to the width it is drawn at, so the
/// caret stays inside the field (#723).
#[test]
fn a_field_shortened_in_an_overflowing_row_keeps_its_caret_inside() {
let value = create_signal("a".repeat(80));
clear_pending_jobs();
clear_scheduled_jobs();
crate::reactive::focus::clear_focus();
let mut tree = Tree::new();
let root = tree.register(Box::new(
crate::widgets::container()
.layout(crate::layout::Flex::row())
.child(
crate::widgets::container()
.overflow(crate::widgets::Overflow::Hidden)
.child(text_input(value)),
)
.child(crate::widgets::container().width(60.0).height(10.0)),
));
tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));
let clip = tree.get_children(root)[0];
let id = tree.get_children(clip)[0];
relayout(&mut tree, root);
request_focus(&tree, id);
clear_pending_jobs();
caret_to_end(&mut tree, id);
value.set("a".repeat(40));
relayout(&mut tree, root);
let width = tree.get_bounds(id).unwrap().width;
assert!(width < 200.0, "the row squeezed the field: {width}");
let caret = drawn_rects(&mut tree, id)[0].x;
assert!(
(0.0..=width).contains(&caret),
"the caret at {caret}, in a field {width} wide"
);
}
/// A revealed password reads its text back on every layout. With its caret
/// moved back from the end, a layout leaves its view where it was.
#[test]
fn a_revealed_password_with_its_caret_moved_back_keeps_its_view() {
let password = crate::reactive::create_password();
password.set(Secret::from("a".repeat(80)));
let mask = create_signal('*');
let (mut tree, root, id) =
field_in_container(password_input(password).reveal(true).mask_char(mask));
caret_to_end(&mut tree, id);
for _ in 0..3 {
key(&mut tree, id, Key::Left, false);
}
let before = drawn_rects(&mut tree, id)[0].x;
// Something the field reads changes, so the field is laid out again.
mask.set('.');
relayout(&mut tree, root);
assert_eq!(drawn_rects(&mut tree, id)[0].x, before);
}
/// Revealing is a value the field can be told, and the eye icon beside a
/// password box is what needs it. Declaring it rather than rebuilding the
/// field is what keeps the focus.
///
/// Read off the caret's x, which sits at the end of the *displayed* text:
/// bullets and `iiii` are different widths in any font.
#[test]
fn revealing_answers_to_a_signal() {
let shown = create_signal(false);
let password = crate::reactive::create_password();
password.set(Secret::from("iiiiiiii".to_owned()));
let (mut tree, root, id) = field_in_container(password_input(password).reveal(shown));
caret_to_end(&mut tree, id);
let masked = drawn_rects(&mut tree, id);
assert_eq!(drawn_strings(&mut tree, id), ["••••••••"]);
shown.set(true);
relayout(&mut tree, root);
assert_eq!(drawn_strings(&mut tree, id), ["iiiiiiii"]);
assert_ne!(
drawn_rects(&mut tree, id)[0].x,
masked[0].x,
"the caret did not follow the revealed text"
);
shown.set(false);
relayout(&mut tree, root);
assert_eq!(drawn_strings(&mut tree, id), ["••••••••"]);
assert!(has_focus(id), "revealing cost the field its focus");
}
/// A revealed field follows a change to its text that keeps its length.
#[test]
fn a_revealed_field_follows_a_same_length_change() {
let password = crate::reactive::create_password();
password.set(Secret::from("abc".to_owned()));
let (mut tree, root, id) = field_in_container(password_input(password).reveal(true));
assert_eq!(drawn_strings(&mut tree, id), ["abc"]);
password.set(Secret::from("xyz".to_owned()));
relayout(&mut tree, root);
assert_eq!(drawn_strings(&mut tree, id), ["xyz"]);
}
/// What the mask is made of is a value the field can be told.
#[test]
fn the_mask_character_answers_to_a_signal() {
let mask = create_signal('.');
let password = crate::reactive::create_password();
password.set(Secret::from("aaaaaaaa".to_owned()));
let (mut tree, root, id) = field_in_container(password_input(password).mask_char(mask));
caret_to_end(&mut tree, id);
let narrow = drawn_rects(&mut tree, id);
mask.set('W');
relayout(&mut tree, root);
let wide = drawn_rects(&mut tree, id);
assert!(
wide[0].x > narrow[0].x,
"eight W's have to be wider than eight full stops: {narrow:?} then \
{wide:?}"
);
}
/// Whether a caret is drawn at all, likewise.
#[test]
fn the_caret_answers_to_a_signal() {
let show = create_signal(true);
let (mut tree, root, id) =
field_in_container(text_input(create_signal("hi".to_owned())).caret(show));
assert_eq!(drawn_rects(&mut tree, id).len(), 1, "a caret to begin with");
show.set(false);
relayout(&mut tree, root);
assert!(
drawn_rects(&mut tree, id).is_empty(),
"asked for no caret and got one anyway"
);
assert!(has_focus(id), "and the focus is still here");
}
/// A field's declared colour eases exactly as a text's does.
///
/// The two widgets take their style setters from one list
/// (`declares_text_style`), so this is parity being *observed* rather than
/// assumed: the macro guarantees the method exists, and this guarantees the
/// storage behind it is wired — an input that accepted a transition and
/// ignored it would be the silently-dropped value the whole rule exists to
/// prevent.
#[test]
fn a_declared_transition_eases_an_input_colour() {
use crate::animation::Animate;
let hue = create_signal(Color::rgb(0.0, 0.0, 0.0));
let (mut tree, root, _id) = field_in_container(
text_input(create_signal("abc".to_owned()))
.color((move || hue.get()).transition(400.0)),
);
let t0 = std::time::Instant::now();
drawn_text(&mut tree, root, t0);
hue.set(Color::rgb(1.0, 1.0, 1.0));
drawn_text(&mut tree, root, t0 + std::time::Duration::from_millis(1));
let (midway, _) = drawn_text(&mut tree, root, t0 + std::time::Duration::from_millis(100))
.expect("the field draws its text");
assert!(
midway.r > 0.01 && midway.r < 0.99,
"an input's declared colour has to ease like a text's, got {midway:?}"
);
}
/// A field's own font size is resolved by its own `refresh`, so the door
/// `Text` passes through has to be on this path too.
///
/// One more way to see the same poisoning: a bad size reaches the glyph
/// positions the caret is placed from as well as the measurement, so a field
/// that has seen one keeps the size it had and stops following its signal.
#[test]
fn a_fields_font_size_follows_its_signal_again_once_the_signal_recovers() {
use crate::animation::Animate;
let ms = std::time::Duration::from_millis;
let size = create_signal(10.0f32);
let (mut tree, root, _id) = field_in_container(
text_input(create_signal("abc".to_owned()))
.font_size((move || size.get()).transition(200.0)),
);
let t0 = std::time::Instant::now();
drawn_text(&mut tree, root, t0);
size.set(f32::NAN);
drawn_text(&mut tree, root, t0 + ms(1));
drawn_text(&mut tree, root, t0 + ms(50));
size.set(30.0);
drawn_text(&mut tree, root, t0 + ms(100));
let painted = drawn_text(&mut tree, root, t0 + ms(1000)).map(|(_, size)| size);
assert!(
painted.is_some_and(|size| (size - 30.0).abs() < 0.5),
"a field given one bad size never followed its signal again: the \
glyphs are drawn at {painted:?} rather than 30"
);
}
/// A field resolves its colour on two complementary paths, and both are the
/// door's.
///
/// `refresh` reads it only where a motion was declared, and paint only where
/// one was not, so no single scenario reaches both — this is the second.
/// Nothing downstream guards: the channels go to the shader as they are.
#[test]
fn a_fields_colour_with_no_motion_is_painted_through_the_door() {
use crate::animation::Animatable;
let hue = create_signal(Color::rgba(f32::NAN, 0.0, 0.0, 1.0));
let (mut tree, root, _id) =
field_in_container(text_input(create_signal("abc".to_owned())).color(hue));
let (painted, _) = drawn_text(&mut tree, root, std::time::Instant::now())
.expect("the field draws its text");
assert!(
painted.channels().iter().all(|c| c.is_finite()),
"a colour nobody can compute reached the shader: {painted:?}"
);
}
/// And the path `refresh` owns: a colour with a motion, poisoned and then
/// finite again.
#[test]
fn a_fields_colour_follows_its_signal_again_once_the_signal_recovers() {
use crate::animation::Animate;
let ms = std::time::Duration::from_millis;
let hue = create_signal(Color::rgb(0.0, 0.0, 0.0));
let (mut tree, root, _id) = field_in_container(
text_input(create_signal("abc".to_owned()))
.color((move || hue.get()).transition(200.0)),
);
let t0 = std::time::Instant::now();
drawn_text(&mut tree, root, t0);
hue.set(Color::rgba(f32::NAN, 0.0, 0.0, 1.0));
drawn_text(&mut tree, root, t0 + ms(1));
drawn_text(&mut tree, root, t0 + ms(50));
// Red, not white: white is what a colour nobody declared falls back to.
hue.set(Color::rgb(1.0, 0.0, 0.0));
drawn_text(&mut tree, root, t0 + ms(100));
let painted = drawn_text(&mut tree, root, t0 + ms(1000)).map(|(color, _)| color);
assert!(
painted.is_some_and(|color| color.r > 0.99 && color.g < 0.01),
"a field given one bad colour never followed its signal again: \
got {painted:?}"
);
}
/// The field walks its own chain, so the fall-through is its own to get
/// right — see `an_override_that_is_not_a_number_falls_through_to_the_declaration`
/// for the rule and why a fold could not state it.
#[test]
fn an_override_that_is_not_a_number_falls_through_to_the_fields_declaration() {
let hot = create_signal(true);
let (mut tree, root, _id) = field_in_container(
text_input(create_signal("abc".to_owned()))
.font_size(32.0)
.color(Color::RED)
.state(hot, |s: TextStyle| {
s.font_size(f32::NAN)
.color(Color::rgba(f32::NAN, 0.0, 0.0, 1.0))
}),
);
let (color, size) = drawn_text(&mut tree, root, std::time::Instant::now())
.expect("the field draws its text");
assert!(
(size - 32.0).abs() < 0.01,
"a bad override falls through to the size the field declares, not to \
the default: got {size}"
);
assert_eq!(color, Color::RED, "and to the colour it declares");
}
/// A field's font size appears after a measure too, under a box of exact
/// size that hands it the same constraints in both passes.
///
/// The field is never skipped itself; the box around it is, and nothing
/// that box declares moves. What keeps it laid out for real is the size the
/// measure placed in the field without letting it appear.
/// Read off the glyphs rather than the box: the field's height only grows.
#[test]
fn a_font_size_under_an_exact_box_appears_after_a_measure() {
use crate::prelude::*;
let mut tree = Tree::new();
let root = tree.register(Box::new(
container().width(200.0).height(100.0).child(
container().width(200.0).height(60.0).child(
text_input(create_signal(String::from("entering"))).font_size(
40.0f32
.transition(Transition::new(100.0, TimingFunction::Linear))
.entering_from(10.0),
),
),
),
));
tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));
let field = tree.get_children(tree.get_children(root)[0])[0];
let t0 = std::time::Instant::now();
// The loop's order: jobs, the layout roots they queued — the inner box
// is one — at the constraints they last had, then the surface root.
let frame = |tree: &mut Tree, ms: u64, constraints: Constraints| {
tree.set_frame_instant(Some(t0 + std::time::Duration::from_millis(ms)));
let roots = [root].into_iter().collect();
crate::jobs::distribute_jobs(tree, &roots);
let drained = crate::jobs::drain_surface_jobs(root);
let mut layout_roots = Vec::new();
crate::jobs::process_jobs(&drained, tree, &mut layout_roots);
crate::jobs::recycle_job_buffer(drained);
for boundary in layout_roots {
let c = tree
.last_layout_constraints(boundary)
.unwrap_or(constraints);
tree.layout_widget(boundary, c);
}
tree.layout_widget(root, constraints);
let node = paint_once(tree, field);
tree.set_frame_instant(None);
node.commands.iter().find_map(|cmd| match &**cmd {
crate::renderer::DrawCommand::Text { font_size, .. } => Some(*font_size),
_ => None,
})
};
// The popup path first: a measure of the natural size, before the
// layouts that place it.
let measure = |tree: &mut Tree, ms: u64, constraints: Constraints| {
tree.set_frame_instant(Some(t0 + std::time::Duration::from_millis(ms)));
let _ = crate::jobs::pump_and_measure(tree, root, constraints);
tree.set_frame_instant(None);
};
measure(&mut tree, 0, Constraints::new(200.0, 0.0, 200.0, 300.0));
let loose = Constraints::new(0.0, 0.0, 200.0, 100.0);
frame(&mut tree, 0, loose);
let midway = frame(&mut tree, 50, loose).expect("the field draws its text");
assert!(
midway > 10.0 && midway < 40.0,
"the size has to grow rather than be grown, got {midway}"
);
}
/// A laid-out input, focused unless told otherwise.
fn field(input: TextInput, focused: bool) -> (Tree, WidgetId) {
clear_pending_jobs();
clear_scheduled_jobs();
crate::reactive::focus::clear_focus();
let mut tree = Tree::new();
let id = tree.register(Box::new(input));
tree.with_widget_mut(id, |w, id, t| w.register_children(t, id));
tree.layout_widget(id, Constraints::new(0.0, 0.0, 200.0, 40.0));
if focused {
request_focus(&tree, id);
}
clear_pending_jobs();
(tree, id)
}
fn advance(tree: &mut Tree, id: WidgetId) -> bool {
tree.with_widget_mut(id, |w, id, t| w.advance_animations(t, id))
.unwrap_or(false)
}
fn paint_once(tree: &mut Tree, id: WidgetId) -> crate::renderer::RenderNode {
let mut node = crate::renderer::RenderNode::new(id.as_u64());
tree.paint_widget(id, &mut node, 1.0);
node
}
#[test]
fn painting_a_focused_caret_asks_for_the_wake_that_toggles_it() {
// The regression: the toggle lives in `advance_animations`, which the loop
// only calls for an Animation job, and *nothing* asked for one — focus from
// a click, from `autofocus` or from `WidgetRef::focus()` all queue a plain
// repaint. So the caret never blinked at all, while the tests that called
// `advance_animations` by hand were happy: they skipped the broken part.
let (mut tree, id) = field(text_input(create_signal(String::new())), true);
assert_eq!(next_deadline(), None, "nothing has been drawn yet");
paint_once(&mut tree, id);
assert!(
next_deadline().is_some(),
"a caret on screen has to ask to be woken, or it stays as it is forever"
);
}
#[test]
fn the_blink_keeps_asking_after_each_toggle() {
// One wake is a blink that stops after half a cycle.
let (mut tree, id) = field(text_input(create_signal(String::new())), true);
paint_once(&mut tree, id);
advance(&mut tree, id);
clear_pending_jobs();
clear_scheduled_jobs();
paint_once(&mut tree, id);
assert!(next_deadline().is_some());
}
#[test]
fn painting_a_field_without_a_caret_asks_for_nothing() {
let (mut tree, id) = field(text_input(create_signal(String::new())).no_caret(), true);
paint_once(&mut tree, id);
assert_eq!(
next_deadline(),
None,
"no caret, no wake — this is what a lock screen costs while nobody \
touches it"
);
}
#[test]
fn painting_an_unfocused_field_asks_for_nothing() {
let (mut tree, id) = field(text_input(create_signal(String::new())), false);
paint_once(&mut tree, id);
assert_eq!(next_deadline(), None);
}
#[test]
fn advancing_a_blinking_caret_never_asks_for_a_frame() {
// The division of labour: `advance_animations` applies the toggle, `paint`
// asks for the next wake. What neither may do is request an animation job,
// which means "advance me every frame" and is what pinned the loop at
// 60 fps to redraw the same pixels 113 frames out of 114.
let (mut tree, id) = field(text_input(create_signal(String::new())), true);
let blinking = advance(&mut tree, id);
assert!(blinking, "a focused caret is a blinking one");
assert!(
!queued_job_types(id).contains(&JobType::Animation),
"queued: {:?}",
queued_job_types(id)
);
}
#[test]
fn a_field_without_a_caret_asks_for_nothing() {
let (mut tree, id) = field(text_input(create_signal(String::new())).no_caret(), true);
let blinking = advance(&mut tree, id);
assert!(!blinking);
assert_eq!(
next_deadline(),
None,
"no caret, no blink, nothing to wake the loop for — this is what a \
lock screen costs while nobody touches it"
);
}
#[test]
fn an_unfocused_field_asks_for_nothing() {
let (mut tree, id) = field(text_input(create_signal(String::new())), false);
let blinking = advance(&mut tree, id);
assert!(!blinking);
assert_eq!(next_deadline(), None);
}
#[test]
fn a_focused_field_whose_surface_is_without_the_keyboard_asks_for_nothing() {
// The field keeps the focus while the keyboard is elsewhere (#726),
// and a bar's field kept that way all night must not wake the loop
// twice a second for a caret nobody can type at.
let (mut tree, id) = field(text_input(create_signal(String::new())), true);
tree.set_event_instant(Some(std::time::Instant::now()));
tree.dispatch(id, &Event::FocusOut);
tree.set_event_instant(None);
clear_pending_jobs();
let blinking = advance(&mut tree, id);
paint_once(&mut tree, id);
assert!(has_focus(id), "the focus stayed");
assert!(!blinking, "but the caret does not blink");
assert_eq!(next_deadline(), None, "and asks for no wake");
}
/// What a field measures its caret, its selection and its clicks against
/// once it is spaced — with the vendored font, so a glyph's advance is
/// DejaVu Sans Mono's 1233 of 2048 units and every boundary is a number
/// worked out by hand.
mod letter_spacing {
use super::*;
use crate::widgets::FontFamily;
const FONT: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
/// One glyph's advance at the default 14 px.
const ADVANCE: f32 = 1233.0 / 2048.0 * 14.0;
fn dejavu() -> FontFamily {
// The measurer reads the registered fonts when this thread first
// builds it, so they are registered before anything is measured.
crate::load_font(FONT.to_vec());
FontFamily::name("DejaVu Sans Mono")
}
/// The x of the one rect a focused field with no selection draws.
fn caret_x(tree: &mut Tree, id: WidgetId) -> f32 {
let rects = drawn_rects(tree, id);
assert_eq!(rects.len(), 1, "the caret, and nothing else: {rects:?}");
rects[0].x
}
fn assert_near(actual: f32, expected: f32, what: &str) {
assert!(
(actual - expected).abs() < 0.01,
"{what}: got {actual}, expected {expected}"
);
}
#[test]
fn the_caret_stands_after_the_spacing_of_every_letter_before_it() {
let family = dejavu();
let (mut tree, _, id) = field_in_container(
text_input(create_signal("abcd".to_owned()))
.font_family(family)
.letter_spacing(3.0),
);
caret_to_end(&mut tree, id);
assert_near(caret_x(&mut tree, id), 4.0 * (ADVANCE + 3.0), "at the end");
key(&mut tree, id, Key::Left, false);
assert_near(caret_x(&mut tree, id), 3.0 * (ADVANCE + 3.0), "one back");
}
/// A letter and a mark the font cannot compose are two glyphs of one
/// cluster, each taking a spacing: the caret before the cluster
/// stands before the letter, not after it.
#[test]
fn the_caret_before_a_marked_letter_stands_before_it() {
let family = dejavu();
let (mut tree, _, id) = field_in_container(
text_input(create_signal("x\u{301}".to_owned()))
.font_family(family)
.letter_spacing(3.0),
);
caret_to_end(&mut tree, id);
assert_near(caret_x(&mut tree, id), ADVANCE + 6.0, "at the end");
key(&mut tree, id, Key::Home, false);
assert_near(caret_x(&mut tree, id), 0.0, "at the start");
}
#[test]
fn a_selection_spans_the_spaced_letters() {
let family = dejavu();
let (mut tree, _, id) = field_in_container(
text_input(create_signal("abcd".to_owned()))
.font_family(family)
.letter_spacing(3.0),
);
caret_to_end(&mut tree, id);
key(&mut tree, id, Key::Left, true);
key(&mut tree, id, Key::Left, true);
let band = drawn_rects(&mut tree, id)[0];
assert_near(
band.x,
2.0 * (ADVANCE + 3.0),
"the band starts at boundary 2",
);
assert_near(
band.width,
2.0 * (ADVANCE + 3.0),
"and is two spaced letters wide",
);
}
/// A click lands on the nearest boundary of the spaced line: two
/// spaced letters in is boundary 2, where the unspaced one would put
/// it past the third letter.
#[test]
fn a_click_lands_on_the_boundary_of_the_spaced_line() {
let family = dejavu();
let (mut tree, _, id) = field_in_container(
text_input(create_signal("abcdefgh".to_owned()))
.font_family(family)
.letter_spacing(6.0),
);
let x = 2.0 * (ADVANCE + 6.0) + 1.0;
for event in [
Event::mouse_down(x, 8.0, crate::widgets::MouseButton::Left),
Event::mouse_up(x, 8.0, crate::widgets::MouseButton::Left),
] {
tree.with_widget_mut(id, |w, wid, t| w.event(t, wid, &event));
}
assert_near(caret_x(&mut tree, id), 2.0 * (ADVANCE + 6.0), "the caret");
}
/// The spacing is a declared value, so a write re-measures the
/// positions the caret is placed from.
#[test]
fn a_fields_spacing_follows_its_signal() {
let family = dejavu();
let spacing = create_signal(0.0f32);
let (mut tree, root, id) = field_in_container(
text_input(create_signal("abcd".to_owned()))
.font_family(family)
.letter_spacing(spacing),
);
caret_to_end(&mut tree, id);
assert_near(caret_x(&mut tree, id), 4.0 * ADVANCE, "unspaced");
spacing.set(2.0);
relayout(&mut tree, root);
assert_near(caret_x(&mut tree, id), 4.0 * (ADVANCE + 2.0), "spaced");
}
/// A password field spaces the characters it draws, which are its
/// mask's: the caret follows them and every drawn text carries it.
#[test]
fn a_password_spaces_its_mask() {
let family = dejavu();
let password = crate::reactive::create_password();
password.set(Secret::from("abcd".to_owned()));
let (mut tree, _, id) = field_in_container(
password_input(password)
.font_family(family)
.letter_spacing(3.0),
);
caret_to_end(&mut tree, id);
assert_near(caret_x(&mut tree, id), 4.0 * (ADVANCE + 3.0), "the caret");
fn spacings(node: &crate::renderer::RenderNode, out: &mut Vec<(String, f32)>) {
for cmd in &node.commands {
if let crate::renderer::DrawCommand::Text {
text,
letter_spacing,
..
} = &**cmd
{
out.push((text.to_string(), *letter_spacing));
}
}
node.children.iter().for_each(|c| spacings(c, out));
}
let mut drawn = Vec::new();
spacings(&paint_once(&mut tree, id), &mut drawn);
assert_eq!(drawn, [("••••".to_owned(), 3.0)]);
}
}
}