DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TextControlState.h"
#include "mozilla/TextInputListener.h"
#include "mozilla/TextInputListener.h"

#include "nsCOMPtr.h"
#include "nsView.h"
#include "nsCaret.h"
#include "nsLayoutCID.h"
#include "nsLayoutCID.h"
#include "nsITextControlFrame.h"
#include "nsContentCreatorFunctions.h"
#include "nsTextControlFrame.h"
#include "nsIControllers.h"
#include "nsIControllerContext.h"
#include "nsIControllerContext.h"
#include "nsAttrValue.h"
#include "nsAttrValueInlines.h"
#include "nsGenericHTMLElement.h"
#include "nsIDOMEventListener.h"
#include "nsIWidget.h"
#include "nsIWidget.h"
#include "nsIDocumentEncoder.h"
#include "nsPIDOMWindow.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/EventListenerManager.h"
#include "nsContentUtils.h"
#include "mozilla/Preferences.h"
#include "nsTextNode.h"
#include "nsIController.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/InputEventOptions.h"
#include "mozilla/PresShell.h"
#include "mozilla/TextEvents.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/HTMLTextAreaElement.h"
#include "mozilla/dom/Text.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_dom.h"
#include "nsFrameSelection.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/Telemetry.h"
#include "mozilla/ShortcutKeys.h"
#include "mozilla/KeyEventHandler.h"
#include "mozilla/KeyEventHandler.h"
#include "mozilla/dom/KeyboardEvent.h"
#include "mozilla/ScrollTypes.h"

namespace mozilla {


using namespace dom;

/*****************************************************************************
 * TextControlElement
 *****************************************************************************/
 *****************************************************************************/

NS_IMPL_CYCLE_COLLECTION_CLASS(TextControlElement)

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(
    TextControlElement, nsGenericHTMLFormElementWithState)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(
    TextControlElement, nsGenericHTMLFormElementWithState)
    TextControlElement, nsGenericHTMLFormElementWithState)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED_0(
    TextControlElement, nsGenericHTMLFormElementWithState)

/*static*/
/*static*/
bool TextControlElement::GetWrapPropertyEnum(
    nsIContent* aContent, TextControlElement::nsHTMLTextWrap& aWrapProp) {
  // soft is the default; "physical" defaults to soft as well because all other
  // browsers treat it that way and there is no real reason to maintain physical
  // and virtual as separate entities if no one else does.  Only hard and off
  // and virtual as separate entities if no one else does.  Only hard and off
  // do anything different.
  aWrapProp = eHTMLTextWrap_Soft;  // the default

  if (!aContent->IsHTMLElement()) {
    return false;
    return false;
  }

  static mozilla::dom::Element::AttrValuesArray strings[] = {
      nsGkAtoms::HARD, nsGkAtoms::OFF, nullptr};
  switch (aContent->AsElement()->FindAttrValueIn(
  switch (aContent->AsElement()->FindAttrValueIn(
      kNameSpaceID_None, nsGkAtoms::wrap, strings, eIgnoreCase)) {
    case 0:
      aWrapProp = eHTMLTextWrap_Hard;
      break;
      break;
    case 1:
      aWrapProp = eHTMLTextWrap_Off;
      break;
  }
  }

  return true;
}

/*static*/
/*static*/
already_AddRefed<TextControlElement>
TextControlElement::GetTextControlElementFromEditingHost(nsIContent* aHost) {
  if (!aHost) {
    return nullptr;
  }
  }

  RefPtr<TextControlElement> parent =
      TextControlElement::FromNodeOrNull(aHost->GetParent());
  return parent.forget();
}
}

using ValueChangeKind = TextControlElement::ValueChangeKind;

inline nsresult SetEditorFlagsIfNecessary(EditorBase& aEditorBase,
                                          uint32_t aFlags) {
                                          uint32_t aFlags) {
  if (aEditorBase.Flags() == aFlags) {
    return NS_OK;
  }
  return aEditorBase.SetFlags(aFlags);
  return aEditorBase.SetFlags(aFlags);
}

/*****************************************************************************
 * mozilla::AutoInputEventSuppresser
 *****************************************************************************/

class MOZ_STACK_CLASS AutoInputEventSuppresser final {
class MOZ_STACK_CLASS AutoInputEventSuppresser final {
 public:
  explicit AutoInputEventSuppresser(TextEditor* aTextEditor)
      : mTextEditor(aTextEditor),
        // To protect against a reentrant call to SetValue, we check whether
        // another SetValue is already happening for this editor.  If it is,
        // another SetValue is already happening for this editor.  If it is,
        // we must wait until we unwind to re-enable oninput events.
        mOuterTransaction(aTextEditor->IsSuppressingDispatchingInputEvent()) {
    MOZ_ASSERT(mTextEditor);
    mTextEditor->SuppressDispatchingInputEvent(true);
  }
  }
  ~AutoInputEventSuppresser() {
    mTextEditor->SuppressDispatchingInputEvent(mOuterTransaction);
  }

 private:
 private:
  RefPtr<TextEditor> mTextEditor;
  bool mOuterTransaction;
};

/*****************************************************************************
 * mozilla::RestoreSelectionState
 *****************************************************************************/


class RestoreSelectionState : public Runnable {
 public:
  RestoreSelectionState(TextControlState* aState, nsTextControlFrame* aFrame)
      : Runnable("RestoreSelectionState"),
      : Runnable("RestoreSelectionState"),
        mFrame(aFrame),
        mTextControlState(aState) {}

  MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Run() override {
    if (!mTextControlState) {
    if (!mTextControlState) {
      return NS_OK;
    }

    AutoHideSelectionChanges hideSelectionChanges(
        mFrame->GetConstFrameSelection());
        mFrame->GetConstFrameSelection());

    if (mFrame) {
      // SetSelectionRange leads to
      // Selection::AddRangeAndSelectFramesAndNotifyListeners which flushes
      // Layout - need to block script to avoid nested PrepareEditor calls (bug
      // Layout - need to block script to avoid nested PrepareEditor calls (bug
      // 642800).
      nsAutoScriptBlocker scriptBlocker;
      TextControlState::SelectionProperties& properties =
          mTextControlState->GetSelectionProperties();
      if (properties.IsDirty()) {
      if (properties.IsDirty()) {
        mFrame->SetSelectionRange(properties.GetStart(), properties.GetEnd(),
                                  properties.GetDirection());
      }
    }

    if (mTextControlState) {
    if (mTextControlState) {
      mTextControlState->FinishedRestoringSelection();
    }
    return NS_OK;
  }


  // Let the text editor tell us we're no longer relevant - avoids use of
  // AutoWeakFrame
  void Revoke() {
    mFrame = nullptr;
    mFrame = nullptr;
    mTextControlState = nullptr;
  }

 private:
  nsTextControlFrame* mFrame;
  nsTextControlFrame* mFrame;
  TextControlState* mTextControlState;
};

/*****************************************************************************
 * mozilla::AutoRestoreEditorState
 * mozilla::AutoRestoreEditorState
 *****************************************************************************/

class MOZ_RAII AutoRestoreEditorState final {
 public:
  explicit AutoRestoreEditorState(
      TextEditor* aTextEditor MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
      : mTextEditor(aTextEditor),
      : mTextEditor(aTextEditor),
        mSavedFlags(mTextEditor->Flags()),
        mSavedMaxLength(mTextEditor->MaxTextLength()) {
    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
    MOZ_ASSERT(mTextEditor);


    // EditorBase::SetFlags() is a virtual method.  Even though it does nothing
    // if new flags and current flags are same, the calling cost causes
    // appearing the method in profile.  So, this class should check if it's
    // necessary to call.
    uint32_t flags = mSavedFlags;
    uint32_t flags = mSavedFlags;
    flags &= ~(nsIEditor::eEditorReadonlyMask);
    flags |= nsIEditor::eEditorDontEchoPassword;
    if (mSavedFlags != flags) {
      mTextEditor->SetFlags(flags);
    }
    mTextEditor->SetMaxTextLength(-1);
  }

  ~AutoRestoreEditorState() {
  ~AutoRestoreEditorState() {
    mTextEditor->SetMaxTextLength(mSavedMaxLength);
    SetEditorFlagsIfNecessary(*mTextEditor, mSavedFlags);
  }

 private:
 private:
  TextEditor* mTextEditor;
  uint32_t mSavedFlags;
  uint32_t mSavedFlags;
  int32_t mSavedMaxLength;
  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};

/*****************************************************************************
/*****************************************************************************
 * mozilla::AutoDisableUndo
 *****************************************************************************/

class MOZ_RAII AutoDisableUndo final {
 public:
 public:
  explicit AutoDisableUndo(
      TextEditor* aTextEditor MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
      : mTextEditor(aTextEditor), mNumberOfMaximumTransactions(0) {
    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
    MOZ_ASSERT(mTextEditor);

    mNumberOfMaximumTransactions =
    mNumberOfMaximumTransactions =
        mTextEditor ? mTextEditor->NumberOfMaximumTransactions() : 0;
    DebugOnly<bool> disabledUndoRedo = mTextEditor->DisableUndoRedo();
    NS_WARNING_ASSERTION(disabledUndoRedo,
                         "Failed to disable undo/redo transactions");
  }
  }

  ~AutoDisableUndo() {
    // Don't change enable/disable of undo/redo if it's enabled after
    // it's disabled by the constructor because we shouldn't change
    // the maximum undo/redo count to the old value.
    if (mTextEditor->IsUndoRedoEnabled()) {
    if (mTextEditor->IsUndoRedoEnabled()) {
      return;
    }
    // If undo/redo was enabled, mNumberOfMaximumTransactions is -1 or lager
    // than 0.  Only when it's 0, it was disabled.
    if (mNumberOfMaximumTransactions) {
    if (mNumberOfMaximumTransactions) {
      DebugOnly<bool> enabledUndoRedo =
          mTextEditor->EnableUndoRedo(mNumberOfMaximumTransactions);
      NS_WARNING_ASSERTION(enabledUndoRedo,
                           "Failed to enable undo/redo transactions");
    } else {
      DebugOnly<bool> disabledUndoRedo = mTextEditor->DisableUndoRedo();
      NS_WARNING_ASSERTION(disabledUndoRedo,
      NS_WARNING_ASSERTION(disabledUndoRedo,
                           "Failed to disable undo/redo transactions");
    }
  }

 private:
 private:
  TextEditor* mTextEditor;
  int32_t mNumberOfMaximumTransactions;
  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};


static bool SuppressEventHandlers(nsPresContext* aPresContext) {
  bool suppressHandlers = false;

  if (aPresContext) {
  if (aPresContext) {
    // Right now we only suppress event handlers and controller manipulation
    // when in a print preview or print context!

    // In the current implementation, we only paginate when
    // printing or in print preview.
    // printing or in print preview.

    suppressHandlers = aPresContext->IsPaginated();
  }

  return suppressHandlers;
  return suppressHandlers;
}

/*****************************************************************************
 * mozilla::TextInputSelectionController
 *****************************************************************************/
 *****************************************************************************/

class TextInputSelectionController final : public nsSupportsWeakReference,
                                           public nsISelectionController {
  ~TextInputSelectionController() = default;


 public:
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(TextInputSelectionController,
  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(TextInputSelectionController,
                                           nsISelectionController)


  TextInputSelectionController(PresShell* aPresShell, nsIContent* aLimiter);

  void SetScrollableFrame(nsIScrollableFrame* aScrollableFrame);
  nsFrameSelection* GetConstFrameSelection() { return mFrameSelection; }
  // Will return null if !mFrameSelection.
  // Will return null if !mFrameSelection.
  Selection* GetSelection(SelectionType aSelectionType);

  // NSISELECTIONCONTROLLER INTERFACES
  NS_IMETHOD SetDisplaySelection(int16_t toggle) override;
  NS_IMETHOD GetDisplaySelection(int16_t* _retval) override;
  NS_IMETHOD GetDisplaySelection(int16_t* _retval) override;
  NS_IMETHOD SetSelectionFlags(int16_t aInEnable) override;
  NS_IMETHOD GetSelectionFlags(int16_t* aOutEnable) override;
  NS_IMETHOD GetSelectionFromScript(RawSelectionType aRawSelectionType,
                                    Selection** aSelection) override;
  Selection* GetSelection(RawSelectionType aRawSelectionType) override;
  Selection* GetSelection(RawSelectionType aRawSelectionType) override;
  NS_IMETHOD ScrollSelectionIntoView(RawSelectionType aRawSelectionType,
                                     int16_t aRegion, int16_t aFlags) override;
  NS_IMETHOD RepaintSelection(RawSelectionType aRawSelectionType) override;
  nsresult RepaintSelection(nsPresContext* aPresContext,
                            SelectionType aSelectionType);
                            SelectionType aSelectionType);
  NS_IMETHOD SetCaretEnabled(bool enabled) override;
  NS_IMETHOD SetCaretReadOnly(bool aReadOnly) override;
  NS_IMETHOD GetCaretEnabled(bool* _retval) override;
  NS_IMETHOD GetCaretVisible(bool* _retval) override;
  NS_IMETHOD SetCaretVisibilityDuringSelection(bool aVisibility) override;
  NS_IMETHOD PhysicalMove(int16_t aDirection, int16_t aAmount,
                          bool aExtend) override;
                          bool aExtend) override;
  NS_IMETHOD CharacterMove(bool aForward, bool aExtend) override;
  NS_IMETHOD WordMove(bool aForward, bool aExtend) override;
  NS_IMETHOD LineMove(bool aForward, bool aExtend) override;
  NS_IMETHOD IntraLineMove(bool aForward, bool aExtend) override;
  MOZ_CAN_RUN_SCRIPT
  MOZ_CAN_RUN_SCRIPT
  NS_IMETHOD PageMove(bool aForward, bool aExtend) override;
  NS_IMETHOD CompleteScroll(bool aForward) override;
  NS_IMETHOD CompleteMove(bool aForward, bool aExtend) override;
  NS_IMETHOD ScrollPage(bool aForward) override;
  NS_IMETHOD ScrollLine(bool aForward) override;
  NS_IMETHOD ScrollLine(bool aForward) override;
  NS_IMETHOD ScrollCharacter(bool aRight) override;
  NS_IMETHOD SelectAll(void) override;
  NS_IMETHOD CheckVisibility(nsINode* node, int16_t startOffset,
                             int16_t EndOffset, bool* _retval) override;
                             int16_t EndOffset, bool* _retval) override;
  virtual nsresult CheckVisibilityContent(nsIContent* aNode,
                                          int16_t aStartOffset,
                                          int16_t aEndOffset,
                                          bool* aRetval) override;
  void SelectionWillTakeFocus() override;
  void SelectionWillLoseFocus() override;


 private:
  RefPtr<nsFrameSelection> mFrameSelection;
  nsIScrollableFrame* mScrollFrame;
  nsWeakPtr mPresShellWeak;
};
};

NS_IMPL_CYCLE_COLLECTING_ADDREF(TextInputSelectionController)
NS_IMPL_CYCLE_COLLECTING_RELEASE(TextInputSelectionController)
NS_INTERFACE_TABLE_HEAD(TextInputSelectionController)
  NS_INTERFACE_TABLE(TextInputSelectionController, nsISelectionController,
  NS_INTERFACE_TABLE(TextInputSelectionController, nsISelectionController,
                     nsISelectionDisplay, nsISupportsWeakReference)
  NS_INTERFACE_TABLE_TO_MAP_SEGUE_CYCLE_COLLECTION(TextInputSelectionController)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTION_WEAK(TextInputSelectionController, mFrameSelection)
NS_IMPL_CYCLE_COLLECTION_WEAK(TextInputSelectionController, mFrameSelection)

TextInputSelectionController::TextInputSelectionController(
    PresShell* aPresShell, nsIContent* aLimiter)
    : mScrollFrame(nullptr) {
    : mScrollFrame(nullptr) {
  if (aPresShell) {
    bool accessibleCaretEnabled =
        PresShell::AccessibleCaretEnabled(aLimiter->OwnerDoc()->GetDocShell());
    mFrameSelection =
    mFrameSelection =
        new nsFrameSelection(aPresShell, aLimiter, accessibleCaretEnabled);
    mPresShellWeak = do_GetWeakReference(aPresShell);
  }
}


void TextInputSelectionController::SetScrollableFrame(
    nsIScrollableFrame* aScrollableFrame) {
  mScrollFrame = aScrollableFrame;
  if (!mScrollFrame && mFrameSelection) {
    mFrameSelection->DisconnectFromPresShell();
    mFrameSelection->DisconnectFromPresShell();
    mFrameSelection = nullptr;
  }
}

Selection* TextInputSelectionController::GetSelection(
Selection* TextInputSelectionController::GetSelection(
    SelectionType aSelectionType) {
  if (!mFrameSelection) {
    return nullptr;
  }


  return mFrameSelection->GetSelection(aSelectionType);
}

NS_IMETHODIMP
TextInputSelectionController::SetDisplaySelection(int16_t aToggle) {
TextInputSelectionController::SetDisplaySelection(int16_t aToggle) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }
  mFrameSelection->SetDisplaySelection(aToggle);
  return NS_OK;
}

NS_IMETHODIMP
TextInputSelectionController::GetDisplaySelection(int16_t* aToggle) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
    return NS_ERROR_NULL_POINTER;
  }
  *aToggle = mFrameSelection->GetDisplaySelection();
  return NS_OK;
}


NS_IMETHODIMP
TextInputSelectionController::SetSelectionFlags(int16_t aToggle) {
  return NS_OK;  // stub this out. not used in input
}


NS_IMETHODIMP
TextInputSelectionController::GetSelectionFlags(int16_t* aOutEnable) {
  *aOutEnable = nsISelectionDisplay::DISPLAY_TEXT;
  return NS_OK;
}
}

NS_IMETHODIMP
TextInputSelectionController::GetSelectionFromScript(
    RawSelectionType aRawSelectionType, Selection** aSelection) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }


  *aSelection =
      mFrameSelection->GetSelection(ToSelectionType(aRawSelectionType));

  // GetSelection() fails only when aRawSelectionType is invalid value.
  if (!(*aSelection)) {
  if (!(*aSelection)) {
    return NS_ERROR_INVALID_ARG;
  }

  NS_ADDREF(*aSelection);
  return NS_OK;
  return NS_OK;
}

Selection* TextInputSelectionController::GetSelection(
    RawSelectionType aRawSelectionType) {
  return GetSelection(ToSelectionType(aRawSelectionType));
  return GetSelection(ToSelectionType(aRawSelectionType));
}

NS_IMETHODIMP
TextInputSelectionController::ScrollSelectionIntoView(
    RawSelectionType aRawSelectionType, int16_t aRegion, int16_t aFlags) {
    RawSelectionType aRawSelectionType, int16_t aRegion, int16_t aFlags) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->ScrollSelectionIntoView(
      ToSelectionType(aRawSelectionType), aRegion, aFlags);
}


NS_IMETHODIMP
TextInputSelectionController::RepaintSelection(
    RawSelectionType aRawSelectionType) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
    return NS_ERROR_NULL_POINTER;
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->RepaintSelection(ToSelectionType(aRawSelectionType));
}


nsresult TextInputSelectionController::RepaintSelection(
    nsPresContext* aPresContext, SelectionType aSelectionType) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->RepaintSelection(aSelectionType);
}

NS_IMETHODIMP
NS_IMETHODIMP
TextInputSelectionController::SetCaretEnabled(bool enabled) {
  if (!mPresShellWeak) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  }
  RefPtr<PresShell> presShell = do_QueryReferent(mPresShellWeak);
  if (!presShell) {
    return NS_ERROR_FAILURE;
    return NS_ERROR_FAILURE;
  }

  // tell the pres shell to enable the caret, rather than settings its
  // visibility directly. this way the presShell's idea of caret visibility is
  // maintained.
  // maintained.
  presShell->SetCaretEnabled(enabled);

  return NS_OK;
}


NS_IMETHODIMP
TextInputSelectionController::SetCaretReadOnly(bool aReadOnly) {
  if (!mPresShellWeak) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  }
  nsresult rv;
  RefPtr<PresShell> presShell = do_QueryReferent(mPresShellWeak, &rv);
  if (!presShell) {
    return NS_ERROR_FAILURE;
    return NS_ERROR_FAILURE;
  }
  RefPtr<nsCaret> caret = presShell->GetCaret();
  if (!caret) {
    return NS_ERROR_FAILURE;
  }
  }
  Selection* selection = mFrameSelection->GetSelection(SelectionType::eNormal);
  Selection* selection = mFrameSelection->GetSelection(SelectionType::eNormal);
  if (selection) {
    caret->SetCaretReadOnly(aReadOnly);
  }
  return NS_OK;
}
}

NS_IMETHODIMP
TextInputSelectionController::GetCaretEnabled(bool* _retval) {
  return GetCaretVisible(_retval);
}
}

NS_IMETHODIMP
TextInputSelectionController::GetCaretVisible(bool* _retval) {
  if (!mPresShellWeak) {
    return NS_ERROR_NOT_INITIALIZED;
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsresult rv;
  RefPtr<PresShell> presShell = do_QueryReferent(mPresShellWeak, &rv);
  if (!presShell) {
    return NS_ERROR_FAILURE;
  }
  RefPtr<nsCaret> caret = presShell->GetCaret();
  RefPtr<nsCaret> caret = presShell->GetCaret();
  if (!caret) {
    return NS_ERROR_FAILURE;
  }
  *_retval = caret->IsVisible();
  return NS_OK;
  return NS_OK;
}

NS_IMETHODIMP
TextInputSelectionController::SetCaretVisibilityDuringSelection(
TextInputSelectionController::SetCaretVisibilityDuringSelection(
    bool aVisibility) {
  if (!mPresShellWeak) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsresult rv;
  nsresult rv;
  RefPtr<PresShell> presShell = do_QueryReferent(mPresShellWeak, &rv);
  if (!presShell) {
    return NS_ERROR_FAILURE;
  }
  RefPtr<nsCaret> caret = presShell->GetCaret();
  RefPtr<nsCaret> caret = presShell->GetCaret();
  if (!caret) {
    return NS_ERROR_FAILURE;
  }
  Selection* selection = mFrameSelection->GetSelection(SelectionType::eNormal);
  if (selection) {
  if (selection) {
    caret->SetVisibilityDuringSelection(aVisibility);
  }
  return NS_OK;
}


NS_IMETHODIMP
TextInputSelectionController::PhysicalMove(int16_t aDirection, int16_t aAmount,
                                           bool aExtend) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->PhysicalMove(aDirection, aAmount, aExtend);
  return frameSelection->PhysicalMove(aDirection, aAmount, aExtend);
}

NS_IMETHODIMP
TextInputSelectionController::CharacterMove(bool aForward, bool aExtend) {
  if (!mFrameSelection) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->CharacterMove(aForward, aExtend);
}
}

NS_IMETHODIMP
TextInputSelectionController::WordMove(bool aForward, bool aExtend) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
    return NS_ERROR_NULL_POINTER;
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->WordMove(aForward, aExtend);
}


NS_IMETHODIMP
TextInputSelectionController::LineMove(bool aForward, bool aExtend) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  nsresult result = frameSelection->LineMove(aForward, aExtend);
  nsresult result = frameSelection->LineMove(aForward, aExtend);
  if (NS_FAILED(result)) {
    result = CompleteMove(aForward, aExtend);
  }
  return result;
}
}

NS_IMETHODIMP
TextInputSelectionController::IntraLineMove(bool aForward, bool aExtend) {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
    return NS_ERROR_NULL_POINTER;
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->IntraLineMove(aForward, aExtend);
}


NS_IMETHODIMP
TextInputSelectionController::PageMove(bool aForward, bool aExtend) {
  // expected behavior for PageMove is to scroll AND move the caret
  // and to remain relative position of the caret in view. see Bug 4302.
  if (mScrollFrame) {
  if (mScrollFrame) {
    RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
    nsIFrame* scrollFrame = do_QueryFrame(mScrollFrame);
    // We won't scroll parent scrollable element of mScrollFrame.  Therefore,
    // this may be handled when mScrollFrame is completely outside of the view.
    // In such case, user may be confused since they might have wanted to
    // In such case, user may be confused since they might have wanted to
    // scroll a parent scrollable element.  For making clearer which element
    // handles PageDown/PageUp, we should move selection into view even if
    // selection is not changed.
    return frameSelection->PageMove(aForward, aExtend, scrollFrame,
                                    nsFrameSelection::SelectionIntoView::Yes);
                                    nsFrameSelection::SelectionIntoView::Yes);
  }
  // Similarly, if there is no scrollable frame, we should move the editor
  // frame into the view for making it clearer which element handles
  // PageDown/PageUp.
  return ScrollSelectionIntoView(
  return ScrollSelectionIntoView(
      nsISelectionController::SELECTION_NORMAL,
      nsISelectionController::SELECTION_FOCUS_REGION,
      nsISelectionController::SCROLL_SYNCHRONOUS |
          nsISelectionController::SCROLL_FOR_CARET_MOVE);
}
}

NS_IMETHODIMP
TextInputSelectionController::CompleteScroll(bool aForward) {
  if (!mScrollFrame) {
  if (!mScrollFrame) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  mScrollFrame->ScrollBy(nsIntPoint(0, aForward ? 1 : -1), ScrollUnit::WHOLE,
                         ScrollMode::Instant);
  return NS_OK;
}


NS_IMETHODIMP
TextInputSelectionController::CompleteMove(bool aForward, bool aExtend) {
  if (NS_WARN_IF(!mFrameSelection)) {
    return NS_ERROR_NULL_POINTER;
  }
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;

  // grab the parent / root DIV for this text widget
  nsIContent* parentDIV = frameSelection->GetLimiter();
  if (!parentDIV) {
  if (!parentDIV) {
    return NS_ERROR_UNEXPECTED;
  }

  // make the caret be either at the very beginning (0) or the very end
  // make the caret be either at the very beginning (0) or the very end
  int32_t offset = 0;
  CaretAssociationHint hint = CARET_ASSOCIATE_BEFORE;
  if (aForward) {
    offset = parentDIV->GetChildCount();


    // Prevent the caret from being placed after the last
    // BR node in the content tree!

    if (offset > 0) {
      nsIContent* child = parentDIV->GetLastChild();

      if (child->IsHTMLElement(nsGkAtoms::br)) {
      if (child->IsHTMLElement(nsGkAtoms::br)) {
        --offset;
        --offset;
        hint = CARET_ASSOCIATE_AFTER;  // for Bug 106855
      }
    }
    }
  }

  const nsFrameSelection::FocusMode focusMode =
      aExtend ? nsFrameSelection::FocusMode::kExtendSelection
              : nsFrameSelection::FocusMode::kCollapseToNewPoint;
              : nsFrameSelection::FocusMode::kCollapseToNewPoint;
  frameSelection->HandleClick(parentDIV, offset, offset, focusMode, hint);

  // if we got this far, attempt to scroll no matter what the above result is
  return CompleteScroll(aForward);
}
}

NS_IMETHODIMP
TextInputSelectionController::ScrollPage(bool aForward) {
  if (!mScrollFrame) {
    return NS_ERROR_NOT_INITIALIZED;
    return NS_ERROR_NOT_INITIALIZED;
  }
  mScrollFrame->ScrollBy(nsIntPoint(0, aForward ? 1 : -1), ScrollUnit::PAGES,
                         ScrollMode::Smooth);
  return NS_OK;
}
}

NS_IMETHODIMP
NS_IMETHODIMP
TextInputSelectionController::ScrollLine(bool aForward) {
  if (!mScrollFrame) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  mScrollFrame->ScrollBy(nsIntPoint(0, aForward ? 1 : -1), ScrollUnit::LINES,
  mScrollFrame->ScrollBy(nsIntPoint(0, aForward ? 1 : -1), ScrollUnit::LINES,
                         ScrollMode::Smooth);
  return NS_OK;
}

NS_IMETHODIMP
NS_IMETHODIMP
TextInputSelectionController::ScrollCharacter(bool aRight) {
  if (!mScrollFrame) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  }
  mScrollFrame->ScrollBy(nsIntPoint(aRight ? 1 : -1, 0), ScrollUnit::LINES,
                         ScrollMode::Smooth);
  return NS_OK;
}


NS_IMETHODIMP
TextInputSelectionController::SelectAll() {
  if (!mFrameSelection) {
    return NS_ERROR_NULL_POINTER;
  }
  }
  RefPtr<nsFrameSelection> frameSelection = mFrameSelection;
  return frameSelection->SelectAll();
}

void TextInputSelectionController::SelectionWillTakeFocus() {
void TextInputSelectionController::SelectionWillTakeFocus() {
  if (mFrameSelection) {
    if (PresShell* shell = mFrameSelection->GetPresShell()) {
      shell->FrameSelectionWillTakeFocus(*mFrameSelection);
    }
  }
  }
}

void TextInputSelectionController::SelectionWillLoseFocus() {
  if (mFrameSelection) {
    if (PresShell* shell = mFrameSelection->GetPresShell()) {
    if (PresShell* shell = mFrameSelection->GetPresShell()) {
      shell->FrameSelectionWillLoseFocus(*mFrameSelection);
    }
  }
}


NS_IMETHODIMP
TextInputSelectionController::CheckVisibility(nsINode* node,
                                              int16_t startOffset,
                                              int16_t EndOffset,
                                              bool* _retval) {
  if (!mPresShellWeak) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  nsresult rv;
  nsresult rv;
  nsCOMPtr<nsISelectionController> presShell =
      do_QueryReferent(mPresShellWeak, &rv);
  if (!presShell) {
    return NS_ERROR_FAILURE;
  }
  }
  return presShell->CheckVisibility(node, startOffset, EndOffset, _retval);
}

nsresult TextInputSelectionController::CheckVisibilityContent(
    nsIContent* aNode, int16_t aStartOffset, int16_t aEndOffset,
    bool* aRetval) {
  if (!mPresShellWeak) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  }
  nsCOMPtr<nsISelectionController> presShell = do_QueryReferent(mPresShellWeak);
  if (NS_WARN_IF(!presShell)) {
    return NS_ERROR_FAILURE;
  }
  return presShell->CheckVisibilityContent(aNode, aStartOffset, aEndOffset,
  return presShell->CheckVisibilityContent(aNode, aStartOffset, aEndOffset,
                                           aRetval);
}

/*****************************************************************************
 * mozilla::TextInputListener
 * mozilla::TextInputListener
 *****************************************************************************/

TextInputListener::TextInputListener(TextControlElement* aTxtCtrlElement)
    : mFrame(nullptr),
      mTxtCtrlElement(aTxtCtrlElement),
      mTextControlState(aTxtCtrlElement ? aTxtCtrlElement->GetTextControlState()
      mTextControlState(aTxtCtrlElement ? aTxtCtrlElement->GetTextControlState()
                                        : nullptr),
      mSelectionWasCollapsed(true),
      mHadUndoItems(false),
      mHadRedoItems(false),
      mSettingValue(false),
      mSettingValue(false),
      mSetValueChanged(true),
      mListeningToSelectionChange(false) {}

NS_IMPL_CYCLE_COLLECTING_ADDREF(TextInputListener)
NS_IMPL_CYCLE_COLLECTING_RELEASE(TextInputListener)
NS_IMPL_CYCLE_COLLECTING_RELEASE(TextInputListener)

NS_INTERFACE_MAP_BEGIN(TextInputListener)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
  NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMEventListener)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMEventListener)
  NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(TextInputListener)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTION_CLASS(TextInputListener)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(TextInputListener)
  NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(TextInputListener)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

void TextInputListener::OnSelectionChange(Selection& aSelection,
                                          int16_t aReason) {
  if (!mListeningToSelectionChange) {
  if (!mListeningToSelectionChange) {
    return;
  }

  AutoWeakFrame weakFrame = mFrame;


  // Fire the select event
  // The specs don't exactly say when we should fire the select event.
  // IE: Whenever you add/remove a character to/from the selection. Also
  //     each time for select all. Also if you get to the end of the text
  //     field you will get new event for each keypress or a continuous
  //     field you will get new event for each keypress or a continuous
  //     stream of events if you use the mouse. IE will fire select event
  //     when the selection collapses to nothing if you are holding down
  //     the shift or mouse button.
  // Mozilla: If we have non-empty selection we will fire a new event for each
  //          keypress (or mouseup) if the selection changed. Mozilla will also
  //          keypress (or mouseup) if the selection changed. Mozilla will also
  //          create the event each time select all is called, even if
  //          everything was previously selected, becase technically select all
  //          will first collapse and then extend. Mozilla will never create an
  //          event if the selection collapses to nothing.
  //          event if the selection collapses to nothing.
  bool collapsed = aSelection.IsCollapsed();
  if (!collapsed && (aReason & (nsISelectionListener::MOUSEUP_REASON |
                                nsISelectionListener::KEYPRESS_REASON |
                                nsISelectionListener::SELECTALL_REASON))) {
    if (nsCOMPtr<nsIContent> content = mFrame->GetContent()) {
    if (nsCOMPtr<nsIContent> content = mFrame->GetContent()) {
      if (nsCOMPtr<Document> doc = content->GetComposedDoc()) {
        if (RefPtr<PresShell> presShell = doc->GetPresShell()) {
          nsEventStatus status = nsEventStatus_eIgnore;
          WidgetEvent event(true, eFormSelect);


          presShell->HandleEventWithTarget(&event, mFrame, content, &status);
        }
      }
    }
  }
  }

  // if the collapsed state did not change, don't fire notifications
  if (collapsed == mSelectionWasCollapsed) {
    return;
  }
  }

  mSelectionWasCollapsed = collapsed;

  if (!weakFrame.IsAlive() || !mFrame ||
      !nsContentUtils::IsFocusedContent(mFrame->GetContent())) {
    return;
  }
  }

  UpdateTextInputCommands(NS_LITERAL_STRING("select"), &aSelection, aReason);
}
}

MOZ_CAN_RUN_SCRIPT
static void DoCommandCallback(Command aCommand, void* aData) {
  nsTextControlFrame* frame = static_cast<nsTextControlFrame*>(aData);
  nsIContent* content = frame->GetContent();
  nsIContent* content = frame->GetContent();

  nsCOMPtr<nsIControllers> controllers;
  HTMLInputElement* input = HTMLInputElement::FromNode(content);
  if (input) {
  if (input) {
    input->GetControllers(getter_AddRefs(controllers));
  } else {
    HTMLTextAreaElement* textArea = HTMLTextAreaElement::FromNode(content);

    if (textArea) {
    if (textArea) {
      textArea->GetControllers(getter_AddRefs(controllers));
    }
  }

  if (!controllers) {
  if (!controllers) {
    NS_WARNING("Could not get controllers");
    return;
  }

  const char* commandStr = WidgetKeyboardEvent::GetCommandStr(aCommand);
  const char* commandStr = WidgetKeyboardEvent::GetCommandStr(aCommand);

  nsCOMPtr<nsIController> controller;
  controllers->GetControllerForCommand(commandStr, getter_AddRefs(controller));
  if (!controller) {
  if (!controller) {
    return;
  }

  bool commandEnabled;
  if (NS_WARN_IF(NS_FAILED(
  if (NS_WARN_IF(NS_FAILED(
          controller->IsCommandEnabled(commandStr, &commandEnabled)))) {
    return;
  }
  }
  if (commandEnabled) {
  if (commandEnabled) {
    controller->DoCommand(commandStr);
  }
}
}

NS_IMETHODIMP
TextInputListener::HandleEvent(Event* aEvent) {
  if (aEvent->DefaultPrevented()) {
    return NS_OK;
    return NS_OK;
  }

  if (!aEvent->IsTrusted()) {
    return NS_OK;
  }
  }

  RefPtr<KeyboardEvent> keyEvent = aEvent->AsKeyboardEvent();
  if (!keyEvent) {
    return NS_ERROR_UNEXPECTED;
  }

  WidgetKeyboardEvent* widgetKeyEvent =
      aEvent->WidgetEventPtr()->AsKeyboardEvent();
      aEvent->WidgetEventPtr()->AsKeyboardEvent();
  if (!widgetKeyEvent) {
    return NS_ERROR_UNEXPECTED;
  }

  {
  {
    auto* input = HTMLInputElement::FromNode(mTxtCtrlElement);
    if (input && input->StepsInputValue(*widgetKeyEvent)) {
      // As an special case, don't handle key events that would step the value
      // of our <input type=number>.
      return NS_OK;
      return NS_OK;
    }
  }

  KeyEventHandler* keyHandlers = ShortcutKeys::GetHandlers(
      mTxtCtrlElement->IsTextArea() ? HandlerType::eTextArea
      mTxtCtrlElement->IsTextArea() ? HandlerType::eTextArea
                                    : HandlerType::eInput);

  RefPtr<nsAtom> eventTypeAtom =
      ShortcutKeys::ConvertEventToDOMEventType(widgetKeyEvent);
  for (KeyEventHandler* handler = keyHandlers; handler;
  for (KeyEventHandler* handler = keyHandlers; handler;
       handler = handler->GetNextHandler()) {
    if (!handler->EventTypeEquals(eventTypeAtom)) {
      continue;
    }
    }

    if (!handler->KeyEventMatched(keyEvent, 0, IgnoreModifierState())) {
      continue;
    }
    }

    // XXX Do we execute only one handler even if the handler neither stops
    //     propagation nor prevents default of the event?
    RefPtr<TextControlElement> textControlElement(mTxtCtrlElement);
    nsresult rv = handler->ExecuteHandler(textControlElement, aEvent);
    nsresult rv = handler->ExecuteHandler(textControlElement, aEvent);
    if (NS_SUCCEEDED(rv)) {
      return rv;
    }
  }


  if (widgetKeyEvent->mMessage != eKeyPress) {
    return NS_OK;
  }

  nsIWidget::NativeKeyBindingsType nativeKeyBindingsType =
  nsIWidget::NativeKeyBindingsType nativeKeyBindingsType =
      mTxtCtrlElement->IsTextArea()
          ? nsIWidget::NativeKeyBindingsForMultiLineEditor
          : nsIWidget::NativeKeyBindingsForSingleLineEditor;

  nsIWidget* widget = widgetKeyEvent->mWidget;
  // If the event is created by chrome script, the widget is nullptr.
  if (!widget) {
    widget = mFrame->GetNearestWidget();
    if (NS_WARN_IF(!widget)) {
      return NS_OK;
      return NS_OK;
    }
  }

  // WidgetKeyboardEvent::ExecuteEditCommands() requires non-nullptr mWidget.
  // If the event is created by chrome script, it is nullptr but we need to
  // If the event is created by chrome script, it is nullptr but we need to
  // execute native key bindings.  Therefore, we need to set widget to
  // WidgetEvent::mWidget temporarily.
  AutoRestore<nsCOMPtr<nsIWidget>> saveWidget(widgetKeyEvent->mWidget);
  widgetKeyEvent->mWidget = widget;
  if (widgetKeyEvent->ExecuteEditCommands(nativeKeyBindingsType,
  if (widgetKeyEvent->ExecuteEditCommands(nativeKeyBindingsType,
                                          DoCommandCallback, mFrame)) {
    aEvent->PreventDefault();
  }
  return NS_OK;
}
}

nsresult TextInputListener::OnEditActionHandled(TextEditor& aTextEditor) {
  if (mFrame) {
    AutoWeakFrame weakFrame = mFrame;


    nsITextControlFrame* frameBase = do_QueryFrame(mFrame);
    nsTextControlFrame* frame = static_cast<nsTextControlFrame*>(frameBase);
    NS_ASSERTION(frame, "Where is our frame?");
    //
    // Update the undo / redo menus
    // Update the undo / redo menus
    //
    size_t numUndoItems = aTextEditor.NumberOfUndoItems();
    size_t numRedoItems = aTextEditor.NumberOfRedoItems();
    if ((numUndoItems && !mHadUndoItems) || (!numUndoItems && mHadUndoItems) ||
        (numRedoItems && !mHadRedoItems) || (!numRedoItems && mHadRedoItems)) {
        (numRedoItems && !mHadRedoItems) || (!numRedoItems && mHadRedoItems)) {
      // Modify the menu if undo or redo items are different
      UpdateTextInputCommands(NS_LITERAL_STRING("undo"));

      mHadUndoItems = numUndoItems != 0;
      mHadRedoItems = numRedoItems != 0;
    }

    if (weakFrame.IsAlive()) {
      HandleValueChanged(frame);
      HandleValueChanged(frame);
    }
  }

  return mTextControlState ? mTextControlState->OnEditActionHandled() : NS_OK;
}
}

void TextInputListener::HandleValueChanged(nsTextControlFrame* aFrame) {
  // Make sure we know we were changed (do NOT set this to false if there are
  // no undo items; JS could change the value and we'd still need to save it)
  if (mSetValueChanged) {
  if (mSetValueChanged) {
    if (!aFrame) {
      nsITextControlFrame* frameBase = do_QueryFrame(mFrame);
      aFrame = static_cast<nsTextControlFrame*>(frameBase);
      NS_ASSERTION(aFrame, "Where is our frame?");
    }
    }
    aFrame->SetValueChanged(true);
  }

  if (!mSettingValue) {
    mTxtCtrlElement->OnValueChanged(ValueChangeKind::UserInteraction);
    mTxtCtrlElement->OnValueChanged(ValueChangeKind::UserInteraction);
  }
}


nsresult TextInputListener::UpdateTextInputCommands(
nsresult TextInputListener::UpdateTextInputCommands(
    const nsAString& aCommandsToUpdate, Selection* aSelection,
    int16_t aReason) {
  nsIContent* content = mFrame->GetContent();
  nsIContent* content = mFrame->GetContent();
  if (NS_WARN_IF(!content)) {
    return NS_ERROR_FAILURE;
  }
  nsCOMPtr<Document> doc = content->GetComposedDoc();
  if (NS_WARN_IF(!doc)) {
  if (NS_WARN_IF(!doc)) {
    return NS_ERROR_FAILURE;
  }
  nsPIDOMWindowOuter* domWindow = doc->GetWindow();
  if (NS_WARN_IF(!domWindow)) {
    return NS_ERROR_FAILURE;
    return NS_ERROR_FAILURE;
  }
  domWindow->UpdateCommands(aCommandsToUpdate, aSelection, aReason);
  return NS_OK;
  return NS_OK;
}

/*****************************************************************************
 * mozilla::AutoTextControlHandlingState
 *
 *
 * This class is temporarily created in the stack and can manage nested
 * handling state of TextControlState.  While this instance exists, lifetime of
 * TextControlState which created the instance is guaranteed.  In other words,
 * you can use this class as "kungFuDeathGrip" for TextControlState.
 *****************************************************************************/
 *****************************************************************************/

enum class TextControlAction {
  CacheForReuse,
  CommitComposition,
  Destructor,
  Destructor,
  PrepareEditor,
  SetRangeText,
  SetSelectionRange,
  SetValue,
  UnbindFromFrame,
  UnbindFromFrame,
  Unlink,
};

class MOZ_STACK_CLASS AutoTextControlHandlingState {
class MOZ_STACK_CLASS AutoTextControlHandlingState {
 public:
  AutoTextControlHandlingState() = delete;
  explicit AutoTextControlHandlingState(const AutoTextControlHandlingState&) =
      delete;
  AutoTextControlHandlingState(AutoTextControlHandlingState&&) = delete;
  void operator=(AutoTextControlHandlingState&) = delete;
  void operator=(const AutoTextControlHandlingState&) = delete;
  void operator=(const AutoTextControlHandlingState&) = delete;

  /**
   * Generic constructor.  If TextControlAction does not require additional
   * data, must use this constructor.
   */
  MOZ_CAN_RUN_SCRIPT AutoTextControlHandlingState(
      TextControlState& aTextControlState, TextControlAction aTextControlAction)
      TextControlState& aTextControlState, TextControlAction aTextControlAction)
      : mParent(aTextControlState.mHandlingState),
        mTextControlState(aTextControlState),
        mTextCtrlElement(aTextControlState.mTextCtrlElement),
        mTextInputListener(aTextControlState.mTextListener),
        mTextControlAction(aTextControlAction) {
        mTextControlAction(aTextControlAction) {
    MOZ_ASSERT(aTextControlAction != TextControlAction::SetValue,
               "Use specific constructor");
    mTextControlState.mHandlingState = this;
    if (Is(TextControlAction::CommitComposition)) {
      MOZ_ASSERT(mParent);
      MOZ_ASSERT(mParent);
      MOZ_ASSERT(mParent->Is(TextControlAction::SetValue));
      // If we're trying to commit composition before handling SetValue,
      // the parent old values will be outdated so that we need to clear
      // them.
      mParent->InvalidateOldValue();
      mParent->InvalidateOldValue();
    }
  }

  /**
   * TextControlAction::SetValue specific constructor.  Current setting value
   * must be specified and the creator should check whether we succeeded to
   * allocate memory for line breaker conversion.
   * allocate memory for line breaker conversion.
   */
  MOZ_CAN_RUN_SCRIPT AutoTextControlHandlingState(
      TextControlState& aTextControlState, TextControlAction aTextControlAction,
      const nsAString& aSettingValue, const nsAString* aOldValue,
      uint32_t aFlags, ErrorResult& aRv)
      uint32_t aFlags, ErrorResult& aRv)
      : mParent(aTextControlState.mHandlingState),
        mTextControlState(aTextControlState),
        mTextCtrlElement(aTextControlState.mTextCtrlElement),
        mTextInputListener(aTextControlState.mTextListener),
        mSettingValue(aSettingValue),
        mSettingValue(aSettingValue),
        mOldValue(aOldValue),
        mSetValueFlags(aFlags),
        mTextControlAction(aTextControlAction) {
    MOZ_ASSERT(aTextControlAction == TextControlAction::SetValue,
               "Use generic constructor");
               "Use generic constructor");
    mTextControlState.mHandlingState = this;
    if (!nsContentUtils::PlatformToDOMLineBreaks(mSettingValue, fallible)) {
      aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
      return;
      return;
    }
    // Update all setting value's new value because older value shouldn't
    // overwrite newer value.
    if (mParent) {
      // If SetValue is nested, parents cannot trust their old value anymore.
      // If SetValue is nested, parents cannot trust their old value anymore.
      // So, we need to clear them.
      mParent->UpdateSettingValueAndInvalidateOldValue(mSettingValue);
    }
  }


  MOZ_CAN_RUN_SCRIPT ~AutoTextControlHandlingState() {
    mTextControlState.mHandlingState = mParent;
    if (!mParent && mTextControlStateDestroyed) {
      mTextControlState.DeleteOrCacheForReuse();
    }
    }
    if (!mTextControlStateDestroyed && mPreareEditorLater) {
      MOZ_ASSERT(nsContentUtils::IsSafeToRunScript());
      mTextControlState.PrepareEditor();
    }
  }
  }

  void OnDestroyTextControlState() {
    if (IsHandling(TextControlAction::Destructor) ||
        IsHandling(TextControlAction::CacheForReuse)) {
        IsHandling(TextControlAction::CacheForReuse)) {
      // Do nothing since mTextContrlState.DeleteOrCacheForReuse() has
      // already been called.
      return;
    }
    mTextControlStateDestroyed = true;
    mTextControlStateDestroyed = true;
    if (mParent) {
      mParent->OnDestroyTextControlState();
    }
  }


  void PrepareEditorLater() {
    MOZ_ASSERT(IsHandling(TextControlAction::SetValue));
    MOZ_ASSERT(!IsHandling(TextControlAction::PrepareEditor));
    // Look for the top most SetValue.
    // Look for the top most SetValue.
    AutoTextControlHandlingState* settingValue = nullptr;
    for (AutoTextControlHandlingState* handlingSomething = this;
         handlingSomething; handlingSomething = handlingSomething->mParent) {
      if (handlingSomething->Is(TextControlAction::SetValue)) {
        settingValue = handlingSomething;
        settingValue = handlingSomething;
      }
    }
    settingValue->mPreareEditorLater = true;
  }


  /**
   * WillSetValueWithTextEditor() is called when TextControlState sets
   * value with its mTextEditor.
   */
  void WillSetValueWithTextEditor() {
  void WillSetValueWithTextEditor() {
    MOZ_ASSERT(Is(TextControlAction::SetValue));
    MOZ_ASSERT(mTextControlState.mBoundFrame);
    mTextControlFrame = mTextControlState.mBoundFrame;
    // If we'reemulating user input, we don't need to manage mTextInputListener
    // by ourselves since everything should be handled by TextEditor as normal
    // user input.
    if (mSetValueFlags & TextControlState::eSetValue_BySetUserInput) {
    if (mSetValueFlags & TextControlState::eSetValue_BySetUserInput) {
      return;
    }
    // Otherwise, if we're setting the value programatically, we need to manage
    // mTextInputListener by ourselves since TextEditor users special path
    // for the performance.
    // for the performance.
    mTextInputListener->SettingValue(true);
    mTextInputListener->SetValueChanged(mSetValueFlags &
                                        TextControlState::eSetValue_Notify);
    mEditActionHandled = false;
    // Even if falling back to `TextControlState::SetValueWithoutTextEditor()`
    // Even if falling back to `TextControlState::SetValueWithoutTextEditor()`
    // due to editor destruction, it shouldn't dispatch "beforeinput" event
    // anymore.  Therefore, we should mark that we've already dispatched
    // "beforeinput" event.
    WillDispatchBeforeInputEvent();
  }
  }


  /**
   * WillDispatchBeforeInputEvent() is called immediately before dispatching
   * "beforeinput" event in `TextControlState`.
   */
  void WillDispatchBeforeInputEvent() {
  void WillDispatchBeforeInputEvent() {
    mBeforeInputEventHasBeenDispatched = true;
  }

  /**
   * OnEditActionHandled() is called when the TextEditor handles something
   * OnEditActionHandled() is called when the TextEditor handles something
   * and immediately before dispatching "input" event.
   */
  MOZ_CAN_RUN_SCRIPT MOZ_MUST_USE nsresult OnEditActionHandled() {
    MOZ_ASSERT(!mEditActionHandled);
    mEditActionHandled = true;
    mEditActionHandled = true;
    if (!Is(TextControlAction::SetValue)) {
      return NS_OK;
    }
    if (!(mSetValueFlags & TextControlState::eSetValue_BySetUserInput)) {
    if (!(mSetValueFlags & TextControlState::eSetValue_BySetUserInput)) {
      mTextInputListener->SetValueChanged(true);
      mTextInputListener->SettingValue(
          mParent && mParent->IsHandling(TextControlAction::SetValue));
      if (!(mSetValueFlags & TextControlState::eSetValue_Notify)) {
        // Listener doesn't update frame, but it is required for
        // Listener doesn't update frame, but it is required for
        // placeholder
        mTextControlState.ValueWasChanged();
        mTextControlState.ValueWasChanged();
      }
      }
    }
    if (!IsOriginalTextControlFrameAlive()) {
      return SetValueWithoutTextEditorAgain() ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
      return SetValueWithoutTextEditorAgain() ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
    }
    // The new value never includes line breaks caused by hard-wrap.
    // So, mCachedValue can always cache the new value.
    nsITextControlFrame* textControlFrame =
        do_QueryFrame(mTextControlFrame.GetFrame());
        do_QueryFrame(mTextControlFrame.GetFrame());
    return static_cast<nsTextControlFrame*>(textControlFrame)
                   ->CacheValue(mSettingValue, fallible)
               ? NS_OK
               : NS_ERROR_OUT_OF_MEMORY;
  }
  }

  /**
   * SetValueWithoutTextEditorAgain() should be called if the frame for
   * mTextControlState was destroyed during setting value.
   */
   */
  MOZ_CAN_RUN_SCRIPT MOZ_MUST_USE bool SetValueWithoutTextEditorAgain() {
    MOZ_ASSERT(!IsOriginalTextControlFrameAlive());
    // If the frame was destroyed because of a flush somewhere inside
    // TextEditor, mBoundFrame here will be nullptr.  But it's also
    // possible for the frame to go away because of another reason (such
    // possible for the frame to go away because of another reason (such
    // as deleting the existing selection -- see bug 574558), in which
    // case we don't need to reset the value here.
    if (mTextControlState.mBoundFrame) {
      return true;
    }
    // XXX It's odd to drop flags except eSetValue_Notify.  Probably, this
    // XXX It's odd to drop flags except eSetValue_Notify.  Probably, this
    //     intended to drop eSetValue_BySetUserInput and eSetValue_ByContent,
    //     but other flags are added later.
    ErrorResult error;
    AutoTextControlHandlingState handlingSetValueWithoutEditor(
        mTextControlState, TextControlAction::SetValue, mSettingValue,
        mTextControlState, TextControlAction::SetValue, mSettingValue,
        mOldValue, mSetValueFlags & TextControlState::eSetValue_Notify, error);
    if (error.Failed()) {
      MOZ_ASSERT(error.ErrorCodeIs(NS_ERROR_OUT_OF_MEMORY));
      error.SuppressException();
      return false;
      return false;
    }
    return mTextControlState.SetValueWithoutTextEditor(
        handlingSetValueWithoutEditor);
  }


  bool IsTextControlStateDestroyed() const {
    return mTextControlStateDestroyed;
  }
  bool IsOriginalTextControlFrameAlive() const {
    return const_cast<AutoTextControlHandlingState*>(this)
        ->mTextControlFrame.IsAlive();
  }
  bool HasEditActionHandled() const { return mEditActionHandled; }
  bool HasEditActionHandled() const { return mEditActionHandled; }
  bool HasBeforeInputEventDispatched() const {
    return mBeforeInputEventHasBeenDispatched;
  }
  bool Is(TextControlAction aTextControlAction) const {
    return mTextControlAction == aTextControlAction;
    return mTextControlAction == aTextControlAction;
  }
  bool IsHandling(TextControlAction aTextControlAction) const {
    if (mTextControlAction == aTextControlAction) {
      return true;
    }
    }
    return mParent ? mParent->IsHandling(aTextControlAction) : false;
  }
  TextControlElement* GetTextControlElement() const { return mTextCtrlElement; }
  TextInputListener* GetTextInputListener() const { return mTextInputListener; }
  uint32_t GetSetValueFlags() const {
  uint32_t GetSetValueFlags() const {
    MOZ_ASSERT(Is(TextControlAction::SetValue));
    return mSetValueFlags;
  }
  const nsAString* GetOldValue() const {
    MOZ_ASSERT(Is(TextControlAction::SetValue));
    MOZ_ASSERT(Is(TextControlAction::SetValue));
    return mOldValue;
  }
  const nsString& GetSettingValue() const {
  const nsString& GetSettingValue() const {
    MOZ_ASSERT(IsHandling(TextControlAction::SetValue));
    if (mTextControlAction == TextControlAction::SetValue) {
      return mSettingValue;
    }
    return mParent->GetSettingValue();
    return mParent->GetSettingValue();
  }

 private:
  void UpdateSettingValueAndInvalidateOldValue(const nsString& aSettingValue) {
    if (mTextControlAction == TextControlAction::SetValue) {
      mSettingValue = aSettingValue;
    }
    }
    mOldValue = nullptr;
    if (mParent) {
      mParent->UpdateSettingValueAndInvalidateOldValue(aSettingValue);
    }
  }
  }
  void InvalidateOldValue() {
    mOldValue = nullptr;
    if (mParent) {
      mParent->InvalidateOldValue();
    }
    }
  }

  AutoTextControlHandlingState* const mParent;
  TextControlState& mTextControlState;
  // mTextControlFrame should be set immediately before calling methods
  // which may destroy the frame.  Then, you can check whether the frame
  // was destroyed/replaced.
  // was destroyed/replaced.
  AutoWeakFrame mTextControlFrame;
  // mTextCtrlElement grabs TextControlState::mTextCtrlElement since
  // if the text control element releases mTextControlState, only this
  // can guarantee the instance of the text control element.
  RefPtr<TextControlElement> const mTextCtrlElement;
  RefPtr<TextControlElement> const mTextCtrlElement;
  // mTextInputListener grabs TextControlState::mTextListener because if
  // TextControlState is unbind from the frame, it's released.
  RefPtr<TextInputListener> const mTextInputListener;
  nsString mSettingValue;
  const nsAString* mOldValue = nullptr;
  const nsAString* mOldValue = nullptr;
  uint32_t mSetValueFlags = 0;
  TextControlAction const mTextControlAction;
  bool mTextControlStateDestroyed = false;
  bool mEditActionHandled = false;
  bool mPreareEditorLater = false;
  bool mPreareEditorLater = false;
  bool mBeforeInputEventHasBeenDispatched = false;
};

/*****************************************************************************
 * mozilla::TextControlState
 *****************************************************************************/

AutoTArray<TextControlState*, TextControlState::kMaxCountOfCacheToReuse>*
    TextControlState::sReleasedInstances = nullptr;
    TextControlState::sReleasedInstances = nullptr;
bool TextControlState::sHasShutDown = false;

TextControlState::TextControlState(TextControlElement* aOwningElement)
    : mTextCtrlElement(aOwningElement),
      mBoundFrame(nullptr),
      mBoundFrame(nullptr),
      mEverInited(false),
      mEditorInitialized(false),
      mValueTransferInProgress(false),
      mSelectionCached(true),
      mPlaceholderVisibility(false),
      mPlaceholderVisibility(false),
      mPreviewVisibility(false)
// When adding more member variable initializations here, add the same
// also to ::Construct.
{
  MOZ_COUNT_CTOR(TextControlState);
  MOZ_COUNT_CTOR(TextControlState);
  static_assert(sizeof(*this) <= 128,
                "Please keep small TextControlState as far as possible");
}

TextControlState* TextControlState::Construct(
TextControlState* TextControlState::Construct(
    TextControlElement* aOwningElement) {
  if (sReleasedInstances && !sReleasedInstances->IsEmpty()) {
    TextControlState* state = sReleasedInstances->PopLastElement();
    state->mTextCtrlElement = aOwningElement;
    state->mBoundFrame = nullptr;
    state->mSelectionProperties = SelectionProperties();
    state->mBoundFrame = nullptr;
    state->mEverInited = false;
    state->mEditorInitialized = false;
    state->mValueTransferInProgress = false;
    state->mSelectionCached = true;
    state->mPlaceholderVisibility = false;
    state->mSelectionCached = true;
    state->mPreviewVisibility = false;
    // When adding more member variable initializations here, add the same
    // also to the constructor.
    return state;
  }
    return state;

  return new TextControlState(aOwningElement);
}

TextControlState::~TextControlState() {

  MOZ_ASSERT(!mHandlingState);
  MOZ_COUNT_DTOR(TextControlState);
  AutoTextControlHandlingState handlingDesctructor(
  AutoTextControlHandlingState handlingDesctructor(
      *this, TextControlAction::Destructor);
  Clear();
}

void TextControlState::Shutdown() {
  sHasShutDown = true;
  if (sReleasedInstances) {
    for (TextControlState* textControlState : *sReleasedInstances) {
  if (sReleasedInstances) {
      textControlState->DeleteOrCacheForReuse();
    }
    delete sReleasedInstances;
  }
}
  }

void TextControlState::Destroy() {
  // If we're handling something, we should be deleted later.
  if (mHandlingState) {
    mHandlingState->OnDestroyTextControlState();
  if (mHandlingState) {
    return;
  }
  DeleteOrCacheForReuse();
  // Note that this instance may have already been deleted here.  Don't touch
  // any members.
}

}
void TextControlState::DeleteOrCacheForReuse() {
  MOZ_ASSERT(!IsBusy());

  // If we can cache this instance, we should do it instead of deleting it.
  if (!sHasShutDown && (!sReleasedInstances || sReleasedInstances->Length() <
  // If we can cache this instance, we should do it instead of deleting it.
                                                   kMaxCountOfCacheToReuse)) {
    AutoTextControlHandlingState handlingCacheForReuse(
        *this, TextControlAction::CacheForReuse);

    // Prepare for reuse, unlink and release any refcountable objects.
    // Prepare for reuse, unlink and release any refcountable objects.
    UnlinkInternal();
    mValue.reset();
    mTextCtrlElement = nullptr;

    // Put this instance to the cache.  Note that now, the array may be full,
    // Put this instance to the cache.  Note that now, the array may be full,
    // but it's not problem to cache more instances than kMaxCountOfCacheToReuse
    // because it just requires reallocation cost of the array buffer.
    if (!sReleasedInstances) {
      sReleasedInstances =
          new AutoTArray<TextControlState*, kMaxCountOfCacheToReuse>;
          new AutoTArray<TextControlState*, kMaxCountOfCacheToReuse>;
    }
    sReleasedInstances->AppendElement(this);

    return;
  }
  }
  delete this;
}

nsresult TextControlState::OnEditActionHandled() {
  return mHandlingState ? mHandlingState->OnEditActionHandled() : NS_OK;
  return mHandlingState ? mHandlingState->OnEditActionHandled() : NS_OK;
}

Element* TextControlState::GetRootNode() {
  return mBoundFrame ? mBoundFrame->GetRootNode() : nullptr;
}

Element* TextControlState::GetPreviewNode() {

  return mBoundFrame ? mBoundFrame->GetPreviewNode() : nullptr;
}

void TextControlState::Clear() {
void TextControlState::Clear() {
  MOZ_ASSERT(mHandlingState);
  MOZ_ASSERT(mHandlingState->Is(TextControlAction::Destructor) ||
             mHandlingState->Is(TextControlAction::CacheForReuse) ||
             mHandlingState->Is(TextControlAction::Unlink));
  if (mTextEditor) {
  if (mTextEditor) {
    mTextEditor->SetTextInputListener(nullptr);
  }

  if (mBoundFrame) {
  if (mBoundFrame) {
    // Oops, we still have a frame!
    // This should happen when the type of a text input control is being changed
    // to something which is not a text control.  In this case, we should
    // pretend that a frame is being destroyed, and clean up after ourselves
    // properly.
    // properly.
    UnbindFromFrame(mBoundFrame);
    mTextEditor = nullptr;
  } else {
    // If we have a bound frame around, UnbindFromFrame will call DestroyEditor
    // for us.
    DestroyEditor();
  }
  mTextListener = nullptr;
}

}
void TextControlState::Unlink() {
  AutoTextControlHandlingState handlingUnlink(*this, TextControlAction::Unlink);
  UnlinkInternal();
}
}

void TextControlState::UnlinkInternal() {
  MOZ_ASSERT(mHandlingState);
  MOZ_ASSERT(mHandlingState->Is(TextControlAction::Unlink) ||
             mHandlingState->Is(TextControlAction::CacheForReuse));
             mHandlingState->Is(TextControlAction::CacheForReuse));
  TextControlState* tmp = this;
  tmp->Clear();
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelCon)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTextEditor)
}

void TextControlState::Traverse(nsCycleCollectionTraversalCallback& cb) {
void TextControlState::Traverse(nsCycleCollectionTraversalCallback& cb) {
  TextControlState* tmp = this;
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelCon)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTextEditor)
}


nsFrameSelection* TextControlState::GetConstFrameSelection() {
  return mSelCon ? mSelCon->GetConstFrameSelection() : nullptr;
}

TextEditor* TextControlState::GetTextEditor() {
TextEditor* TextControlState::GetTextEditor() {
  // Note that if the instance is destroyed in PrepareEditor(), it returns
  // NS_ERROR_NOT_INITIALIZED so that we don't need to create kungFuDeathGrip
  // in this hot path.
  if (!mTextEditor && NS_WARN_IF(NS_FAILED(PrepareEditor()))) {
    return nullptr;
    return nullptr;
  }
  return mTextEditor;
}

TextEditor* TextControlState::GetTextEditorWithoutCreation() {
TextEditor* TextControlState::GetTextEditorWithoutCreation() {
  return mTextEditor;
}

nsISelectionController* TextControlState::GetSelectionController() const {
  return mSelCon;
  return mSelCon;
}

// Helper class, used below in BindToFrame().
class PrepareEditorEvent : public Runnable {
 public:
 public:
  PrepareEditorEvent(TextControlState& aState, nsIContent* aOwnerContent,
                     const nsAString& aCurrentValue)
      : Runnable("PrepareEditorEvent"),
        mState(&aState),
        mOwnerContent(aOwnerContent),
        mOwnerContent(aOwnerContent),
        mCurrentValue(aCurrentValue) {
    aState.mValueTransferInProgress = true;
  }

  MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Run() override {
  MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Run() override {
    if (NS_WARN_IF(!mState)) {
      return NS_ERROR_NULL_POINTER;
    }

    // Transfer the saved value to the editor if we have one
    // Transfer the saved value to the editor if we have one
    const nsAString* value = nullptr;
    if (!mCurrentValue.IsEmpty()) {
      value = &mCurrentValue;
    }


    nsAutoScriptBlocker scriptBlocker;

    mState->PrepareEditor(value);

    mState->mValueTransferInProgress = false;
    mState->mValueTransferInProgress = false;

    return NS_OK;
  }

 private:
 private:
  WeakPtr<TextControlState> mState;
  nsCOMPtr<nsIContent> mOwnerContent;  // strong reference
  WeakPtr<TextControlState> mState;
  nsAutoString mCurrentValue;
};

nsresult TextControlState::BindToFrame(nsTextControlFrame* aFrame) {
  MOZ_ASSERT(
nsresult TextControlState::BindToFrame(nsTextControlFrame* aFrame) {
      !nsContentUtils::IsSafeToRunScript(),
      "TextControlState::BindToFrame() has to be called with script blocker");
  NS_ASSERTION(aFrame, "The frame to bind to should be valid");
  if (!aFrame) {
    return NS_ERROR_INVALID_ARG;
  if (!aFrame) {
  }

  NS_ASSERTION(!mBoundFrame, "Cannot bind twice, need to unbind first");
  if (mBoundFrame) {
    return NS_ERROR_FAILURE;
  if (mBoundFrame) {
  }

  // If we'll need to transfer our current value to the editor, save it before
  // binding to the frame.
  // binding to the frame.
  nsAutoString currentValue;
  if (mTextEditor) {
    GetValue(currentValue, true);
  }


  mBoundFrame = aFrame;

  Element* rootNode = aFrame->GetRootNode();
  MOZ_ASSERT(rootNode);

  PresShell* presShell = aFrame->PresContext()->GetPresShell();
  MOZ_ASSERT(presShell);
  PresShell* presShell = aFrame->PresContext()->GetPresShell();

  // Create a SelectionController
  mSelCon = new TextInputSelectionController(presShell, rootNode);
  MOZ_ASSERT(!mTextListener, "Should not overwrite the object");
  mTextListener = new TextInputListener(mTextCtrlElement);
  MOZ_ASSERT(!mTextListener, "Should not overwrite the object");

  mTextListener->SetFrame(mBoundFrame);

  // Editor will override this as needed from InitializeSelection.

  mSelCon->SetDisplaySelection(nsISelectionController::SELECTION_HIDDEN);

  // Get the caret and make it a selection listener.
  // FYI: It's safe to use raw pointer for calling
  //      Selection::AddSelectionListner() because it only appends the listener
  // FYI: It's safe to use raw pointer for calling
  //      to its internal array.
  Selection* selection = mSelCon->GetSelection(SelectionType::eNormal);
  if (selection) {
    RefPtr<nsCaret> caret = presShell->GetCaret();
    if (caret) {
    RefPtr<nsCaret> caret = presShell->GetCaret();
      selection->AddSelectionListener(caret);
    }
    mTextListener->StartToListenToSelectionChange();
  }

  // If an editor exists from before, prepare it for usage
  if (mTextEditor) {
  if (mTextEditor) {
    if (NS_WARN_IF(!mTextCtrlElement)) {
      return NS_ERROR_FAILURE;
    }

    // Set the correct direction on the newly created root node
    // Set the correct direction on the newly created root node
    if (mTextEditor->IsRightToLeft()) {
      rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir,
                        NS_LITERAL_STRING("rtl"), false);
    } else if (mTextEditor->IsLeftToRight()) {
      rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir,
      rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir,
                        NS_LITERAL_STRING("ltr"), false);
    } else {
      // otherwise, inherit the content node's direction
    }


    nsContentUtils::AddScriptRunner(
        new PrepareEditorEvent(*this, mTextCtrlElement, currentValue));
  }

  return NS_OK;
  return NS_OK;
}

struct MOZ_STACK_CLASS PreDestroyer {
struct MOZ_STACK_CLASS PreDestroyer {
  void Init(TextEditor* aTextEditor) { mTextEditor = aTextEditor; }
  MOZ_CAN_RUN_SCRIPT ~PreDestroyer() {
    if (mTextEditor) {
      MOZ_KnownLive(mTextEditor)->PreDestroy(true);
    }
    }
  }
  void Swap(RefPtr<TextEditor>& aTextEditor) {
    return mTextEditor.swap(aTextEditor);
  }


 private:
  RefPtr<TextEditor> mTextEditor;
};


nsresult TextControlState::PrepareEditor(const nsAString* aValue) {
  if (!mBoundFrame) {
    // Cannot create an editor without a bound frame.
    // Don't return a failure code, because js callers can't handle that.
    return NS_OK;
    return NS_OK;
  }

  if (mEditorInitialized) {
    // Do not initialize the editor multiple times.
    return NS_OK;
    return NS_OK;
  }

  AutoHideSelectionChanges hideSelectionChanges(GetConstFrameSelection());

  if (mHandlingState) {

    // Don't attempt to initialize recursively!
    if (mHandlingState->IsHandling(TextControlAction::PrepareEditor)) {
      return NS_ERROR_NOT_INITIALIZED;
    }
    // Reschedule creating editor later if we're setting value.
    }
    if (mHandlingState->IsHandling(TextControlAction::SetValue)) {
      mHandlingState->PrepareEditorLater();
      return NS_ERROR_NOT_INITIALIZED;
    }
    }
  }

  MOZ_ASSERT(mTextCtrlElement);

  AutoTextControlHandlingState preparingEditor(
      *this, TextControlAction::PrepareEditor);

  // Note that we don't check mTextEditor here, because we might already have

  // one around, in which case we don't create a new one, and we'll just tie
  // the required machinery to it.

  nsPresContext* presContext = mBoundFrame->PresContext();
  PresShell* presShell = presContext->GetPresShell();
  nsPresContext* presContext = mBoundFrame->PresContext();

  // Setup the editor flags
  uint32_t editorFlags = nsIEditor::eEditorPlaintextMask;
  if (IsSingleLineTextControl()) {
    editorFlags |= nsIEditor::eEditorSingleLineMask;
    editorFlags |= nsIEditor::eEditorSingleLineMask;
  }
  if (IsPasswordTextControl()) {
    editorFlags |= nsIEditor::eEditorPasswordMask;
  }


  // All nsTextControlFrames are widgets
  editorFlags |= nsIEditor::eEditorWidgetMask;

  // Spell check is diabled at creation time. It is enabled once
  // the editor comes into focus.
  // the editor comes into focus.
  editorFlags |= nsIEditor::eEditorSkipSpellCheck;

  bool shouldInitializeEditor = false;
  RefPtr<TextEditor> newTextEditor;  // the editor that we might create
  nsresult rv = NS_OK;
  nsresult rv = NS_OK;
  PreDestroyer preDestroyer;
  if (!mTextEditor) {
    shouldInitializeEditor = true;

    // Create an editor
    // Create an editor
    newTextEditor = new TextEditor();
    preDestroyer.Init(newTextEditor);

    // Make sure we clear out the non-breaking space before we initialize the
    // editor
    rv = mBoundFrame->UpdateValueDisplay(true, true);
    if (NS_FAILED(rv)) {
      NS_WARNING("nsTextControlFrame::UpdateValueDisplay() failed");
      NS_WARNING("nsTextControlFrame::UpdateValueDisplay() failed");
      return rv;
    }
  } else {
    if (aValue || !mEditorInitialized) {
      // Set the correct value in the root node
      // Set the correct value in the root node
      rv = mBoundFrame->UpdateValueDisplay(true, !mEditorInitialized, aValue);
      if (NS_FAILED(rv)) {
        NS_WARNING("nsTextControlFrame::UpdateValueDisplay() failed");
        return rv;
        return rv;
      }
    }

    newTextEditor = mTextEditor;  // just pretend that we have a new editor!


    // Don't lose application flags in the process.
    if (newTextEditor->IsMailEditor()) {
      editorFlags |= nsIEditor::eEditorMailMask;
    }
  }
  }

  // Get the current value of the textfield from the content.
  // Note that if we've created a new editor, mTextEditor is null at this stage,
  // so we will get the real value from the content.
  // so we will get the real value from the content.
  nsAutoString defaultValue;
  if (aValue) {
    defaultValue = *aValue;
  } else {
    GetValue(defaultValue, true);
  }
    GetValue(defaultValue, true);

  if (!mEditorInitialized) {
    // Now initialize the editor.
    //
    // NOTE: Conversion of '\n' to <BR> happens inside the
    //
    //       editor's Init() call.

    // Get the DOM document
    nsCOMPtr<Document> doc = presShell->GetDocument();
    if (NS_WARN_IF(!doc)) {
    nsCOMPtr<Document> doc = presShell->GetDocument();
      return NS_ERROR_FAILURE;
    }

    // What follows is a bit of a hack.  The editor uses the public DOM APIs
    // for its content manipulations, and it causes it to fail some security
    // What follows is a bit of a hack.  The editor uses the public DOM APIs
    // checks deep inside when initializing. So we explictly make it clear that
    // we're native code.
    // Note that any script that's directly trying to access our value
    // Note that any script that's directly trying to access our value
    // has to be going through some scriptable object to do that and that
    // already does the relevant security checks.
    AutoNoJSAPI nojsapi;

    RefPtr<Element> rootElement = GetRootNode();
    RefPtr<Element> rootElement = GetRootNode();
    RefPtr<TextInputSelectionController> selectionController = mSelCon;
    rv = newTextEditor->Init(*doc, rootElement, selectionController,
                             editorFlags, defaultValue);
    if (NS_FAILED(rv)) {
      NS_WARNING("TextEditor::Init() failed");
      NS_WARNING("TextEditor::Init() failed");
      return rv;
    }
  }

  // Initialize the controller for the editor

  if (!SuppressEventHandlers(presContext)) {
  if (!SuppressEventHandlers(presContext)) {
    nsCOMPtr<nsIControllers> controllers;
    if (HTMLInputElement* inputElement =
            HTMLInputElement::FromNodeOrNull(mTextCtrlElement)) {
      rv = inputElement->GetControllers(getter_AddRefs(controllers));
      if (NS_WARN_IF(NS_FAILED(rv))) {
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    } else {
      HTMLTextAreaElement* textAreaElement =
          HTMLTextAreaElement::FromNodeOrNull(mTextCtrlElement);
          HTMLTextAreaElement::FromNodeOrNull(mTextCtrlElement);
      if (!textAreaElement) {
        return NS_ERROR_FAILURE;
      }

      rv = textAreaElement->GetControllers(getter_AddRefs(controllers));
      rv = textAreaElement->GetControllers(getter_AddRefs(controllers));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    }


    if (controllers) {
      uint32_t numControllers;
      bool found = false;
      rv = controllers->GetControllerCount(&numControllers);
      for (uint32_t i = 0; i < numControllers; i++) {
        nsCOMPtr<nsIController> controller;
        rv = controllers->GetControllerAt(i, getter_AddRefs(controller));
        if (NS_SUCCEEDED(rv) && controller) {
          nsCOMPtr<nsIControllerContext> editController =
              do_QueryInterface(controller);
              do_QueryInterface(controller);
          if (editController) {
            editController->SetCommandContext(
                static_cast<nsIEditor*>(newTextEditor));
            found = true;
          }
          }
        }
      }
      if (!found) {
        rv = NS_ERROR_FAILURE;
      }
    }
  }
  }

  // Initialize the plaintext editor
  if (shouldInitializeEditor) {
    const int32_t wrapCols = GetWrapCols();
    MOZ_ASSERT(wrapCols >= 0);
    newTextEditor->SetWrapColumn(wrapCols);
  }
  }

  // Set max text field length
  newTextEditor->SetMaxTextLength(mTextCtrlElement->UsedMaxLength());

  editorFlags = newTextEditor->Flags();
  editorFlags = newTextEditor->Flags();

  // Check if the readonly attribute is set.
  //
  // TODO: Should probably call IsDisabled(), as it is cheaper.
  if (mTextCtrlElement->HasAttr(kNameSpaceID_None, nsGkAtoms::readonly) ||
  if (mTextCtrlElement->HasAttr(kNameSpaceID_None, nsGkAtoms::readonly) ||
      mTextCtrlElement->HasAttr(kNameSpaceID_None, nsGkAtoms::disabled)) {
    editorFlags |= nsIEditor::eEditorReadonlyMask;
  }

  SetEditorFlagsIfNecessary(*newTextEditor, editorFlags);
  SetEditorFlagsIfNecessary(*newTextEditor, editorFlags);

  if (shouldInitializeEditor) {
    // Hold on to the newly created editor
    // Hold on to the newly created editor
    preDestroyer.Swap(mTextEditor);
  }

  // If we have a default value, insert it under the div we created
  // above, but be sure to use the editor so that '*' characters get
  // above, but be sure to use the editor so that '*' characters get
  // displayed for password fields, etc. SetValue() will call the
  // editor for us.

  if (!defaultValue.IsEmpty()) {
    // XXX rv may store error code which indicates there is no controller.
    //     However, we overwrite it only in this case.
    rv = SetEditorFlagsIfNecessary(*newTextEditor, editorFlags);
    rv = SetEditorFlagsIfNecessary(*newTextEditor, editorFlags);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    // Now call SetValue() which will make the necessary editor calls to set
    // Now call SetValue() which will make the necessary editor calls to set
    // the default value.  Make sure to turn off undo before setting the default
    // value, and turn it back on afterwards. This will make sure we can't undo
    // past the default value.
    // So, we use eSetValue_Internal flag only that it will turn off undo.


    if (NS_WARN_IF(!SetValue(defaultValue, eSetValue_Internal))) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    // Now restore the original editor flags.
    rv = SetEditorFlagsIfNecessary(*newTextEditor, editorFlags);
    if (NS_WARN_IF(NS_FAILED(rv))) {
    rv = SetEditorFlagsIfNecessary(*newTextEditor, editorFlags);
      return rv;
    }
  }

  if (IsPasswordTextControl()) {

    // Disable undo for <input type="password">.  Note that we want to do this
    // at the very end of InitEditor(), so the calls to EnableUndoRedo() when
    // setting the default value don't screw us up.  Since changing the
    // control type does a reframe, we don't have to worry about dynamic type
    // changes here.
    DebugOnly<bool> disabledUndoRedo = newTextEditor->DisableUndoRedo();
    DebugOnly<bool> disabledUndoRedo = newTextEditor->DisableUndoRedo();
    NS_WARNING_ASSERTION(disabledUndoRedo,
                         "Failed to disable undo/redo transaction");
  } else {
    DebugOnly<bool> enabledUndoRedo =
        newTextEditor->EnableUndoRedo(TextControlElement::DEFAULT_UNDO_CAP);
        newTextEditor->EnableUndoRedo(TextControlElement::DEFAULT_UNDO_CAP);
    NS_WARNING_ASSERTION(enabledUndoRedo,
                         "Failed to enable undo/redo transaction");
  }

  if (!mEditorInitialized) {
    newTextEditor->PostCreate();
    mEverInited = true;
    mEditorInitialized = true;
  }

  }
  if (mTextListener) {
    newTextEditor->SetTextInputListener(mTextListener);
  }

  // Restore our selection after being bound to a new frame

  if (mSelectionCached) {
    if (mRestoringSelection) {  // paranoia
      mRestoringSelection->Revoke();
    }
    mRestoringSelection = new RestoreSelectionState(this, mBoundFrame);
    }
    if (mRestoringSelection) {
      nsContentUtils::AddScriptRunner(mRestoringSelection);
    }
  }
  }

  // The selection cache is no longer going to be valid.
  //
  // XXXbz Shouldn't we do this at the point when we're actually about to
  // restore the properties or something?  As things stand, if UnbindFromFrame
  // restore the properties or something?  As things stand, if UnbindFromFrame
  // happens before our RestoreSelectionState runs, it looks like we'll lose our
  // selection info, because we will think we don't have it cached and try to
  // read it from the selection controller, which will not have it yet.
  mSelectionCached = false;

  return preparingEditor.IsTextControlStateDestroyed()
             ? NS_ERROR_NOT_INITIALIZED
  return preparingEditor.IsTextControlStateDestroyed()
             : rv;
}

void TextControlState::FinishedRestoringSelection() {
  mRestoringSelection = nullptr;
void TextControlState::FinishedRestoringSelection() {
}

void TextControlState::SyncUpSelectionPropertiesBeforeDestruction() {
  if (mBoundFrame) {
  if (mBoundFrame) {
    UnbindFromFrame(mBoundFrame);
  }
}

void TextControlState::SetSelectionProperties(
void TextControlState::SetSelectionProperties(
    TextControlState::SelectionProperties& aProps) {
  if (mBoundFrame) {
    mBoundFrame->SetSelectionRange(aProps.GetStart(), aProps.GetEnd(),
                                   aProps.GetDirection());
                                   aProps.GetDirection());
    // The instance may have already been deleted here.
  } else {
    mSelectionProperties = aProps;
  }
  }
}

void TextControlState::GetSelectionRange(uint32_t* aSelectionStart,
                                         uint32_t* aSelectionEnd,
                                         ErrorResult& aRv) {
  MOZ_ASSERT(aSelectionStart);
                                         ErrorResult& aRv) {
  MOZ_ASSERT(aSelectionEnd);
  MOZ_ASSERT(IsSelectionCached() || GetSelectionController(),
             "How can we not have a cached selection if we have no selection "
             "controller?");

             "controller?");
  // Note that we may have both IsSelectionCached() _and_
  // GetSelectionController() if we haven't initialized our editor yet.
  if (IsSelectionCached()) {
  if (IsSelectionCached()) {
    const SelectionProperties& props = GetSelectionProperties();
    *aSelectionStart = props.GetStart();
    *aSelectionEnd = props.GetEnd();
    return;
  }
  }

  Selection* sel = mSelCon->GetSelection(SelectionType::eNormal);
  if (NS_WARN_IF(!sel)) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
    return;
  }

  Element* root = GetRootNode();

  if (NS_WARN_IF(!root)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
  nsContentUtils::GetSelectionInTextControl(sel, root, *aSelectionStart,
                                            *aSelectionEnd);
                                            *aSelectionEnd);
}

nsITextControlFrame::SelectionDirection TextControlState::GetSelectionDirection(
    ErrorResult& aRv) {
  MOZ_ASSERT(IsSelectionCached() || GetSelectionController(),
  MOZ_ASSERT(IsSelectionCached() || GetSelectionController(),
             "How can we not have a cached selection if we have no selection "
             "controller?");

  // Note that we may have both IsSelectionCached() _and_
  // GetSelectionController() if we haven't initialized our editor yet.
  if (IsSelectionCached()) {
  // GetSelectionController() if we haven't initialized our editor yet.
    return GetSelectionProperties().GetDirection();
  }

  Selection* sel = mSelCon->GetSelection(SelectionType::eNormal);
  if (NS_WARN_IF(!sel)) {
  Selection* sel = mSelCon->GetSelection(SelectionType::eNormal);
    aRv.Throw(NS_ERROR_FAILURE);
    return nsITextControlFrame::eForward;  // Doesn't really matter
  }

  nsDirection direction = sel->GetDirection();

  if (direction == eDirNext) {
    return nsITextControlFrame::eForward;
  }

  MOZ_ASSERT(direction == eDirPrevious);

  return nsITextControlFrame::eBackward;
}

void TextControlState::SetSelectionRange(
    uint32_t aStart, uint32_t aEnd,
void TextControlState::SetSelectionRange(
    nsITextControlFrame::SelectionDirection aDirection, ErrorResult& aRv) {
  MOZ_ASSERT(IsSelectionCached() || mBoundFrame,
             "How can we have a non-cached selection but no frame?");

  AutoTextControlHandlingState handlingSetSelectionRange(

      *this, TextControlAction::SetSelectionRange);

  if (aStart > aEnd) {
    aStart = aEnd;
  }
    aStart = aEnd;

  bool changed = false;
  nsresult rv = NS_OK;  // For the ScrollSelectionIntoView() return value.
  if (IsSelectionCached()) {
    nsAutoString value;
    // XXXbz is "false" the right thing to pass here?  Hard to tell, given the
    nsAutoString value;
    // various mismatches between our impl and the spec.
    GetValue(value, false);
    uint32_t length = value.Length();
    if (aStart > length) {
      aStart = length;
    if (aStart > length) {
    }
    if (aEnd > length) {
      aEnd = length;
    }
    SelectionProperties& props = GetSelectionProperties();
    }
    changed = props.GetStart() != aStart || props.GetEnd() != aEnd ||
              props.GetDirection() != aDirection;
    props.SetStart(aStart);
    props.SetEnd(aEnd);
    props.SetDirection(aDirection);
    props.SetEnd(aEnd);
  } else {
    MOZ_ASSERT(mBoundFrame, "Our frame should still be valid");
    aRv = mBoundFrame->SetSelectionRange(aStart, aEnd, aDirection);
    if (aRv.Failed() ||
        handlingSetSelectionRange.IsTextControlStateDestroyed()) {
    if (aRv.Failed() ||
      return;
    }
    if (mBoundFrame) {
      mBoundFrame->ScrollSelectionIntoViewAsync();
    }
      mBoundFrame->ScrollSelectionIntoViewAsync();
    // Press on to firing the event even if that failed, like our old code did.
    // But is that really what we want?  Firing the event _and_ throwing from
    // here is weird.  Maybe we should just ignore ScrollSelectionIntoView
    // But is that really what we want?  Firing the event _and_ throwing from
    // failures?

    // XXXbz This is preserving our current behavior of firing a "select" event
    // on all mutations when we have an editor, but we should really consider
    // fixing that...
    // on all mutations when we have an editor, but we should really consider
    changed = true;
  }

  if (changed) {
    // It sure would be nice if we had an existing Element* or so to work with.
  if (changed) {
    RefPtr<AsyncEventDispatcher> asyncDispatcher =
        new AsyncEventDispatcher(mTextCtrlElement, NS_LITERAL_STRING("select"),
                                 CanBubble::eYes, ChromeOnlyDispatch::eNo);
    asyncDispatcher->PostDOMEvent();
  }
    asyncDispatcher->PostDOMEvent();

  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
  }
}
  }

void TextControlState::SetSelectionStart(const Nullable<uint32_t>& aStart,
                                         ErrorResult& aRv) {
  uint32_t start = 0;
  if (!aStart.IsNull()) {
    start = aStart.Value();
  }


  uint32_t ignored, end;
  GetSelectionRange(&ignored, &end, aRv);
  if (aRv.Failed()) {
    return;
  }

  nsITextControlFrame::SelectionDirection dir = GetSelectionDirection(aRv);
  if (aRv.Failed()) {
  nsITextControlFrame::SelectionDirection dir = GetSelectionDirection(aRv);
    return;
  }

  if (end < start) {
    end = start;
  if (end < start) {
  }

  SetSelectionRange(start, end, dir, aRv);
  // The instance may have already been deleted here.
}
  // The instance may have already been deleted here.

void TextControlState::SetSelectionEnd(const Nullable<uint32_t>& aEnd,
                                       ErrorResult& aRv) {
  uint32_t end = 0;
  if (!aEnd.IsNull()) {
  uint32_t end = 0;
    end = aEnd.Value();
  }

  uint32_t start, ignored;

  GetSelectionRange(&start, &ignored, aRv);
  if (aRv.Failed()) {
    return;
  }

  }
  nsITextControlFrame::SelectionDirection dir = GetSelectionDirection(aRv);
  if (aRv.Failed()) {
    return;
  }
  }

  SetSelectionRange(start, end, dir, aRv);
  // The instance may have already been deleted here.
}


static void DirectionToName(nsITextControlFrame::SelectionDirection dir,
                            nsAString& aDirection) {
  switch (dir) {
    case nsITextControlFrame::eNone:
      // TODO(mbrodesser): this should be supported, see
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1541454.
      NS_WARNING("We don't actually support this... how did we get it?");
      aDirection.AssignLiteral("none");
      NS_WARNING("We don't actually support this... how did we get it?");
      break;
    case nsITextControlFrame::eForward:
      aDirection.AssignLiteral("forward");
      break;
    case nsITextControlFrame::eBackward:
      aDirection.AssignLiteral("backward");
    case nsITextControlFrame::eBackward:
      break;
    default:
      MOZ_ASSERT_UNREACHABLE("Invalid SelectionDirection value");
      MOZ_ASSERT_UNREACHABLE("Invalid SelectionDirection value");
  }
}

void TextControlState::GetSelectionDirectionString(nsAString& aDirection,
                                                   ErrorResult& aRv) {
                                                   ErrorResult& aRv) {
  nsITextControlFrame::SelectionDirection dir = GetSelectionDirection(aRv);
  if (aRv.Failed()) {
    return;
  }
  DirectionToName(dir, aDirection);
  DirectionToName(dir, aDirection);
}

static nsITextControlFrame::SelectionDirection
DirectionStringToSelectionDirection(const nsAString& aDirection) {
  if (aDirection.EqualsLiteral("backward")) {
  if (aDirection.EqualsLiteral("backward")) {
    return nsITextControlFrame::eBackward;
  }

  // We don't support directionless selections.
  return nsITextControlFrame::eForward;
  return nsITextControlFrame::eForward;
}

void TextControlState::SetSelectionDirection(const nsAString& aDirection,
                                             ErrorResult& aRv) {
  nsITextControlFrame::SelectionDirection dir =
  nsITextControlFrame::SelectionDirection dir =
      DirectionStringToSelectionDirection(aDirection);

  if (IsSelectionCached()) {
    GetSelectionProperties().SetDirection(dir);
    return;
    return;
  }

  uint32_t start, end;
  GetSelectionRange(&start, &end, aRv);
  if (aRv.Failed()) {
    return;
  if (aRv.Failed()) {
  }

  SetSelectionRange(start, end, dir, aRv);
  // The instance may have already been deleted here.
}


static nsITextControlFrame::SelectionDirection
DirectionStringToSelectionDirection(const Optional<nsAString>& aDirection) {
  if (!aDirection.WasPassed()) {
    // We don't support directionless selections.
    return nsITextControlFrame::eForward;
  }

  return DirectionStringToSelectionDirection(aDirection.Value());

}

void TextControlState::SetSelectionRange(uint32_t aSelectionStart,
                                         uint32_t aSelectionEnd,
                                         const Optional<nsAString>& aDirection,
                                         uint32_t aSelectionEnd,
                                         ErrorResult& aRv) {
  nsITextControlFrame::SelectionDirection dir =
      DirectionStringToSelectionDirection(aDirection);

  SetSelectionRange(aSelectionStart, aSelectionEnd, dir, aRv);
  // The instance may have already been deleted here.
  // The instance may have already been deleted here.
}

void TextControlState::SetRangeText(const nsAString& aReplacement,
                                    ErrorResult& aRv) {
  uint32_t start, end;
  uint32_t start, end;
  GetSelectionRange(&start, &end, aRv);
  if (aRv.Failed()) {
    return;
  }


  SetRangeText(aReplacement, start, end, SelectionMode::Preserve, aRv,
               Some(start), Some(end));
  // The instance may have already been deleted here.
  // The instance may have already been deleted here.
}

void TextControlState::SetRangeText(const nsAString& aReplacement,
                                    uint32_t aStart, uint32_t aEnd,
                                    SelectionMode aSelectMode, ErrorResult& aRv,
                                    SelectionMode aSelectMode, ErrorResult& aRv,
                                    const Maybe<uint32_t>& aSelectionStart,
                                    const Maybe<uint32_t>& aSelectionEnd) {
  if (aStart > aEnd) {
    aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
    return;
    return;
  }

  AutoTextControlHandlingState handlingSetRangeText(
      *this, TextControlAction::SetRangeText);


  nsAutoString value;
  mTextCtrlElement->GetValueFromSetRangeText(value);
  uint32_t inputValueLength = value.Length();

  if (aStart > inputValueLength) {
  if (aStart > inputValueLength) {
    aStart = inputValueLength;
  }

  if (aEnd > inputValueLength) {
    aEnd = inputValueLength;
  }

  uint32_t selectionStart, selectionEnd;
  if (!aSelectionStart) {
  uint32_t selectionStart, selectionEnd;
    MOZ_ASSERT(!aSelectionEnd);
    GetSelectionRange(&selectionStart, &selectionEnd, aRv);
    if (aRv.Failed()) {
      return;
    }
      return;
  } else {
    MOZ_ASSERT(aSelectionEnd);
    selectionStart = *aSelectionStart;
    selectionEnd = *aSelectionEnd;
  }
    selectionEnd = *aSelectionEnd;

  MOZ_ASSERT(aStart <= aEnd);
  value.Replace(aStart, aEnd - aStart, aReplacement);
  nsresult rv =
      MOZ_KnownLive(mTextCtrlElement)->SetValueFromSetRangeText(value);
  nsresult rv =
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
    return;
    return;
  }

  uint32_t newEnd = aStart + aReplacement.Length();
  int32_t delta = aReplacement.Length() - (aEnd - aStart);

  switch (aSelectMode) {
    case SelectionMode::Select:
      selectionStart = aStart;
      selectionStart = aStart;
      selectionEnd = newEnd;
      break;
    case SelectionMode::Start:
      selectionStart = selectionEnd = aStart;
      selectionStart = selectionEnd = aStart;
      break;
    case SelectionMode::End:
      selectionStart = selectionEnd = newEnd;
      break;
    case SelectionMode::Preserve:
    case SelectionMode::Preserve:
      if (selectionStart > aEnd) {
        selectionStart += delta;
      } else if (selectionStart > aStart) {
        selectionStart = aStart;
      }
      }

      if (selectionEnd > aEnd) {
        selectionEnd += delta;
      } else if (selectionEnd > aStart) {
        selectionEnd = newEnd;
        selectionEnd = newEnd;
      }
      break;
    default:
      MOZ_ASSERT_UNREACHABLE("Unknown mode!");
  }


  SetSelectionRange(selectionStart, selectionEnd, Optional<nsAString>(), aRv);
  // The instance may have already been deleted here.
}

void TextControlState::DestroyEditor() {
void TextControlState::DestroyEditor() {
  // notify the editor that we are going away
  if (mEditorInitialized) {
    // FYI: TextEditor checks whether it's destroyed or not immediately after
    //      changes the DOM tree or selection so that it's safe to call
    //      PreDestroy() here even while we're handling actions with
    //      PreDestroy() here even while we're handling actions with
    //      mTextEditor.
    RefPtr<TextEditor> textEditor = mTextEditor;
    textEditor->PreDestroy(true);
    mEditorInitialized = false;
  }
  }
}

void TextControlState::UnbindFromFrame(nsTextControlFrame* aFrame) {
  if (NS_WARN_IF(!mBoundFrame)) {
    return;
    return;
  }

  // If it was, however, it should be unbounded from the same frame.
  MOZ_ASSERT(aFrame == mBoundFrame, "Unbinding from the wrong frame");
  if (aFrame && aFrame != mBoundFrame) {
    return;
  }
  }

  AutoTextControlHandlingState handlingUnbindFromFrame(
      *this, TextControlAction::UnbindFromFrame);

  if (mSelCon) {
  if (mSelCon) {
    mSelCon->SelectionWillLoseFocus();
  }

  // We need to start storing the value outside of the editor if we're not
  // going to use it anymore, so retrieve it for now.
  // going to use it anymore, so retrieve it for now.
  nsAutoString value;
  GetValue(value, true);

  if (mRestoringSelection) {
    mRestoringSelection->Revoke();
    mRestoringSelection->Revoke();
    mRestoringSelection = nullptr;
  }

  // Save our selection state if needed.

  // Save our selection state if needed.
  // Note that GetSelectionRange will attempt to work with our selection
  // controller, so we should make sure we do it before we start doing things
  // like destroying our editor (if we have one), tearing down the selection
  // like destroying our editor (if we have one), tearing down the selection
  // controller, and so forth.
  if (!IsSelectionCached()) {
    // Go ahead and cache it now.
    uint32_t start = 0, end = 0;
    // Go ahead and cache it now.
    GetSelectionRange(&start, &end, IgnoreErrors());

    nsITextControlFrame::SelectionDirection direction =
        GetSelectionDirection(IgnoreErrors());

        GetSelectionDirection(IgnoreErrors());
    SelectionProperties& props = GetSelectionProperties();
    props.SetStart(start);
    props.SetEnd(end);
    props.SetEnd(end);
    props.SetDirection(direction);
    mSelectionCached = true;
  }

  // Destroy our editor
  // Destroy our editor
  DestroyEditor();

  // Clean up the controller
  if (!SuppressEventHandlers(mBoundFrame->PresContext())) {
    nsCOMPtr<nsIControllers> controllers;
    nsCOMPtr<nsIControllers> controllers;
    if (HTMLInputElement* inputElement =
            HTMLInputElement::FromNodeOrNull(mTextCtrlElement)) {
      inputElement->GetControllers(getter_AddRefs(controllers));
    } else {
      HTMLTextAreaElement* textAreaElement =
      HTMLTextAreaElement* textAreaElement =
          HTMLTextAreaElement::FromNodeOrNull(mTextCtrlElement);
      if (textAreaElement) {
        textAreaElement->GetControllers(getter_AddRefs(controllers));
      }
    }
    }

    if (controllers) {
      uint32_t numControllers;
      nsresult rv = controllers->GetControllerCount(&numControllers);
      NS_ASSERTION((NS_SUCCEEDED(rv)),
      NS_ASSERTION((NS_SUCCEEDED(rv)),
                   "bad result in gfx text control destructor");
      for (uint32_t i = 0; i < numControllers; i++) {
        nsCOMPtr<nsIController> controller;
        rv = controllers->GetControllerAt(i, getter_AddRefs(controller));
        if (NS_SUCCEEDED(rv) && controller) {
        if (NS_SUCCEEDED(rv) && controller) {
          nsCOMPtr<nsIControllerContext> editController =
              do_QueryInterface(controller);
          if (editController) {
            editController->SetCommandContext(nullptr);
          }
          }
        }
      }
    }
  }


  if (mSelCon) {
    if (mTextListener) {
      mTextListener->EndListeningToSelectionChange();
    }

    mSelCon->SetScrollableFrame(nullptr);
    mSelCon->SetScrollableFrame(nullptr);
    mSelCon = nullptr;
  }

  if (mTextListener) {
    mTextListener->SetFrame(nullptr);

    mTextListener->SetFrame(nullptr);
    EventListenerManager* manager =
        mTextCtrlElement->GetExistingListenerManager();
    if (manager) {
      manager->RemoveEventListenerByType(mTextListener,
                                         NS_LITERAL_STRING("keydown"),
      manager->RemoveEventListenerByType(mTextListener,
                                         TrustedEventsAtSystemGroupBubble());
      manager->RemoveEventListenerByType(mTextListener,
                                         NS_LITERAL_STRING("keypress"),
                                         TrustedEventsAtSystemGroupBubble());
      manager->RemoveEventListenerByType(mTextListener,
                                         TrustedEventsAtSystemGroupBubble());
                                         NS_LITERAL_STRING("keyup"),
                                         TrustedEventsAtSystemGroupBubble());
    }

    mTextListener = nullptr;

  }

  mBoundFrame = nullptr;

  // Now that we don't have a frame any more, store the value in the text
  // buffer. The only case where we don't do this is if a value transfer is in
  // progress.
  // progress.
  if (!mValueTransferInProgress) {
    DebugOnly<bool> ok = SetValue(value, eSetValue_Internal);
    // TODO Find something better to do if this fails...
    NS_WARNING_ASSERTION(ok, "SetValue() couldn't allocate memory");
  }
  }
}

void TextControlState::GetValue(nsAString& aValue, bool aIgnoreWrap) const {
  // While SetValue() is being called and requesting to commit composition to
  // IME, GetValue() may be called for appending text or something.  Then, we
  // IME, GetValue() may be called for appending text or something.  Then, we
  // need to return the latest aValue of SetValue() since the value hasn't
  // been set to the editor yet.
  // XXX After implementing "beforeinput" event, this becomes wrong.  The
  //     value should be modified immediately after "beforeinput" event for
  //     "insertReplacementText".
  //     "insertReplacementText".
  if (mHandlingState &&
      mHandlingState->IsHandling(TextControlAction::CommitComposition)) {
    aValue = mHandlingState->GetSettingValue();
    MOZ_ASSERT(aValue.FindChar(static_cast<char16_t>('\r')) == -1);
    MOZ_ASSERT(aValue.FindChar(static_cast<char16_t>('\r')) == -1);
    return;
  }

  if (mTextEditor && mBoundFrame &&
      (mEditorInitialized || !IsSingleLineTextControl())) {
      (mEditorInitialized || !IsSingleLineTextControl())) {
    if (aIgnoreWrap && !mBoundFrame->CachedValue().IsVoid()) {
      aValue = mBoundFrame->CachedValue();
      MOZ_ASSERT(aValue.FindChar(static_cast<char16_t>('\r')) == -1);
      return;
    }
    }

    aValue.Truncate();  // initialize out param

    uint32_t flags = (nsIDocumentEncoder::OutputLFLineBreak |
                      nsIDocumentEncoder::OutputPreformatted |
                      nsIDocumentEncoder::OutputPreformatted |
                      nsIDocumentEncoder::OutputPersistNBSP |
                      nsIDocumentEncoder::OutputBodyOnly);
    if (!aIgnoreWrap) {
      TextControlElement::nsHTMLTextWrap wrapProp;
      if (mTextCtrlElement &&
          TextControlElement::GetWrapPropertyEnum(mTextCtrlElement, wrapProp) &&
      if (mTextCtrlElement &&
          wrapProp == TextControlElement::eHTMLTextWrap_Hard) {
        flags |= nsIDocumentEncoder::OutputWrap;
      }
    }

    }
    // What follows is a bit of a hack.  The problem is that we could be in
    // this method because we're being destroyed for whatever reason while
    // this method because we're being destroyed for whatever reason while
    // script is executing.  If that happens, editor will run with the
    // privileges of the executing script, which means it may not be able to
    // access its own DOM nodes!  Let's try to deal with that by pushing a null
    // JSContext on the JSContext stack to make it clear that we're native
    // code.  Note that any script that's directly trying to access our value
    // code.  Note that any script that's directly trying to access our value
    // has to be going through some scriptable object to do that and that
    // already does the relevant security checks.
    // XXXbz if we could just get the textContent of our anonymous content (eg
    // if plaintext editor didn't create <br> nodes all over), we wouldn't need
    // this.
    // this.
    { /* Scope for AutoNoJSAPI. */
      AutoNoJSAPI nojsapi;

      DebugOnly<nsresult> rv = mTextEditor->ComputeTextValue(flags, aValue);
      MOZ_ASSERT(aValue.FindChar(static_cast<char16_t>('\r')) == -1);
      NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to get value");
    }
    // Only when the result doesn't include line breaks caused by hard-wrap,
    }
    // mCacheValue should cache the value.
    if (!(flags & nsIDocumentEncoder::OutputWrap)) {
      mBoundFrame->CacheValue(aValue);
    } else {
      mBoundFrame->ClearCachedValue();
    } else {
    }
  } else {
    if (!mTextCtrlElement->ValueChanged() || !mValue) {
    if (!mTextCtrlElement->ValueChanged() || !mValue) {
      // Use nsString to avoid copying string buffer at setting aValue.
      nsString value;
      mTextCtrlElement->GetDefaultValueFromContent(value);
      // TODO: We should make default value not include \r.
      nsContentUtils::PlatformToDOMLineBreaks(value);
      nsContentUtils::PlatformToDOMLineBreaks(value);
      aValue = value;
    } else {
      aValue = *mValue;
      MOZ_ASSERT(aValue.FindChar(static_cast<char16_t>('\r')) == -1);
    }
  }
    }
}

bool TextControlState::ValueEquals(const nsAString& aValue) const {
  // We can avoid copying string buffer in many cases.  Therefore, we should
  // use nsString rather than nsAutoString here.
  // We can avoid copying string buffer in many cases.  Therefore, we should
  nsString value;
  GetValue(value, true);
  return aValue.Equals(value);
  return aValue.Equals(value);
}

#ifdef DEBUG
// @param aFlags TextControlState::SetValueFlags
bool AreFlagsNotDemandingContradictingMovements(uint32_t aFlags) {
  return !(
      !!(aFlags &
      !!(aFlags &
         TextControlState::
             eSetValue_MoveCursorToBeginSetSelectionDirectionForward) &&
      !!(aFlags & TextControlState::eSetValue_MoveCursorToEndIfValueChanged));
}
#endif  // DEBUG
#endif  // DEBUG

bool TextControlState::SetValue(const nsAString& aValue,
                                const nsAString* aOldValue, uint32_t aFlags) {
  if (mHandlingState &&
      mHandlingState->IsHandling(TextControlAction::CommitComposition)) {
      mHandlingState->IsHandling(TextControlAction::CommitComposition)) {
    // GetValue doesn't return current text frame's content during committing.
    // So we cannot trust this old value
    aOldValue = nullptr;
  }
    aOldValue = nullptr;

  ErrorResult error;
  AutoTextControlHandlingState handlingSetValue(
      *this, TextControlAction::SetValue, aValue, aOldValue, aFlags, error);
  if (error.Failed()) {
      *this, TextControlAction::SetValue, aValue, aOldValue, aFlags, error);
    MOZ_ASSERT(error.ErrorCodeIs(NS_ERROR_OUT_OF_MEMORY));
    error.SuppressException();
    return false;
  }

  // Note that if this may be called during reframe of the editor.  In such
  // case, we shouldn't commit composition.  Therefore, when this is called
  // for internal processing, we shouldn't commit the composition.
  // TODO: In strictly speaking, we should move committing composition into
  // TODO: In strictly speaking, we should move committing composition into
  //       editor because if "beforeinput" for this setting value is canceled,
  //       we shouldn't commit composition.  However, in Firefox, we never
  //       call this via `setUserInput` during composition.  Therefore, the
  //       bug must not be reproducible actually.
  if (aFlags & (eSetValue_BySetUserInput | eSetValue_ByContent)) {
  if (aFlags & (eSetValue_BySetUserInput | eSetValue_ByContent)) {
    if (EditorHasComposition()) {
      // When this is called recursively, there shouldn't be composition.
      if (handlingSetValue.IsHandling(TextControlAction::CommitComposition)) {
        // Don't request to commit composition again.  But if it occurs,
        // we should skip to set the new value to the editor here.  It should
        // we should skip to set the new value to the editor here.  It should
        // be set later with the newest value.
        return true;
      }
      if (NS_WARN_IF(!mBoundFrame)) {
        // We're not sure if this case is possible.
        // We're not sure if this case is possible.
      } else {
        // If setting value won't change current value, we shouldn't commit
        // composition for compatibility with the other browsers.
        MOZ_ASSERT(!aOldValue || mBoundFrame->TextEquals(*aOldValue));
        bool isSameAsCurrentValue =
            aOldValue
                ? aOldValue->Equals(handlingSetValue.GetSettingValue())
                : mBoundFrame->TextEquals(handlingSetValue.GetSettingValue());
        if (isSameAsCurrentValue) {
          // Note that in this case, we shouldn't fire any events with setting
          // value because event handlers may try to set value recursively but
          // value because event handlers may try to set value recursively but
          // we cannot commit composition at that time due to unsafe to run
          // script (see below).
          return true;
        }
      }
      }
      // If there is composition, need to commit composition first because
      // other browsers do that.
      // NOTE: We don't need to block nested calls of this because input nor
      //       other events won't be fired by setting values and script blocker
      //       is used during setting the value to the editor.  IE also allows
      //       is used during setting the value to the editor.  IE also allows
      //       to set the editor value on the input event which is caused by
      //       forcibly committing composition.
      AutoTextControlHandlingState handlingCommitComposition(
          *this, TextControlAction::CommitComposition);
      if (nsContentUtils::IsSafeToRunScript()) {
      if (nsContentUtils::IsSafeToRunScript()) {
        // WARNING: During this call, compositionupdate, compositionend, input
        // events will be fired.  Therefore, everything can occur.  E.g., the
        // document may be unloaded.
        RefPtr<TextEditor> textEditor = mTextEditor;
        nsresult rv = textEditor->CommitComposition();
        if (handlingCommitComposition.IsTextControlStateDestroyed()) {
        if (handlingCommitComposition.IsTextControlStateDestroyed()) {
          return true;
        }
        if (NS_FAILED(rv)) {
          NS_WARNING("TextControlState failed to commit composition");
          return true;
          return true;
        }
        // Note that if a composition event listener sets editor value again,
        // we should use the new value here.  The new value is stored in
        // handlingSetValue right now.
      } else {
        // handlingSetValue right now.
        NS_WARNING(
            "SetValue() is called when there is composition but "
            "it's not safe to request to commit the composition");
      }
      }
    }
  }

  if (mTextEditor && mBoundFrame) {
    AutoWeakFrame weakFrame(mBoundFrame);
    AutoWeakFrame weakFrame(mBoundFrame);

    if (!SetValueWithTextEditor(handlingSetValue)) {
      return false;
      return false;
    }

    if (!weakFrame.IsAlive()) {
      return true;
    }
  } else if (!SetValueWithoutTextEditor(handlingSetValue)) {
    }
    return false;
  }

  // TODO(emilio): It seems wrong to pass ValueChangeKind::Script if
  // TODO(emilio): It seems wrong to pass ValueChangeKind::Script if
  // BySetUserInput is in aFlags.
  auto changeKind = (aFlags & eSetValue_Internal) ? ValueChangeKind::Internal
                                                  : ValueChangeKind::Script;

  handlingSetValue.GetTextControlElement()->OnValueChanged(changeKind);
  handlingSetValue.GetTextControlElement()->OnValueChanged(changeKind);
  return true;
}

bool TextControlState::SetValueWithTextEditor(
    AutoTextControlHandlingState& aHandlingSetValue) {
bool TextControlState::SetValueWithTextEditor(
  MOZ_ASSERT(aHandlingSetValue.Is(TextControlAction::SetValue));
  MOZ_ASSERT(mTextEditor);
  MOZ_ASSERT(mBoundFrame);
  NS_WARNING_ASSERTION(!EditorHasComposition(),
                       "Failed to commit composition before setting value.  "
  NS_WARNING_ASSERTION(!EditorHasComposition(),
                       "Investigate the cause!");

#ifdef DEBUG
  if (IsSingleLineTextControl()) {
    NS_ASSERTION(mEditorInitialized || aHandlingSetValue.IsHandling(
  if (IsSingleLineTextControl()) {
                                           TextControlAction::PrepareEditor),
                 "We should never try to use the editor if we're not "
                 "initialized unless we're being initialized");
  }
#endif
  }

  MOZ_ASSERT(!aHandlingSetValue.GetOldValue() ||
             mBoundFrame->TextEquals(*aHandlingSetValue.GetOldValue()));
  bool isSameAsCurrentValue =
      aHandlingSetValue.GetOldValue()
  bool isSameAsCurrentValue =
          ? aHandlingSetValue.GetOldValue()->Equals(
                aHandlingSetValue.GetSettingValue())
          : mBoundFrame->TextEquals(aHandlingSetValue.GetSettingValue());

  // this is necessary to avoid infinite recursion

  if (isSameAsCurrentValue) {
    return true;
  }

  RefPtr<TextEditor> textEditor = mTextEditor;


  nsCOMPtr<Document> document = textEditor->GetDocument();
  if (NS_WARN_IF(!document)) {
    return true;
  }

  // Time to mess with our security context... See comments in GetValue()

  // for why this is needed.  Note that we have to do this up here, because
  // otherwise SelectAll() will fail.
  AutoNoJSAPI nojsapi;

  // FYI: It's safe to use raw pointer for selection here because

  //      SelectionBatcher will grab it with RefPtr.
  Selection* selection = mSelCon->GetSelection(SelectionType::eNormal);
  SelectionBatcher selectionBatcher(selection);

  // get the flags, remove readonly, disabled and max-length,
  // set the value, restore flags
  // set the value, restore flags
  AutoRestoreEditorState restoreState(textEditor);

  aHandlingSetValue.WillSetValueWithTextEditor();

  if (aHandlingSetValue.GetSetValueFlags() & eSetValue_BySetUserInput) {
  if (aHandlingSetValue.GetSetValueFlags() & eSetValue_BySetUserInput) {
    // If the caller inserts text as part of user input, for example,
    // autocomplete, we need to replace the text as "insert string"
    // because undo should cancel only this operation (i.e., previous
    // transactions typed by user shouldn't be merged with this).
    // In this case, we need to dispatch "input" event because
    // web apps may need to know the user's operation.
    // In this case, we need to dispatch "beforeinput" events since
    // we're emulating the user's input.  Passing nullptr as
    // we're emulating the user's input.  Passing nullptr as
    // nsIPrincipal means that that may be user's input.  So, let's
    // do it.
    nsresult rv = textEditor->ReplaceTextAsAction(
        aHandlingSetValue.GetSettingValue(), nullptr, nullptr);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                         "TextEditor::ReplaceTextAsAction() failed");
    return rv != NS_ERROR_OUT_OF_MEMORY;
    return rv != NS_ERROR_OUT_OF_MEMORY;
  }

  // Don't dispatch "beforeinput" event nor "input" event for setting value
  // by script.
  AutoInputEventSuppresser suppressInputEventDispatching(textEditor);
  AutoInputEventSuppresser suppressInputEventDispatching(textEditor);

  if (aHandlingSetValue.GetSetValueFlags() & eSetValue_ForXUL) {
    // On XUL <textbox> element, we need to preserve existing undo
    // transactions.
    // XXX Do we really need to do such complicated optimization?
    // XXX Do we really need to do such complicated optimization?
    //     This was landed for web pages which set <textarea> value
    //     per line (bug 518122).  For example:
    //       for (;;) {
    //         textarea.value += oneLineText + "\n";
    //       }
    //     However, this path won't be used in web content anymore.
    //     However, this path won't be used in web content anymore.
    nsCOMPtr<nsISelectionController> kungFuDeathGrip = mSelCon.get();
    // Use nsString to avoid copying string buffer in most cases.
    nsString currentValue;
    if (aHandlingSetValue.GetOldValue()) {
      currentValue.Assign(*aHandlingSetValue.GetOldValue());
    } else {
      currentValue.Assign(*aHandlingSetValue.GetOldValue());
      mBoundFrame->GetText(currentValue);
    }
    uint32_t currentLength = currentValue.Length();
    uint32_t newlength = aHandlingSetValue.GetSettingValue().Length();
    if (!currentLength ||
    uint32_t newlength = aHandlingSetValue.GetSettingValue().Length();
        !StringBeginsWith(aHandlingSetValue.GetSettingValue(), currentValue)) {
      // Replace the whole text.
      currentLength = 0;
      kungFuDeathGrip->SelectAll();
    } else {
      kungFuDeathGrip->SelectAll();
      // Collapse selection to the end so that we can append data.
      mBoundFrame->SelectAllOrCollapseToEndOfText(false);
    }
    const nsAString& insertValue = StringTail(
        aHandlingSetValue.GetSettingValue(), newlength - currentLength);
    const nsAString& insertValue = StringTail(

    if (insertValue.IsEmpty()) {
      // In this case, we makes the editor stop dispatching "input"
      // event so that passing nullptr as nsIPrincipal is safe for
      // In this case, we makes the editor stop dispatching "input"
      // now.
      nsresult rv = textEditor->DeleteSelectionAsAction(
          nsIEditor::eNone, nsIEditor::eNoStrip, nullptr);
      NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                           "TextEditor::DeleteSelectionAsAction() failed");
      NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
      return rv != NS_ERROR_OUT_OF_MEMORY;
    }
    // In this case, we makes the editor stop dispatching "input"
    // event so that passing nullptr as nsIPrincipal is safe for
    // now.
    // event so that passing nullptr as nsIPrincipal is safe for
    nsresult rv = textEditor->InsertTextAsAction(insertValue, nullptr);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                         "TextEditor::InsertTextAsAction() failed");
    return rv != NS_ERROR_OUT_OF_MEMORY;
  }
    return rv != NS_ERROR_OUT_OF_MEMORY;

  // On <input> or <textarea>, we shouldn't preserve existing undo
  // transactions because other browsers do not preserve them too
  // and not preserving transactions makes setting value faster.
  AutoDisableUndo disableUndo(textEditor);
  // and not preserving transactions makes setting value faster.
  if (selection) {
    // Since we don't use undo transaction, we don't need to store
    // selection state.  SetText will set selection to tail.
    IgnoredErrorResult ignoredError;
    selection->RemoveAllRanges(ignoredError);
    NS_WARNING_ASSERTION(!ignoredError.Failed(),
                         "Selection::RemoveAllRanges() failed, but ignored");
  }
                         "Selection::RemoveAllRanges() failed, but ignored");

  // In this case, we makes the editor stop dispatching "input"
  // event so that passing nullptr as nsIPrincipal is safe for now.
  nsresult rv =
  nsresult rv =
      textEditor->SetTextAsAction(aHandlingSetValue.GetSettingValue(), nullptr);
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                       "TextEditor::SetTextAsAction() failed");

  // Call the listener's OnEditActionHandled() callback manually if
  // Call the listener's OnEditActionHandled() callback manually if
  // OnEditActionHandled() hasn't been called yet since TextEditor don't use
  // the transaction manager in this path and it could be that the editor
  // would bypass calling the listener for that reason.
  if (!aHandlingSetValue.HasEditActionHandled()) {
    nsresult rvOnEditActionHandled =
  if (!aHandlingSetValue.HasEditActionHandled()) {
        MOZ_KnownLive(aHandlingSetValue.GetTextInputListener())
            ->OnEditActionHandled(*textEditor);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rvOnEditActionHandled),
                         "TextInputListener::OnEditActionHandled() failed");
    if (rv != NS_ERROR_OUT_OF_MEMORY) {
                         "TextInputListener::OnEditActionHandled() failed");
      rv = rvOnEditActionHandled;
    }
      rv = rvOnEditActionHandled;
  }

  return rv != NS_ERROR_OUT_OF_MEMORY;
}

}
bool TextControlState::SetValueWithoutTextEditor(
    AutoTextControlHandlingState& aHandlingSetValue) {
  MOZ_ASSERT(aHandlingSetValue.Is(TextControlAction::SetValue));
  MOZ_ASSERT(!mTextEditor || !mBoundFrame);
  NS_WARNING_ASSERTION(!EditorHasComposition(),
  MOZ_ASSERT(!mTextEditor || !mBoundFrame);
                       "Failed to commit composition before setting value.  "
                       "Investigate the cause!");

  if (!mValue) {
    mValue.emplace();
  if (!mValue) {
  }

  // We can't just early-return here, because ValueWasChanged and
  // OnValueChanged below still need to be called.
  if (!mValue->Equals(aHandlingSetValue.GetSettingValue()) ||
  // OnValueChanged below still need to be called.
      !StaticPrefs::dom_input_skip_cursor_move_for_same_value_set()) {
    bool handleSettingValue = true;
    // If `SetValue()` call is nested, `GetSettingValue()` result will be
    // modified.  So, we need to store input event data value before
    // dispatching beforeinput event.
    // modified.  So, we need to store input event data value before
    nsString inputEventData(aHandlingSetValue.GetSettingValue());
    if ((aHandlingSetValue.GetSetValueFlags() & eSetValue_BySetUserInput) &&
        StaticPrefs::dom_input_events_beforeinput_enabled() &&
        !aHandlingSetValue.HasBeforeInputEventDispatched()) {
        StaticPrefs::dom_input_events_beforeinput_enabled() &&
      // This probably occurs when session restorer sets the old value with
      // `setUserInput`.  If so, we need to dispatch "beforeinput" event of
      // "insertReplacementText" for conforming to the spec.  However, the
      // spec does NOT treat the session restoring case.  Therefore, if this
      // spec does NOT treat the session restoring case.  Therefore, if this
      // breaks session restorere in a lot of web apps, we should probably
      // stop dispatching it or make it non-cancelable.
      MOZ_ASSERT(aHandlingSetValue.GetTextControlElement());
      MOZ_ASSERT(!aHandlingSetValue.GetSettingValue().IsVoid());
      aHandlingSetValue.WillDispatchBeforeInputEvent();
      aHandlingSetValue.WillDispatchBeforeInputEvent();
      nsEventStatus status = nsEventStatus_eIgnore;
      DebugOnly<nsresult> rvIgnored = nsContentUtils::DispatchInputEvent(
          MOZ_KnownLive(aHandlingSetValue.GetTextControlElement()),
          eEditorBeforeInput, EditorInputType::eInsertReplacementText, nullptr,
          InputEventOptions(inputEventData), &status);
      NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
                           "Failed to dispatch beforeinput event");
      if (status == nsEventStatus_eConsumeNoDefault) {
                           "Failed to dispatch beforeinput event");
        return true;  // "beforeinput" event was canceled.
      }
      // If we were destroyed by "beforeinput" event listeners, probably, we
      // don't need to keep handling it.
      if (aHandlingSetValue.IsTextControlStateDestroyed()) {
      // don't need to keep handling it.
        return true;
      }
      // Even if "beforeinput" event was not canceled, its listeners may do
      // something.  If it causes creating `TextEditor` and bind this to a
      // frame, we need to use the path, but `TextEditor` shouldn't fire
      // something.  If it causes creating `TextEditor` and bind this to a
      // "beforeinput" event again.  Therefore, we need to prevent editor
      // to dispatch it.
      if (mTextEditor && mBoundFrame) {
        AutoInputEventSuppresser suppressInputEvent(mTextEditor);
        if (!SetValueWithTextEditor(aHandlingSetValue)) {
        AutoInputEventSuppresser suppressInputEvent(mTextEditor);
          return false;
        }
        // If we were destroyed by "beforeinput" event listeners, probably, we
        // don't need to keep handling it.
        if (aHandlingSetValue.IsTextControlStateDestroyed()) {
        // don't need to keep handling it.
          return true;
        }
        handleSettingValue = false;
      }
    }
      }

    if (handleSettingValue) {
      if (!mValue->Assign(aHandlingSetValue.GetSettingValue(), fallible)) {
        return false;
      }

      // Since we have no editor we presumably have cached selection state.

      if (IsSelectionCached()) {
      if (IsSelectionCached()) {
        MOZ_ASSERT(AreFlagsNotDemandingContradictingMovements(
            aHandlingSetValue.GetSetValueFlags()));

        SelectionProperties& props = GetSelectionProperties();
        if (aHandlingSetValue.GetSetValueFlags() &
        if (aHandlingSetValue.GetSetValueFlags() &
            eSetValue_MoveCursorToEndIfValueChanged) {
          props.SetStart(aHandlingSetValue.GetSettingValue().Length());
          props.SetEnd(aHandlingSetValue.GetSettingValue().Length());
          props.SetDirection(nsITextControlFrame::eForward);
        } else if (aHandlingSetValue.GetSetValueFlags() &
        } else if (aHandlingSetValue.GetSetValueFlags() &
                   eSetValue_MoveCursorToBeginSetSelectionDirectionForward) {
          props.SetStart(0);
          props.SetEnd(0);
          props.SetDirection(nsITextControlFrame::eForward);
          props.SetDirection(nsITextControlFrame::eForward);
        } else {
          // Make sure our cached selection position is not outside the new
          // value.
          props.SetStart(std::min(
              props.GetStart(), aHandlingSetValue.GetSettingValue().Length()));
              props.GetStart(), aHandlingSetValue.GetSettingValue().Length()));
          props.SetEnd(std::min(props.GetEnd(),
                                aHandlingSetValue.GetSettingValue().Length()));
                                aHandlingSetValue.GetSettingValue().Length()));
        }
      }

      // Update the frame display if needed
      if (mBoundFrame) {
      if (mBoundFrame) {
        mBoundFrame->UpdateValueDisplay(true);
      }
    }

    // If this is called as part of user input, we need to dispatch "input"

    // event with "insertReplacementText" since web apps may want to know
    // the user operation which changes editor value with a built-in function
    // like autocomplete, password manager, session restore, etc.
    // XXX Should we stop dispatching `input` event if the text control
    //     element has already removed from the DOM tree by a `beforeinput`
    // XXX Should we stop dispatching `input` event if the text control
    //     event listener?
    if (aHandlingSetValue.GetSetValueFlags() & eSetValue_BySetUserInput) {
      MOZ_ASSERT(aHandlingSetValue.GetTextControlElement());

      // Update validity state before dispatching "input" event for its

      // listeners like `EditorBase::NotifyEditorObservers()`.
      aHandlingSetValue.GetTextControlElement()->OnValueChanged(
          ValueChangeKind::UserInteraction);


      MOZ_ASSERT(!aHandlingSetValue.GetSettingValue().IsVoid());
      DebugOnly<nsresult> rvIgnored = nsContentUtils::DispatchInputEvent(
          MOZ_KnownLive(aHandlingSetValue.GetTextControlElement()),
      DebugOnly<nsresult> rvIgnored = nsContentUtils::DispatchInputEvent(
          eEditorInput, EditorInputType::eInsertReplacementText, nullptr,
          InputEventOptions(inputEventData));
      NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
                           "Failed to dispatch input event");
    }
                           "Failed to dispatch input event");
  } else {
    // Even if our value is not actually changing, apparently we need to mark
    // our SelectionProperties dirty to make accessibility tests happy.
    // Probably because they depend on the SetSelectionRange() call we make on
    // our frame in RestoreSelectionState, but I have no idea why they do.
    // Probably because they depend on the SetSelectionRange() call we make on
    if (IsSelectionCached()) {
      SelectionProperties& props = GetSelectionProperties();
      props.SetIsDirty();
    }
      props.SetIsDirty();
  }

  ValueWasChanged();
  return true;
}
  return true;

bool TextControlState::HasNonEmptyValue() {
  // If the frame for editor is alive, we can compute it with mTextEditor.
  // Otherwise, we need to check cached value via GetValue().
  if (mTextEditor && mBoundFrame && mEditorInitialized &&
  // Otherwise, we need to check cached value via GetValue().
      !(mHandlingState &&
      !(mHandlingState &&
        mHandlingState->IsHandling(TextControlAction::CommitComposition))) {
    return !mTextEditor->IsEmpty();
  }

  nsAutoString value;
  nsAutoString value;
  GetValue(value, true);
  return !value.IsEmpty();
}

void TextControlState::InitializeKeyboardEventListeners() {
void TextControlState::InitializeKeyboardEventListeners() {
  // register key listeners
  EventListenerManager* manager =
      mTextCtrlElement->GetOrCreateListenerManager();
  if (manager) {
    manager->AddEventListenerByType(mTextListener, NS_LITERAL_STRING("keydown"),
    manager->AddEventListenerByType(mTextListener, NS_LITERAL_STRING("keydown"),
                                    TrustedEventsAtSystemGroupBubble());
    manager->AddEventListenerByType(mTextListener,
                                    NS_LITERAL_STRING("keypress"),
                                    TrustedEventsAtSystemGroupBubble());
                                    TrustedEventsAtSystemGroupBubble());
    manager->AddEventListenerByType(mTextListener, NS_LITERAL_STRING("keyup"),
                                    TrustedEventsAtSystemGroupBubble());
  }

  mSelCon->SetScrollableFrame(mBoundFrame->GetScrollTargetFrame());
  mSelCon->SetScrollableFrame(mBoundFrame->GetScrollTargetFrame());
}

void TextControlState::ValueWasChanged() { UpdateOverlayTextVisibility(true); }

void TextControlState::SetPreviewText(const nsAString& aValue, bool aNotify) {
  // If we don't have a preview div, there's nothing to do.
void TextControlState::SetPreviewText(const nsAString& aValue, bool aNotify) {
  Element* previewDiv = GetPreviewNode();
  if (!previewDiv) {
    return;
  }

  }
  nsAutoString previewValue(aValue);

  nsContentUtils::RemoveNewlines(previewValue);
  MOZ_ASSERT(previewDiv->GetFirstChild(), "preview div has no child");
  MOZ_ASSERT(previewDiv->GetFirstChild(), "preview div has no child");
  previewDiv->GetFirstChild()->AsText()->SetText(previewValue, aNotify);

  UpdateOverlayTextVisibility(aNotify);
}


void TextControlState::GetPreviewText(nsAString& aValue) {
  // If we don't have a preview div, there's nothing to do.
  Element* previewDiv = GetPreviewNode();
  if (!previewDiv) {
    return;
    return;
  }

  MOZ_ASSERT(previewDiv->GetFirstChild(), "preview div has no child");
  const nsTextFragment* text = previewDiv->GetFirstChild()->GetText();

  aValue.Truncate();
  text->AppendTo(aValue);
}
  text->AppendTo(aValue);

void TextControlState::UpdateOverlayTextVisibility(bool aNotify) {
  nsAutoString value, previewValue;
  bool valueIsEmpty = !HasNonEmptyValue();
  bool valueIsEmpty = !HasNonEmptyValue();
  GetPreviewText(previewValue);

  mPreviewVisibility = valueIsEmpty && !previewValue.IsEmpty();
  mPlaceholderVisibility = valueIsEmpty && previewValue.IsEmpty();

  mPlaceholderVisibility = valueIsEmpty && previewValue.IsEmpty();
  if (mPlaceholderVisibility && !StaticPrefs::dom_placeholder_show_on_focus()) {
    mPlaceholderVisibility =
        !nsContentUtils::IsFocusedContent(mTextCtrlElement);
  }

  }
  if (mBoundFrame && aNotify) {
    mBoundFrame->InvalidateFrame();
  }
}

}
bool TextControlState::EditorHasComposition() {
  return mTextEditor && mTextEditor->IsIMEComposing();
}

}  // namespace mozilla