summaryrefslogtreecommitdiffstats
path: root/src/quick/items/qquicktextinput.cpp
blob: a378359c9594d95063d8f6383c98a5c7c19fa280 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qquicktextinput_p.h"
#include "qquicktextinput_p_p.h"
#include "qquickwindow.h"
#include "qquicktextutil_p.h"

#include <private/qqmlglobal_p.h>
#include <private/qv4scopedvalue_p.h>

#include <QtCore/qcoreapplication.h>
#include <QtCore/qmimedata.h>
#include <QtQml/qqmlinfo.h>
#include <QtGui/qevent.h>
#include <QTextBoundaryFinder>
#include "qquicktextnode_p.h"
#include <QtQuick/qsgsimplerectnode.h>

#include <QtGui/qstylehints.h>
#include <QtGui/qinputmethod.h>
#include <QtCore/qmath.h>

#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#include "qquickaccessibleattached_p.h"
#endif

#include <QtGui/private/qtextengine_p.h>
#include <QtGui/private/qinputcontrol_p.h>

QT_BEGIN_NAMESPACE

DEFINE_BOOL_CONFIG_OPTION(qmlDisableDistanceField, QML_DISABLE_DISTANCEFIELD)

/*!
    \qmltype TextInput
    \instantiates QQuickTextInput
    \inqmlmodule QtQuick
    \ingroup qtquick-visual
    \ingroup qtquick-input
    \inherits Item
    \brief Displays an editable line of text

    The TextInput type displays a single line of editable plain text.

    TextInput is used to accept a line of text input. Input constraints
    can be placed on a TextInput item (for example, through a \l validator or \l inputMask),
    and setting \l echoMode to an appropriate value enables TextInput to be used for
    a password input field.

    On \macos, the Up/Down key bindings for Home/End are explicitly disabled.
    If you want such bindings (on any platform), you will need to construct them in QML.

    \sa TextEdit, Text
*/
QQuickTextInput::QQuickTextInput(QQuickItem* parent)
: QQuickImplicitSizeItem(*(new QQuickTextInputPrivate), parent)
{
    Q_D(QQuickTextInput);
    d->init();
}

QQuickTextInput::QQuickTextInput(QQuickTextInputPrivate &dd, QQuickItem *parent)
: QQuickImplicitSizeItem(dd, parent)
{
    Q_D(QQuickTextInput);
    d->init();
}

QQuickTextInput::~QQuickTextInput()
{
}

void QQuickTextInput::componentComplete()
{
    Q_D(QQuickTextInput);

    QQuickImplicitSizeItem::componentComplete();

    d->checkIsValid();
    d->updateLayout();
    updateCursorRectangle();
    if (d->cursorComponent && isCursorVisible())
        QQuickTextUtil::createCursor(d);
}

/*!
    \qmlproperty string QtQuick::TextInput::text

    The text in the TextInput.

    \sa clear()
*/
QString QQuickTextInput::text() const
{
    Q_D(const QQuickTextInput);

    QString content = d->m_text;
    QString res = d->m_maskData ? d->stripString(content) : content;
    return (res.isNull() ? QString::fromLatin1("") : res);
}

void QQuickTextInput::setText(const QString &s)
{
    Q_D(QQuickTextInput);
    if (s == text())
        return;

#if QT_CONFIG(im)
    d->cancelPreedit();
#endif
    d->internalSetText(s, -1, false);
}


/*!
    \qmlproperty enumeration QtQuick::TextInput::renderType

    Override the default rendering type for this component.

    Supported render types are:
    \list
    \li Text.QtRendering - the default
    \li Text.NativeRendering
    \endlist

    Select Text.NativeRendering if you prefer text to look native on the target platform and do
    not require advanced features such as transformation of the text. Using such features in
    combination with the NativeRendering render type will lend poor and sometimes pixelated
    results.
*/
QQuickTextInput::RenderType QQuickTextInput::renderType() const
{
    Q_D(const QQuickTextInput);
    return d->renderType;
}

void QQuickTextInput::setRenderType(QQuickTextInput::RenderType renderType)
{
    Q_D(QQuickTextInput);
    if (d->renderType == renderType)
        return;

    d->renderType = renderType;
    emit renderTypeChanged();

    if (isComponentComplete())
        d->updateLayout();
}

/*!
    \qmlproperty int QtQuick::TextInput::length

    Returns the total number of characters in the TextInput item.

    If the TextInput has an inputMask the length will include mask characters and may differ
    from the length of the string returned by the \l text property.

    This property can be faster than querying the length the \l text property as it doesn't
    require any copying or conversion of the TextInput's internal string data.
*/

int QQuickTextInput::length() const
{
    Q_D(const QQuickTextInput);
    return d->m_text.length();
}

/*!
    \qmlmethod string QtQuick::TextInput::getText(int start, int end)

    Returns the section of text that is between the \a start and \a end positions.

    If the TextInput has an inputMask the length will include mask characters.
*/

QString QQuickTextInput::getText(int start, int end) const
{
    Q_D(const QQuickTextInput);

    if (start > end)
        qSwap(start, end);

    return d->m_text.mid(start, end - start);
}

QString QQuickTextInputPrivate::realText() const
{
    QString res = m_maskData ? stripString(m_text) : m_text;
    return (res.isNull() ? QString::fromLatin1("") : res);
}

/*!
    \qmlproperty string QtQuick::TextInput::font.family

    Sets the family name of the font.

    The family name is case insensitive and may optionally include a foundry name, e.g. "Helvetica [Cronyx]".
    If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen.
    If the family isn't available a family will be set using the font matching algorithm.
*/

/*!
    \qmlproperty string QtQuick::TextInput::font.styleName
    \since 5.6

    Sets the style name of the font.

    The style name is case insensitive. If set, the font will be matched against style name instead
    of the font properties \l font.weight, \l font.bold and \l font.italic.
*/

/*!
    \qmlproperty bool QtQuick::TextInput::font.bold

    Sets whether the font weight is bold.
*/

/*!
    \qmlproperty enumeration QtQuick::TextInput::font.weight

    Sets the font's weight.

    The weight can be one of:
    \list
    \li Font.Thin
    \li Font.Light
    \li Font.ExtraLight
    \li Font.Normal - the default
    \li Font.Medium
    \li Font.DemiBold
    \li Font.Bold
    \li Font.ExtraBold
    \li Font.Black
    \endlist

    \qml
    TextInput { text: "Hello"; font.weight: Font.DemiBold }
    \endqml
*/

/*!
    \qmlproperty bool QtQuick::TextInput::font.italic

    Sets whether the font has an italic style.
*/

/*!
    \qmlproperty bool QtQuick::TextInput::font.underline

    Sets whether the text is underlined.
*/

/*!
    \qmlproperty bool QtQuick::TextInput::font.strikeout

    Sets whether the font has a strikeout style.
*/

/*!
    \qmlproperty real QtQuick::TextInput::font.pointSize

    Sets the font size in points. The point size must be greater than zero.
*/

/*!
    \qmlproperty int QtQuick::TextInput::font.pixelSize

    Sets the font size in pixels.

    Using this function makes the font device dependent.
    Use \c pointSize to set the size of the font in a device independent manner.
*/

/*!
    \qmlproperty real QtQuick::TextInput::font.letterSpacing

    Sets the letter spacing for the font.

    Letter spacing changes the default spacing between individual letters in the font.
    A positive value increases the letter spacing by the corresponding pixels; a negative value decreases the spacing.
*/

/*!
    \qmlproperty real QtQuick::TextInput::font.wordSpacing

    Sets the word spacing for the font.

    Word spacing changes the default spacing between individual words.
    A positive value increases the word spacing by a corresponding amount of pixels,
    while a negative value decreases the inter-word spacing accordingly.
*/

/*!
    \qmlproperty enumeration QtQuick::TextInput::font.capitalization

    Sets the capitalization for the text.

    \list
    \li Font.MixedCase - This is the normal text rendering option where no capitalization change is applied.
    \li Font.AllUppercase - This alters the text to be rendered in all uppercase type.
    \li Font.AllLowercase - This alters the text to be rendered in all lowercase type.
    \li Font.SmallCaps - This alters the text to be rendered in small-caps type.
    \li Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character.
    \endlist

    \qml
    TextInput { text: "Hello"; font.capitalization: Font.AllLowercase }
    \endqml
*/

/*!
    \qmlproperty enumeration QtQuick::TextInput::font.hintingPreference
    \since 5.8

    Sets the preferred hinting on the text. This is a hint to the underlying text rendering system
    to use a certain level of hinting, and has varying support across platforms. See the table in
    the documentation for QFont::HintingPreference for more details.

    \note This property only has an effect when used together with render type TextInput.NativeRendering.

    \list
    \value Font.PreferDefaultHinting - Use the default hinting level for the target platform.
    \value Font.PreferNoHinting - If possible, render text without hinting the outlines
           of the glyphs. The text layout will be typographically accurate, using the same metrics
           as are used e.g. when printing.
    \value Font.PreferVerticalHinting - If possible, render text with no horizontal hinting,
           but align glyphs to the pixel grid in the vertical direction. The text will appear
           crisper on displays where the density is too low to give an accurate rendering
           of the glyphs. But since the horizontal metrics of the glyphs are unhinted, the text's
           layout will be scalable to higher density devices (such as printers) without impacting
           details such as line breaks.
    \value Font.PreferFullHinting - If possible, render text with hinting in both horizontal and
           vertical directions. The text will be altered to optimize legibility on the target
           device, but since the metrics will depend on the target size of the text, the positions
           of glyphs, line breaks, and other typographical detail will not scale, meaning that a
           text layout may look different on devices with different pixel densities.
    \endlist

    \qml
    TextInput { text: "Hello"; renderType: TextInput.NativeRendering; font.hintingPreference: Font.PreferVerticalHinting }
    \endqml
*/
QFont QQuickTextInput::font() const
{
    Q_D(const QQuickTextInput);
    return d->sourceFont;
}

void QQuickTextInput::setFont(const QFont &font)
{
    Q_D(QQuickTextInput);
    if (d->sourceFont == font)
        return;

    d->sourceFont = font;
    QFont oldFont = d->font;
    d->font = font;
    if (d->font.pointSizeF() != -1) {
        // 0.5pt resolution
        qreal size = qRound(d->font.pointSizeF()*2.0);
        d->font.setPointSizeF(size/2.0);
    }
    if (oldFont != d->font) {
        d->updateLayout();
        updateCursorRectangle();
#if QT_CONFIG(im)
        updateInputMethod(Qt::ImCursorRectangle | Qt::ImFont | Qt::ImAnchorRectangle);
#endif
    }
    emit fontChanged(d->sourceFont);
}

/*!
    \qmlproperty color QtQuick::TextInput::color

    The text color.
*/
QColor QQuickTextInput::color() const
{
    Q_D(const QQuickTextInput);
    return d->color;
}

void QQuickTextInput::setColor(const QColor &c)
{
    Q_D(QQuickTextInput);
    if (c != d->color) {
        d->color = c;
        d->textLayoutDirty = true;
        d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
        polish();
        update();
        emit colorChanged();
    }
}


/*!
    \qmlproperty color QtQuick::TextInput::selectionColor

    The text highlight color, used behind selections.
*/
QColor QQuickTextInput::selectionColor() const
{
    Q_D(const QQuickTextInput);
    return d->selectionColor;
}

void QQuickTextInput::setSelectionColor(const QColor &color)
{
    Q_D(QQuickTextInput);
    if (d->selectionColor == color)
        return;

    d->selectionColor = color;
    if (d->hasSelectedText()) {
        d->textLayoutDirty = true;
        d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
        polish();
        update();
    }
    emit selectionColorChanged();
}
/*!
    \qmlproperty color QtQuick::TextInput::selectedTextColor

    The highlighted text color, used in selections.
*/
QColor QQuickTextInput::selectedTextColor() const
{
    Q_D(const QQuickTextInput);
    return d->selectedTextColor;
}

void QQuickTextInput::setSelectedTextColor(const QColor &color)
{
    Q_D(QQuickTextInput);
    if (d->selectedTextColor == color)
        return;

    d->selectedTextColor = color;
    if (d->hasSelectedText()) {
        d->textLayoutDirty = true;
        d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
        polish();
        update();
    }
    emit selectedTextColorChanged();
}

/*!
    \qmlproperty enumeration QtQuick::TextInput::horizontalAlignment
    \qmlproperty enumeration QtQuick::TextInput::effectiveHorizontalAlignment
    \qmlproperty enumeration QtQuick::TextInput::verticalAlignment

    Sets the horizontal alignment of the text within the TextInput item's
    width and height. By default, the text alignment follows the natural alignment
    of the text, for example text that is read from left to right will be aligned to
    the left.

    TextInput does not have vertical alignment, as the natural height is
    exactly the height of the single line of text. If you set the height
    manually to something larger, TextInput will always be top aligned
    vertically. You can use anchors to align it however you want within
    another item.

    The valid values for \c horizontalAlignment are \c TextInput.AlignLeft, \c TextInput.AlignRight and
    \c TextInput.AlignHCenter.

    Valid values for \c verticalAlignment are \c TextInput.AlignTop (default),
    \c TextInput.AlignBottom \c TextInput.AlignVCenter.

    When using the attached property LayoutMirroring::enabled to mirror application
    layouts, the horizontal alignment of text will also be mirrored. However, the property
    \c horizontalAlignment will remain unchanged. To query the effective horizontal alignment
    of TextInput, use the read-only property \c effectiveHorizontalAlignment.
*/
QQuickTextInput::HAlignment QQuickTextInput::hAlign() const
{
    Q_D(const QQuickTextInput);
    return d->hAlign;
}

void QQuickTextInput::setHAlign(HAlignment align)
{
    Q_D(QQuickTextInput);
    bool forceAlign = d->hAlignImplicit && d->effectiveLayoutMirror;
    d->hAlignImplicit = false;
    if (d->setHAlign(align, forceAlign) && isComponentComplete()) {
        d->updateLayout();
        updateCursorRectangle();
    }
}

void QQuickTextInput::resetHAlign()
{
    Q_D(QQuickTextInput);
    d->hAlignImplicit = true;
    if (d->determineHorizontalAlignment() && isComponentComplete()) {
        d->updateLayout();
        updateCursorRectangle();
    }
}

QQuickTextInput::HAlignment QQuickTextInput::effectiveHAlign() const
{
    Q_D(const QQuickTextInput);
    QQuickTextInput::HAlignment effectiveAlignment = d->hAlign;
    if (!d->hAlignImplicit && d->effectiveLayoutMirror) {
        switch (d->hAlign) {
        case QQuickTextInput::AlignLeft:
            effectiveAlignment = QQuickTextInput::AlignRight;
            break;
        case QQuickTextInput::AlignRight:
            effectiveAlignment = QQuickTextInput::AlignLeft;
            break;
        default:
            break;
        }
    }
    return effectiveAlignment;
}

bool QQuickTextInputPrivate::setHAlign(QQuickTextInput::HAlignment alignment, bool forceAlign)
{
    Q_Q(QQuickTextInput);
    if ((hAlign != alignment || forceAlign) && alignment <= QQuickTextInput::AlignHCenter) { // justify not supported
        QQuickTextInput::HAlignment oldEffectiveHAlign = q->effectiveHAlign();
        hAlign = alignment;
        emit q->horizontalAlignmentChanged(alignment);
        if (oldEffectiveHAlign != q->effectiveHAlign())
            emit q->effectiveHorizontalAlignmentChanged();
        return true;
    }
    return false;
}

Qt::LayoutDirection QQuickTextInputPrivate::textDirection() const
{
    QString text = m_text;
#if QT_CONFIG(im)
    if (text.isEmpty())
        text = m_textLayout.preeditAreaText();
#endif

    const QChar *character = text.constData();
    while (!character->isNull()) {
        switch (character->direction()) {
        case QChar::DirL:
            return Qt::LeftToRight;
        case QChar::DirR:
        case QChar::DirAL:
        case QChar::DirAN:
            return Qt::RightToLeft;
        default:
            break;
        }
        character++;
    }
    return Qt::LayoutDirectionAuto;
}

Qt::LayoutDirection QQuickTextInputPrivate::layoutDirection() const
{
    Qt::LayoutDirection direction = m_layoutDirection;
    if (direction == Qt::LayoutDirectionAuto) {
        direction = textDirection();
#if QT_CONFIG(im)
        if (direction == Qt::LayoutDirectionAuto)
            direction = QGuiApplication::inputMethod()->inputDirection();
#endif
    }
    return (direction == Qt::LayoutDirectionAuto) ? Qt::LeftToRight : direction;
}

bool QQuickTextInputPrivate::determineHorizontalAlignment()
{
    if (hAlignImplicit) {
        // if no explicit alignment has been set, follow the natural layout direction of the text
        Qt::LayoutDirection direction = textDirection();
#if QT_CONFIG(im)
        if (direction == Qt::LayoutDirectionAuto)
            direction = QGuiApplication::inputMethod()->inputDirection();
#endif
        return setHAlign(direction == Qt::RightToLeft ? QQuickTextInput::AlignRight : QQuickTextInput::AlignLeft);
    }
    return false;
}

QQuickTextInput::VAlignment QQuickTextInput::vAlign() const
{
    Q_D(const QQuickTextInput);
    return d->vAlign;
}

void QQuickTextInput::setVAlign(QQuickTextInput::VAlignment alignment)
{
    Q_D(QQuickTextInput);
    if (alignment == d->vAlign)
        return;
    d->vAlign = alignment;
    emit verticalAlignmentChanged(d->vAlign);
    if (isComponentComplete()) {
        updateCursorRectangle();
        d->updateBaselineOffset();
    }
}

/*!
    \qmlproperty enumeration QtQuick::TextInput::wrapMode

    Set this property to wrap the text to the TextInput item's width.
    The text will only wrap if an explicit width has been set.

    \list
    \li TextInput.NoWrap - no wrapping will be performed. If the text contains insufficient newlines, then implicitWidth will exceed a set width.
    \li TextInput.WordWrap - wrapping is done on word boundaries only. If a word is too long, implicitWidth will exceed a set width.
    \li TextInput.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word.
    \li TextInput.Wrap - if possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word.
    \endlist

    The default is TextInput.NoWrap. If you set a width, consider using TextInput.Wrap.
*/
QQuickTextInput::WrapMode QQuickTextInput::wrapMode() const
{
    Q_D(const QQuickTextInput);
    return d->wrapMode;
}

void QQuickTextInput::setWrapMode(WrapMode mode)
{
    Q_D(QQuickTextInput);
    if (mode == d->wrapMode)
        return;
    d->wrapMode = mode;
    d->updateLayout();
    updateCursorRectangle();
    emit wrapModeChanged();
}

void QQuickTextInputPrivate::mirrorChange()
{
    Q_Q(QQuickTextInput);
    if (q->isComponentComplete()) {
        if (!hAlignImplicit && (hAlign == QQuickTextInput::AlignRight || hAlign == QQuickTextInput::AlignLeft)) {
            q->updateCursorRectangle();
            emit q->effectiveHorizontalAlignmentChanged();
        }
    }
}

/*!
    \qmlproperty bool QtQuick::TextInput::readOnly

    Sets whether user input can modify the contents of the TextInput.

    If readOnly is set to true, then user input will not affect the text
    property. Any bindings or attempts to set the text property will still
    work.
*/
bool QQuickTextInput::isReadOnly() const
{
    Q_D(const QQuickTextInput);
    return d->m_readOnly;
}

void QQuickTextInput::setReadOnly(bool ro)
{
    Q_D(QQuickTextInput);
    if (d->m_readOnly == ro)
        return;

#if QT_CONFIG(im)
    setFlag(QQuickItem::ItemAcceptsInputMethod, !ro);
#endif
    d->m_readOnly = ro;
    d->setCursorPosition(d->end());
#if QT_CONFIG(im)
    updateInputMethod(Qt::ImEnabled);
#endif
    q_canPasteChanged();
    d->emitUndoRedoChanged();
    emit readOnlyChanged(ro);
    if (ro) {
        setCursorVisible(false);
    } else if (hasActiveFocus()) {
        setCursorVisible(true);
    }
    update();
}

/*!
    \qmlproperty int QtQuick::TextInput::maximumLength
    The maximum permitted length of the text in the TextInput.

    If the text is too long, it is truncated at the limit.

    By default, this property contains a value of 32767.
*/
int QQuickTextInput::maxLength() const
{
    Q_D(const QQuickTextInput);
    return d->m_maxLength;
}

void QQuickTextInput::setMaxLength(int ml)
{
    Q_D(QQuickTextInput);
    if (d->m_maxLength == ml || d->m_maskData)
        return;

    d->m_maxLength = ml;
    d->internalSetText(d->m_text, -1, false);

    emit maximumLengthChanged(ml);
}

/*!
    \qmlproperty bool QtQuick::TextInput::cursorVisible
    Set to true when the TextInput shows a cursor.

    This property is set and unset when the TextInput gets active focus, so that other
    properties can be bound to whether the cursor is currently showing. As it
    gets set and unset automatically, when you set the value yourself you must
    keep in mind that your value may be overwritten.

    It can be set directly in script, for example if a KeyProxy might
    forward keys to it and you desire it to look active when this happens
    (but without actually giving it active focus).

    It should not be set directly on the item, like in the below QML,
    as the specified value will be overridden and lost on focus changes.

    \code
    TextInput {
        text: "Text"
        cursorVisible: false
    }
    \endcode

    In the above snippet the cursor will still become visible when the
    TextInput gains active focus.
*/
bool QQuickTextInput::isCursorVisible() const
{
    Q_D(const QQuickTextInput);
    return d->cursorVisible;
}

void QQuickTextInput::setCursorVisible(bool on)
{
    Q_D(QQuickTextInput);
    if (d->cursorVisible == on)
        return;
    d->cursorVisible = on;
    if (on && isComponentComplete())
        QQuickTextUtil::createCursor(d);
    if (!d->cursorItem)
        d->updateCursorBlinking();
    emit cursorVisibleChanged(d->cursorVisible);
}

/*!
    \qmlproperty int QtQuick::TextInput::cursorPosition
    The position of the cursor in the TextInput.
*/
int QQuickTextInput::cursorPosition() const
{
    Q_D(const QQuickTextInput);
    return d->m_cursor;
}

void QQuickTextInput::setCursorPosition(int cp)
{
    Q_D(QQuickTextInput);
    if (cp < 0 || cp > text().length())
        return;
    d->moveCursor(cp);
}

/*!
    \qmlproperty rectangle QtQuick::TextInput::cursorRectangle

    The rectangle where the standard text cursor is rendered within the text input.  Read only.

    The position and height of a custom cursorDelegate are updated to follow the cursorRectangle
    automatically when it changes.  The width of the delegate is unaffected by changes in the
    cursor rectangle.
*/

QRectF QQuickTextInput::cursorRectangle() const
{
    Q_D(const QQuickTextInput);

    int c = d->m_cursor;
#if QT_CONFIG(im)
    c += d->m_preeditCursor;
#endif
    if (d->m_echoMode == NoEcho)
        c = 0;
    QTextLine l = d->m_textLayout.lineForTextPosition(c);
    if (!l.isValid())
        return QRectF();
    qreal x = l.cursorToX(c) - d->hscroll + leftPadding();
    qreal y = l.y() - d->vscroll + topPadding();
    qreal w = 1;
    if (d->overwriteMode) {
        if (c < text().length())
            w = l.cursorToX(c + 1) - x;
        else
            w = QFontMetrics(font()).width(QLatin1Char(' ')); // in sync with QTextLine::draw()
    }
    return QRectF(x, y, w, l.height());
}

/*!
    \qmlproperty int QtQuick::TextInput::selectionStart

    The cursor position before the first character in the current selection.

    This property is read-only. To change the selection, use select(start,end),
    selectAll(), or selectWord().

    \sa selectionEnd, cursorPosition, selectedText
*/
int QQuickTextInput::selectionStart() const
{
    Q_D(const QQuickTextInput);
    return d->lastSelectionStart;
}
/*!
    \qmlproperty int QtQuick::TextInput::selectionEnd

    The cursor position after the last character in the current selection.

    This property is read-only. To change the selection, use select(start,end),
    selectAll(), or selectWord().

    \sa selectionStart, cursorPosition, selectedText
*/
int QQuickTextInput::selectionEnd() const
{
    Q_D(const QQuickTextInput);
    return d->lastSelectionEnd;
}
/*!
    \qmlmethod QtQuick::TextInput::select(int start, int end)

    Causes the text from \a start to \a end to be selected.

    If either start or end is out of range, the selection is not changed.

    After calling this, selectionStart will become the lesser
    and selectionEnd will become the greater (regardless of the order passed
    to this method).

    \sa selectionStart, selectionEnd
*/
void QQuickTextInput::select(int start, int end)
{
    Q_D(QQuickTextInput);
    if (start < 0 || end < 0 || start > d->m_text.length() || end > d->m_text.length())
        return;
    d->setSelection(start, end-start);
}

/*!
    \qmlproperty string QtQuick::TextInput::selectedText

    This read-only property provides the text currently selected in the
    text input.

    It is equivalent to the following snippet, but is faster and easier
    to use.

    \js
    myTextInput.text.toString().substring(myTextInput.selectionStart,
        myTextInput.selectionEnd);
    \endjs
*/
QString QQuickTextInput::selectedText() const
{
    Q_D(const QQuickTextInput);
    return d->selectedText();
}

/*!
    \qmlproperty bool QtQuick::TextInput::activeFocusOnPress

    Whether the TextInput should gain active focus on a mouse press. By default this is
    set to true.
*/
bool QQuickTextInput::focusOnPress() const
{
    Q_D(const QQuickTextInput);
    return d->focusOnPress;
}

void QQuickTextInput::setFocusOnPress(bool b)
{
    Q_D(QQuickTextInput);
    if (d->focusOnPress == b)
        return;

    d->focusOnPress = b;

    emit activeFocusOnPressChanged(d->focusOnPress);
}
/*!
    \qmlproperty bool QtQuick::TextInput::autoScroll

    Whether the TextInput should scroll when the text is longer than the width. By default this is
    set to true.

    \sa ensureVisible()
*/
bool QQuickTextInput::autoScroll() const
{
    Q_D(const QQuickTextInput);
    return d->autoScroll;
}

void QQuickTextInput::setAutoScroll(bool b)
{
    Q_D(QQuickTextInput);
    if (d->autoScroll == b)
        return;

    d->autoScroll = b;
    //We need to repaint so that the scrolling is taking into account.
    updateCursorRectangle();
    emit autoScrollChanged(d->autoScroll);
}

/*!
    \qmlproperty Validator QtQuick::TextInput::validator

    Allows you to set a validator on the TextInput. When a validator is set
    the TextInput will only accept input which leaves the text property in
    an acceptable or intermediate state. The accepted signal will only be sent
    if the text is in an acceptable state when enter is pressed.

    Currently supported validators are IntValidator, DoubleValidator and
    RegExpValidator. An example of using validators is shown below, which allows
    input of integers between 11 and 31 into the text input:

    \code
    import QtQuick 2.0
    TextInput{
        validator: IntValidator{bottom: 11; top: 31;}
        focus: true
    }
    \endcode

    \sa acceptableInput, inputMask
*/

QValidator* QQuickTextInput::validator() const
{
#if !QT_CONFIG(validator)
    return 0;
#else
    Q_D(const QQuickTextInput);
    return d->m_validator;
#endif // validator
}

void QQuickTextInput::setValidator(QValidator* v)
{
#if !QT_CONFIG(validator)
    Q_UNUSED(v);
#else
    Q_D(QQuickTextInput);
    if (d->m_validator == v)
        return;

    if (d->m_validator) {
        qmlobject_disconnect(
                d->m_validator, QValidator, SIGNAL(changed()),
                this, QQuickTextInput, SLOT(q_validatorChanged()));
    }

    d->m_validator = v;

    if (d->m_validator) {
        qmlobject_connect(
                d->m_validator, QValidator, SIGNAL(changed()),
                this, QQuickTextInput, SLOT(q_validatorChanged()));
    }

    if (isComponentComplete())
        d->checkIsValid();

    emit validatorChanged();
#endif // validator
}

#if QT_CONFIG(validator)
void QQuickTextInput::q_validatorChanged()
{
    Q_D(QQuickTextInput);
    d->checkIsValid();
}
#endif // validator

QRectF QQuickTextInputPrivate::anchorRectangle() const
{
    Q_Q(const QQuickTextInput);
    QRectF rect;
    int a;
    // Unfortunately we cannot use selectionStart() and selectionEnd()
    // since they always assume that the selectionStart is logically before selectionEnd.
    // To rely on that would cause havoc if the user was interactively moving the end selection
    // handle to become before the start selection
    if (m_selstart == m_selend)
        // This is to handle the case when there is "no selection" while moving the handle onto the
        // same position as the other handle (in which case it would hide the selection handles)
        a = m_cursor;
    else
        a = m_selstart == m_cursor ? m_selend : m_selstart;
    if (a >= 0) {
#if QT_CONFIG(im)
        a += m_preeditCursor;
#endif
        if (m_echoMode == QQuickTextInput::NoEcho)
            a = 0;
        QTextLine l = m_textLayout.lineForTextPosition(a);
        if (l.isValid()) {
            qreal x = l.cursorToX(a) - hscroll + q->leftPadding();
            qreal y = l.y() - vscroll + q->topPadding();
            rect.setRect(x, y, 1, l.height());
        }
    }
    return rect;
}

void QQuickTextInputPrivate::checkIsValid()
{
    Q_Q(QQuickTextInput);

    ValidatorState state = hasAcceptableInput(m_text);
    m_validInput = state != InvalidInput;
    if (state != AcceptableInput) {
        if (m_acceptableInput) {
            m_acceptableInput = false;
            emit q->acceptableInputChanged();
        }
    } else if (!m_acceptableInput) {
        m_acceptableInput = true;
        emit q->acceptableInputChanged();
    }
}

/*!
    \qmlproperty string QtQuick::TextInput::inputMask

    Allows you to set an input mask on the TextInput, restricting the allowable
    text inputs. See QLineEdit::inputMask for further details, as the exact
    same mask strings are used by TextInput.

    \sa acceptableInput, validator
*/
QString QQuickTextInput::inputMask() const
{
    Q_D(const QQuickTextInput);
    return d->inputMask();
}

void QQuickTextInput::setInputMask(const QString &im)
{
    Q_D(QQuickTextInput);
    if (d->inputMask() == im)
        return;

    d->setInputMask(im);
    emit inputMaskChanged(d->inputMask());
}

/*!
    \qmlproperty bool QtQuick::TextInput::acceptableInput

    This property is always true unless a validator or input mask has been set.
    If a validator or input mask has been set, this property will only be true
    if the current text is acceptable to the validator or input mask as a final
    string (not as an intermediate string).
*/
bool QQuickTextInput::hasAcceptableInput() const
{
    Q_D(const QQuickTextInput);
    return d->m_acceptableInput;
}

/*!
    \qmlsignal QtQuick::TextInput::accepted()

    This signal is emitted when the Return or Enter key is pressed.
    Note that if there is a \l validator or \l inputMask set on the text
    input, the signal will only be emitted if the input is in an acceptable
    state.

    The corresponding handler is \c onAccepted.
*/

/*!
    \qmlsignal QtQuick::TextInput::editingFinished()
    \since 5.2

    This signal is emitted when the Return or Enter key is pressed or
    the text input loses focus. Note that if there is a validator or
    inputMask set on the text input and enter/return is pressed, this
    signal will only be emitted if the input follows
    the inputMask and the validator returns an acceptable state.

    The corresponding handler is \c onEditingFinished.
*/

/*!
    \qmlsignal QtQuick::TextInput::textEdited()
    \since 5.9

    This signal is emitted whenever the text is edited. Unlike \c textChanged(),
    this signal is not emitted when the text is changed programmatically, for example,
    by changing the value of the \c text property or by calling \c clear().

    The corresponding handler is \c onTextEdited.
*/

#if QT_CONFIG(im)
Qt::InputMethodHints QQuickTextInputPrivate::effectiveInputMethodHints() const
{
    Qt::InputMethodHints hints = inputMethodHints;
    if (m_echoMode == QQuickTextInput::Password || m_echoMode == QQuickTextInput::NoEcho)
        hints |= Qt::ImhHiddenText;
    else if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit)
        hints &= ~Qt::ImhHiddenText;
    if (m_echoMode != QQuickTextInput::Normal)
        hints |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText | Qt::ImhSensitiveData);
    return hints;
}
#endif

/*!
    \qmlproperty enumeration QtQuick::TextInput::echoMode

    Specifies how the text should be displayed in the TextInput.
    \list
    \li TextInput.Normal - Displays the text as it is. (Default)
    \li TextInput.Password - Displays platform-dependent password mask
    characters instead of the actual characters.
    \li TextInput.NoEcho - Displays nothing.
    \li TextInput.PasswordEchoOnEdit - Displays characters as they are entered
    while editing, otherwise identical to \c TextInput.Password.
    \endlist
*/
QQuickTextInput::EchoMode QQuickTextInput::echoMode() const
{
    Q_D(const QQuickTextInput);
    return QQuickTextInput::EchoMode(d->m_echoMode);
}

void QQuickTextInput::setEchoMode(QQuickTextInput::EchoMode echo)
{
    Q_D(QQuickTextInput);
    if (echoMode() == echo)
        return;
    d->cancelPasswordEchoTimer();
    d->m_echoMode = echo;
    d->m_passwordEchoEditing = false;
#if QT_CONFIG(im)
    updateInputMethod(Qt::ImHints);
#endif
    d->updateDisplayText();
    updateCursorRectangle();

    emit echoModeChanged(echoMode());
}

/*!
    \qmlproperty enumeration QtQuick::TextInput::inputMethodHints

    Provides hints to the input method about the expected content of the text input and how it
    should operate.

    The value is a bit-wise combination of flags, or Qt.ImhNone if no hints are set.

    Flags that alter behaviour are:

    \list
    \li Qt.ImhHiddenText - Characters should be hidden, as is typically used when entering passwords.
            This is automatically set when setting echoMode to \c TextInput.Password.
    \li Qt.ImhSensitiveData - Typed text should not be stored by the active input method
            in any persistent storage like predictive user dictionary.
    \li Qt.ImhNoAutoUppercase - The input method should not try to automatically switch to upper case
            when a sentence ends.
    \li Qt.ImhPreferNumbers - Numbers are preferred (but not required).
    \li Qt.ImhPreferUppercase - Upper case letters are preferred (but not required).
    \li Qt.ImhPreferLowercase - Lower case letters are preferred (but not required).
    \li Qt.ImhNoPredictiveText - Do not use predictive text (i.e. dictionary lookup) while typing.

    \li Qt.ImhDate - The text editor functions as a date field.
    \li Qt.ImhTime - The text editor functions as a time field.
    \li Qt.ImhMultiLine - The text editor doesn't close software input keyboard when Return or Enter key is pressed (since QtQuick 2.4).
    \endlist

    Flags that restrict input (exclusive flags) are:

    \list
    \li Qt.ImhDigitsOnly - Only digits are allowed.
    \li Qt.ImhFormattedNumbersOnly - Only number input is allowed. This includes decimal point and minus sign.
    \li Qt.ImhUppercaseOnly - Only upper case letter input is allowed.
    \li Qt.ImhLowercaseOnly - Only lower case letter input is allowed.
    \li Qt.ImhDialableCharactersOnly - Only characters suitable for phone dialing are allowed.
    \li Qt.ImhEmailCharactersOnly - Only characters suitable for email addresses are allowed.
    \li Qt.ImhUrlCharactersOnly - Only characters suitable for URLs are allowed.
    \endlist

    Masks:

    \list
    \li Qt.ImhExclusiveInputMask - This mask yields nonzero if any of the exclusive flags are used.
    \endlist
*/

Qt::InputMethodHints QQuickTextInput::inputMethodHints() const
{
#if !QT_CONFIG(im)
    return Qt::ImhNone;
#else
    Q_D(const QQuickTextInput);
    return d->inputMethodHints;
#endif // im
}

void QQuickTextInput::setInputMethodHints(Qt::InputMethodHints hints)
{
#if !QT_CONFIG(im)
    Q_UNUSED(hints);
#else
    Q_D(QQuickTextInput);

    if (hints == d->inputMethodHints)
        return;

    d->inputMethodHints = hints;
    updateInputMethod(Qt::ImHints);
    emit inputMethodHintsChanged();
#endif // im
}

/*!
    \qmlproperty Component QtQuick::TextInput::cursorDelegate
    The delegate for the cursor in the TextInput.

    If you set a cursorDelegate for a TextInput, this delegate will be used for
    drawing the cursor instead of the standard cursor. An instance of the
    delegate will be created and managed by the TextInput when a cursor is
    needed, and the x property of the delegate instance will be set so as
    to be one pixel before the top left of the current character.

    Note that the root item of the delegate component must be a QQuickItem or
    QQuickItem derived item.
*/
QQmlComponent* QQuickTextInput::cursorDelegate() const
{
    Q_D(const QQuickTextInput);
    return d->cursorComponent;
}

void QQuickTextInput::setCursorDelegate(QQmlComponent* c)
{
    Q_D(QQuickTextInput);
    QQuickTextUtil::setCursorDelegate(d, c);
}

void QQuickTextInput::createCursor()
{
    Q_D(QQuickTextInput);
    d->cursorPending = true;
    QQuickTextUtil::createCursor(d);
}

/*!
    \qmlmethod rect QtQuick::TextInput::positionToRectangle(int pos)

    This function takes a character position and returns the rectangle that the
    cursor would occupy, if it was placed at that character position.

    This is similar to setting the cursorPosition, and then querying the cursor
    rectangle, but the cursorPosition is not changed.
*/
QRectF QQuickTextInput::positionToRectangle(int pos) const
{
    Q_D(const QQuickTextInput);
    if (d->m_echoMode == NoEcho)
        pos = 0;
#if QT_CONFIG(im)
    else if (pos > d->m_cursor)
        pos += d->preeditAreaText().length();
#endif
    QTextLine l = d->m_textLayout.lineForTextPosition(pos);
    if (!l.isValid())
        return QRectF();
    qreal x = l.cursorToX(pos) - d->hscroll;
    qreal y = l.y() - d->vscroll;
    qreal w = 1;
    if (d->overwriteMode) {
        if (pos < text().length())
            w = l.cursorToX(pos + 1) - x;
        else
            w = QFontMetrics(font()).width(QLatin1Char(' ')); // in sync with QTextLine::draw()
    }
    return QRectF(x, y, w, l.height());
}

/*!
    \qmlmethod int QtQuick::TextInput::positionAt(real x, real y, CursorPosition position = CursorBetweenCharacters)

    This function returns the character position at
    x and y pixels from the top left  of the textInput. Position 0 is before the
    first character, position 1 is after the first character but before the second,
    and so on until position text.length, which is after all characters.

    This means that for all x values before the first character this function returns 0,
    and for all x values after the last character this function returns text.length.  If
    the y value is above the text the position will be that of the nearest character on
    the first line and if it is below the text the position of the nearest character
    on the last line will be returned.

    The cursor position type specifies how the cursor position should be resolved.

    \list
    \li TextInput.CursorBetweenCharacters - Returns the position between characters that is nearest x.
    \li TextInput.CursorOnCharacter - Returns the position before the character that is nearest x.
    \endlist
*/

void QQuickTextInput::positionAt(QQmlV4Function *args) const
{
    Q_D(const QQuickTextInput);

    qreal x = 0;
    qreal y = 0;
    QTextLine::CursorPosition position = QTextLine::CursorBetweenCharacters;

    if (args->length() < 1)
        return;

    int i = 0;
    QV4::Scope scope(args->v4engine());
    QV4::ScopedValue arg(scope, (*args)[0]);
    x = arg->toNumber();

    if (++i < args->length()) {
        arg = (*args)[i];
        y = arg->toNumber();
    }

    if (++i < args->length()) {
        arg = (*args)[i];
        position = QTextLine::CursorPosition(arg->toInt32());
    }

    int pos = d->positionAt(x, y, position);
    const int cursor = d->m_cursor;
    if (pos > cursor) {
#if QT_CONFIG(im)
        const int preeditLength = d->preeditAreaText().length();
        pos = pos > cursor + preeditLength
                ? pos - preeditLength
                : cursor;
#else
        pos = cursor;
#endif
    }
    args->setReturnValue(QV4::Encode(pos));
}

int QQuickTextInputPrivate::positionAt(qreal x, qreal y, QTextLine::CursorPosition position) const
{
    Q_Q(const QQuickTextInput);
    x += hscroll - q->leftPadding();
    y += vscroll - q->topPadding();
    QTextLine line = m_textLayout.lineAt(0);
    for (int i = 1; i < m_textLayout.lineCount(); ++i) {
        QTextLine nextLine = m_textLayout.lineAt(i);

        if (y < (line.rect().bottom() + nextLine.y()) / 2)
            break;
        line = nextLine;
    }
    return line.isValid() ? line.xToCursor(x, position) : 0;
}

/*!
    \qmlproperty bool QtQuick::TextInput::overwriteMode
    \since 5.8

    Whether text entered by the user will overwrite existing text.

    As with many text editors, the text editor widget can be configured
    to insert or overwrite existing text with new text entered by the user.

    If this property is \c true, existing text is overwritten, character-for-character
    by new text; otherwise, text is inserted at the cursor position, displacing
    existing text.

    By default, this property is \c false (new text does not overwrite existing text).
*/
bool QQuickTextInput::overwriteMode() const
{
    Q_D(const QQuickTextInput);
    return d->overwriteMode;
}

void QQuickTextInput::setOverwriteMode(bool overwrite)
{
    Q_D(QQuickTextInput);
    if (d->overwriteMode == overwrite)
        return;
    d->overwriteMode = overwrite;
    emit overwriteModeChanged(overwrite);
}

void QQuickTextInput::keyPressEvent(QKeyEvent* ev)
{
    Q_D(QQuickTextInput);
    // Don't allow MacOSX up/down support, and we don't allow a completer.
    bool ignore = (ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) && ev->modifiers() == Qt::NoModifier;
    if (!ignore && (d->lastSelectionStart == d->lastSelectionEnd) && (ev->key() == Qt::Key_Right || ev->key() == Qt::Key_Left)) {
        // Ignore when moving off the end unless there is a selection,
        // because then moving will do something (deselect).
        int cursorPosition = d->m_cursor;
        if (cursorPosition == 0)
            ignore = ev->key() == (d->layoutDirection() == Qt::LeftToRight ? Qt::Key_Left : Qt::Key_Right);
        if (!ignore && cursorPosition == d->m_text.length())
            ignore = ev->key() == (d->layoutDirection() == Qt::LeftToRight ? Qt::Key_Right : Qt::Key_Left);
    }
    if (ignore) {
        ev->ignore();
    } else {
        d->processKeyEvent(ev);
    }
    if (!ev->isAccepted())
        QQuickImplicitSizeItem::keyPressEvent(ev);
}

#if QT_CONFIG(im)
void QQuickTextInput::inputMethodEvent(QInputMethodEvent *ev)
{
    Q_D(QQuickTextInput);
    const bool wasComposing = d->hasImState;
    if (d->m_readOnly) {
        ev->ignore();
    } else {
        d->processInputMethodEvent(ev);
    }
    if (!ev->isAccepted())
        QQuickImplicitSizeItem::inputMethodEvent(ev);

    if (wasComposing != d->hasImState)
        emit inputMethodComposingChanged();
}
#endif

void QQuickTextInput::mouseDoubleClickEvent(QMouseEvent *event)
{
    Q_D(QQuickTextInput);

    if (d->selectByMouse && event->button() == Qt::LeftButton) {
#if QT_CONFIG(im)
        d->commitPreedit();
#endif
        int cursor = d->positionAt(event->localPos());
        d->selectWordAtPos(cursor);
        event->setAccepted(true);
        if (!d->hasPendingTripleClick()) {
            d->tripleClickStartPoint = event->localPos();
            d->tripleClickTimer.start();
        }
    } else {
        if (d->sendMouseEventToInputContext(event))
            return;
        QQuickImplicitSizeItem::mouseDoubleClickEvent(event);
    }
}

void QQuickTextInput::mousePressEvent(QMouseEvent *event)
{
    Q_D(QQuickTextInput);

    d->pressPos = event->localPos();

    if (d->sendMouseEventToInputContext(event))
        return;

    if (d->selectByMouse) {
        setKeepMouseGrab(false);
        d->selectPressed = true;
        QPointF distanceVector = d->pressPos - d->tripleClickStartPoint;
        if (d->hasPendingTripleClick()
            && distanceVector.manhattanLength() < QGuiApplication::styleHints()->startDragDistance()) {
            event->setAccepted(true);
            selectAll();
            return;
        }
    }

    bool mark = (event->modifiers() & Qt::ShiftModifier) && d->selectByMouse;
    int cursor = d->positionAt(event->localPos());
    d->moveCursor(cursor, mark);

    if (d->focusOnPress && !qGuiApp->styleHints()->setFocusOnTouchRelease())
        ensureActiveFocus();

    event->setAccepted(true);
}

void QQuickTextInput::mouseMoveEvent(QMouseEvent *event)
{
    Q_D(QQuickTextInput);

    if (d->selectPressed) {
        if (qAbs(int(event->localPos().x() - d->pressPos.x())) > QGuiApplication::styleHints()->startDragDistance())
            setKeepMouseGrab(true);

#if QT_CONFIG(im)
        if (d->composeMode()) {
            // start selection
            int startPos = d->positionAt(d->pressPos);
            int currentPos = d->positionAt(event->localPos());
            if (startPos != currentPos)
                d->setSelection(startPos, currentPos - startPos);
        } else
#endif
        {
            moveCursorSelection(d->positionAt(event->localPos()), d->mouseSelectionMode);
        }
        event->setAccepted(true);
    } else {
        QQuickImplicitSizeItem::mouseMoveEvent(event);
    }
}

void QQuickTextInput::mouseReleaseEvent(QMouseEvent *event)
{
    Q_D(QQuickTextInput);
    if (d->sendMouseEventToInputContext(event))
        return;
    if (d->selectPressed) {
        d->selectPressed = false;
        setKeepMouseGrab(false);
    }
#if QT_CONFIG(clipboard)
    if (QGuiApplication::clipboard()->supportsSelection()) {
        if (event->button() == Qt::LeftButton) {
            d->copy(QClipboard::Selection);
        } else if (!d->m_readOnly && event->button() == Qt::MidButton) {
            d->deselect();
            d->insert(QGuiApplication::clipboard()->text(QClipboard::Selection));
        }
    }
#endif

    if (d->focusOnPress && qGuiApp->styleHints()->setFocusOnTouchRelease())
        ensureActiveFocus();

    if (!event->isAccepted())
        QQuickImplicitSizeItem::mouseReleaseEvent(event);
}

bool QQuickTextInputPrivate::sendMouseEventToInputContext(QMouseEvent *event)
{
#if QT_CONFIG(im)
    if (composeMode()) {
        int tmp_cursor = positionAt(event->localPos());
        int mousePos = tmp_cursor - m_cursor;
        if (mousePos >= 0 && mousePos <= m_textLayout.preeditAreaText().length()) {
            if (event->type() == QEvent::MouseButtonRelease) {
                QGuiApplication::inputMethod()->invokeAction(QInputMethod::Click, mousePos);
            }
            return true;
        }
    }
#else
    Q_UNUSED(event);
#endif

    return false;
}

void QQuickTextInput::mouseUngrabEvent()
{
    Q_D(QQuickTextInput);
    d->selectPressed = false;
    setKeepMouseGrab(false);
}

bool QQuickTextInput::event(QEvent* ev)
{
#if QT_CONFIG(shortcut)
    Q_D(QQuickTextInput);
    if (ev->type() == QEvent::ShortcutOverride) {
        if (d->m_readOnly)
            return false;
        QKeyEvent* ke = static_cast<QKeyEvent*>(ev);
        if (ke == QKeySequence::Copy
            || ke == QKeySequence::Paste
            || ke == QKeySequence::Cut
            || ke == QKeySequence::Redo
            || ke == QKeySequence::Undo
            || ke == QKeySequence::MoveToNextWord
            || ke == QKeySequence::MoveToPreviousWord
            || ke == QKeySequence::MoveToStartOfDocument
            || ke == QKeySequence::MoveToEndOfDocument
            || ke == QKeySequence::SelectNextWord
            || ke == QKeySequence::SelectPreviousWord
            || ke == QKeySequence::SelectStartOfLine
            || ke == QKeySequence::SelectEndOfLine
            || ke == QKeySequence::SelectStartOfBlock
            || ke == QKeySequence::SelectEndOfBlock
            || ke == QKeySequence::SelectStartOfDocument
            || ke == QKeySequence::SelectAll
            || ke == QKeySequence::SelectEndOfDocument
            || ke == QKeySequence::DeleteCompleteLine) {
            ke->accept();
            return true;
        } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier
                   || ke->modifiers() == Qt::KeypadModifier) {
            if (ke->key() < Qt::Key_Escape) {
                ke->accept();
                return true;
            } else {
                switch (ke->key()) {
                case Qt::Key_Delete:
                case Qt::Key_Home:
                case Qt::Key_End:
                case Qt::Key_Backspace:
                case Qt::Key_Left:
                case Qt::Key_Right:
                    ke->accept();
                    return true;
                default:
                    break;
                }
            }
        }
    }
#endif

    return QQuickImplicitSizeItem::event(ev);
}

void QQuickTextInput::geometryChanged(const QRectF &newGeometry,
                                  const QRectF &oldGeometry)
{
    Q_D(QQuickTextInput);
    if (!d->inLayout) {
        if (newGeometry.width() != oldGeometry.width())
            d->updateLayout();
        else if (newGeometry.height() != oldGeometry.height() && d->vAlign != QQuickTextInput::AlignTop)
            d->updateBaselineOffset();
        updateCursorRectangle();
    }
    QQuickImplicitSizeItem::geometryChanged(newGeometry, oldGeometry);
}

void QQuickTextInputPrivate::ensureVisible(int position, int preeditCursor, int preeditLength)
{
    Q_Q(QQuickTextInput);
    QTextLine textLine = m_textLayout.lineForTextPosition(position + preeditCursor);
    const qreal width = qMax<qreal>(0, q->width() - q->leftPadding() - q->rightPadding());
    qreal cix = 0;
    qreal widthUsed = 0;
    if (textLine.isValid()) {
        cix = textLine.cursorToX(position + preeditLength);
        const qreal cursorWidth = cix >= 0 ? cix : width - cix;
        widthUsed = qMax(textLine.naturalTextWidth(), cursorWidth);
    }
    int previousScroll = hscroll;

    if (widthUsed <= width) {
        hscroll = 0;
    } else {
        Q_ASSERT(textLine.isValid());
        if (cix - hscroll >= width) {
            // text doesn't fit, cursor is to the right of br (scroll right)
            hscroll = cix - width;
        } else if (cix - hscroll < 0 && hscroll < widthUsed) {
            // text doesn't fit, cursor is to the left of br (scroll left)
            hscroll = cix;
        } else if (widthUsed - hscroll < width) {
            // text doesn't fit, text document is to the left of br; align
            // right
            hscroll = widthUsed - width;
        } else if (width - hscroll > widthUsed) {
            // text doesn't fit, text document is to the right of br; align
            // left
            hscroll = width - widthUsed;
        }
#if QT_CONFIG(im)
        if (preeditLength > 0) {
            // check to ensure long pre-edit text doesn't push the cursor
            // off to the left
             cix = textLine.cursorToX(position + qMax(0, preeditCursor - 1));
             if (cix < hscroll)
                 hscroll = cix;
        }
#endif
    }
    if (previousScroll != hscroll)
        textLayoutDirty = true;
}

void QQuickTextInputPrivate::updateHorizontalScroll()
{
    if (autoScroll && m_echoMode != QQuickTextInput::NoEcho) {
#if QT_CONFIG(im)
        const int preeditLength = m_textLayout.preeditAreaText().length();
        ensureVisible(m_cursor, m_preeditCursor, preeditLength);
#else
        ensureVisible(m_cursor);
#endif
    } else {
        hscroll = 0;
    }
}

void QQuickTextInputPrivate::updateVerticalScroll()
{
    Q_Q(QQuickTextInput);
#if QT_CONFIG(im)
    const int preeditLength = m_textLayout.preeditAreaText().length();
#endif
    const qreal height = qMax<qreal>(0, q->height() - q->topPadding() - q->bottomPadding());
    qreal heightUsed = contentSize.height();
    qreal previousScroll = vscroll;

    if (!autoScroll || heightUsed <=  height) {
        // text fits in br; use vscroll for alignment
        vscroll = -QQuickTextUtil::alignedY(
                    heightUsed, height, vAlign & ~(Qt::AlignAbsolute|Qt::AlignHorizontal_Mask));
    } else {
#if QT_CONFIG(im)
        QTextLine currentLine = m_textLayout.lineForTextPosition(m_cursor + preeditLength);
#else
        QTextLine currentLine = m_textLayout.lineForTextPosition(m_cursor);
#endif
        QRectF r = currentLine.isValid() ? currentLine.rect() : QRectF();
        qreal top = r.top();
        int bottom = r.bottom();

        if (bottom - vscroll >= height) {
            // text doesn't fit, cursor is to the below the br (scroll down)
            vscroll = bottom - height;
        } else if (top - vscroll < 0 && vscroll < heightUsed) {
            // text doesn't fit, cursor is above br (scroll up)
            vscroll = top;
        } else if (heightUsed - vscroll < height) {
            // text doesn't fit, text document is to the left of br; align
            // right
            vscroll = heightUsed - height;
        }
#if QT_CONFIG(im)
        if (preeditLength > 0) {
            // check to ensure long pre-edit text doesn't push the cursor
            // off the top
            currentLine = m_textLayout.lineForTextPosition(m_cursor + qMax(0, m_preeditCursor - 1));
            top = currentLine.isValid() ? currentLine.rect().top() : 0;
            if (top < vscroll)
                vscroll = top;
        }
#endif
    }
    if (previousScroll != vscroll)
        textLayoutDirty = true;
}

void QQuickTextInput::triggerPreprocess()
{
    Q_D(QQuickTextInput);
    if (d->updateType == QQuickTextInputPrivate::UpdateNone)
        d->updateType = QQuickTextInputPrivate::UpdateOnlyPreprocess;
    polish();
    update();
}

void QQuickTextInput::updatePolish()
{
    invalidateFontCaches();
}

void QQuickTextInput::invalidateFontCaches()
{
    Q_D(QQuickTextInput);

    if (d->m_textLayout.engine() != 0)
        d->m_textLayout.engine()->resetFontEngineCache();
}

void QQuickTextInput::ensureActiveFocus()
{
    bool hadActiveFocus = hasActiveFocus();
    forceActiveFocus();
#if QT_CONFIG(im)
    Q_D(QQuickTextInput);
    // re-open input panel on press if already focused
    if (hasActiveFocus() && hadActiveFocus && !d->m_readOnly)
        qGuiApp->inputMethod()->show();
#else
    Q_UNUSED(hadActiveFocus);
#endif
}

QSGNode *QQuickTextInput::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
{
    Q_UNUSED(data);
    Q_D(QQuickTextInput);

    if (d->updateType != QQuickTextInputPrivate::UpdatePaintNode && oldNode != 0) {
        // Update done in preprocess() in the nodes
        d->updateType = QQuickTextInputPrivate::UpdateNone;
        return oldNode;
    }

    d->updateType = QQuickTextInputPrivate::UpdateNone;

    QQuickTextNode *node = static_cast<QQuickTextNode *>(oldNode);
    if (node == 0)
        node = new QQuickTextNode(this);
    d->textNode = node;

    const bool showCursor = !isReadOnly() && d->cursorItem == 0 && d->cursorVisible && d->m_blinkStatus;

    if (!d->textLayoutDirty && oldNode != 0) {
        if (showCursor)
            node->setCursor(cursorRectangle(), d->color);
        else
            node->clearCursor();
    } else {
        node->setUseNativeRenderer(d->renderType == NativeRendering);
        node->deleteContent();
        node->setMatrix(QMatrix4x4());

        QPointF offset(leftPadding(), topPadding());
        if (d->autoScroll && d->m_textLayout.lineCount() > 0) {
            QFontMetricsF fm(d->font);
            // the y offset is there to keep the baseline constant in case we have script changes in the text.
            offset += -QPointF(d->hscroll, d->vscroll + d->m_textLayout.lineAt(0).ascent() - fm.ascent());
        } else {
            offset += -QPointF(d->hscroll, d->vscroll);
        }

        if (!d->m_textLayout.text().isEmpty()
#if QT_CONFIG(im)
                || !d->m_textLayout.preeditAreaText().isEmpty()
#endif
                ) {
            node->addTextLayout(offset, &d->m_textLayout, d->color,
                                QQuickText::Normal, QColor(), QColor(),
                                d->selectionColor, d->selectedTextColor,
                                d->selectionStart(),
                                d->selectionEnd() - 1); // selectionEnd() returns first char after
                                                                 // selection
        }

        if (showCursor)
                node->setCursor(cursorRectangle(), d->color);

        d->textLayoutDirty = false;
    }

    invalidateFontCaches();

    return node;
}

#if QT_CONFIG(im)
QVariant QQuickTextInput::inputMethodQuery(Qt::InputMethodQuery property) const
{
    return inputMethodQuery(property, QVariant());
}

QVariant QQuickTextInput::inputMethodQuery(Qt::InputMethodQuery property, QVariant argument) const
{
    Q_D(const QQuickTextInput);
    switch (property) {
    case Qt::ImEnabled:
        return QVariant((bool)(flags() & ItemAcceptsInputMethod));
    case Qt::ImHints:
        return QVariant((int) d->effectiveInputMethodHints());
    case Qt::ImCursorRectangle:
        return cursorRectangle();
    case Qt::ImAnchorRectangle:
        return d->anchorRectangle();
    case Qt::ImFont:
        return font();
    case Qt::ImCursorPosition: {
        const QPointF pt = argument.toPointF();
        if (!pt.isNull())
            return QVariant(d->positionAt(pt));
        return QVariant(d->m_cursor);
    }
    case Qt::ImSurroundingText:
        if (d->m_echoMode == PasswordEchoOnEdit && !d->m_passwordEchoEditing) {
            return QVariant(displayText());
        } else {
            return QVariant(d->realText());
        }
    case Qt::ImCurrentSelection:
        return QVariant(selectedText());
    case Qt::ImMaximumTextLength:
        return QVariant(maxLength());
    case Qt::ImAnchorPosition:
        if (d->selectionStart() == d->selectionEnd())
            return QVariant(d->m_cursor);
        else if (d->selectionStart() == d->m_cursor)
            return QVariant(d->selectionEnd());
        else
            return QVariant(d->selectionStart());
    case Qt::ImAbsolutePosition:
        return QVariant(d->m_cursor);
    case Qt::ImTextAfterCursor:
        if (argument.isValid())
            return QVariant(d->m_text.mid(d->m_cursor, argument.toInt()));
        return QVariant(d->m_text.mid(d->m_cursor));
    case Qt::ImTextBeforeCursor:
        if (argument.isValid())
            return QVariant(d->m_text.leftRef(d->m_cursor).right(argument.toInt()).toString());
        return QVariant(d->m_text.left(d->m_cursor));
    default:
        return QQuickItem::inputMethodQuery(property);
    }
}
#endif // im

/*!
    \qmlmethod QtQuick::TextInput::deselect()

    Removes active text selection.
*/
void QQuickTextInput::deselect()
{
    Q_D(QQuickTextInput);
    d->deselect();
}

/*!
    \qmlmethod QtQuick::TextInput::selectAll()

    Causes all text to be selected.
*/
void QQuickTextInput::selectAll()
{
    Q_D(QQuickTextInput);
    d->setSelection(0, text().length());
}

/*!
    \qmlmethod QtQuick::TextInput::isRightToLeft(int start, int end)

    Returns true if the natural reading direction of the editor text
    found between positions \a start and \a end is right to left.
*/
bool QQuickTextInput::isRightToLeft(int start, int end)
{
    if (start > end) {
        qmlWarning(this) << "isRightToLeft(start, end) called with the end property being smaller than the start.";
        return false;
    } else {
        return text().midRef(start, end - start).isRightToLeft();
    }
}

#if QT_CONFIG(clipboard)
/*!
    \qmlmethod QtQuick::TextInput::cut()

    Moves the currently selected text to the system clipboard.

    \note If the echo mode is set to a mode other than Normal then cut
    will not work.  This is to prevent using cut as a method of bypassing
    password features of the line control.
*/
void QQuickTextInput::cut()
{
    Q_D(QQuickTextInput);
    if (!d->m_readOnly && d->m_echoMode == QQuickTextInput::Normal) {
        d->copy();
        d->del();
    }
}

/*!
    \qmlmethod QtQuick::TextInput::copy()

    Copies the currently selected text to the system clipboard.

    \note If the echo mode is set to a mode other than Normal then copy
    will not work.  This is to prevent using copy as a method of bypassing
    password features of the line control.
*/
void QQuickTextInput::copy()
{
    Q_D(QQuickTextInput);
    d->copy();
}

/*!
    \qmlmethod QtQuick::TextInput::paste()

    Replaces the currently selected text by the contents of the system clipboard.
*/
void QQuickTextInput::paste()
{
    Q_D(QQuickTextInput);
    if (!d->m_readOnly)
        d->paste();
}
#endif // clipboard

/*!
    \qmlmethod QtQuick::TextInput::undo()

    Undoes the last operation if undo is \l {canUndo}{available}. Deselects any
    current selection, and updates the selection start to the current cursor
    position.
*/

void QQuickTextInput::undo()
{
    Q_D(QQuickTextInput);
    if (!d->m_readOnly) {
        d->resetInputMethod();
        d->internalUndo();
        d->finishChange(-1, true);
    }
}

/*!
    \qmlmethod QtQuick::TextInput::redo()

    Redoes the last operation if redo is \l {canRedo}{available}.
*/

void QQuickTextInput::redo()
{
    Q_D(QQuickTextInput);
    if (!d->m_readOnly) {
        d->resetInputMethod();
        d->internalRedo();
        d->finishChange();
    }
}

/*!
    \qmlmethod QtQuick::TextInput::insert(int position, string text)

    Inserts \a text into the TextInput at position.
*/

void QQuickTextInput::insert(int position, const QString &text)
{
    Q_D(QQuickTextInput);
    if (d->m_echoMode == QQuickTextInput::Password) {
        if (d->m_passwordMaskDelay > 0)
            d->m_passwordEchoTimer.start(d->m_passwordMaskDelay, this);
    }
    if (position < 0 || position > d->m_text.length())
        return;

    const int priorState = d->m_undoState;

    QString insertText = text;

    if (d->hasSelectedText()) {
        d->addCommand(QQuickTextInputPrivate::Command(
                QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend));
    }
    if (d->m_maskData) {
        insertText = d->maskString(position, insertText);
        for (int i = 0; i < insertText.length(); ++i) {
            d->addCommand(QQuickTextInputPrivate::Command(
                    QQuickTextInputPrivate::DeleteSelection, position + i, d->m_text.at(position + i), -1, -1));
            d->addCommand(QQuickTextInputPrivate::Command(
                    QQuickTextInputPrivate::Insert, position + i, insertText.at(i), -1, -1));
        }
        d->m_text.replace(position, insertText.length(), insertText);
        if (!insertText.isEmpty())
            d->m_textDirty = true;
        if (position < d->m_selend && position + insertText.length() > d->m_selstart)
            d->m_selDirty = true;
    } else {
        int remaining = d->m_maxLength - d->m_text.length();
        if (remaining != 0) {
            insertText = insertText.left(remaining);
            d->m_text.insert(position, insertText);
            for (int i = 0; i < insertText.length(); ++i)
               d->addCommand(QQuickTextInputPrivate::Command(
                    QQuickTextInputPrivate::Insert, position + i, insertText.at(i), -1, -1));
            if (d->m_cursor >= position)
                d->m_cursor += insertText.length();
            if (d->m_selstart >= position)
                d->m_selstart += insertText.length();
            if (d->m_selend >= position)
                d->m_selend += insertText.length();
            d->m_textDirty = true;
            if (position >= d->m_selstart && position <= d->m_selend)
                d->m_selDirty = true;
        }
    }

    d->addCommand(QQuickTextInputPrivate::Command(
            QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend));
    d->finishChange(priorState);

    if (d->lastSelectionStart != d->lastSelectionEnd) {
        if (d->m_selstart != d->lastSelectionStart) {
            d->lastSelectionStart = d->m_selstart;
            emit selectionStartChanged();
        }
        if (d->m_selend != d->lastSelectionEnd) {
            d->lastSelectionEnd = d->m_selend;
            emit selectionEndChanged();
        }
    }
}

/*!
    \qmlmethod QtQuick::TextInput::remove(int start, int end)

    Removes the section of text that is between the \a start and \a end positions from the TextInput.
*/

void QQuickTextInput::remove(int start, int end)
{
    Q_D(QQuickTextInput);

    start = qBound(0, start, d->m_text.length());
    end = qBound(0, end, d->m_text.length());

    if (start > end)
        qSwap(start, end);
    else if (start == end)
        return;

    if (start < d->m_selend && end > d->m_selstart)
        d->m_selDirty = true;

    const int priorState = d->m_undoState;

    d->addCommand(QQuickTextInputPrivate::Command(
            QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend));

    if (start <= d->m_cursor && d->m_cursor < end) {
        // cursor is within the selection. Split up the commands
        // to be able to restore the correct cursor position
        for (int i = d->m_cursor; i >= start; --i) {
            d->addCommand(QQuickTextInputPrivate::Command(
                    QQuickTextInputPrivate::DeleteSelection, i, d->m_text.at(i), -1, 1));
        }
        for (int i = end - 1; i > d->m_cursor; --i) {
            d->addCommand(QQuickTextInputPrivate::Command(
                    QQuickTextInputPrivate::DeleteSelection, i - d->m_cursor + start - 1, d->m_text.at(i), -1, -1));
        }
    } else {
        for (int i = end - 1; i >= start; --i) {
            d->addCommand(QQuickTextInputPrivate::Command(
                    QQuickTextInputPrivate::RemoveSelection, i, d->m_text.at(i), -1, -1));
        }
    }
    if (d->m_maskData) {
        d->m_text.replace(start, end - start,  d->clearString(start, end - start));
        for (int i = 0; i < end - start; ++i) {
            d->addCommand(QQuickTextInputPrivate::Command(
                    QQuickTextInputPrivate::Insert, start + i, d->m_text.at(start + i), -1, -1));
        }
    } else {
        d->m_text.remove(start, end - start);

        if (d->m_cursor > start)
            d->m_cursor -= qMin(d->m_cursor, end) - start;
        if (d->m_selstart > start)
            d->m_selstart -= qMin(d->m_selstart, end) - start;
        if (d->m_selend > end)
            d->m_selend -= qMin(d->m_selend, end) - start;
    }
    d->addCommand(QQuickTextInputPrivate::Command(
            QQuickTextInputPrivate::SetSelection, d->m_cursor, 0, d->m_selstart, d->m_selend));

    d->m_textDirty = true;
    d->finishChange(priorState);

    if (d->lastSelectionStart != d->lastSelectionEnd) {
        if (d->m_selstart != d->lastSelectionStart) {
            d->lastSelectionStart = d->m_selstart;
            emit selectionStartChanged();
        }
        if (d->m_selend != d->lastSelectionEnd) {
            d->lastSelectionEnd = d->m_selend;
            emit selectionEndChanged();
        }
    }
}


/*!
    \qmlmethod QtQuick::TextInput::selectWord()

    Causes the word closest to the current cursor position to be selected.
*/
void QQuickTextInput::selectWord()
{
    Q_D(QQuickTextInput);
    d->selectWordAtPos(d->m_cursor);
}

/*!
   \qmlproperty string QtQuick::TextInput::passwordCharacter

   This is the character displayed when echoMode is set to Password or
   PasswordEchoOnEdit. By default it is the password character used by
   the platform theme.

   If this property is set to a string with more than one character,
   the first character is used. If the string is empty, the value
   is ignored and the property is not set.
*/
QString QQuickTextInput::passwordCharacter() const
{
    Q_D(const QQuickTextInput);
    return QString(d->m_passwordCharacter);
}

void QQuickTextInput::setPasswordCharacter(const QString &str)
{
    Q_D(QQuickTextInput);
    if (str.length() < 1)
        return;
    d->m_passwordCharacter = str.constData()[0];
    if (d->m_echoMode == Password || d->m_echoMode == PasswordEchoOnEdit)
        d->updateDisplayText();
    emit passwordCharacterChanged();
}

/*!
   \qmlproperty int QtQuick::TextInput::passwordMaskDelay
   \since 5.4

   Sets the delay before visible character is masked with password character, in milliseconds.

   The reset method will be called by assigning undefined.
*/
int QQuickTextInput::passwordMaskDelay() const
{
    Q_D(const QQuickTextInput);
    return d->m_passwordMaskDelay;
}

void QQuickTextInput::setPasswordMaskDelay(int delay)
{
    Q_D(QQuickTextInput);
    if (d->m_passwordMaskDelay != delay) {
        d->m_passwordMaskDelay = delay;
        emit passwordMaskDelayChanged(delay);
    }
}

void QQuickTextInput::resetPasswordMaskDelay()
{
    setPasswordMaskDelay(qGuiApp->styleHints()->passwordMaskDelay());
}

/*!
   \qmlproperty string QtQuick::TextInput::displayText

   This is the text displayed in the TextInput.

   If \l echoMode is set to TextInput::Normal, this holds the
   same value as the TextInput::text property. Otherwise,
   this property holds the text visible to the user, while
   the \l text property holds the actual entered text.

   \note Unlike the TextInput::text property, this contains
   partial text input from an input method.

   \readonly
   \sa preeditText
*/
QString QQuickTextInput::displayText() const
{
    Q_D(const QQuickTextInput);
    return d->m_textLayout.text().insert(d->m_textLayout.preeditAreaPosition(), d->m_textLayout.preeditAreaText());
}

/*!
    \qmlproperty string QtQuick::TextInput::preeditText
    \readonly
    \since 5.7

    This property contains partial text input from an input method.

    \sa displayText
*/
QString QQuickTextInput::preeditText() const
{
    Q_D(const QQuickTextInput);
    return d->m_textLayout.preeditAreaText();
}

/*!
    \qmlproperty bool QtQuick::TextInput::selectByMouse

    Defaults to false.

    If true, the user can use the mouse to select text in some
    platform-specific way. Note that for some platforms this may
    not be an appropriate interaction (it may conflict with how
    the text needs to behave inside a \l Flickable, for example).
*/
bool QQuickTextInput::selectByMouse() const
{
    Q_D(const QQuickTextInput);
    return d->selectByMouse;
}

void QQuickTextInput::setSelectByMouse(bool on)
{
    Q_D(QQuickTextInput);
    if (d->selectByMouse != on) {
        d->selectByMouse = on;
        emit selectByMouseChanged(on);
    }
}

/*!
    \qmlproperty enumeration QtQuick::TextInput::mouseSelectionMode

    Specifies how text should be selected using a mouse.

    \list
    \li TextInput.SelectCharacters - The selection is updated with individual characters. (Default)
    \li TextInput.SelectWords - The selection is updated with whole words.
    \endlist

    This property only applies when \l selectByMouse is true.
*/

QQuickTextInput::SelectionMode QQuickTextInput::mouseSelectionMode() const
{
    Q_D(const QQuickTextInput);
    return d->mouseSelectionMode;
}

void QQuickTextInput::setMouseSelectionMode(SelectionMode mode)
{
    Q_D(QQuickTextInput);
    if (d->mouseSelectionMode != mode) {
        d->mouseSelectionMode = mode;
        emit mouseSelectionModeChanged(mode);
    }
}

/*!
    \qmlproperty bool QtQuick::TextInput::persistentSelection

    Whether the TextInput should keep its selection when it loses active focus to another
    item in the scene. By default this is set to false;
*/

bool QQuickTextInput::persistentSelection() const
{
    Q_D(const QQuickTextInput);
    return d->persistentSelection;
}

void QQuickTextInput::setPersistentSelection(bool on)
{
    Q_D(QQuickTextInput);
    if (d->persistentSelection == on)
        return;
    d->persistentSelection = on;
    emit persistentSelectionChanged();
}

/*!
    \qmlproperty bool QtQuick::TextInput::canPaste

    Returns true if the TextInput is writable and the content of the clipboard is
    suitable for pasting into the TextInput.
*/
bool QQuickTextInput::canPaste() const
{
#if QT_CONFIG(clipboard)
    Q_D(const QQuickTextInput);
    if (!d->canPasteValid) {
        if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData())
            const_cast<QQuickTextInputPrivate *>(d)->canPaste = !d->m_readOnly && mimeData->hasText();
        const_cast<QQuickTextInputPrivate *>(d)->canPasteValid = true;
    }
    return d->canPaste;
#else
    return false;
#endif
}

/*!
    \qmlproperty bool QtQuick::TextInput::canUndo

    Returns true if the TextInput is writable and there are previous operations
    that can be undone.
*/

bool QQuickTextInput::canUndo() const
{
    Q_D(const QQuickTextInput);
    return d->canUndo;
}

/*!
    \qmlproperty bool QtQuick::TextInput::canRedo

    Returns true if the TextInput is writable and there are \l {undo}{undone}
    operations that can be redone.
*/

bool QQuickTextInput::canRedo() const
{
    Q_D(const QQuickTextInput);
    return d->canRedo;
}

/*!
    \qmlproperty real QtQuick::TextInput::contentWidth

    Returns the width of the text, including the width past the width
    which is covered due to insufficient wrapping if \l wrapMode is set.
*/

qreal QQuickTextInput::contentWidth() const
{
    Q_D(const QQuickTextInput);
    return d->contentSize.width();
}

/*!
    \qmlproperty real QtQuick::TextInput::contentHeight

    Returns the height of the text, including the height past the height
    that is covered if the text does not fit within the set height.
*/

qreal QQuickTextInput::contentHeight() const
{
    Q_D(const QQuickTextInput);
    return d->contentSize.height();
}

void QQuickTextInput::moveCursorSelection(int position)
{
    Q_D(QQuickTextInput);
    d->moveCursor(position, true);
}

/*!
    \qmlmethod QtQuick::TextInput::moveCursorSelection(int position, SelectionMode mode = TextInput.SelectCharacters)

    Moves the cursor to \a position and updates the selection according to the optional \a mode
    parameter.  (To only move the cursor, set the \l cursorPosition property.)

    When this method is called it additionally sets either the
    selectionStart or the selectionEnd (whichever was at the previous cursor position)
    to the specified position. This allows you to easily extend and contract the selected
    text range.

    The selection mode specifies whether the selection is updated on a per character or a per word
    basis.  If not specified the selection mode will default to TextInput.SelectCharacters.

    \list
    \li TextInput.SelectCharacters - Sets either the selectionStart or selectionEnd (whichever was at
    the previous cursor position) to the specified position.
    \li TextInput.SelectWords - Sets the selectionStart and selectionEnd to include all
    words between the specified position and the previous cursor position.  Words partially in the
    range are included.
    \endlist

    For example, take this sequence of calls:

    \code
        cursorPosition = 5
        moveCursorSelection(9, TextInput.SelectCharacters)
        moveCursorSelection(7, TextInput.SelectCharacters)
    \endcode

    This moves the cursor to position 5, extend the selection end from 5 to 9
    and then retract the selection end from 9 to 7, leaving the text from position 5 to 7
    selected (the 6th and 7th characters).

    The same sequence with TextInput.SelectWords will extend the selection start to a word boundary
    before or on position 5 and extend the selection end to a word boundary on or past position 9.
*/
void QQuickTextInput::moveCursorSelection(int pos, SelectionMode mode)
{
    Q_D(QQuickTextInput);

    if (mode == SelectCharacters) {
        d->moveCursor(pos, true);
    } else if (pos != d->m_cursor){
        const int cursor = d->m_cursor;
        int anchor;
        if (!d->hasSelectedText())
            anchor = d->m_cursor;
        else if (d->selectionStart() == d->m_cursor)
            anchor = d->selectionEnd();
        else
            anchor = d->selectionStart();

        if (anchor < pos || (anchor == pos && cursor < pos)) {
            const QString text = this->text();
            QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text);
            finder.setPosition(anchor);

            const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons();
            if (anchor < text.length() && (reasons == QTextBoundaryFinder::NotAtBoundary
                                           || (reasons & QTextBoundaryFinder::EndOfItem))) {
                finder.toPreviousBoundary();
            }
            anchor = finder.position() != -1 ? finder.position() : 0;

            finder.setPosition(pos);
            if (pos > 0 && !finder.boundaryReasons())
                finder.toNextBoundary();
            const int cursor = finder.position() != -1 ? finder.position() : text.length();

            d->setSelection(anchor, cursor - anchor);
        } else if (anchor > pos || (anchor == pos && cursor > pos)) {
            const QString text = this->text();
            QTextBoundaryFinder finder(QTextBoundaryFinder::Word, text);
            finder.setPosition(anchor);

            const QTextBoundaryFinder::BoundaryReasons reasons = finder.boundaryReasons();
            if (anchor > 0 && (reasons == QTextBoundaryFinder::NotAtBoundary
                               || (reasons & QTextBoundaryFinder::StartOfItem))) {
                finder.toNextBoundary();
            }
            anchor = finder.position() != -1 ? finder.position() : text.length();

            finder.setPosition(pos);
            if (pos < text.length() && !finder.boundaryReasons())
                 finder.toPreviousBoundary();
            const int cursor = finder.position() != -1 ? finder.position() : 0;

            d->setSelection(anchor, cursor - anchor);
        }
    }
}

void QQuickTextInput::focusInEvent(QFocusEvent *event)
{
    Q_D(QQuickTextInput);
    d->handleFocusEvent(event);
    QQuickImplicitSizeItem::focusInEvent(event);
}

void QQuickTextInputPrivate::handleFocusEvent(QFocusEvent *event)
{
    Q_Q(QQuickTextInput);
    bool focus = event->gotFocus();
    if (!m_readOnly) {
        q->setCursorVisible(focus);
        setBlinkingCursorEnabled(focus);
    }
    if (focus) {
        q->q_updateAlignment();
#if QT_CONFIG(im)
        if (focusOnPress && !m_readOnly)
            qGuiApp->inputMethod()->show();
        q->connect(QGuiApplication::inputMethod(), SIGNAL(inputDirectionChanged(Qt::LayoutDirection)),
                   q, SLOT(q_updateAlignment()));
#endif
    } else {
        if ((m_passwordEchoEditing || m_passwordEchoTimer.isActive())) {
            updatePasswordEchoEditing(false);//QQuickTextInputPrivate sets it on key events, but doesn't deal with focus events
        }

        if (event->reason() != Qt::ActiveWindowFocusReason
                && event->reason() != Qt::PopupFocusReason
                && hasSelectedText()
                && !persistentSelection)
            deselect();

        if (hasAcceptableInput(m_text) == AcceptableInput || fixup())
            emit q->editingFinished();

#if QT_CONFIG(im)
        q->disconnect(QGuiApplication::inputMethod(), SIGNAL(inputDirectionChanged(Qt::LayoutDirection)),
                      q, SLOT(q_updateAlignment()));
#endif
    }
}

void QQuickTextInput::focusOutEvent(QFocusEvent *event)
{
    Q_D(QQuickTextInput);
    d->handleFocusEvent(event);
    QQuickImplicitSizeItem::focusOutEvent(event);
}

/*!
    \qmlproperty bool QtQuick::TextInput::inputMethodComposing


    This property holds whether the TextInput has partial text input from an
    input method.

    While it is composing an input method may rely on mouse or key events from
    the TextInput to edit or commit the partial text.  This property can be
    used to determine when to disable events handlers that may interfere with
    the correct operation of an input method.
*/
bool QQuickTextInput::isInputMethodComposing() const
{
#if !QT_CONFIG(im)
    return false;
#else
    Q_D(const QQuickTextInput);
    return d->hasImState;
#endif
}

QQuickTextInputPrivate::ExtraData::ExtraData()
    : padding(0)
    , topPadding(0)
    , leftPadding(0)
    , rightPadding(0)
    , bottomPadding(0)
    , explicitTopPadding(false)
    , explicitLeftPadding(false)
    , explicitRightPadding(false)
    , explicitBottomPadding(false)
    , implicitResize(true)
{
}

void QQuickTextInputPrivate::init()
{
    Q_Q(QQuickTextInput);
#if QT_CONFIG(clipboard)
    if (QGuiApplication::clipboard()->supportsSelection())
        q->setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton);
    else
#endif
        q->setAcceptedMouseButtons(Qt::LeftButton);

#if QT_CONFIG(im)
    q->setFlag(QQuickItem::ItemAcceptsInputMethod);
#endif
    q->setFlag(QQuickItem::ItemHasContents);
#if QT_CONFIG(clipboard)
    qmlobject_connect(QGuiApplication::clipboard(), QClipboard, SIGNAL(dataChanged()),
            q, QQuickTextInput, SLOT(q_canPasteChanged()));
#endif // clipboard

    lastSelectionStart = 0;
    lastSelectionEnd = 0;
    determineHorizontalAlignment();

    if (!qmlDisableDistanceField()) {
        QTextOption option = m_textLayout.textOption();
        option.setUseDesignMetrics(renderType != QQuickTextInput::NativeRendering);
        m_textLayout.setTextOption(option);
    }

    m_inputControl = new QInputControl(QInputControl::LineEdit, q);
}

void QQuickTextInputPrivate::resetInputMethod()
{
    Q_Q(QQuickTextInput);
    if (!m_readOnly && q->hasActiveFocus() && qGuiApp)
        QGuiApplication::inputMethod()->reset();
}

void QQuickTextInput::updateCursorRectangle(bool scroll)
{
    Q_D(QQuickTextInput);
    if (!isComponentComplete())
        return;

    if (scroll) {
        d->updateHorizontalScroll();
        d->updateVerticalScroll();
    }
    d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
    polish();
    update();
    emit cursorRectangleChanged();
    if (d->cursorItem) {
        QRectF r = cursorRectangle();
        d->cursorItem->setPosition(r.topLeft());
        d->cursorItem->setHeight(r.height());
    }
#if QT_CONFIG(im)
    updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorRectangle);
#endif
}

void QQuickTextInput::selectionChanged()
{
    Q_D(QQuickTextInput);
    d->textLayoutDirty = true; //TODO: Only update rect in selection
    d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
    polish();
    update();
    emit selectedTextChanged();

    if (d->lastSelectionStart != d->selectionStart()) {
        d->lastSelectionStart = d->selectionStart();
        if (d->lastSelectionStart == -1)
            d->lastSelectionStart = d->m_cursor;
        emit selectionStartChanged();
    }
    if (d->lastSelectionEnd != d->selectionEnd()) {
        d->lastSelectionEnd = d->selectionEnd();
        if (d->lastSelectionEnd == -1)
            d->lastSelectionEnd = d->m_cursor;
        emit selectionEndChanged();
    }
}

QRectF QQuickTextInput::boundingRect() const
{
    Q_D(const QQuickTextInput);

    int cursorWidth = d->cursorItem ? 0 : 1;

    qreal hscroll = d->hscroll;
    if (!d->autoScroll || d->contentSize.width() < width())
        hscroll -= QQuickTextUtil::alignedX(d->contentSize.width(), width(), effectiveHAlign());

    // Could include font max left/right bearings to either side of rectangle.
    QRectF r(-hscroll, -d->vscroll, d->contentSize.width(), d->contentSize.height());
    r.setRight(r.right() + cursorWidth);
    return r;
}

QRectF QQuickTextInput::clipRect() const
{
    Q_D(const QQuickTextInput);

    int cursorWidth = d->cursorItem ? d->cursorItem->width() : 1;

    // Could include font max left/right bearings to either side of rectangle.
    QRectF r = QQuickImplicitSizeItem::clipRect();
    r.setRight(r.right() + cursorWidth);
    return r;
}

void QQuickTextInput::q_canPasteChanged()
{
    Q_D(QQuickTextInput);
    bool old = d->canPaste;
#if QT_CONFIG(clipboard)
    if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData())
        d->canPaste = !d->m_readOnly && mimeData->hasText();
    else
        d->canPaste = false;
#endif

    bool changed = d->canPaste != old || !d->canPasteValid;
    d->canPasteValid = true;
    if (changed)
        emit canPasteChanged();

}

void QQuickTextInput::q_updateAlignment()
{
    Q_D(QQuickTextInput);
    if (d->determineHorizontalAlignment()) {
        d->updateLayout();
        updateCursorRectangle();
    }
}

/*!
    \internal

    Updates the display text based of the current edit text
    If the text has changed will emit displayTextChanged()
*/
void QQuickTextInputPrivate::updateDisplayText(bool forceUpdate)
{
    QString orig = m_textLayout.text();
    QString str;
    if (m_echoMode == QQuickTextInput::NoEcho)
        str = QString::fromLatin1("");
    else
        str = m_text;

    if (m_echoMode == QQuickTextInput::Password) {
         str.fill(m_passwordCharacter);
        if (m_passwordEchoTimer.isActive() && m_cursor > 0 && m_cursor <= m_text.length()) {
            int cursor = m_cursor - 1;
            QChar uc = m_text.at(cursor);
            str[cursor] = uc;
            if (cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) {
                // second half of a surrogate, check if we have the first half as well,
                // if yes restore both at once
                uc = m_text.at(cursor - 1);
                if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00)
                    str[cursor - 1] = uc;
            }
        }
    } else if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit && !m_passwordEchoEditing) {
        str.fill(m_passwordCharacter);
    }

    // replace certain non-printable characters with spaces (to avoid
    // drawing boxes when using fonts that don't have glyphs for such
    // characters)
    QChar* uc = str.data();
    for (int i = 0; i < str.length(); ++i) {
        if ((uc[i].unicode() < 0x20 && uc[i] != QChar::Tabulation)
            || uc[i] == QChar::LineSeparator
            || uc[i] == QChar::ParagraphSeparator
            || uc[i] == QChar::ObjectReplacementCharacter)
            uc[i] = QChar(0x0020);
    }

    if (str != orig || forceUpdate) {
        m_textLayout.setText(str);
        updateLayout(); // polish?
        emit q_func()->displayTextChanged();
    }
}

qreal QQuickTextInputPrivate::getImplicitWidth() const
{
    Q_Q(const QQuickTextInput);
    if (!requireImplicitWidth) {
        QQuickTextInputPrivate *d = const_cast<QQuickTextInputPrivate *>(this);
        d->requireImplicitWidth = true;

        if (q->isComponentComplete()) {
            // One time cost, only incurred if implicitWidth is first requested after
            // componentComplete.
            QTextLayout layout(m_text);

            QTextOption option = m_textLayout.textOption();
            option.setTextDirection(m_layoutDirection);
            option.setFlags(QTextOption::IncludeTrailingSpaces);
            option.setWrapMode(QTextOption::WrapMode(wrapMode));
            option.setAlignment(Qt::Alignment(q->effectiveHAlign()));
            layout.setTextOption(option);
            layout.setFont(font);
#if QT_CONFIG(im)
            layout.setPreeditArea(m_textLayout.preeditAreaPosition(), m_textLayout.preeditAreaText());
#endif
            layout.beginLayout();

            QTextLine line = layout.createLine();
            line.setLineWidth(INT_MAX);
            d->implicitWidth = qCeil(line.naturalTextWidth()) + q->leftPadding() + q->rightPadding();

            layout.endLayout();
        }
    }
    return implicitWidth;
}

void QQuickTextInputPrivate::setTopPadding(qreal value, bool reset)
{
    Q_Q(QQuickTextInput);
    qreal oldPadding = q->topPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().topPadding = value;
        extra.value().explicitTopPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        updateLayout();
        emit q->topPaddingChanged();
    }
}

void QQuickTextInputPrivate::setLeftPadding(qreal value, bool reset)
{
    Q_Q(QQuickTextInput);
    qreal oldPadding = q->leftPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().leftPadding = value;
        extra.value().explicitLeftPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        updateLayout();
        emit q->leftPaddingChanged();
    }
}

void QQuickTextInputPrivate::setRightPadding(qreal value, bool reset)
{
    Q_Q(QQuickTextInput);
    qreal oldPadding = q->rightPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().rightPadding = value;
        extra.value().explicitRightPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        updateLayout();
        emit q->rightPaddingChanged();
    }
}

void QQuickTextInputPrivate::setBottomPadding(qreal value, bool reset)
{
    Q_Q(QQuickTextInput);
    qreal oldPadding = q->bottomPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().bottomPadding = value;
        extra.value().explicitBottomPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        updateLayout();
        emit q->bottomPaddingChanged();
    }
}

bool QQuickTextInputPrivate::isImplicitResizeEnabled() const
{
    return !extra.isAllocated() || extra->implicitResize;
}

void QQuickTextInputPrivate::setImplicitResizeEnabled(bool enabled)
{
    if (!enabled)
        extra.value().implicitResize = false;
    else if (extra.isAllocated())
        extra->implicitResize = true;
}

void QQuickTextInputPrivate::updateLayout()
{
    Q_Q(QQuickTextInput);

    if (!q->isComponentComplete())
        return;


    QTextOption option = m_textLayout.textOption();
    option.setTextDirection(layoutDirection());
    option.setWrapMode(QTextOption::WrapMode(wrapMode));
    option.setAlignment(Qt::Alignment(q->effectiveHAlign()));
    if (!qmlDisableDistanceField())
        option.setUseDesignMetrics(renderType != QQuickTextInput::NativeRendering);

    m_textLayout.setTextOption(option);
    m_textLayout.setFont(font);

    m_textLayout.beginLayout();

    QTextLine line = m_textLayout.createLine();
    if (requireImplicitWidth) {
        line.setLineWidth(INT_MAX);
        const bool wasInLayout = inLayout;
        inLayout = true;
        if (isImplicitResizeEnabled())
            q->setImplicitWidth(qCeil(line.naturalTextWidth()) + q->leftPadding() + q->rightPadding());
        inLayout = wasInLayout;
        if (inLayout)       // probably the result of a binding loop, but by letting it
            return;         // get this far we'll get a warning to that effect.
    }
    qreal lineWidth = q->widthValid() || !isImplicitResizeEnabled() ? q->width() - q->leftPadding() - q->rightPadding() : INT_MAX;
    qreal height = 0;
    qreal width = 0;
    do {
        line.setLineWidth(lineWidth);
        line.setPosition(QPointF(0, height));

        height += line.height();
        width = qMax(width, line.naturalTextWidth());

        line = m_textLayout.createLine();
    } while (line.isValid());
    m_textLayout.endLayout();

    option.setWrapMode(QTextOption::NoWrap);
    m_textLayout.setTextOption(option);

    textLayoutDirty = true;

    const QSizeF previousSize = contentSize;
    contentSize = QSizeF(width, height);

    updateType = UpdatePaintNode;
    q->polish();
    q->update();

    if (isImplicitResizeEnabled()) {
        if (!requireImplicitWidth && !q->widthValid())
            q->setImplicitSize(width + q->leftPadding() + q->rightPadding(), height + q->topPadding() + q->bottomPadding());
        else
            q->setImplicitHeight(height + q->topPadding() + q->bottomPadding());
    }

    updateBaselineOffset();

    if (previousSize != contentSize)
        emit q->contentSizeChanged();
}

/*!
    \internal
    \brief QQuickTextInputPrivate::updateBaselineOffset

    Assumes contentSize.height() is already calculated.
 */
void QQuickTextInputPrivate::updateBaselineOffset()
{
    Q_Q(QQuickTextInput);
    if (!q->isComponentComplete())
        return;
    QFontMetricsF fm(font);
    qreal yoff = 0;
    if (q->heightValid()) {
        const qreal surplusHeight = q->height() - contentSize.height() - q->topPadding() - q->bottomPadding();
        if (vAlign == QQuickTextInput::AlignBottom)
            yoff = surplusHeight;
        else if (vAlign == QQuickTextInput::AlignVCenter)
            yoff = surplusHeight/2;
    }
    q->setBaselineOffset(fm.ascent() + yoff + q->topPadding());
}

#if QT_CONFIG(clipboard)
/*!
    \internal

    Copies the currently selected text into the clipboard using the given
    \a mode.

    \note If the echo mode is set to a mode other than Normal then copy
    will not work.  This is to prevent using copy as a method of bypassing
    password features of the line control.
*/
void QQuickTextInputPrivate::copy(QClipboard::Mode mode) const
{
    QString t = selectedText();
    if (!t.isEmpty() && m_echoMode == QQuickTextInput::Normal) {
        QGuiApplication::clipboard()->setText(t, mode);
    }
}

/*!
    \internal

    Inserts the text stored in the application clipboard into the line
    control.

    \sa insert()
*/
void QQuickTextInputPrivate::paste(QClipboard::Mode clipboardMode)
{
    QString clip = QGuiApplication::clipboard()->text(clipboardMode);
    if (!clip.isEmpty() || hasSelectedText()) {
        separate(); //make it a separate undo/redo command
        insert(clip);
        separate();
    }
}

#endif // clipboard

#if QT_CONFIG(im)
/*!
    \internal
*/
void QQuickTextInputPrivate::commitPreedit()
{
    Q_Q(QQuickTextInput);

    if (!hasImState)
        return;

    QGuiApplication::inputMethod()->commit();

    if (!hasImState)
        return;

    QInputMethodEvent ev;
    QCoreApplication::sendEvent(q, &ev);
}

void QQuickTextInputPrivate::cancelPreedit()
{
    Q_Q(QQuickTextInput);

    if (!hasImState)
        return;

    QGuiApplication::inputMethod()->reset();

    QInputMethodEvent ev;
    QCoreApplication::sendEvent(q, &ev);
}
#endif // im

/*!
    \internal

    Handles the behavior for the backspace key or function.
    Removes the current selection if there is a selection, otherwise
    removes the character prior to the cursor position.

    \sa del()
*/
void QQuickTextInputPrivate::backspace()
{
    int priorState = m_undoState;
    if (separateSelection()) {
        removeSelectedText();
    } else if (m_cursor) {
            --m_cursor;
            if (m_maskData)
                m_cursor = prevMaskBlank(m_cursor);
            QChar uc = m_text.at(m_cursor);
            if (m_cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) {
                // second half of a surrogate, check if we have the first half as well,
                // if yes delete both at once
                uc = m_text.at(m_cursor - 1);
                if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) {
                    internalDelete(true);
                    --m_cursor;
                }
            }
            internalDelete(true);
    }
    finishChange(priorState);
}

/*!
    \internal

    Handles the behavior for the delete key or function.
    Removes the current selection if there is a selection, otherwise
    removes the character after the cursor position.

    \sa del()
*/
void QQuickTextInputPrivate::del()
{
    int priorState = m_undoState;
    if (separateSelection()) {
        removeSelectedText();
    } else {
        int n = m_textLayout.nextCursorPosition(m_cursor) - m_cursor;
        while (n--)
            internalDelete();
    }
    finishChange(priorState);
}

/*!
    \internal

    Inserts the given \a newText at the current cursor position.
    If there is any selected text it is removed prior to insertion of
    the new text.
*/
void QQuickTextInputPrivate::insert(const QString &newText)
{
    int priorState = m_undoState;
    if (separateSelection())
        removeSelectedText();
    internalInsert(newText);
    finishChange(priorState);
}

/*!
    \internal

    Clears the line control text.
*/
void QQuickTextInputPrivate::clear()
{
    int priorState = m_undoState;
    separateSelection();
    m_selstart = 0;
    m_selend = m_text.length();
    removeSelectedText();
    separate();
    finishChange(priorState, /*update*/false, /*edited*/false);
}

/*!
    \internal

    Sets \a length characters from the given \a start position as selected.
    The given \a start position must be within the current text for
    the line control.  If \a length characters cannot be selected, then
    the selection will extend to the end of the current text.
*/
void QQuickTextInputPrivate::setSelection(int start, int length)
{
    Q_Q(QQuickTextInput);
#if QT_CONFIG(im)
    commitPreedit();
#endif

    if (start < 0 || start > m_text.length()) {
        qWarning("QQuickTextInputPrivate::setSelection: Invalid start position");
        return;
    }

    if (length > 0) {
        if (start == m_selstart && start + length == m_selend && m_cursor == m_selend)
            return;
        m_selstart = start;
        m_selend = qMin(start + length, m_text.length());
        m_cursor = m_selend;
    } else if (length < 0){
        if (start == m_selend && start + length == m_selstart && m_cursor == m_selstart)
            return;
        m_selstart = qMax(start + length, 0);
        m_selend = start;
        m_cursor = m_selstart;
    } else if (m_selstart != m_selend) {
        m_selstart = 0;
        m_selend = 0;
        m_cursor = start;
    } else {
        m_cursor = start;
        emitCursorPositionChanged();
        return;
    }
    emit q->selectionChanged();
    emitCursorPositionChanged();
#if QT_CONFIG(im)
    q->updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorRectangle | Qt::ImCursorPosition | Qt::ImAnchorPosition
                       | Qt::ImCurrentSelection);
#endif
}

/*!
    \internal

    Sets the password echo editing to \a editing.  If password echo editing
    is true, then the text of the password is displayed even if the echo
    mode is set to QLineEdit::PasswordEchoOnEdit.  Password echoing editing
    does not affect other echo modes.
*/
void QQuickTextInputPrivate::updatePasswordEchoEditing(bool editing)
{
    cancelPasswordEchoTimer();
    m_passwordEchoEditing = editing;
    updateDisplayText();
}

/*!
    \internal

    Fixes the current text so that it is valid given any set validators.

    Returns true if the text was changed.  Otherwise returns false.
*/
bool QQuickTextInputPrivate::fixup() // this function assumes that validate currently returns != Acceptable
{
#if QT_CONFIG(validator)
    if (m_validator) {
        QString textCopy = m_text;
        int cursorCopy = m_cursor;
        m_validator->fixup(textCopy);
        if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) {
            if (textCopy != m_text || cursorCopy != m_cursor)
                internalSetText(textCopy, cursorCopy);
            return true;
        }
    }
#endif
    return false;
}

/*!
    \internal

    Moves the cursor to the given position \a pos.   If \a mark is true will
    adjust the currently selected text.
*/
void QQuickTextInputPrivate::moveCursor(int pos, bool mark)
{
    Q_Q(QQuickTextInput);
#if QT_CONFIG(im)
    commitPreedit();
#endif

    if (pos != m_cursor) {
        separate();
        if (m_maskData)
            pos = pos > m_cursor ? nextMaskBlank(pos) : prevMaskBlank(pos);
    }
    if (mark) {
        int anchor;
        if (m_selend > m_selstart && m_cursor == m_selstart)
            anchor = m_selend;
        else if (m_selend > m_selstart && m_cursor == m_selend)
            anchor = m_selstart;
        else
            anchor = m_cursor;
        m_selstart = qMin(anchor, pos);
        m_selend = qMax(anchor, pos);
    } else {
        internalDeselect();
    }
    m_cursor = pos;
    if (mark || m_selDirty) {
        m_selDirty = false;
        emit q->selectionChanged();
    }
    emitCursorPositionChanged();
#if QT_CONFIG(im)
    q->updateInputMethod();
#endif
}

#if QT_CONFIG(im)
/*!
    \internal

    Applies the given input method event \a event to the text of the line
    control
*/
void QQuickTextInputPrivate::processInputMethodEvent(QInputMethodEvent *event)
{
    Q_Q(QQuickTextInput);

    int priorState = -1;
    bool isGettingInput = !event->commitString().isEmpty()
            || event->preeditString() != preeditAreaText()
            || event->replacementLength() > 0;
    bool cursorPositionChanged = false;
    bool selectionChange = false;
    m_preeditDirty = event->preeditString() != preeditAreaText();

    if (isGettingInput) {
        // If any text is being input, remove selected text.
        priorState = m_undoState;
        separateSelection();
        if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit && !m_passwordEchoEditing) {
            updatePasswordEchoEditing(true);
            m_selstart = 0;
            m_selend = m_text.length();
        }
        removeSelectedText();
    }

    int c = m_cursor; // cursor position after insertion of commit string
    if (event->replacementStart() <= 0)
        c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength());

    m_cursor += event->replacementStart();
    if (m_cursor < 0)
        m_cursor = 0;

    // insert commit string
    if (event->replacementLength()) {
        m_selstart = m_cursor;
        m_selend = m_selstart + event->replacementLength();
        m_selend = qMin(m_selend, m_text.length());
        removeSelectedText();
    }
    if (!event->commitString().isEmpty()) {
        internalInsert(event->commitString());
        cursorPositionChanged = true;
    }

    m_cursor = qBound(0, c, m_text.length());

    for (int i = 0; i < event->attributes().size(); ++i) {
        const QInputMethodEvent::Attribute &a = event->attributes().at(i);
        if (a.type == QInputMethodEvent::Selection) {
            m_cursor = qBound(0, a.start + a.length, m_text.length());
            if (a.length) {
                m_selstart = qMax(0, qMin(a.start, m_text.length()));
                m_selend = m_cursor;
                if (m_selend < m_selstart) {
                    qSwap(m_selstart, m_selend);
                }
                selectionChange = true;
            } else {
                m_selstart = m_selend = 0;
            }
            cursorPositionChanged = true;
        }
    }
    QString oldPreeditString = m_textLayout.preeditAreaText();
    m_textLayout.setPreeditArea(m_cursor, event->preeditString());
    if (oldPreeditString != m_textLayout.preeditAreaText())
        emit q->preeditTextChanged();
    const int oldPreeditCursor = m_preeditCursor;
    m_preeditCursor = event->preeditString().length();
    hasImState = !event->preeditString().isEmpty();
    bool cursorVisible = true;
    QVector<QTextLayout::FormatRange> formats;
    for (int i = 0; i < event->attributes().size(); ++i) {
        const QInputMethodEvent::Attribute &a = event->attributes().at(i);
        if (a.type == QInputMethodEvent::Cursor) {
            hasImState = true;
            m_preeditCursor = a.start;
            cursorVisible = a.length != 0;
        } else if (a.type == QInputMethodEvent::TextFormat) {
            hasImState = true;
            QTextCharFormat f = qvariant_cast<QTextFormat>(a.value).toCharFormat();
            if (f.isValid()) {
                QTextLayout::FormatRange o;
                o.start = a.start + m_cursor;
                o.length = a.length;
                o.format = f;
                formats.append(o);
            }
        }
    }
    m_textLayout.setFormats(formats);

    updateDisplayText(/*force*/ true);
    if ((cursorPositionChanged && !emitCursorPositionChanged())
            || m_preeditCursor != oldPreeditCursor
            || isGettingInput) {
        q->updateCursorRectangle();
    }

    if (isGettingInput)
        finishChange(priorState);

    q->setCursorVisible(cursorVisible);

    if (selectionChange) {
        emit q->selectionChanged();
        q->updateInputMethod(Qt::ImCursorRectangle | Qt::ImAnchorRectangle
                            | Qt::ImCurrentSelection);
    }
}
#endif // im

/*!
    \internal

    Sets the selection to cover the word at the given cursor position.
    The word boundaries are defined by the behavior of QTextLayout::SkipWords
    cursor mode.
*/
void QQuickTextInputPrivate::selectWordAtPos(int cursor)
{
    int next = cursor + 1;
    if (next > end())
        --next;
    int c = m_textLayout.previousCursorPosition(next, QTextLayout::SkipWords);
    moveCursor(c, false);
    // ## text layout should support end of words.
    int end = m_textLayout.nextCursorPosition(c, QTextLayout::SkipWords);
    while (end > cursor && m_text[end-1].isSpace())
        --end;
    moveCursor(end, true);
}

/*!
    \internal

    Completes a change to the line control text.  If the change is not valid
    will undo the line control state back to the given \a validateFromState.

    If \a edited is true and the change is valid, will emit textEdited() in
    addition to textChanged().  Otherwise only emits textChanged() on a valid
    change.

    The \a update value is currently unused.
*/
bool QQuickTextInputPrivate::finishChange(int validateFromState, bool update, bool edited)
{
    Q_Q(QQuickTextInput);

    Q_UNUSED(update)
#if QT_CONFIG(im)
    bool inputMethodAttributesChanged = m_textDirty || m_selDirty;
#endif
    bool alignmentChanged = false;
    bool textChanged = false;

    if (m_textDirty) {
        // do validation
        bool wasValidInput = m_validInput;
        bool wasAcceptable = m_acceptableInput;
        m_validInput = true;
        m_acceptableInput = true;
#if QT_CONFIG(validator)
        if (m_validator) {
            QString textCopy = m_text;
            int cursorCopy = m_cursor;
            QValidator::State state = m_validator->validate(textCopy, cursorCopy);
            m_validInput = state != QValidator::Invalid;
            m_acceptableInput = state == QValidator::Acceptable;
            if (m_validInput) {
                if (m_text != textCopy) {
                    internalSetText(textCopy, cursorCopy);
                    return true;
                }
                m_cursor = cursorCopy;
            }
        }
#endif

        if (m_maskData) {
            if (m_text.length() != m_maxLength) {
                m_acceptableInput = false;
            } else {
                for (int i = 0; i < m_maxLength; ++i) {
                    if (m_maskData[i].separator) {
                        if (m_text.at(i) != m_maskData[i].maskChar) {
                            m_acceptableInput = false;
                            break;
                        }
                    } else {
                        if (!isValidInput(m_text.at(i), m_maskData[i].maskChar)) {
                            m_acceptableInput = false;
                            break;
                        }
                    }
                }
            }
        }

        if (validateFromState >= 0 && wasValidInput && !m_validInput) {
            if (m_transactions.count())
                return false;
            internalUndo(validateFromState);
            m_history.resize(m_undoState);
            m_validInput = true;
            m_acceptableInput = wasAcceptable;
            m_textDirty = false;
        }

        if (m_textDirty) {
            textChanged = true;
            m_textDirty = false;
#if QT_CONFIG(im)
            m_preeditDirty = false;
#endif
            alignmentChanged = determineHorizontalAlignment();
            if (edited)
                emit q->textEdited();
            emit q->textChanged();
        }

        updateDisplayText(alignmentChanged);

        if (m_acceptableInput != wasAcceptable)
            emit q->acceptableInputChanged();
    }
#if QT_CONFIG(im)
    if (m_preeditDirty) {
        m_preeditDirty = false;
        if (determineHorizontalAlignment()) {
            alignmentChanged = true;
            updateLayout();
        }
    }
#endif

    if (m_selDirty) {
        m_selDirty = false;
        emit q->selectionChanged();
    }

#if QT_CONFIG(im)
    inputMethodAttributesChanged |= (m_cursor != m_lastCursorPos);
    if (inputMethodAttributesChanged)
        q->updateInputMethod();
#endif
    emitUndoRedoChanged();

    if (!emitCursorPositionChanged() && (alignmentChanged || textChanged))
        q->updateCursorRectangle();

    return true;
}

/*!
    \internal

    An internal function for setting the text of the line control.
*/
void QQuickTextInputPrivate::internalSetText(const QString &txt, int pos, bool edited)
{
    internalDeselect();
    QString oldText = m_text;
    if (m_maskData) {
        m_text = maskString(0, txt, true);
        m_text += clearString(m_text.length(), m_maxLength - m_text.length());
    } else {
        m_text = txt.isEmpty() ? txt : txt.left(m_maxLength);
    }
    m_history.clear();
    m_undoState = 0;
    m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos;
    m_textDirty = (oldText != m_text);

    bool changed = finishChange(-1, true, edited);
#if !QT_CONFIG(accessibility)
    Q_UNUSED(changed)
#else
    Q_Q(QQuickTextInput);
    if (changed && QAccessible::isActive()) {
        if (QObject *acc = QQuickAccessibleAttached::findAccessible(q, QAccessible::EditableText)) {
            QAccessibleTextUpdateEvent ev(acc, 0, oldText, m_text);
            QAccessible::updateAccessibility(&ev);
        }
    }
#endif
}


/*!
    \internal

    Adds the given \a command to the undo history
    of the line control.  Does not apply the command.
*/
void QQuickTextInputPrivate::addCommand(const Command &cmd)
{
    if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator) {
        m_history.resize(m_undoState + 2);
        m_history[m_undoState++] = Command(Separator, m_cursor, 0, m_selstart, m_selend);
    } else {
        m_history.resize(m_undoState + 1);
    }
    m_separator = false;
    m_history[m_undoState++] = cmd;
}

/*!
    \internal

    Inserts the given string \a s into the line
    control.

    Also adds the appropriate commands into the undo history.
    This function does not call finishChange(), and may leave the text
    in an invalid state.
*/
void QQuickTextInputPrivate::internalInsert(const QString &s)
{
    Q_Q(QQuickTextInput);
    if (m_echoMode == QQuickTextInput::Password) {
        if (m_passwordMaskDelay > 0)
            m_passwordEchoTimer.start(m_passwordMaskDelay, q);
    }
    Q_ASSERT(!hasSelectedText());   // insert(), processInputMethodEvent() call removeSelectedText() first.
    if (m_maskData) {
        QString ms = maskString(m_cursor, s);
        for (int i = 0; i < ms.length(); ++i) {
            addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1));
            addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1));
        }
        m_text.replace(m_cursor, ms.length(), ms);
        m_cursor += ms.length();
        m_cursor = nextMaskBlank(m_cursor);
        m_textDirty = true;
    } else {
        int remaining = m_maxLength - m_text.length();
        if (remaining != 0) {
            const QStringRef remainingStr = s.leftRef(remaining);
            m_text.insert(m_cursor, remainingStr);
            for (auto e : remainingStr)
               addCommand(Command(Insert, m_cursor++, e, -1, -1));
            m_textDirty = true;
        }
    }
}

/*!
    \internal

    deletes a single character from the current text.  If \a wasBackspace,
    the character prior to the cursor is removed.  Otherwise the character
    after the cursor is removed.

    Also adds the appropriate commands into the undo history.
    This function does not call finishChange(), and may leave the text
    in an invalid state.
*/
void QQuickTextInputPrivate::internalDelete(bool wasBackspace)
{
    if (m_cursor < m_text.length()) {
        cancelPasswordEchoTimer();
        Q_ASSERT(!hasSelectedText());   // del(), backspace() call removeSelectedText() first.
        addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)),
                   m_cursor, m_text.at(m_cursor), -1, -1));
        if (m_maskData) {
            m_text.replace(m_cursor, 1, clearString(m_cursor, 1));
            addCommand(Command(Insert, m_cursor, m_text.at(m_cursor), -1, -1));
        } else {
            m_text.remove(m_cursor, 1);
        }
        m_textDirty = true;
    }
}

/*!
    \internal

    removes the currently selected text from the line control.

    Also adds the appropriate commands into the undo history.
    This function does not call finishChange(), and may leave the text
    in an invalid state.
*/
void QQuickTextInputPrivate::removeSelectedText()
{
    if (m_selstart < m_selend && m_selend <= m_text.length()) {
        cancelPasswordEchoTimer();
        int i ;
        if (m_selstart <= m_cursor && m_cursor < m_selend) {
            // cursor is within the selection. Split up the commands
            // to be able to restore the correct cursor position
            for (i = m_cursor; i >= m_selstart; --i)
                addCommand (Command(DeleteSelection, i, m_text.at(i), -1, 1));
            for (i = m_selend - 1; i > m_cursor; --i)
                addCommand (Command(DeleteSelection, i - m_cursor + m_selstart - 1, m_text.at(i), -1, -1));
        } else {
            for (i = m_selend-1; i >= m_selstart; --i)
                addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1));
        }
        if (m_maskData) {
            m_text.replace(m_selstart, m_selend - m_selstart,  clearString(m_selstart, m_selend - m_selstart));
            for (int i = 0; i < m_selend - m_selstart; ++i)
                addCommand(Command(Insert, m_selstart + i, m_text.at(m_selstart + i), -1, -1));
        } else {
            m_text.remove(m_selstart, m_selend - m_selstart);
        }
        if (m_cursor > m_selstart)
            m_cursor -= qMin(m_cursor, m_selend) - m_selstart;
        internalDeselect();
        m_textDirty = true;
    }
}

/*!
    \internal

    Adds the current selection to the undo history.

    Returns true if there is a current selection and false otherwise.
*/

bool QQuickTextInputPrivate::separateSelection()
{
    if (hasSelectedText()) {
        separate();
        addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend));
        return true;
    } else {
        return false;
    }
}

/*!
    \internal

    Parses the input mask specified by \a maskFields to generate
    the mask data used to handle input masks.
*/
void QQuickTextInputPrivate::parseInputMask(const QString &maskFields)
{
    int delimiter = maskFields.indexOf(QLatin1Char(';'));
    if (maskFields.isEmpty() || delimiter == 0) {
        if (m_maskData) {
            delete [] m_maskData;
            m_maskData = 0;
            m_maxLength = 32767;
            internalSetText(QString());
        }
        return;
    }

    if (delimiter == -1) {
        m_blank = QLatin1Char(' ');
        m_inputMask = maskFields;
    } else {
        m_inputMask = maskFields.left(delimiter);
        m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' ');
    }

    // calculate m_maxLength / m_maskData length
    m_maxLength = 0;
    QChar c = 0;
    for (int i=0; i<m_inputMask.length(); i++) {
        c = m_inputMask.at(i);
        if (i > 0 && m_inputMask.at(i-1) == QLatin1Char('\\')) {
            m_maxLength++;
            continue;
        }
        if (c != QLatin1Char('\\') && c != QLatin1Char('!') &&
             c != QLatin1Char('<') && c != QLatin1Char('>') &&
             c != QLatin1Char('{') && c != QLatin1Char('}') &&
             c != QLatin1Char('[') && c != QLatin1Char(']'))
            m_maxLength++;
    }

    delete [] m_maskData;
    m_maskData = new MaskInputData[m_maxLength];

    MaskInputData::Casemode m = MaskInputData::NoCaseMode;
    c = 0;
    bool s;
    bool escape = false;
    int index = 0;
    for (int i = 0; i < m_inputMask.length(); i++) {
        c = m_inputMask.at(i);
        if (escape) {
            s = true;
            m_maskData[index].maskChar = c;
            m_maskData[index].separator = s;
            m_maskData[index].caseMode = m;
            index++;
            escape = false;
        } else if (c == QLatin1Char('<')) {
                m = MaskInputData::Lower;
        } else if (c == QLatin1Char('>')) {
            m = MaskInputData::Upper;
        } else if (c == QLatin1Char('!')) {
            m = MaskInputData::NoCaseMode;
        } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) {
            switch (c.unicode()) {
            case 'A':
            case 'a':
            case 'N':
            case 'n':
            case 'X':
            case 'x':
            case '9':
            case '0':
            case 'D':
            case 'd':
            case '#':
            case 'H':
            case 'h':
            case 'B':
            case 'b':
                s = false;
                break;
            case '\\':
                escape = true;
                Q_FALLTHROUGH();
            default:
                s = true;
                break;
            }

            if (!escape) {
                m_maskData[index].maskChar = c;
                m_maskData[index].separator = s;
                m_maskData[index].caseMode = m;
                index++;
            }
        }
    }
    internalSetText(m_text);
}


/*!
    \internal

    checks if the key is valid compared to the inputMask
*/
bool QQuickTextInputPrivate::isValidInput(QChar key, QChar mask) const
{
    switch (mask.unicode()) {
    case 'A':
        if (key.isLetter())
            return true;
        break;
    case 'a':
        if (key.isLetter() || key == m_blank)
            return true;
        break;
    case 'N':
        if (key.isLetterOrNumber())
            return true;
        break;
    case 'n':
        if (key.isLetterOrNumber() || key == m_blank)
            return true;
        break;
    case 'X':
        if (key.isPrint())
            return true;
        break;
    case 'x':
        if (key.isPrint() || key == m_blank)
            return true;
        break;
    case '9':
        if (key.isNumber())
            return true;
        break;
    case '0':
        if (key.isNumber() || key == m_blank)
            return true;
        break;
    case 'D':
        if (key.isNumber() && key.digitValue() > 0)
            return true;
        break;
    case 'd':
        if ((key.isNumber() && key.digitValue() > 0) || key == m_blank)
            return true;
        break;
    case '#':
        if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank)
            return true;
        break;
    case 'B':
        if (key == QLatin1Char('0') || key == QLatin1Char('1'))
            return true;
        break;
    case 'b':
        if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank)
            return true;
        break;
    case 'H':
        if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')))
            return true;
        break;
    case 'h':
        if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank)
            return true;
        break;
    default:
        break;
    }
    return false;
}

/*!
    \internal

    Returns true if the given text \a str is valid for any
    validator or input mask set for the line control.

    Otherwise returns false
*/
QQuickTextInputPrivate::ValidatorState QQuickTextInputPrivate::hasAcceptableInput(const QString &str) const
{
#if QT_CONFIG(validator)
    QString textCopy = str;
    int cursorCopy = m_cursor;
    if (m_validator) {
        QValidator::State state = m_validator->validate(textCopy, cursorCopy);
        if (state != QValidator::Acceptable)
            return ValidatorState(state);
    }
#endif

    if (!m_maskData)
        return AcceptableInput;

    if (str.length() != m_maxLength)
        return InvalidInput;

    for (int i=0; i < m_maxLength; ++i) {
        if (m_maskData[i].separator) {
            if (str.at(i) != m_maskData[i].maskChar)
                return InvalidInput;
        } else {
            if (!isValidInput(str.at(i), m_maskData[i].maskChar))
                return InvalidInput;
        }
    }
    return AcceptableInput;
}

/*!
    \internal

    Applies the inputMask on \a str starting from position \a pos in the mask. \a clear
    specifies from where characters should be gotten when a separator is met in \a str - true means
    that blanks will be used, false that previous input is used.
    Calling this when no inputMask is set is undefined.
*/
QString QQuickTextInputPrivate::maskString(uint pos, const QString &str, bool clear) const
{
    if (pos >= (uint)m_maxLength)
        return QString::fromLatin1("");

    QString fill;
    fill = clear ? clearString(0, m_maxLength) : m_text;

    int strIndex = 0;
    QString s = QString::fromLatin1("");
    int i = pos;
    while (i < m_maxLength) {
        if (strIndex < str.length()) {
            if (m_maskData[i].separator) {
                s += m_maskData[i].maskChar;
                if (str[strIndex] == m_maskData[i].maskChar)
                    strIndex++;
                ++i;
            } else {
                if (isValidInput(str[strIndex], m_maskData[i].maskChar)) {
                    switch (m_maskData[i].caseMode) {
                    case MaskInputData::Upper:
                        s += str[strIndex].toUpper();
                        break;
                    case MaskInputData::Lower:
                        s += str[strIndex].toLower();
                        break;
                    default:
                        s += str[strIndex];
                    }
                    ++i;
                } else {
                    // search for separator first
                    int n = findInMask(i, true, true, str[strIndex]);
                    if (n != -1) {
                        if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[strIndex]))) {
                            s += fill.midRef(i, n-i+1);
                            i = n + 1; // update i to find + 1
                        }
                    } else {
                        // search for valid m_blank if not
                        n = findInMask(i, true, false, str[strIndex]);
                        if (n != -1) {
                            s += fill.midRef(i, n-i);
                            switch (m_maskData[n].caseMode) {
                            case MaskInputData::Upper:
                                s += str[strIndex].toUpper();
                                break;
                            case MaskInputData::Lower:
                                s += str[strIndex].toLower();
                                break;
                            default:
                                s += str[strIndex];
                            }
                            i = n + 1; // updates i to find + 1
                        }
                    }
                }
                ++strIndex;
            }
        } else
            break;
    }

    return s;
}



/*!
    \internal

    Returns a "cleared" string with only separators and blank chars.
    Calling this when no inputMask is set is undefined.
*/
QString QQuickTextInputPrivate::clearString(uint pos, uint len) const
{
    if (pos >= (uint)m_maxLength)
        return QString();

    QString s;
    int end = qMin((uint)m_maxLength, pos + len);
    for (int i = pos; i < end; ++i)
        if (m_maskData[i].separator)
            s += m_maskData[i].maskChar;
        else
            s += m_blank;

    return s;
}

/*!
    \internal

    Strips blank parts of the input in a QQuickTextInputPrivate when an inputMask is set,
    separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1".
*/
QString QQuickTextInputPrivate::stripString(const QString &str) const
{
    if (!m_maskData)
        return str;

    QString s;
    int end = qMin(m_maxLength, str.length());
    for (int i = 0; i < end; ++i) {
        if (m_maskData[i].separator)
            s += m_maskData[i].maskChar;
        else if (str[i] != m_blank)
            s += str[i];
    }

    return s;
}

/*!
    \internal
    searches forward/backward in m_maskData for either a separator or a m_blank
*/
int QQuickTextInputPrivate::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const
{
    if (pos >= m_maxLength || pos < 0)
        return -1;

    int end = forward ? m_maxLength : -1;
    int step = forward ? 1 : -1;
    int i = pos;

    while (i != end) {
        if (findSeparator) {
            if (m_maskData[i].separator && m_maskData[i].maskChar == searchChar)
                return i;
        } else {
            if (!m_maskData[i].separator) {
                if (searchChar.isNull())
                    return i;
                else if (isValidInput(searchChar, m_maskData[i].maskChar))
                    return i;
            }
        }
        i += step;
    }
    return -1;
}

void QQuickTextInputPrivate::internalUndo(int until)
{
    if (!isUndoAvailable())
        return;
    cancelPasswordEchoTimer();
    internalDeselect();
    while (m_undoState && m_undoState > until) {
        Command& cmd = m_history[--m_undoState];
        switch (cmd.type) {
        case Insert:
            m_text.remove(cmd.pos, 1);
            m_cursor = cmd.pos;
            break;
        case SetSelection:
            m_selstart = cmd.selStart;
            m_selend = cmd.selEnd;
            m_cursor = cmd.pos;
            break;
        case Remove:
        case RemoveSelection:
            m_text.insert(cmd.pos, cmd.uc);
            m_cursor = cmd.pos + 1;
            break;
        case Delete:
        case DeleteSelection:
            m_text.insert(cmd.pos, cmd.uc);
            m_cursor = cmd.pos;
            break;
        case Separator:
            continue;
        }
        if (until < 0 && m_undoState) {
            Command& next = m_history[m_undoState-1];
            if (next.type != cmd.type
                    && next.type < RemoveSelection
                    && (cmd.type < RemoveSelection || next.type == Separator)) {
                break;
            }
        }
    }
    separate();
    m_textDirty = true;
}

void QQuickTextInputPrivate::internalRedo()
{
    if (!isRedoAvailable())
        return;
    internalDeselect();
    while (m_undoState < m_history.size()) {
        Command& cmd = m_history[m_undoState++];
        switch (cmd.type) {
        case Insert:
            m_text.insert(cmd.pos, cmd.uc);
            m_cursor = cmd.pos + 1;
            break;
        case SetSelection:
            m_selstart = cmd.selStart;
            m_selend = cmd.selEnd;
            m_cursor = cmd.pos;
            break;
        case Remove:
        case Delete:
        case RemoveSelection:
        case DeleteSelection:
            m_text.remove(cmd.pos, 1);
            m_selstart = cmd.selStart;
            m_selend = cmd.selEnd;
            m_cursor = cmd.pos;
            break;
        case Separator:
            m_selstart = cmd.selStart;
            m_selend = cmd.selEnd;
            m_cursor = cmd.pos;
            break;
        }
        if (m_undoState < m_history.size()) {
            Command& next = m_history[m_undoState];
            if (next.type != cmd.type
                    && cmd.type < RemoveSelection
                    && next.type != Separator
                    && (next.type < RemoveSelection || cmd.type == Separator)) {
                break;
            }
        }
    }
    m_textDirty = true;
}

void QQuickTextInputPrivate::emitUndoRedoChanged()
{
    Q_Q(QQuickTextInput);
    const bool previousUndo = canUndo;
    const bool previousRedo = canRedo;

    canUndo = isUndoAvailable();
    canRedo = isRedoAvailable();

    if (previousUndo != canUndo)
        emit q->canUndoChanged();
    if (previousRedo != canRedo)
        emit q->canRedoChanged();
}

/*!
    \internal

    If the current cursor position differs from the last emitted cursor
    position, emits cursorPositionChanged().
*/
bool QQuickTextInputPrivate::emitCursorPositionChanged()
{
    Q_Q(QQuickTextInput);
    if (m_cursor != m_lastCursorPos) {
        m_lastCursorPos = m_cursor;

        q->updateCursorRectangle();
        emit q->cursorPositionChanged();

        if (!hasSelectedText()) {
            if (lastSelectionStart != m_cursor) {
                lastSelectionStart = m_cursor;
                emit q->selectionStartChanged();
            }
            if (lastSelectionEnd != m_cursor) {
                lastSelectionEnd = m_cursor;
                emit q->selectionEndChanged();
            }
        }

#if QT_CONFIG(accessibility)
        if (QAccessible::isActive()) {
            if (QObject *acc = QQuickAccessibleAttached::findAccessible(q, QAccessible::EditableText)) {
                QAccessibleTextCursorEvent ev(acc, m_cursor);
                QAccessible::updateAccessibility(&ev);
            }
        }
#endif

        return true;
    }
    return false;
}


void QQuickTextInputPrivate::setBlinkingCursorEnabled(bool enable)
{
    if (enable == m_blinkEnabled)
        return;

    m_blinkEnabled = enable;
    updateCursorBlinking();

    if (enable)
        connect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QQuickTextInputPrivate::updateCursorBlinking);
    else
        disconnect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QQuickTextInputPrivate::updateCursorBlinking);
}

void QQuickTextInputPrivate::updateCursorBlinking()
{
    Q_Q(QQuickTextInput);

    if (m_blinkTimer) {
        q->killTimer(m_blinkTimer);
        m_blinkTimer = 0;
    }

    if (m_blinkEnabled && cursorVisible && !cursorItem && !m_readOnly) {
        int flashTime = QGuiApplication::styleHints()->cursorFlashTime();
        if (flashTime >= 2)
            m_blinkTimer = q->startTimer(flashTime / 2);
    }

    m_blinkStatus = 1;
    updateType = UpdatePaintNode;
    q->polish();
    q->update();
}

void QQuickTextInput::timerEvent(QTimerEvent *event)
{
    Q_D(QQuickTextInput);
    if (event->timerId() == d->m_blinkTimer) {
        d->m_blinkStatus = !d->m_blinkStatus;
        d->updateType = QQuickTextInputPrivate::UpdatePaintNode;
        polish();
        update();
    } else if (event->timerId() == d->m_passwordEchoTimer.timerId()) {
        d->m_passwordEchoTimer.stop();
        d->updateDisplayText();
        updateCursorRectangle();
    }
}

void QQuickTextInputPrivate::processKeyEvent(QKeyEvent* event)
{
    Q_Q(QQuickTextInput);

    if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
        if (hasAcceptableInput(m_text) == AcceptableInput || fixup()) {

            QInputMethod *inputMethod = QGuiApplication::inputMethod();
            inputMethod->commit();
            if (!(q->inputMethodHints() & Qt::ImhMultiLine))
                inputMethod->hide();

            if (activeFocus) {
                // If we lost focus after hiding the virtual keyboard, we've already emitted
                // editingFinished from handleFocusEvent. Otherwise we emit it now.
                emit q->editingFinished();
            }

            emit q->accepted();
        }
        event->ignore();
        return;
    }

    if (m_blinkEnabled)
        updateCursorBlinking();

    if (m_echoMode == QQuickTextInput::PasswordEchoOnEdit
        && !m_passwordEchoEditing
        && !m_readOnly
        && !event->text().isEmpty()
        && !(event->modifiers() & Qt::ControlModifier)) {
        // Clear the edit and reset to normal echo mode while editing; the
        // echo mode switches back when the edit loses focus
        // ### resets current content.  dubious code; you can
        // navigate with keys up, down, back, and select(?), but if you press
        // "left" or "right" it clears?
        updatePasswordEchoEditing(true);
        clear();
    }

    bool unknown = false;
#if QT_CONFIG(shortcut)
    bool visual = cursorMoveStyle() == Qt::VisualMoveStyle;
#endif

    if (false) {
    }
#if QT_CONFIG(shortcut)
    else if (event == QKeySequence::Undo) {
        q->undo();
    }
    else if (event == QKeySequence::Redo) {
        q->redo();
    }
    else if (event == QKeySequence::SelectAll) {
        selectAll();
    }
#if QT_CONFIG(clipboard)
    else if (event == QKeySequence::Copy) {
        copy();
    }
    else if (event == QKeySequence::Paste) {
        if (!m_readOnly) {
            QClipboard::Mode mode = QClipboard::Clipboard;
            paste(mode);
        }
    }
    else if (event == QKeySequence::Cut) {
        q->cut();
    }
    else if (event == QKeySequence::DeleteEndOfLine) {
        if (!m_readOnly)
            deleteEndOfLine();
    }
#endif // clipboard
    else if (event == QKeySequence::MoveToStartOfLine || event == QKeySequence::MoveToStartOfBlock) {
        home(0);
    }
    else if (event == QKeySequence::MoveToEndOfLine || event == QKeySequence::MoveToEndOfBlock) {
        end(0);
    }
    else if (event == QKeySequence::SelectStartOfLine || event == QKeySequence::SelectStartOfBlock) {
        home(1);
    }
    else if (event == QKeySequence::SelectEndOfLine || event == QKeySequence::SelectEndOfBlock) {
        end(1);
    }
    else if (event == QKeySequence::MoveToNextChar) {
        if (hasSelectedText()) {
            moveCursor(selectionEnd(), false);
        } else {
            cursorForward(0, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1));
        }
    }
    else if (event == QKeySequence::SelectNextChar) {
        cursorForward(1, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1));
    }
    else if (event == QKeySequence::MoveToPreviousChar) {
        if (hasSelectedText()) {
            moveCursor(selectionStart(), false);
        } else {
            cursorForward(0, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1));
        }
    }
    else if (event == QKeySequence::SelectPreviousChar) {
        cursorForward(1, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1));
    }
    else if (event == QKeySequence::MoveToNextWord) {
        if (m_echoMode == QQuickTextInput::Normal)
            layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0);
        else
            layoutDirection() == Qt::LeftToRight ? end(0) : home(0);
    }
    else if (event == QKeySequence::MoveToPreviousWord) {
        if (m_echoMode == QQuickTextInput::Normal)
            layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0);
        else if (!m_readOnly) {
            layoutDirection() == Qt::LeftToRight ? home(0) : end(0);
        }
    }
    else if (event == QKeySequence::SelectNextWord) {
        if (m_echoMode == QQuickTextInput::Normal)
            layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1);
        else
            layoutDirection() == Qt::LeftToRight ? end(1) : home(1);
    }
    else if (event == QKeySequence::SelectPreviousWord) {
        if (m_echoMode == QQuickTextInput::Normal)
            layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1);
        else
            layoutDirection() == Qt::LeftToRight ? home(1) : end(1);
    }
    else if (event == QKeySequence::Delete) {
        if (!m_readOnly)
            del();
    }
    else if (event == QKeySequence::DeleteEndOfWord) {
        if (!m_readOnly)
            deleteEndOfWord();
    }
    else if (event == QKeySequence::DeleteStartOfWord) {
        if (!m_readOnly)
            deleteStartOfWord();
    } else if (event == QKeySequence::DeleteCompleteLine) {
        if (!m_readOnly) {
            selectAll();
#if QT_CONFIG(clipboard)
            copy();
#endif
            del();
        }
    }
#endif // shortcut
    else {
        bool handled = false;
        if (event->modifiers() & Qt::ControlModifier) {
            switch (event->key()) {
            case Qt::Key_Backspace:
                if (!m_readOnly)
                    deleteStartOfWord();
                break;
            default:
                if (!handled)
                    unknown = true;
            }
        } else { // ### check for *no* modifier
            switch (event->key()) {
            case Qt::Key_Backspace:
                if (!m_readOnly) {
                    backspace();
                }
                break;
            default:
                if (!handled)
                    unknown = true;
            }
        }
    }

    if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) {
        setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft);
        unknown = false;
    }

    if (unknown && !m_readOnly) {
        if (m_inputControl->isAcceptableInput(event)) {
            if (overwriteMode
                // no need to call del() if we have a selection, insert
                // does it already
                && !hasSelectedText()
                && !(m_cursor == q_func()->text().length())) {
                del();
            }

            insert(event->text());
            event->accept();
            return;
        }
    }

    if (unknown)
        event->ignore();
    else
        event->accept();
}

/*!
    \internal

    Deletes the portion of the word before the current cursor position.
*/

void QQuickTextInputPrivate::deleteStartOfWord()
{
    int priorState = m_undoState;
    Command cmd(SetSelection, m_cursor, 0, m_selstart, m_selend);
    separate();
    cursorWordBackward(true);
    addCommand(cmd);
    removeSelectedText();
    finishChange(priorState);
}

/*!
    \internal

    Deletes the portion of the word after the current cursor position.
*/

void QQuickTextInputPrivate::deleteEndOfWord()
{
    int priorState = m_undoState;
    Command cmd(SetSelection, m_cursor, 0, m_selstart, m_selend);
    separate();
    cursorWordForward(true);
    // moveCursor (sometimes) calls separate() so we need to add the command after that so the
    // cursor position and selection are restored in the same undo operation as the remove.
    addCommand(cmd);
    removeSelectedText();
    finishChange(priorState);
}

/*!
    \internal

    Deletes all text from the cursor position to the end of the line.
*/

void QQuickTextInputPrivate::deleteEndOfLine()
{
    int priorState = m_undoState;
    Command cmd(SetSelection, m_cursor, 0, m_selstart, m_selend);
    separate();
    setSelection(m_cursor, end());
    addCommand(cmd);
    removeSelectedText();
    finishChange(priorState);
}

/*!
    \qmlmethod QtQuick::TextInput::ensureVisible(int position)
    \since 5.4

    Scrolls the contents of the text input so that the specified character
    \a position is visible inside the boundaries of the text input.

    \sa autoScroll
*/
void QQuickTextInput::ensureVisible(int position)
{
    Q_D(QQuickTextInput);
    d->ensureVisible(position);
    updateCursorRectangle(false);
}

/*!
    \qmlmethod QtQuick::TextInput::clear()
    \since 5.7

    Clears the contents of the text input
    and resets partial text input from an input method.

    Use this method instead of setting the \l text property to an empty string.

    \sa QInputMethod::reset()
*/
void QQuickTextInput::clear()
{
    Q_D(QQuickTextInput);
    d->resetInputMethod();
    d->clear();
}

/*!
    \since 5.6
    \qmlproperty real QtQuick::TextInput::padding
    \qmlproperty real QtQuick::TextInput::topPadding
    \qmlproperty real QtQuick::TextInput::leftPadding
    \qmlproperty real QtQuick::TextInput::bottomPadding
    \qmlproperty real QtQuick::TextInput::rightPadding

    These properties hold the padding around the content. This space is reserved
    in addition to the contentWidth and contentHeight.
*/
qreal QQuickTextInput::padding() const
{
    Q_D(const QQuickTextInput);
    return d->padding();
}

void QQuickTextInput::setPadding(qreal padding)
{
    Q_D(QQuickTextInput);
    if (qFuzzyCompare(d->padding(), padding))
        return;

    d->extra.value().padding = padding;
    d->updateLayout();
    emit paddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitTopPadding)
        emit topPaddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitLeftPadding)
        emit leftPaddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitRightPadding)
        emit rightPaddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitBottomPadding)
        emit bottomPaddingChanged();
}

void QQuickTextInput::resetPadding()
{
    setPadding(0);
}

qreal QQuickTextInput::topPadding() const
{
    Q_D(const QQuickTextInput);
    if (d->extra.isAllocated() && d->extra->explicitTopPadding)
        return d->extra->topPadding;
    return d->padding();
}

void QQuickTextInput::setTopPadding(qreal padding)
{
    Q_D(QQuickTextInput);
    d->setTopPadding(padding);
}

void QQuickTextInput::resetTopPadding()
{
    Q_D(QQuickTextInput);
    d->setTopPadding(0, true);
}

qreal QQuickTextInput::leftPadding() const
{
    Q_D(const QQuickTextInput);
    if (d->extra.isAllocated() && d->extra->explicitLeftPadding)
        return d->extra->leftPadding;
    return d->padding();
}

void QQuickTextInput::setLeftPadding(qreal padding)
{
    Q_D(QQuickTextInput);
    d->setLeftPadding(padding);
}

void QQuickTextInput::resetLeftPadding()
{
    Q_D(QQuickTextInput);
    d->setLeftPadding(0, true);
}

qreal QQuickTextInput::rightPadding() const
{
    Q_D(const QQuickTextInput);
    if (d->extra.isAllocated() && d->extra->explicitRightPadding)
        return d->extra->rightPadding;
    return d->padding();
}

void QQuickTextInput::setRightPadding(qreal padding)
{
    Q_D(QQuickTextInput);
    d->setRightPadding(padding);
}

void QQuickTextInput::resetRightPadding()
{
    Q_D(QQuickTextInput);
    d->setRightPadding(0, true);
}

qreal QQuickTextInput::bottomPadding() const
{
    Q_D(const QQuickTextInput);
    if (d->extra.isAllocated() && d->extra->explicitBottomPadding)
        return d->extra->bottomPadding;
    return d->padding();
}

void QQuickTextInput::setBottomPadding(qreal padding)
{
    Q_D(QQuickTextInput);
    d->setBottomPadding(padding);
}

void QQuickTextInput::resetBottomPadding()
{
    Q_D(QQuickTextInput);
    d->setBottomPadding(0, true);
}

QT_END_NAMESPACE

#include "moc_qquicktextinput_p.cpp"