1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "HTMLEditor.h"
#include "HTMLEditHelpers.h"
#include "HTMLEditorInlines.h"
#include "HTMLEditorNestedClasses.h"
#include "AutoClonedRangeArray.h"
#include "AutoSelectionRestorer.h"
#include "CSSEditUtils.h"
#include "EditAction.h"
#include "EditorBase.h"
#include "EditorDOMAPIWrapper.h"
#include "EditorDOMPoint.h"
#include "EditorLineBreak.h"
#include "EditorUtils.h"
#include "ErrorList.h"
#include "HTMLEditorEventListener.h"
#include "HTMLEditUtils.h"
#include "InsertNodeTransaction.h"
#include "JoinNodesTransaction.h"
#include "MoveNodeTransaction.h"
#include "PendingStyles.h"
#include "ReplaceTextTransaction.h"
#include "SplitNodeTransaction.h"
#include "WhiteSpaceVisibilityKeeper.h"
#include "WSRunScanner.h"
#include "mozilla/ComposerCommandsUpdater.h"
#include "mozilla/ContentIterator.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/EditorForwards.h"
#include "mozilla/Encoding.h" // for Encoding
#include "mozilla/FlushType.h"
#include "mozilla/IMEStateManager.h"
#include "mozilla/IntegerRange.h" // for IntegerRange
#include "mozilla/mozInlineSpellChecker.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs_editor.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
#include "mozilla/glean/EditorLibeditorMetrics.h"
#include "mozilla/TextControlElement.h"
#include "mozilla/TextEditor.h"
#include "mozilla/TextEvents.h"
#include "mozilla/TextServicesDocument.h"
#include "mozilla/ToString.h"
#include "mozilla/css/Loader.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/Attr.h"
#include "mozilla/dom/BorrowedAttrInfo.h"
#include "mozilla/dom/CharacterDataBuffer.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ElementInlines.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/EventTarget.h"
#include "mozilla/dom/HTMLAnchorElement.h"
#include "mozilla/dom/HTMLBodyElement.h"
#include "mozilla/dom/HTMLBRElement.h"
#include "mozilla/dom/HTMLButtonElement.h"
#include "mozilla/dom/HTMLSummaryElement.h"
#include "mozilla/dom/NameSpaceConstants.h"
#include "mozilla/dom/Selection.h"
#include "nsContentList.h"
#include "nsContentUtils.h"
#include "nsCRT.h"
#include "nsDebug.h"
#include "nsElementTable.h"
#include "nsFocusManager.h"
#include "nsGenericHTMLElement.h"
#include "nsGkAtoms.h"
#include "nsHTMLDocument.h"
#include "nsIContent.h"
#include "nsIContentInlines.h" // for nsINode::IsInDesignMode()
#include "nsIEditActionListener.h"
#include "nsIFrame.h"
#include "nsIPrincipal.h"
#include "nsISelectionController.h"
#include "nsIURI.h"
#include "nsIWidget.h"
#include "nsNetUtil.h"
#include "nsPresContext.h"
#include "nsPrintfCString.h"
#include "nsPIDOMWindow.h"
#include "nsStyledElement.h"
#include "nsUnicharUtils.h"
namespace mozilla {
using namespace dom;
using namespace widget;
LazyLogModule gHTMLEditorFocusLog("HTMLEditorFocus");
using EmptyCheckOption = HTMLEditUtils::EmptyCheckOption;
using LeafNodeType = HTMLEditUtils::LeafNodeType;
using LeafNodeTypes = HTMLEditUtils::LeafNodeTypes;
using WalkTreeOption = HTMLEditUtils::WalkTreeOption;
// Some utilities to handle overloading of "A" tag for link and named anchor.
static bool IsLinkTag(const nsAtom& aTagName) {
return &aTagName == nsGkAtoms::href;
}
static bool IsNamedAnchorTag(const nsAtom& aTagName) {
return &aTagName == nsGkAtoms::anchor;
}
// Helper struct for DoJoinNodes() and DoSplitNode().
struct MOZ_STACK_CLASS SavedRange final {
RefPtr<Selection> mSelection;
nsCOMPtr<nsINode> mStartContainer;
nsCOMPtr<nsINode> mEndContainer;
uint32_t mStartOffset = 0;
uint32_t mEndOffset = 0;
};
/******************************************************************************
* HTMLEditor
*****************************************************************************/
template Result<CreateContentResult, nsresult>
HTMLEditor::InsertNodeIntoProperAncestorWithTransaction(
nsIContent& aContentToInsert, const EditorDOMPoint& aPointToInsert,
SplitAtEdges aSplitAtEdges);
template Result<CreateElementResult, nsresult>
HTMLEditor::InsertNodeIntoProperAncestorWithTransaction(
Element& aContentToInsert, const EditorDOMPoint& aPointToInsert,
SplitAtEdges aSplitAtEdges);
template Result<CreateTextResult, nsresult>
HTMLEditor::InsertNodeIntoProperAncestorWithTransaction(
Text& aContentToInsert, const EditorDOMPoint& aPointToInsert,
SplitAtEdges aSplitAtEdges);
MOZ_RUNINIT HTMLEditor::InitializeInsertingElement
HTMLEditor::DoNothingForNewElement =
[](HTMLEditor&, Element&, const EditorDOMPoint&) { return NS_OK; };
MOZ_RUNINIT HTMLEditor::InitializeInsertingElement
HTMLEditor::InsertNewBRElement =
[](HTMLEditor& aHTMLEditor, Element& aNewElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
MOZ_ASSERT(!aNewElement.IsInComposedDoc());
Result<CreateLineBreakResult, nsresult> insertBRElementResultOrError =
aHTMLEditor.InsertLineBreak(WithTransaction::No,
LineBreakType::BRElement,
EditorDOMPoint(&aNewElement, 0u));
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertLineBreak(WithTransaction::No, "
"LineBreakType::BRElement) failed");
return insertBRElementResultOrError.unwrapErr();
}
insertBRElementResultOrError.unwrap().IgnoreCaretPointSuggestion();
return NS_OK;
};
// static
Result<CreateElementResult, nsresult>
HTMLEditor::AppendNewElementToInsertingElement(
HTMLEditor& aHTMLEditor, const nsStaticAtom& aTagName, Element& aNewElement,
const InitializeInsertingElement& aInitializer) {
MOZ_ASSERT(!aNewElement.IsInComposedDoc());
Result<CreateElementResult, nsresult> createNewElementResult =
aHTMLEditor.CreateAndInsertElement(
WithTransaction::No, const_cast<nsStaticAtom&>(aTagName),
EditorDOMPoint(&aNewElement, 0u), aInitializer);
NS_WARNING_ASSERTION(
createNewElementResult.isOk(),
"HTMLEditor::CreateAndInsertElement(WithTransaction::No) failed");
return createNewElementResult;
}
// static
Result<CreateElementResult, nsresult>
HTMLEditor::AppendNewElementWithBRToInsertingElement(
HTMLEditor& aHTMLEditor, const nsStaticAtom& aTagName,
Element& aNewElement) {
MOZ_ASSERT(!aNewElement.IsInComposedDoc());
Result<CreateElementResult, nsresult> createNewElementWithBRResult =
HTMLEditor::AppendNewElementToInsertingElement(
aHTMLEditor, aTagName, aNewElement, HTMLEditor::InsertNewBRElement);
NS_WARNING_ASSERTION(
createNewElementWithBRResult.isOk(),
"HTMLEditor::AppendNewElementToInsertingElement() failed");
return createNewElementWithBRResult;
}
MOZ_RUNINIT HTMLEditor::AttributeFilter HTMLEditor::CopyAllAttributes =
[](HTMLEditor&, const Element&, const Element&, int32_t, const nsAtom&,
nsString&) { return true; };
MOZ_RUNINIT HTMLEditor::AttributeFilter HTMLEditor::CopyAllAttributesExceptId =
[](HTMLEditor&, const Element&, const Element&, int32_t aNamespaceID,
const nsAtom& aAttrName, nsString&) {
return aNamespaceID != kNameSpaceID_None || &aAttrName != nsGkAtoms::id;
};
MOZ_RUNINIT HTMLEditor::AttributeFilter HTMLEditor::CopyAllAttributesExceptDir =
[](HTMLEditor&, const Element&, const Element&, int32_t aNamespaceID,
const nsAtom& aAttrName, nsString&) {
return aNamespaceID != kNameSpaceID_None || &aAttrName != nsGkAtoms::dir;
};
MOZ_RUNINIT HTMLEditor::AttributeFilter
HTMLEditor::CopyAllAttributesExceptIdAndDir =
[](HTMLEditor&, const Element&, const Element&, int32_t aNamespaceID,
const nsAtom& aAttrName, nsString&) {
return !(
aNamespaceID == kNameSpaceID_None &&
(&aAttrName == nsGkAtoms::id || &aAttrName == nsGkAtoms::dir));
};
HTMLEditor::HTMLEditor(const Document& aDocument)
: EditorBase(EditorBase::EditorType::HTML),
mCRInParagraphCreatesParagraph(false),
mIsObjectResizingEnabled(
StaticPrefs::editor_resizing_enabled_by_default()),
mIsResizing(false),
mPreserveRatio(false),
mResizedObjectIsAnImage(false),
mIsAbsolutelyPositioningEnabled(
StaticPrefs::editor_positioning_enabled_by_default()),
mResizedObjectIsAbsolutelyPositioned(false),
mGrabberClicked(false),
mIsMoving(false),
mSnapToGridEnabled(false),
mIsInlineTableEditingEnabled(
StaticPrefs::editor_inline_table_editing_enabled_by_default()),
mIsCSSPrefChecked(StaticPrefs::editor_use_css()),
mOriginalX(0),
mOriginalY(0),
mResizedObjectX(0),
mResizedObjectY(0),
mResizedObjectWidth(0),
mResizedObjectHeight(0),
mResizedObjectMarginLeft(0),
mResizedObjectMarginTop(0),
mResizedObjectBorderLeft(0),
mResizedObjectBorderTop(0),
mXIncrementFactor(0),
mYIncrementFactor(0),
mWidthIncrementFactor(0),
mHeightIncrementFactor(0),
mInfoXIncrement(20),
mInfoYIncrement(20),
mPositionedObjectX(0),
mPositionedObjectY(0),
mPositionedObjectWidth(0),
mPositionedObjectHeight(0),
mPositionedObjectMarginLeft(0),
mPositionedObjectMarginTop(0),
mPositionedObjectBorderLeft(0),
mPositionedObjectBorderTop(0),
mGridSize(0),
mDefaultParagraphSeparator(ParagraphSeparator::div) {}
HTMLEditor::~HTMLEditor() {
glean::htmleditors::with_beforeinput_listeners
.EnumGet(static_cast<glean::htmleditors::WithBeforeinputListenersLabel>(
MayHaveBeforeInputEventListenersForTelemetry() ? 1 : 0))
.Add();
glean::htmleditors::overridden_by_beforeinput_listeners
.EnumGet(static_cast<
glean::htmleditors::OverriddenByBeforeinputListenersLabel>(
mHasBeforeInputBeenCanceled ? 1 : 0))
.Add();
glean::htmleditors::with_mutation_observers_without_beforeinput_listeners
.EnumGet(static_cast<
glean::htmleditors::
WithMutationObserversWithoutBeforeinputListenersLabel>(
!MayHaveBeforeInputEventListenersForTelemetry() &&
MutationObserverHasObservedNodeForTelemetry()
? 1
: 0))
.Add();
mPendingStylesToApplyToNewContent = nullptr;
if (mDisabledLinkHandling) {
if (Document* doc = GetDocument()) {
doc->SetLinkHandlingEnabled(mOldLinkHandlingEnabled);
}
}
RemoveEventListeners();
HideAnonymousEditingUIs();
}
NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLEditor)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(HTMLEditor, EditorBase)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPendingStylesToApplyToNewContent)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mComposerCommandsUpdater)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mChangedRangeForTopLevelEditSubAction)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPaddingBRElementForEmptyEditor)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mLastCollapsibleWhiteSpaceAppendedTextNode)
tmp->HideAnonymousEditingUIs();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(HTMLEditor, EditorBase)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPendingStylesToApplyToNewContent)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mComposerCommandsUpdater)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChangedRangeForTopLevelEditSubAction)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPaddingBRElementForEmptyEditor)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLastCollapsibleWhiteSpaceAppendedTextNode)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopLeftHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopRightHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLeftHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRightHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomLeftHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomRightHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mActivatedHandle)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizingShadow)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizingInfo)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizedObject)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAbsolutelyPositionedObject)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGrabber)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPositioningShadow)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInlineEditedCell)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddColumnBeforeButton)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRemoveColumnButton)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddColumnAfterButton)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddRowBeforeButton)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRemoveRowButton)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddRowAfterButton)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_ADDREF_INHERITED(HTMLEditor, EditorBase)
NS_IMPL_RELEASE_INHERITED(HTMLEditor, EditorBase)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(HTMLEditor)
NS_INTERFACE_MAP_ENTRY(nsIHTMLEditor)
NS_INTERFACE_MAP_ENTRY(nsIHTMLObjectResizer)
NS_INTERFACE_MAP_ENTRY(nsIHTMLAbsPosEditor)
NS_INTERFACE_MAP_ENTRY(nsIHTMLInlineTableEditor)
NS_INTERFACE_MAP_ENTRY(nsITableEditor)
NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
NS_INTERFACE_MAP_ENTRY(nsIEditorMailSupport)
NS_INTERFACE_MAP_END_INHERITING(EditorBase)
nsresult HTMLEditor::Init(Document& aDocument,
ComposerCommandsUpdater& aComposerCommandsUpdater,
uint32_t aFlags) {
MOZ_ASSERT(!mInitSucceeded,
"HTMLEditor::Init() called again without calling PreDestroy()?");
MOZ_DIAGNOSTIC_ASSERT(!mComposerCommandsUpdater ||
mComposerCommandsUpdater == &aComposerCommandsUpdater);
mComposerCommandsUpdater = &aComposerCommandsUpdater;
RefPtr<PresShell> presShell = aDocument.GetPresShell();
if (NS_WARN_IF(!presShell)) {
return NS_ERROR_FAILURE;
}
nsresult rv = InitInternal(aDocument, nullptr, *presShell, aFlags);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::InitInternal() failed");
return rv;
}
// Init mutation observer
aDocument.AddMutationObserverUnlessExists(this);
if (!mRootElement) {
UpdateRootElement();
}
// disable Composer-only features
if (IsMailEditor()) {
DebugOnly<nsresult> rvIgnored = SetAbsolutePositioningEnabled(false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"HTMLEditor::SetAbsolutePositioningEnabled(false) failed, but ignored");
rvIgnored = SetSnapToGridEnabled(false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"HTMLEditor::SetSnapToGridEnabled(false) failed, but ignored");
}
// disable links
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return NS_ERROR_FAILURE;
}
if (!IsPlaintextMailComposer() && !IsInteractionAllowed()) {
mDisabledLinkHandling = true;
mOldLinkHandlingEnabled = document->LinkHandlingEnabled();
document->SetLinkHandlingEnabled(false);
}
// init the type-in state
mPendingStylesToApplyToNewContent = new PendingStyles();
AutoEditActionDataSetter editActionData(*this, EditAction::eInitializing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_FAILURE;
}
rv = InitEditorContentAndSelection();
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::InitEditorContentAndSelection() failed");
// XXX Sholdn't we expose `NS_ERROR_EDITOR_DESTROYED` even though this
// is a public method?
return EditorBase::ToGenericNSResult(rv);
}
// Throw away the old transaction manager if this is not the first time that
// we're initializing the editor.
ClearUndoRedo();
EnableUndoRedo(); // FYI: Creating mTransactionManager in this call
if (mTransactionManager) {
mTransactionManager->Attach(*this);
}
MOZ_ASSERT(!mInitSucceeded, "HTMLEditor::Init() shouldn't be nested");
mInitSucceeded = true;
editActionData.OnEditorInitialized();
return NS_OK;
}
nsresult HTMLEditor::PostCreate() {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = PostCreateInternal();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::PostCreatInternal() failed");
return rv;
}
void HTMLEditor::PreDestroy() {
if (mDidPreDestroy) {
return;
}
mInitSucceeded = false;
// FYI: Cannot create AutoEditActionDataSetter here. However, it does not
// necessary for the methods called by the following code.
RefPtr<Document> document = GetDocument();
if (document) {
document->RemoveMutationObserver(this);
}
// Clean up after our anonymous content -- we don't want these nodes to
// stay around (which they would, since the frames have an owning reference).
PresShell* presShell = GetPresShell();
if (presShell && presShell->IsDestroying()) {
// Just destroying PresShell now.
// We have to keep UI elements of anonymous content until PresShell
// is destroyed.
RefPtr<HTMLEditor> self = this;
nsContentUtils::AddScriptRunner(NS_NewRunnableFunction(
"HTMLEditor::PreDestroy", [self]() MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA {
self->HideAnonymousEditingUIs();
}));
} else {
// PresShell is alive or already gone.
HideAnonymousEditingUIs();
}
mPaddingBRElementForEmptyEditor = nullptr;
PreDestroyInternal();
}
bool HTMLEditor::IsStyleEditable() const {
if (IsInDesignMode()) {
return true;
}
if (IsPlaintextMailComposer()) {
return false;
}
const Element* const editingHost = ComputeEditingHost(LimitInBodyElement::No);
// Let's return true if there is no focused editing host for the backward
// compatibility.
return !editingHost || !editingHost->IsContentEditablePlainTextOnly();
}
NS_IMETHODIMP HTMLEditor::GetDocumentCharacterSet(nsACString& aCharacterSet) {
nsresult rv = GetDocumentCharsetInternal(aCharacterSet);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetDocumentCharsetInternal() failed");
return rv;
}
NS_IMETHODIMP HTMLEditor::SetDocumentCharacterSet(
const nsACString& aCharacterSet) {
AutoEditActionDataSetter editActionData(*this, EditAction::eSetCharacterSet);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return EditorBase::ToGenericNSResult(rv);
}
RefPtr<Document> document = GetDocument();
if (NS_WARN_IF(!document)) {
return EditorBase::ToGenericNSResult(NS_ERROR_NOT_INITIALIZED);
}
// This method is scriptable, so add-ons could pass in something other
// than a canonical name.
const Encoding* encoding = Encoding::ForLabelNoReplacement(aCharacterSet);
if (!encoding) {
NS_WARNING("Encoding::ForLabelNoReplacement() failed");
return EditorBase::ToGenericNSResult(NS_ERROR_INVALID_ARG);
}
document->SetDocumentCharacterSet(WrapNotNull(encoding));
// Update META charset element.
if (UpdateMetaCharsetWithTransaction(*document, aCharacterSet)) {
return NS_OK;
}
// Set attributes to the created element
if (aCharacterSet.IsEmpty()) {
return NS_OK;
}
RefPtr<nsContentList> headElementList =
document->GetElementsByTagName(u"head"_ns);
if (NS_WARN_IF(!headElementList)) {
return NS_OK;
}
nsCOMPtr<nsIContent> primaryHeadElement = headElementList->Item(0);
if (NS_WARN_IF(!primaryHeadElement)) {
return NS_OK;
}
// Create a new meta charset tag
Result<CreateElementResult, nsresult> createNewMetaElementResult =
CreateAndInsertElement(
WithTransaction::Yes, *nsGkAtoms::meta,
EditorDOMPoint(primaryHeadElement, 0),
[&aCharacterSet](HTMLEditor&, Element& aMetaElement,
const EditorDOMPoint&) {
MOZ_ASSERT(!aMetaElement.IsInComposedDoc());
DebugOnly<nsresult> rvIgnored =
aMetaElement.SetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv,
u"Content-Type"_ns, false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"Element::SetAttr(nsGkAtoms::httpEquiv, \"Content-Type\", "
"false) failed, but ignored");
rvIgnored =
aMetaElement.SetAttr(kNameSpaceID_None, nsGkAtoms::content,
u"text/html;charset="_ns +
NS_ConvertASCIItoUTF16(aCharacterSet),
false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
nsPrintfCString(
"Element::SetAttr(nsGkAtoms::content, "
"\"text/html;charset=%s\", false) failed, but ignored",
nsPromiseFlatCString(aCharacterSet).get())
.get());
return NS_OK;
});
NS_WARNING_ASSERTION(createNewMetaElementResult.isOk(),
"HTMLEditor::CreateAndInsertElement(WithTransaction::"
"Yes, nsGkAtoms::meta) failed, but ignored");
// Probably, we don't need to update selection in this case since we should
// not put selection into <head> element.
createNewMetaElementResult.inspect().IgnoreCaretPointSuggestion();
return NS_OK;
}
bool HTMLEditor::UpdateMetaCharsetWithTransaction(
Document& aDocument, const nsACString& aCharacterSet) {
// get a list of META tags
RefPtr<nsContentList> metaElementList =
aDocument.GetElementsByTagName(u"meta"_ns);
if (NS_WARN_IF(!metaElementList)) {
return false;
}
for (uint32_t i = 0; i < metaElementList->Length(true); ++i) {
RefPtr<Element> metaElement = metaElementList->Item(i)->AsElement();
MOZ_ASSERT(metaElement);
nsAutoString currentValue;
metaElement->GetAttr(nsGkAtoms::httpEquiv, currentValue);
if (!FindInReadable(u"content-type"_ns, currentValue,
nsCaseInsensitiveStringComparator)) {
continue;
}
metaElement->GetAttr(nsGkAtoms::content, currentValue);
constexpr auto charsetEquals = u"charset="_ns;
nsAString::const_iterator originalStart, start, end;
originalStart = currentValue.BeginReading(start);
currentValue.EndReading(end);
if (!FindInReadable(charsetEquals, start, end,
nsCaseInsensitiveStringComparator)) {
continue;
}
// set attribute to <original prefix> charset=text/html
nsresult rv = SetAttributeWithTransaction(
*metaElement, *nsGkAtoms::content,
Substring(originalStart, start) + charsetEquals +
NS_ConvertASCIItoUTF16(aCharacterSet));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction(nsGkAtoms::content) failed");
return NS_SUCCEEDED(rv);
}
return false;
}
NS_IMETHODIMP HTMLEditor::NotifySelectionChanged(Document* aDocument,
Selection* aSelection,
int16_t aReason,
int32_t aAmount) {
if (NS_WARN_IF(!aDocument) || NS_WARN_IF(!aSelection)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
if (mPendingStylesToApplyToNewContent) {
RefPtr<PendingStyles> pendingStyles = mPendingStylesToApplyToNewContent;
pendingStyles->OnSelectionChange(*this, aReason);
// We used a class which derived from nsISelectionListener to call
// HTMLEditor::RefreshEditingUI(). The lifetime of the class was
// exactly same as mPendingStylesToApplyToNewContent. So, call it only when
// mPendingStylesToApplyToNewContent is not nullptr.
if ((aReason & (nsISelectionListener::MOUSEDOWN_REASON |
nsISelectionListener::KEYPRESS_REASON |
nsISelectionListener::SELECTALL_REASON)) &&
aSelection) {
// the selection changed and we need to check if we have to
// hide and/or redisplay resizing handles
// FYI: This is an XPCOM method. So, the caller, Selection, guarantees
// the lifetime of this instance. So, don't need to grab this with
// local variable.
DebugOnly<nsresult> rv = RefreshEditingUI();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::RefreshEditingUI() failed, but ignored");
}
}
if (mComposerCommandsUpdater) {
RefPtr<ComposerCommandsUpdater> updater = mComposerCommandsUpdater;
updater->OnSelectionChange();
}
nsresult rv = EditorBase::NotifySelectionChanged(aDocument, aSelection,
aReason, aAmount);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::NotifySelectionChanged() failed");
return rv;
}
void HTMLEditor::UpdateRootElement() {
// Use the HTML documents body element as the editor root if we didn't
// get a root element during initialization.
mRootElement = GetBodyElement();
if (!mRootElement) {
RefPtr<Document> doc = GetDocument();
if (doc) {
// If there is no HTML body element,
// we should use the document root element instead.
mRootElement = doc->GetDocumentElement();
}
// else leave it null, for lack of anything better.
}
}
nsresult HTMLEditor::FocusedElementOrDocumentBecomesEditable(
Document& aDocument, Element* aElement) {
MOZ_LOG(gHTMLEditorFocusLog, LogLevel::Info,
("%s(aDocument=%p, aElement=%s): mHasFocus=%s, mIsInDesignMode=%s, "
"aDocument.IsInDesignMode()=%s, aElement->IsInDesignMode()=%s",
__FUNCTION__, &aDocument, ToString(RefPtr{aElement}).c_str(),
mHasFocus ? "true" : "false", mIsInDesignMode ? "true" : "false",
aDocument.IsInDesignMode() ? "true" : "false",
aElement ? (aElement->IsInDesignMode() ? "true" : "false") : "N/A"));
const bool enteringInDesignMode =
(aDocument.IsInDesignMode() && (!aElement || aElement->IsInDesignMode()));
// If we should've already handled focus event, selection limiter should not
// be set. However, IMEStateManager is not notified the pseudo focus change
// in this case. Therefore, we need to notify IMEStateManager of this.
if (mHasFocus) {
if (enteringInDesignMode) {
mIsInDesignMode = true;
return NS_OK;
}
// Although editor is already initialized due to re-used, ISM may not
// create IME content observer yet. So we have to create it.
IMEState newState;
nsresult rv = GetPreferredIMEState(&newState);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::GetPreferredIMEState() failed");
mIsInDesignMode = false;
return NS_OK;
}
const RefPtr<Element> focusedElement = GetFocusedElement();
if (focusedElement) {
MOZ_ASSERT(focusedElement == aElement);
TextControlElement* const textControlElement =
TextControlElement::FromNode(focusedElement);
if (textControlElement &&
textControlElement->IsSingleLineTextControlOrTextArea()) {
// Let's emulate blur first.
DebugOnly<nsresult> rv = FinalizeSelection();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::FinalizeSelection() failed, but ignored");
mHasFocus = false;
mIsInDesignMode = false;
}
IMEStateManager::UpdateIMEState(newState, focusedElement, *this);
// XXX Do we need to notify focused TextEditor of focus? In theory,
// the TextEditor should get focus event in this case.
}
mIsInDesignMode = false;
return NS_OK;
}
// If we should be in the design mode, we want to handle focus event fired
// on the document node. Therefore, we should emulate it here.
if (enteringInDesignMode) {
MOZ_ASSERT(&aDocument == GetDocument());
nsresult rv = OnFocus(aDocument);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::OnFocus() failed");
return rv;
}
if (NS_WARN_IF(!aElement)) {
return NS_ERROR_INVALID_ARG;
}
// Otherwise, we should've already handled focus event on the element,
// therefore, we need to emulate it here.
MOZ_ASSERT(nsFocusManager::GetFocusedElementStatic() == aElement);
nsresult rv = OnFocus(*aElement);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::OnFocus() failed");
// Note that we don't need to call
// IMEStateManager::MaybeOnEditableStateDisabled here because
// EditorBase::OnFocus must have already been called IMEStateManager::OnFocus
// if succeeded. And perhaps, it's okay that IME is not enabled when
// HTMLEditor fails to start handling since nobody can handle composition
// events anyway...
return rv;
}
nsresult HTMLEditor::OnFocus(const nsINode& aOriginalEventTargetNode) {
MOZ_LOG(gHTMLEditorFocusLog, LogLevel::Info,
("%s(aOriginalEventTarget=%s): mIsInDesignMode=%s, "
"aOriginalEventTargetNode.IsInDesignMode()=%s",
__FUNCTION__, ToString(RefPtr{&aOriginalEventTargetNode}).c_str(),
mIsInDesignMode ? "true" : "false",
aOriginalEventTargetNode.IsInDesignMode() ? "true" : "false"));
// Before doing anything, we should check whether the original target is still
// valid focus event target because it may have already lost focus.
if (!CanKeepHandlingFocusEvent(aOriginalEventTargetNode)) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_FAILURE;
}
nsresult rv = EditorBase::OnFocus(aOriginalEventTargetNode);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::OnFocus() failed");
return rv;
}
mHasFocus = true;
mIsInDesignMode = aOriginalEventTargetNode.IsInDesignMode();
return NS_OK;
}
nsresult HTMLEditor::FocusedElementOrDocumentBecomesNotEditable(
HTMLEditor* aHTMLEditor, Document& aDocument, Element* aElement) {
MOZ_LOG(
gHTMLEditorFocusLog, LogLevel::Info,
("%s(aHTMLEditor=%p, aDocument=%p, aElement=%s): "
"aHTMLEditor->HasFocus()=%s, aHTMLEditor->IsInDesignMode()=%s, "
"aDocument.IsInDesignMode()=%s, aElement->IsInDesignMode()=%s, "
"nsFocusManager::GetFocusedElementStatic()=%s",
__FUNCTION__, aHTMLEditor, &aDocument,
ToString(RefPtr{aElement}).c_str(),
aHTMLEditor ? (aHTMLEditor->HasFocus() ? "true" : "false") : "N/A",
aHTMLEditor ? (aHTMLEditor->IsInDesignMode() ? "true" : "false") : "N/A",
aDocument.IsInDesignMode() ? "true" : "false",
aElement ? (aElement->IsInDesignMode() ? "true" : "false") : "N/A",
ToString(RefPtr{nsFocusManager::GetFocusedElementStatic()}).c_str()));
nsresult rv = [&]() MOZ_CAN_RUN_SCRIPT {
// If HTMLEditor has not been created yet, we just need to adjust
// IMEStateManager. So, don't return error.
if (!aHTMLEditor || !aHTMLEditor->HasFocus()) {
return NS_OK;
}
// Let's emulate blur first.
nsresult rv = aHTMLEditor->FinalizeSelection();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::FinalizeSelection() failed");
aHTMLEditor->mHasFocus = false;
aHTMLEditor->mIsInDesignMode = false;
RefPtr<Element> focusedElement = nsFocusManager::GetFocusedElementStatic();
if (focusedElement && !focusedElement->IsInComposedDoc()) {
// nsFocusManager may keep storing the focused element even after
// disconnected from the tree, but HTMLEditor cannot work with editable
// nodes not in a composed document. Therefore, we should treat no
// focused element in the case.
focusedElement = nullptr;
}
TextControlElement* const focusedTextControlElement =
TextControlElement::FromNodeOrNull(focusedElement);
if ((focusedElement && focusedElement->IsEditable() &&
focusedElement->OwnerDoc() == aHTMLEditor->GetDocument() &&
(!focusedTextControlElement ||
!focusedTextControlElement->IsSingleLineTextControlOrTextArea())) ||
(!focusedElement && aDocument.IsInDesignMode())) {
// Then, the focused element is still editable, let's emulate focus to
// make the editor be ready to handle input.
DebugOnly<nsresult> rvIgnored = aHTMLEditor->OnFocus(
focusedElement ? static_cast<nsINode&>(*focusedElement)
: static_cast<nsINode&>(aDocument));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"HTMLEditor::OnFocus() failed, but ignored");
} else if (focusedTextControlElement &&
focusedTextControlElement->IsSingleLineTextControlOrTextArea()) {
if (const RefPtr<TextEditor> textEditor =
focusedTextControlElement->GetExtantTextEditor()) {
textEditor->OnFocus(*focusedElement);
}
}
return rv;
}();
// If the element becomes not editable without focus change, IMEStateManager
// does not have a chance to disable IME. Therefore, (even if we fail to
// handle the emulated blur/focus above,) we should notify IMEStateManager of
// the editing state change. Note that if the window of the HTMLEditor has
// already lost focus, we don't need to do that and we should not touch the
// other windows.
if (const RefPtr<nsPresContext> presContext = aDocument.GetPresContext()) {
const RefPtr<Element> focusedElementInDocument =
Element::FromNodeOrNull(aDocument.GetUnretargetedFocusedContent());
MOZ_ASSERT_IF(focusedElementInDocument,
focusedElementInDocument->GetPresContext(
Element::PresContextFor::eForComposedDoc));
IMEStateManager::MaybeOnEditableStateDisabled(*presContext,
focusedElementInDocument);
}
return rv;
}
nsresult HTMLEditor::OnBlur(const EventTarget* aEventTarget) {
MOZ_LOG(gHTMLEditorFocusLog, LogLevel::Info,
("%s(aEventTarget=%s): mHasFocus=%s, mIsInDesignMode=%s, "
"aEventTarget->IsInDesignMode()=%s",
__FUNCTION__, ToString(RefPtr{aEventTarget}).c_str(),
mHasFocus ? "true" : "false", mIsInDesignMode ? "true" : "false",
nsINode::FromEventTargetOrNull(aEventTarget)
? (nsINode::FromEventTarget(aEventTarget)->IsInDesignMode()
? "true"
: "false")
: "N/A"));
const Element* eventTargetAsElement =
Element::FromEventTargetOrNull(aEventTarget);
// If another element already has focus, we should not maintain the selection
// because we may not have the rights doing it.
const Element* focusedElement = nsFocusManager::GetFocusedElementStatic();
if (focusedElement && focusedElement != eventTargetAsElement) {
// XXX If we had focus and new focused element is a text control, we may
// need to notify focus of its TextEditor...
mIsInDesignMode = false;
mHasFocus = false;
return NS_OK;
}
// If we're in the designMode and blur occurs, the target must be the document
// node. If a blur event is fired and the target is an element, it must be
// delayed blur event at initializing the `HTMLEditor`.
if (mIsInDesignMode && eventTargetAsElement &&
eventTargetAsElement->IsInComposedDoc()) {
return NS_OK;
}
nsresult rv = FinalizeSelection();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::FinalizeSelection() failed");
mIsInDesignMode = false;
mHasFocus = false;
return rv;
}
Element* HTMLEditor::FindSelectionRoot(const nsINode& aNode) const {
MOZ_ASSERT(aNode.IsDocument() || aNode.IsContent(),
"aNode must be content or document node");
if (NS_WARN_IF(!aNode.IsInComposedDoc())) {
return nullptr;
}
if (aNode.IsInDesignMode()) {
return GetDocument()->GetRootElement();
}
nsIContent* content = const_cast<nsIContent*>(aNode.AsContent());
if (!content->HasFlag(NODE_IS_EDITABLE)) {
// If the content is in read-write state but is not editable itself,
// return it as the selection root.
if (content->IsElement() &&
content->AsElement()->State().HasState(ElementState::READWRITE)) {
return content->AsElement();
}
return nullptr;
}
// For non-readonly editors we want to find the root of the editable subtree
// containing aContent.
return content->GetEditingHost();
}
bool HTMLEditor::EntireDocumentIsEditable() const {
Document* document = GetDocument();
return document && document->GetDocumentElement() &&
(document->GetDocumentElement()->IsEditable() ||
(document->GetBody() && document->GetBody()->IsEditable()));
}
void HTMLEditor::CreateEventListeners() {
// Don't create the handler twice
if (!mEventListener) {
mEventListener = new HTMLEditorEventListener();
}
}
nsresult HTMLEditor::InstallEventListeners() {
// FIXME InstallEventListeners() should not be called if we failed to set
// document or create an event listener. So, these checks should be
// MOZ_DIAGNOSTIC_ASSERT instead.
MOZ_ASSERT(GetDocument());
if (MOZ_UNLIKELY(!GetDocument()) || NS_WARN_IF(!mEventListener)) {
return NS_ERROR_NOT_INITIALIZED;
}
// NOTE: HTMLEditor doesn't need to initialize mEventTarget here because
// the target must be document node and it must be referenced as weak pointer.
HTMLEditorEventListener* listener =
reinterpret_cast<HTMLEditorEventListener*>(mEventListener.get());
nsresult rv = listener->Connect(this);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditorEventListener::Connect() failed");
return rv;
}
void HTMLEditor::Detach(
const ComposerCommandsUpdater& aComposerCommandsUpdater) {
MOZ_DIAGNOSTIC_ASSERT_IF(
mComposerCommandsUpdater,
&aComposerCommandsUpdater == mComposerCommandsUpdater);
if (mComposerCommandsUpdater == &aComposerCommandsUpdater) {
mComposerCommandsUpdater = nullptr;
if (mTransactionManager) {
mTransactionManager->Detach(*this);
}
}
}
NS_IMETHODIMP HTMLEditor::BeginningOfDocument() {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = MaybeCollapseSelectionAtFirstEditableNode(false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::MaybeCollapseSelectionAtFirstEditableNode(false) failed");
return rv;
}
NS_IMETHODIMP HTMLEditor::EndOfDocument() {
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = CollapseSelectionToEndOfLastLeafNodeOfDocument();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::CollapseSelectionToEndOfLastLeafNodeOfDocument() failed");
// This is low level API for embedders and chrome script so that we can return
// raw error code here.
return rv;
}
nsresult HTMLEditor::CollapseSelectionToEndOfLastLeafNodeOfDocument() const {
MOZ_ASSERT(IsEditActionDataAvailable());
// We should do nothing with the result of GetRoot() if only a part of the
// document is editable.
if (!EntireDocumentIsEditable()) {
return NS_OK;
}
RefPtr<Element> bodyOrDocumentElement = GetRoot();
if (NS_WARN_IF(!bodyOrDocumentElement)) {
return NS_ERROR_NULL_POINTER;
}
auto pointToPutCaret = [&]() -> EditorRawDOMPoint {
nsCOMPtr<nsIContent> lastLeafContent = HTMLEditUtils::GetLastLeafContent(
*bodyOrDocumentElement, {LeafNodeType::OnlyLeafNode});
if (!lastLeafContent) {
return EditorRawDOMPoint::AtEndOf(*bodyOrDocumentElement);
}
// TODO: We should put caret into text node if it's visible.
return lastLeafContent->IsText() ||
HTMLEditUtils::IsContainerNode(*lastLeafContent)
? EditorRawDOMPoint::AtEndOf(*lastLeafContent)
: EditorRawDOMPoint(lastLeafContent);
}();
nsresult rv = CollapseSelectionTo(pointToPutCaret);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
void HTMLEditor::InitializeSelectionAncestorLimit(
Element& aAncestorLimit) const {
MOZ_ASSERT(IsEditActionDataAvailable());
// Hack for initializing selection.
// HTMLEditor::MaybeCollapseSelectionAtFirstEditableNode() will try to
// collapse selection at first editable text node or inline element which
// cannot have text nodes as its children. However, selection has already
// set into the new editing host by user, we should not change it. For
// solving this issue, we should do nothing if selection range is in active
// editing host except it's not collapsed at start of the editing host since
// aSelection.SetAncestorLimiter(aAncestorLimit) will collapse selection
// at start of the new limiter if focus node of aSelection is outside of the
// editing host. However, we need to check here if selection is already
// collapsed at start of the editing host because it's possible JS to do it.
// In such case, we should not modify selection with calling
// MaybeCollapseSelectionAtFirstEditableNode().
// Basically, we should try to collapse selection at first editable node
// in HTMLEditor.
bool tryToCollapseSelectionAtFirstEditableNode = true;
if (SelectionRef().RangeCount() == 1 && SelectionRef().IsCollapsed()) {
Element* editingHost = ComputeEditingHost();
const nsRange* range = SelectionRef().GetRangeAt(0);
if (range->GetStartContainer() == editingHost && !range->StartOffset()) {
// JS or user operation has already collapsed selection at start of
// the editing host. So, we don't need to try to change selection
// in this case.
tryToCollapseSelectionAtFirstEditableNode = false;
}
}
EditorBase::InitializeSelectionAncestorLimit(aAncestorLimit);
// XXX Do we need to check if we still need to change selection? E.g.,
// we could have already lost focus while we're changing the ancestor
// limiter because it may causes "selectionchange" event.
if (tryToCollapseSelectionAtFirstEditableNode) {
DebugOnly<nsresult> rvIgnored =
MaybeCollapseSelectionAtFirstEditableNode(true);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"HTMLEditor::MaybeCollapseSelectionAtFirstEditableNode(true) failed, "
"but ignored");
}
// If the target is a text control element, we won't handle user input
// for the `TextEditor` in it. However, we need to be open for `execCommand`.
// Therefore, we shouldn't set ancestor limit in this case.
// Note that we should do this once setting ancestor limiter for backward
// compatiblity of select events, etc. (Selection should be collapsed into
// the text control element.)
if (aAncestorLimit.HasIndependentSelection()) {
SelectionRef().SetAncestorLimiter(nullptr);
}
}
nsresult HTMLEditor::MaybeCollapseSelectionAtFirstEditableNode(
bool aIgnoreIfSelectionInEditingHost) const {
MOZ_ASSERT(IsEditActionDataAvailable());
RefPtr<Element> editingHost = ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_OK;
}
// If selection range is already in the editing host and the range is not
// start of the editing host, we shouldn't reset selection. E.g., window
// is activated when the editor had focus before inactivated.
if (aIgnoreIfSelectionInEditingHost && SelectionRef().RangeCount() == 1) {
const nsRange* range = SelectionRef().GetRangeAt(0);
if (!range->Collapsed() ||
range->GetStartContainer() != editingHost.get() ||
range->StartOffset()) {
return NS_OK;
}
}
for (nsIContent* leafContent = HTMLEditUtils::GetFirstLeafContent(
*editingHost,
{LeafNodeType::LeafNodeOrNonEditableNode,
LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, editingHost);
leafContent;) {
// If we meet a non-editable node first, we should move caret to start
// of the container block or editing host.
if (!EditorUtils::IsEditableContent(*leafContent, EditorType::HTML)) {
MOZ_ASSERT(leafContent->GetParent());
MOZ_ASSERT(EditorUtils::IsEditableContent(*leafContent->GetParent(),
EditorType::HTML));
if (const Element* editableBlockElementOrInlineEditingHost =
HTMLEditUtils::GetAncestorElement(
*leafContent,
HTMLEditUtils::ClosestEditableBlockElementOrInlineEditingHost,
BlockInlineCheck::UseComputedDisplayStyle)) {
nsresult rv = CollapseSelectionTo(
EditorDOMPoint(editableBlockElementOrInlineEditingHost, 0));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
NS_WARNING("Found leaf content did not have editable parent, why?");
return NS_ERROR_FAILURE;
}
// When we meet an empty inline element, we should look for a next sibling.
// For example, if current editor is:
// <div contenteditable><span></span><b><br></b></div>
// then, we should put caret at the <br> element. So, let's check if found
// node is an empty inline container element.
if (Element* leafElement = Element::FromNode(leafContent)) {
if (HTMLEditUtils::IsInlineContent(
*leafElement, BlockInlineCheck::UseComputedDisplayStyle) &&
!HTMLEditUtils::IsNeverElementContentsEditableByUser(*leafElement) &&
HTMLEditUtils::CanNodeContain(*leafElement,
*nsGkAtoms::textTagName)) {
// Chromium collapses selection to start of the editing host when this
// is the last leaf content. So, we don't need special handling here.
leafContent = HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
*leafElement,
{LeafNodeType::LeafNodeOrNonEditableNode,
LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, editingHost);
continue;
}
}
if (Text* text = leafContent->GetAsText()) {
// If there is editable and visible text node, move caret at first of
// the visible character.
const WSScanResult scanResultInTextNode =
WSRunScanner::ScanInclusiveNextVisibleNodeOrBlockBoundary(
{WSRunScanner::Option::OnlyEditableNodes},
EditorRawDOMPoint(text, 0));
if ((scanResultInTextNode.InVisibleOrCollapsibleCharacters() ||
scanResultInTextNode.ReachedPreformattedLineBreak()) &&
scanResultInTextNode.TextPtr() == text) {
nsresult rv = CollapseSelectionTo(
scanResultInTextNode.PointAtReachedContent<EditorRawDOMPoint>());
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
// If it's an invisible text node, keep scanning next leaf.
leafContent = HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
*leafContent,
{LeafNodeType::LeafNodeOrNonEditableNode,
LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, editingHost);
continue;
}
// If there is editable <br> or something void element like <img>, <input>,
// <hr> etc, move caret before it.
if (!HTMLEditUtils::CanNodeContain(*leafContent, *nsGkAtoms::textTagName) ||
HTMLEditUtils::IsNeverElementContentsEditableByUser(*leafContent)) {
MOZ_ASSERT(leafContent->GetParent());
if (EditorUtils::IsEditableContent(*leafContent, EditorType::HTML)) {
nsresult rv = CollapseSelectionTo(EditorDOMPoint(leafContent));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
MOZ_ASSERT_UNREACHABLE(
"How do we reach editable leaf in non-editable element?");
// But if it's not editable, let's put caret at start of editing host
// for now.
nsresult rv = CollapseSelectionTo(EditorDOMPoint(editingHost, 0));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
// If we meet non-empty block element, we need to scan its child too.
if (HTMLEditUtils::IsBlockElement(
*leafContent, BlockInlineCheck::UseComputedDisplayStyle) &&
!HTMLEditUtils::IsEmptyNode(
*leafContent,
{EmptyCheckOption::TreatSingleBRElementAsVisible,
EmptyCheckOption::TreatNonEditableContentAsInvisible}) &&
!HTMLEditUtils::IsNeverElementContentsEditableByUser(*leafContent)) {
leafContent = HTMLEditUtils::GetFirstLeafContent(
*leafContent,
{LeafNodeType::LeafNodeOrNonEditableNode,
LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, editingHost);
continue;
}
// Otherwise, we must meet an empty block element or a data node like
// comment node. Let's ignore it.
leafContent = HTMLEditUtils::GetNextLeafContentOrNextBlockElement(
*leafContent,
{LeafNodeType::LeafNodeOrNonEditableNode,
LeafNodeType::LeafNodeOrChildBlock},
BlockInlineCheck::UseComputedDisplayStyle, editingHost);
}
// If there is no visible/editable node except another block element in
// current editing host, we should move caret to very first of the editing
// host.
// XXX This may not make sense, but Chromium behaves so. Therefore, the
// reason why we do this is just compatibility with Chromium.
nsresult rv = CollapseSelectionTo(EditorDOMPoint(editingHost, 0));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
void HTMLEditor::PreHandleMouseDown(const MouseEvent& aMouseDownEvent) {
if (mPendingStylesToApplyToNewContent) {
// mPendingStylesToApplyToNewContent will be notified of selection change
// even if aMouseDownEvent is not an acceptable event for this editor.
// Therefore, we need to notify it of this event too.
mPendingStylesToApplyToNewContent->PreHandleMouseEvent(aMouseDownEvent);
}
}
void HTMLEditor::PreHandleMouseUp(const MouseEvent& aMouseUpEvent) {
if (mPendingStylesToApplyToNewContent) {
// mPendingStylesToApplyToNewContent will be notified of selection change
// even if aMouseUpEvent is not an acceptable event for this editor.
// Therefore, we need to notify it of this event too.
mPendingStylesToApplyToNewContent->PreHandleMouseEvent(aMouseUpEvent);
}
}
void HTMLEditor::PreHandleSelectionChangeCommand(Command aCommand) {
if (mPendingStylesToApplyToNewContent) {
mPendingStylesToApplyToNewContent->PreHandleSelectionChangeCommand(
aCommand);
}
}
void HTMLEditor::PostHandleSelectionChangeCommand(Command aCommand) {
if (!mPendingStylesToApplyToNewContent) {
return;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (!editActionData.CanHandle()) {
return;
}
mPendingStylesToApplyToNewContent->PostHandleSelectionChangeCommand(*this,
aCommand);
}
nsresult HTMLEditor::HandleKeyPressEvent(WidgetKeyboardEvent* aKeyboardEvent) {
// NOTE: When you change this method, you should also change:
// * editor/libeditor/tests/test_htmleditor_keyevent_handling.html
if (NS_WARN_IF(!aKeyboardEvent)) {
return NS_ERROR_UNEXPECTED;
}
if (IsReadonly()) {
HandleKeyPressEventInReadOnlyMode(*aKeyboardEvent);
return NS_OK;
}
MOZ_ASSERT(aKeyboardEvent->mMessage == eKeyPress,
"HandleKeyPressEvent gets non-keypress event");
switch (aKeyboardEvent->mKeyCode) {
case NS_VK_META:
case NS_VK_WIN:
case NS_VK_SHIFT:
case NS_VK_CONTROL:
case NS_VK_ALT:
// FYI: This shouldn't occur since modifier key shouldn't cause eKeyPress
// event.
aKeyboardEvent->PreventDefault();
return NS_OK;
case NS_VK_BACK:
case NS_VK_DELETE: {
nsresult rv = EditorBase::HandleKeyPressEvent(aKeyboardEvent);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::HandleKeyPressEvent() failed");
return rv;
}
case NS_VK_TAB: {
// Basically, "Tab" key be used only for focus navigation.
// FYI: In web apps, this is always true.
if (IsTabbable()) {
return NS_OK;
}
// If we're in the plaintext mode, and not tabbable editor, let's
// insert a horizontal tabulation.
if (IsPlaintextMailComposer()) {
if (aKeyboardEvent->IsShift() || aKeyboardEvent->IsControl() ||
aKeyboardEvent->IsAlt() || aKeyboardEvent->IsMeta()) {
return NS_OK;
}
// else we insert the tab straight through
aKeyboardEvent->PreventDefault();
nsresult rv = OnInputText(u"\t"_ns);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::OnInputText(\\t) failed");
return rv;
}
// Otherwise, e.g., we're an embedding editor in chrome, we can handle
// "Tab" key as an input.
if (aKeyboardEvent->IsControl() || aKeyboardEvent->IsAlt() ||
aKeyboardEvent->IsMeta()) {
return NS_OK;
}
RefPtr<Selection> selection = GetSelection();
if (NS_WARN_IF(!selection) || NS_WARN_IF(!selection->RangeCount())) {
return NS_ERROR_FAILURE;
}
nsINode* startContainer = selection->GetRangeAt(0)->GetStartContainer();
MOZ_ASSERT(startContainer);
if (!startContainer->IsContent()) {
break;
}
const Element* editableBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*startContainer->AsContent(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle);
if (!editableBlockElement) {
break;
}
// If selection is in a table element, we need special handling.
if (HTMLEditUtils::IsAnyTableElementExceptColumnElement(
*editableBlockElement)) {
Result<EditActionResult, nsresult> result =
HandleTabKeyPressInTable(aKeyboardEvent);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::HandleTabKeyPressInTable() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
if (!result.inspect().Handled()) {
return NS_OK;
}
nsresult rv = ScrollSelectionFocusIntoView();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::ScrollSelectionFocusIntoView() failed");
return EditorBase::ToGenericNSResult(rv);
}
// If selection is in an list item element, treat it as indent or outdent.
if (HTMLEditUtils::IsListItemElement(*editableBlockElement)) {
aKeyboardEvent->PreventDefault();
if (!aKeyboardEvent->IsShift()) {
nsresult rv = IndentAsAction();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::IndentAsAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult rv = OutdentAsAction();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::OutdentAsAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
// If only "Tab" key is pressed in normal context, just treat it as
// horizontal tab character input.
if (aKeyboardEvent->IsShift()) {
return NS_OK;
}
aKeyboardEvent->PreventDefault();
nsresult rv = OnInputText(u"\t"_ns);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::OnInputText(\\t) failed");
return EditorBase::ToGenericNSResult(rv);
}
case NS_VK_RETURN: {
if (!aKeyboardEvent->IsInputtingLineBreak()) {
return NS_OK;
}
// Anyway consume the event even if we cannot handle it actually because
// we've already checked whether the an editing host has focus.
aKeyboardEvent->PreventDefault();
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_UNEXPECTED;
}
// Shift + Enter should insert a <br> or a LF instead of splitting current
// paragraph. Additionally, if we're in plaintext-only mode, we should
// do so because Chrome does so, but execCommand("insertParagraph") keeps
// working as contenteditable=true. So, we cannot redirect in
// InsertParagraphSeparatorAsAction().
if (aKeyboardEvent->IsShift() ||
editingHost->IsContentEditablePlainTextOnly()) {
// Only inserts a <br> element.
nsresult rv = InsertLineBreakAsAction();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertLineBreakAsAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
// uses rules to figure out what to insert
nsresult rv = InsertParagraphSeparatorAsAction();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::InsertParagraphSeparatorAsAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
}
if (!aKeyboardEvent->IsInputtingText()) {
// we don't PreventDefault() here or keybindings like control-x won't work
return NS_OK;
}
aKeyboardEvent->PreventDefault();
// If we dispatch 2 keypress events for a surrogate pair and we set only
// first `.key` value to the surrogate pair, the preceding one has it and the
// other has empty string. In this case, we should handle only the first one
// with the key value.
if (!StaticPrefs::dom_event_keypress_dispatch_once_per_surrogate_pair() &&
!StaticPrefs::dom_event_keypress_key_allow_lone_surrogate() &&
aKeyboardEvent->mKeyValue.IsEmpty() &&
IS_SURROGATE(aKeyboardEvent->mCharCode)) {
return NS_OK;
}
nsAutoString str(aKeyboardEvent->mKeyValue);
if (str.IsEmpty()) {
str.Assign(static_cast<char16_t>(aKeyboardEvent->mCharCode));
}
// FYI: DIfferent from TextEditor, we can treat \r (CR) as-is in HTMLEditor.
nsresult rv = OnInputText(str);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "EditorBase::OnInputText() failed");
return rv;
}
NS_IMETHODIMP HTMLEditor::NodeIsBlock(nsINode* aNode, bool* aIsBlock) {
if (NS_WARN_IF(!aNode)) {
return NS_ERROR_INVALID_ARG;
}
if (MOZ_UNLIKELY(!aNode->IsElement())) {
*aIsBlock = false;
return NS_OK;
}
// If the node is in composed doc, we'll refer its style. If we don't flush
// pending style here, another API call may change the style. Therefore,
// let's flush the pending style changes right now.
if (aNode->IsInComposedDoc()) {
if (RefPtr<PresShell> presShell = GetPresShell()) {
presShell->FlushPendingNotifications(FlushType::Style);
}
}
*aIsBlock = HTMLEditUtils::IsBlockElement(
*aNode->AsElement(), BlockInlineCheck::UseComputedDisplayOutsideStyle);
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::UpdateBaseURL() {
RefPtr<Document> document = GetDocument();
if (NS_WARN_IF(!document)) {
return NS_ERROR_FAILURE;
}
// Look for an HTML <base> tag
RefPtr<nsContentList> baseElementList =
document->GetElementsByTagName(u"base"_ns);
// If no base tag, then set baseURL to the document's URL. This is very
// important, else relative URLs for links and images are wrong
if (!baseElementList || !baseElementList->Item(0)) {
document->SetBaseURI(document->GetDocumentURI());
}
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::InsertLineBreak() {
// XPCOM method's InsertLineBreak() should insert paragraph separator in
// HTMLEditor.
AutoEditActionDataSetter editActionData(
*this, EditAction::eInsertParagraphSeparator);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
Result<EditActionResult, nsresult> result =
InsertParagraphSeparatorAsSubAction(*editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::InsertParagraphSeparatorAsSubAction() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
nsresult HTMLEditor::InsertLineBreakAsAction(nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertLineBreak,
aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
if (IsSelectionRangeContainerNotContent()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
rv = InsertLineBreakAsSubAction();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertLineBreakAsSubAction() failed");
// Don't return NS_SUCCESS_DOM_NO_OPERATION for compatibility of `execCommand`
// result of Chrome.
return NS_FAILED(rv) ? rv : NS_OK;
}
nsresult HTMLEditor::InsertParagraphSeparatorAsAction(
nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(
*this, EditAction::eInsertParagraphSeparator, aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
Result<EditActionResult, nsresult> result =
InsertParagraphSeparatorAsSubAction(*editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::InsertParagraphSeparatorAsSubAction() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
Result<EditActionResult, nsresult> HTMLEditor::HandleTabKeyPressInTable(
WidgetKeyboardEvent* aKeyboardEvent) {
MOZ_ASSERT(aKeyboardEvent);
AutoEditActionDataSetter dummyEditActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!dummyEditActionData.CanHandle())) {
// Do nothing if we didn't find a table cell.
return EditActionResult::IgnoredResult();
}
// Find enclosing table cell from selection (cell may be selected element)
const RefPtr<Element> cellElement =
GetInclusiveAncestorByTagNameAtSelection(*nsGkAtoms::td);
if (!cellElement) {
NS_WARNING(
"HTMLEditor::GetInclusiveAncestorByTagNameAtSelection(*nsGkAtoms::td) "
"returned nullptr");
// Do nothing if we didn't find a table cell.
return EditActionResult::IgnoredResult();
}
// find enclosing table
RefPtr<Element> table =
HTMLEditUtils::GetClosestAncestorTableElement(*cellElement);
if (!table) {
NS_WARNING("HTMLEditor::GetClosestAncestorTableElement() failed");
return EditActionResult::IgnoredResult();
}
// advance to next cell
// first create an iterator over the table
PostContentIterator postOrderIter;
nsresult rv = postOrderIter.Init(table);
if (NS_FAILED(rv)) {
NS_WARNING("PostContentIterator::Init() failed");
return Err(rv);
}
// position postOrderIter at block
rv = postOrderIter.PositionAt(cellElement);
if (NS_FAILED(rv)) {
NS_WARNING("PostContentIterator::PositionAt() failed");
return Err(rv);
}
do {
if (aKeyboardEvent->IsShift()) {
postOrderIter.Prev();
} else {
postOrderIter.Next();
}
const RefPtr<Element> element =
Element::FromNodeOrNull(postOrderIter.GetCurrentNode());
if (element && HTMLEditUtils::IsTableCellElement(*element) &&
HTMLEditUtils::GetClosestAncestorTableElement(*element) == table) {
aKeyboardEvent->PreventDefault();
CollapseSelectionToDeepestNonTableFirstChild(element);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
return EditActionResult::HandledResult();
}
} while (!postOrderIter.IsDone());
if (aKeyboardEvent->IsShift()) {
return EditActionResult::IgnoredResult();
}
// If we haven't handled it yet, then we must have run off the end of the
// table. Insert a new row.
// XXX We should investigate whether this behavior is supported by other
// browsers later.
AutoEditActionDataSetter editActionData(*this,
EditAction::eInsertTableRowElement);
rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return Err(rv);
}
rv = InsertTableRowsWithTransaction(*cellElement, 1,
InsertPosition::eAfterSelectedCell);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::InsertTableRowsWithTransaction(*cellElement, 1, "
"InsertPosition::eAfterSelectedCell) failed");
return Err(rv);
}
aKeyboardEvent->PreventDefault();
// Put selection in right place. Use table code to get selection and index
// to new row...
RefPtr<Element> tblElement, cell;
int32_t row;
rv = GetCellContext(getter_AddRefs(tblElement), getter_AddRefs(cell), nullptr,
nullptr, &row, nullptr);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::GetCellContext() failed");
return Err(rv);
}
if (!tblElement) {
NS_WARNING("HTMLEditor::GetCellContext() didn't return table element");
return Err(NS_ERROR_FAILURE);
}
// ...so that we can ask for first cell in that row...
cell = GetTableCellElementAt(*tblElement, row, 0);
// ...and then set selection there. (Note that normally you should use
// CollapseSelectionToDeepestNonTableFirstChild(), but we know cell is an
// empty new cell, so this works fine)
if (cell) {
nsresult rv = CollapseSelectionToStartOf(*cell);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionToStartOf() failed");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
}
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
return EditActionResult::HandledResult();
}
void HTMLEditor::CollapseSelectionToDeepestNonTableFirstChild(nsINode* aNode) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aNode);
nsCOMPtr<nsINode> node = aNode;
for (nsIContent* child = node->GetFirstChild(); child;
child = child->GetFirstChild()) {
// Stop if we find a table, don't want to go into nested tables
if (child->IsHTMLElement(nsGkAtoms::table) ||
!HTMLEditUtils::IsContainerNode(*child)) {
break;
}
node = child;
}
DebugOnly<nsresult> rvIgnored = CollapseSelectionToStartOf(*node);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::CollapseSelectionToStartOf() failed, but ignored");
}
NS_IMETHODIMP HTMLEditor::InsertElementAtSelection(Element* aElement,
bool aDeleteSelection) {
InsertElementOptions options;
if (aDeleteSelection) {
options += InsertElementOption::DeleteSelection;
}
nsresult rv = InsertElementAtSelectionAsAction(aElement, options);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertElementAtSelectionAsAction() failed");
return rv;
}
nsresult HTMLEditor::InsertElementAtSelectionAsAction(
Element* aElement, const InsertElementOptions aOptions,
nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(!aElement)) {
return NS_ERROR_INVALID_ARG;
}
if (IsReadonly()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(
*this, HTMLEditUtils::GetEditActionForInsert(*aElement), aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
DebugOnly<nsresult> rvIgnored = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
UndefineCaretBidiLevel();
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertElement, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return EditorBase::ToGenericNSResult(NS_ERROR_FAILURE);
}
rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement(*editingHost);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
if (aOptions.contains(InsertElementOption::DeleteSelection) &&
!SelectionRef().IsCollapsed()) {
if (!HTMLEditUtils::IsBlockElement(
*aElement, BlockInlineCheck::UseComputedDisplayOutsideStyle)) {
// E.g., inserting an image. In this case we don't need to delete any
// inline wrappers before we do the insertion. Otherwise we let
// DeleteSelectionAndPrepareToCreateNode do the deletion for us, which
// calls DeleteSelection with aStripWrappers = eStrip.
nsresult rv = DeleteSelectionAsSubAction(
eNone,
aOptions.contains(InsertElementOption::SplitAncestorInlineElements)
? eStrip
: eNoStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(eNone, eNoStrip) failed");
return EditorBase::ToGenericNSResult(rv);
}
}
nsresult rv = DeleteSelectionAndPrepareToCreateNode();
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteSelectionAndPrepareToCreateNode() failed");
return rv;
}
}
// If deleting, selection will be collapsed.
// so if not, we collapse it
else {
// Named Anchor is a special case,
// We collapse to insert element BEFORE the selection
// For all other tags, we insert AFTER the selection
if (HTMLEditUtils::IsNamedAnchorElement(*aElement)) {
IgnoredErrorResult ignoredError;
SelectionRef().CollapseToStart(ignoredError);
if (NS_WARN_IF(Destroyed())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"Selection::CollapseToStart() failed, but ignored");
} else {
IgnoredErrorResult ignoredError;
SelectionRef().CollapseToEnd(ignoredError);
if (NS_WARN_IF(Destroyed())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"Selection::CollapseToEnd() failed, but ignored");
}
}
if (!SelectionRef().GetAnchorNode()) {
return NS_OK;
}
if (NS_WARN_IF(!SelectionRef().GetAnchorNode()->IsInclusiveDescendantOf(
editingHost))) {
return NS_ERROR_FAILURE;
}
EditorRawDOMPoint atAnchor(SelectionRef().AnchorRef());
// Adjust position based on the node we are going to insert.
EditorDOMPoint pointToInsert =
HTMLEditUtils::GetBetterInsertionPointFor<EditorDOMPoint>(*aElement,
atAnchor);
if (!pointToInsert.IsSet()) {
NS_WARNING("HTMLEditUtils::GetBetterInsertionPointFor() failed");
return NS_ERROR_FAILURE;
}
Result<EditorDOMPoint, nsresult> pointToInsertOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt(
*this, pointToInsert,
{WhiteSpaceVisibilityKeeper::NormalizeOption::
StopIfFollowingWhiteSpacesStartsWithNBSP});
if (MOZ_UNLIKELY(pointToInsertOrError.isErr())) {
NS_WARNING(
"WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt() failed");
return pointToInsertOrError.propagateErr();
}
pointToInsert = pointToInsertOrError.unwrap();
if (NS_WARN_IF(!pointToInsert.IsSetAndValidInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (aOptions.contains(InsertElementOption::SplitAncestorInlineElements)) {
if (const RefPtr<Element> topmostInlineElement = Element::FromNodeOrNull(
HTMLEditUtils::GetMostDistantAncestorInlineElement(
*pointToInsert.ContainerAs<nsIContent>(),
BlockInlineCheck::UseComputedDisplayOutsideStyle,
editingHost))) {
Result<SplitNodeResult, nsresult> splitInlinesResult =
SplitNodeDeepWithTransaction(
*topmostInlineElement, pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitInlinesResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitInlinesResult.unwrapErr();
}
splitInlinesResult.inspect().IgnoreCaretPointSuggestion();
auto splitPoint =
splitInlinesResult.inspect().AtSplitPoint<EditorDOMPoint>();
if (MOZ_LIKELY(splitPoint.IsSet())) {
pointToInsert = std::move(splitPoint);
}
}
}
{
Result<CreateElementResult, nsresult> insertElementResult =
InsertNodeIntoProperAncestorWithTransaction<Element>(
*aElement, pointToInsert,
SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(insertElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eAllowToCreateEmptyContainer) failed");
return EditorBase::ToGenericNSResult(insertElementResult.unwrapErr());
}
if (MOZ_LIKELY(aElement->IsInComposedDoc())) {
const auto afterElement = EditorDOMPoint::After(*aElement);
if (MOZ_LIKELY(afterElement.IsInContentNode())) {
nsresult rv = EnsureNoFollowingUnnecessaryLineBreak(afterElement);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::EnsureNoFollowingUnnecessaryLineBreak() failed");
return EditorBase::ToGenericNSResult(rv);
}
}
}
insertElementResult.inspect().IgnoreCaretPointSuggestion();
}
// Set caret after element, but check for special case
// of inserting table-related elements: set in first cell instead
if (!SetCaretInTableCell(aElement)) {
if (NS_WARN_IF(Destroyed())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
nsresult rv = CollapseSelectionTo(EditorRawDOMPoint::After(*aElement));
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::CollapseSelectionTo() failed");
return EditorBase::ToGenericNSResult(rv);
}
}
// check for inserting a whole table at the end of a block. If so insert
// a br after it.
if (!aElement->IsHTMLElement(nsGkAtoms::table) ||
!HTMLEditUtils::IsLastChild(*aElement,
{WalkTreeOption::IgnoreNonEditableNode})) {
return NS_OK;
}
Result<CreateLineBreakResult, nsresult> insertBRElementResultOrError =
InsertLineBreak(WithTransaction::Yes, LineBreakType::BRElement,
EditorDOMPoint::After(*aElement),
// Will collapse selection to before the new line break.
ePrevious);
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertLineBreak(WithTransaction::Yes, "
"LineBreakType::BRElement, ePrevious) failed");
return EditorBase::ToGenericNSResult(
insertBRElementResultOrError.unwrapErr());
}
CreateLineBreakResult insertBRElementResult =
insertBRElementResultOrError.unwrap();
MOZ_ASSERT(insertBRElementResult.Handled());
rv = insertBRElementResult.SuggestCaretPointTo(*this, {});
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"CaretPoint::SuggestCaretPointTo() failed");
return EditorBase::ToGenericNSResult(rv);
}
template <typename NodeType>
Result<CreateNodeResultBase<NodeType>, nsresult>
HTMLEditor::InsertNodeIntoProperAncestorWithTransaction(
NodeType& aContentToInsert, const EditorDOMPoint& aPointToInsert,
SplitAtEdges aSplitAtEdges) {
MOZ_ASSERT(aPointToInsert.IsSetAndValidInComposedDoc());
if (NS_WARN_IF(!aPointToInsert.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
if (aContentToInsert.NodeType() == nsINode::DOCUMENT_TYPE_NODE ||
aContentToInsert.NodeType() == nsINode::PROCESSING_INSTRUCTION_NODE) {
return CreateNodeResultBase<NodeType>::NotHandled();
}
// Search up the parent chain to find a suitable container.
EditorDOMPoint pointToInsert(aPointToInsert);
MOZ_ASSERT(pointToInsert.IsInContentNode());
while (!HTMLEditUtils::CanNodeContain(*pointToInsert.GetContainer(),
aContentToInsert)) {
// If the current parent is a root (body or table element)
// then go no further - we can't insert.
if (MOZ_UNLIKELY(pointToInsert.IsContainerHTMLElement(nsGkAtoms::body) ||
HTMLEditUtils::IsAnyTableElementExceptColumnElement(
*pointToInsert.ContainerAs<nsIContent>()))) {
NS_WARNING(
"There was no proper container element to insert the content node in "
"the document");
return Err(NS_ERROR_FAILURE);
}
// Get the next point.
pointToInsert = pointToInsert.ParentPoint();
if (MOZ_UNLIKELY(
!pointToInsert.IsInContentNode() ||
!EditorUtils::IsEditableContent(
*pointToInsert.ContainerAs<nsIContent>(), EditorType::HTML))) {
NS_WARNING(
"There was no proper container element to insert the content node in "
"the editing host");
return Err(NS_ERROR_FAILURE);
}
}
if (pointToInsert != aPointToInsert) {
// We need to split some levels above the original selection parent.
MOZ_ASSERT(pointToInsert.GetChild());
Result<SplitNodeResult, nsresult> splitNodeResult =
SplitNodeDeepWithTransaction(MOZ_KnownLive(*pointToInsert.GetChild()),
aPointToInsert, aSplitAtEdges);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitNodeResult.propagateErr();
}
pointToInsert =
splitNodeResult.inspect().template AtSplitPoint<EditorDOMPoint>();
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
// Caret should be set by the caller of this method so that we don't
// need to handle it here.
splitNodeResult.inspect().IgnoreCaretPointSuggestion();
}
// Now we can insert the new node.
Result<CreateNodeResultBase<NodeType>, nsresult> insertContentNodeResult =
InsertNodeWithTransaction<NodeType>(aContentToInsert, pointToInsert);
if (MOZ_LIKELY(insertContentNodeResult.isOk()) &&
MOZ_UNLIKELY(NS_WARN_IF(!aContentToInsert.GetParentNode()) ||
NS_WARN_IF(aContentToInsert.GetParentNode() !=
pointToInsert.GetContainer()))) {
NS_WARNING(
"EditorBase::InsertNodeWithTransaction() succeeded, but the inserted "
"node was moved or removed by the web app");
insertContentNodeResult.inspect().IgnoreCaretPointSuggestion();
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
NS_WARNING_ASSERTION(insertContentNodeResult.isOk(),
"EditorBase::InsertNodeWithTransaction() failed");
return insertContentNodeResult;
}
NS_IMETHODIMP HTMLEditor::SelectElement(Element* aElement) {
if (NS_WARN_IF(!aElement)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = SelectContentInternal(MOZ_KnownLive(*aElement));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::SelectContentInternal() failed");
return rv;
}
nsresult HTMLEditor::SelectContentInternal(nsIContent& aContentToSelect) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Must be sure that element is contained in the editing host
const RefPtr<Element> editingHost = ComputeEditingHost();
if (NS_WARN_IF(!editingHost) ||
NS_WARN_IF(!aContentToSelect.IsInclusiveDescendantOf(editingHost))) {
return NS_ERROR_FAILURE;
}
EditorRawDOMPoint newSelectionStart(&aContentToSelect);
if (NS_WARN_IF(!newSelectionStart.IsSet())) {
return NS_ERROR_FAILURE;
}
EditorRawDOMPoint newSelectionEnd(EditorRawDOMPoint::After(aContentToSelect));
MOZ_ASSERT(newSelectionEnd.IsSet());
ErrorResult error;
SelectionRef().SetStartAndEndInLimiter(newSelectionStart, newSelectionEnd,
error);
NS_WARNING_ASSERTION(!error.Failed(),
"Selection::SetStartAndEndInLimiter() failed");
return error.StealNSResult();
}
nsresult HTMLEditor::AppendContentToSelectionAsRange(nsIContent& aContent) {
MOZ_ASSERT(IsEditActionDataAvailable());
EditorRawDOMPoint atContent(&aContent);
if (NS_WARN_IF(!atContent.IsSet())) {
return NS_ERROR_FAILURE;
}
RefPtr<nsRange> range = nsRange::Create(
atContent.ToRawRangeBoundary(),
atContent.NextPoint().ToRawRangeBoundary(), IgnoreErrors());
if (NS_WARN_IF(!range)) {
NS_WARNING("nsRange::Create() failed");
return NS_ERROR_FAILURE;
}
ErrorResult error;
SelectionRef().AddRangeAndSelectFramesAndNotifyListeners(*range, error);
if (NS_WARN_IF(Destroyed())) {
if (error.Failed()) {
error.SuppressException();
}
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(!error.Failed(), "Failed to add range to Selection");
return error.StealNSResult();
}
nsresult HTMLEditor::ClearSelection() {
MOZ_ASSERT(IsEditActionDataAvailable());
ErrorResult error;
SelectionRef().RemoveAllRanges(error);
if (NS_WARN_IF(Destroyed())) {
if (error.Failed()) {
error.SuppressException();
}
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(!error.Failed(), "Selection::RemoveAllRanges() failed");
return error.StealNSResult();
}
nsresult HTMLEditor::FormatBlockAsAction(const nsAString& aParagraphFormat,
nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(aParagraphFormat.IsEmpty())) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(
*this, EditAction::eInsertBlockElement, aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
RefPtr<nsAtom> tagName = NS_Atomize(aParagraphFormat);
MOZ_ASSERT(tagName);
if (NS_WARN_IF(!tagName->IsStatic()) ||
NS_WARN_IF(!HTMLEditUtils::IsFormatTagForFormatBlockCommand(
*tagName->AsStatic()))) {
return NS_ERROR_INVALID_ARG;
}
if (tagName == nsGkAtoms::dd || tagName == nsGkAtoms::dt) {
// MOZ_KnownLive(tagName->AsStatic()) because nsStaticAtom instances live
// while the process is running.
Result<EditActionResult, nsresult> result =
MakeOrChangeListAndListItemAsSubAction(
MOZ_KnownLive(*tagName->AsStatic()), EmptyString(),
SelectAllOfCurrentList::No, *editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING(
"HTMLEditor::MakeOrChangeListAndListItemAsSubAction("
"SelectAllOfCurrentList::No) failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
rv = FormatBlockContainerAsSubAction(MOZ_KnownLive(*tagName->AsStatic()),
FormatBlockMode::HTMLFormatBlockCommand,
*editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::FormatBlockContainerAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::SetParagraphStateAsAction(
const nsAString& aParagraphFormat, nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(
*this, EditAction::eInsertBlockElement, aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
// TODO: Computing the editing host here makes the `execCommand` in
// docshell/base/crashtests/file_432114-2.xhtml cannot run
// `DOMNodeRemoved` event listener with deleting the bogus <br> element.
// So that it should be rewritten with different mutation event listener
// since we'd like to stop using it.
nsAutoString lowerCaseTagName(aParagraphFormat);
ToLowerCase(lowerCaseTagName);
RefPtr<nsAtom> tagName = NS_Atomize(lowerCaseTagName);
MOZ_ASSERT(tagName);
if (NS_WARN_IF(!tagName->IsStatic())) {
return NS_ERROR_INVALID_ARG;
}
if (tagName == nsGkAtoms::dd || tagName == nsGkAtoms::dt) {
// MOZ_KnownLive(tagName->AsStatic()) because nsStaticAtom instances live
// while the process is running.
Result<EditActionResult, nsresult> result =
MakeOrChangeListAndListItemAsSubAction(
MOZ_KnownLive(*tagName->AsStatic()), EmptyString(),
SelectAllOfCurrentList::No, *editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING(
"HTMLEditor::MakeOrChangeListAndListItemAsSubAction("
"SelectAllOfCurrentList::No) failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
rv = FormatBlockContainerAsSubAction(
MOZ_KnownLive(*tagName->AsStatic()),
FormatBlockMode::XULParagraphStateCommand, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::FormatBlockContainerAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
// static
bool HTMLEditor::IsFormatElement(FormatBlockMode aFormatBlockMode,
const nsIContent& aContent) {
// FYI: Optimize for HTML command because it may run too many times.
return MOZ_LIKELY(aFormatBlockMode == FormatBlockMode::HTMLFormatBlockCommand)
? HTMLEditUtils::IsFormatElementForFormatBlockCommand(aContent)
: (HTMLEditUtils::IsFormatElementForParagraphStateCommand(
aContent) &&
// XXX The XUL paragraph state command treats <dl>, <dd> and
// <dt> elements but all handlers do not treat them as a format
// node. Therefore, we keep the traditional behavior here.
!aContent.IsAnyOfHTMLElements(nsGkAtoms::dd, nsGkAtoms::dl,
nsGkAtoms::dt));
}
NS_IMETHODIMP HTMLEditor::GetParagraphState(bool* aMixed,
nsAString& aFirstParagraphState) {
if (NS_WARN_IF(!aMixed)) {
return NS_ERROR_INVALID_ARG;
}
if (!mInitSucceeded) {
return NS_ERROR_NOT_INITIALIZED;
}
ErrorResult error;
ParagraphStateAtSelection paragraphState(
*this, FormatBlockMode::XULParagraphStateCommand, error);
if (error.Failed()) {
NS_WARNING("ParagraphStateAtSelection failed");
return error.StealNSResult();
}
*aMixed = paragraphState.IsMixed();
if (NS_WARN_IF(!paragraphState.GetFirstParagraphStateAtSelection())) {
// XXX Odd result, but keep this behavior for now...
aFirstParagraphState.AssignASCII("x");
} else {
paragraphState.GetFirstParagraphStateAtSelection()->ToString(
aFirstParagraphState);
}
return NS_OK;
}
nsresult HTMLEditor::GetBackgroundColorState(bool* aMixed,
nsAString& aOutColor) {
if (NS_WARN_IF(!aMixed)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
if (IsCSSEnabled()) {
// if we are in CSS mode, we have to check if the containing block defines
// a background color
nsresult rv = GetCSSBackgroundColorState(
aMixed, aOutColor,
{RetrievingBackgroundColorOption::OnlyBlockBackgroundColor,
RetrievingBackgroundColorOption::
DefaultColorIfNoSpecificBackgroundColor});
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetCSSBackgroundColorState() failed");
return EditorBase::ToGenericNSResult(rv);
}
// in HTML mode, we look only at page's background
nsresult rv = GetHTMLBackgroundColorState(aMixed, aOutColor);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetCSSBackgroundColorState() failed");
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP HTMLEditor::GetHighlightColorState(bool* aMixed,
nsAString& aOutColor) {
if (NS_WARN_IF(!aMixed)) {
return NS_ERROR_INVALID_ARG;
}
*aMixed = false;
aOutColor.AssignLiteral("transparent");
if (!IsCSSEnabled() && IsMailEditor()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
// in CSS mode, text background can be added by the Text Highlight button
// we need to query the background of the selection without looking for
// the block container of the ranges in the selection
RetrievingBackgroundColorOptions options;
if (IsMailEditor()) {
options += RetrievingBackgroundColorOption::StopAtInclusiveAncestorBlock;
}
nsresult rv = GetCSSBackgroundColorState(aMixed, aOutColor, options);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetCSSBackgroundColorState() failed");
return rv;
}
nsresult HTMLEditor::GetCSSBackgroundColorState(
bool* aMixed, nsAString& aOutColor,
RetrievingBackgroundColorOptions aOptions) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!aMixed)) {
return NS_ERROR_INVALID_ARG;
}
*aMixed = false;
// the default background color is transparent
aOutColor.AssignLiteral("transparent");
RefPtr<const nsRange> firstRange = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!firstRange)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsINode> startContainer = firstRange->GetStartContainer();
if (NS_WARN_IF(!startContainer) || NS_WARN_IF(!startContainer->IsContent())) {
return NS_ERROR_FAILURE;
}
// is the selection collapsed?
nsIContent* contentToExamine;
if (SelectionRef().IsCollapsed() || startContainer->IsText()) {
if (NS_WARN_IF(!startContainer->IsContent())) {
return NS_ERROR_FAILURE;
}
// we want to look at the startContainer and ancestors
contentToExamine = startContainer->AsContent();
} else {
// otherwise we want to look at the first editable node after
// {startContainer,offset} and its ancestors for divs with alignment on them
contentToExamine = firstRange->GetChildAtStartOffset();
// GetNextNode(startContainer, offset, true, address_of(contentToExamine));
}
if (NS_WARN_IF(!contentToExamine)) {
return NS_ERROR_FAILURE;
}
if (aOptions.contains(
RetrievingBackgroundColorOption::OnlyBlockBackgroundColor)) {
// we are querying the block background (and not the text background), let's
// climb to the block container. Note that background color of ancestor
// of editing host may be what the caller wants to know. Therefore, we
// should ignore the editing host boundaries.
Element* const closestBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*contentToExamine, HTMLEditUtils::ClosestBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle);
if (NS_WARN_IF(!closestBlockElement)) {
return NS_OK;
}
for (RefPtr<Element> blockElement = closestBlockElement; blockElement;) {
RefPtr<Element> nextBlockElement = HTMLEditUtils::GetAncestorElement(
*blockElement, HTMLEditUtils::ClosestBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle);
DebugOnly<nsresult> rvIgnored = CSSEditUtils::GetComputedProperty(
*blockElement, *nsGkAtoms::background_color, aOutColor);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (MaybeNodeRemovalsObservedByDevTools() &&
NS_WARN_IF(nextBlockElement !=
HTMLEditUtils::GetAncestorElement(
*blockElement, HTMLEditUtils::ClosestBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle))) {
return NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"CSSEditUtils::GetComputedProperty(nsGkAtoms::"
"background_color) failed, but ignored");
// look at parent if the queried color is transparent and if the node to
// examine is not the root of the document
if (!HTMLEditUtils::IsTransparentCSSColor(aOutColor)) {
return NS_OK;
}
if (aOptions.contains(
RetrievingBackgroundColorOption::StopAtInclusiveAncestorBlock)) {
aOutColor.AssignLiteral("transparent");
return NS_OK;
}
blockElement = std::move(nextBlockElement);
}
if (aOptions.contains(RetrievingBackgroundColorOption::
DefaultColorIfNoSpecificBackgroundColor) &&
HTMLEditUtils::IsTransparentCSSColor(aOutColor)) {
CSSEditUtils::GetDefaultBackgroundColor(aOutColor);
}
return NS_OK;
}
// no, we are querying the text background for the Text Highlight button
if (contentToExamine->IsText()) {
// if the node of interest is a text node, let's climb a level
contentToExamine = contentToExamine->GetParent();
}
// Return default value due to no parent node
if (!contentToExamine) {
return NS_OK;
}
for (RefPtr<Element> element :
contentToExamine->InclusiveAncestorsOfType<Element>()) {
// is the node to examine a block ?
if (aOptions.contains(
RetrievingBackgroundColorOption::StopAtInclusiveAncestorBlock) &&
HTMLEditUtils::IsBlockElement(
*element, BlockInlineCheck::UseComputedDisplayOutsideStyle)) {
// yes it is a block; in that case, the text background color is
// transparent
aOutColor.AssignLiteral("transparent");
break;
}
// no, it's not; let's retrieve the computed style of background-color
// for the node to examine
nsCOMPtr<nsINode> parentNode = element->GetParentNode();
DebugOnly<nsresult> rvIgnored = CSSEditUtils::GetComputedProperty(
*element, *nsGkAtoms::background_color, aOutColor);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_WARN_IF(parentNode != element->GetParentNode())) {
return NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"CSSEditUtils::GetComputedProperty(nsGkAtoms::"
"background_color) failed, but ignored");
if (!HTMLEditUtils::IsTransparentCSSColor(aOutColor)) {
HTMLEditUtils::GetNormalizedCSSColorValue(
aOutColor, HTMLEditUtils::ZeroAlphaColor::RGBAValue, aOutColor);
return NS_OK;
}
}
if (aOptions.contains(RetrievingBackgroundColorOption::
DefaultColorIfNoSpecificBackgroundColor) &&
HTMLEditUtils::IsTransparentCSSColor(aOutColor)) {
CSSEditUtils::GetDefaultBackgroundColor(aOutColor);
}
return NS_OK;
}
nsresult HTMLEditor::GetHTMLBackgroundColorState(bool* aMixed,
nsAString& aOutColor) {
MOZ_ASSERT(IsEditActionDataAvailable());
// TODO: We don't handle "mixed" correctly!
if (NS_WARN_IF(!aMixed)) {
return NS_ERROR_INVALID_ARG;
}
*aMixed = false;
aOutColor.Truncate();
Result<RefPtr<Element>, nsresult> cellOrRowOrTableElementOrError =
GetSelectedOrParentTableElement();
if (cellOrRowOrTableElementOrError.isErr()) {
NS_WARNING("HTMLEditor::GetSelectedOrParentTableElement() returned error");
return cellOrRowOrTableElementOrError.unwrapErr();
}
for (RefPtr<Element> element = cellOrRowOrTableElementOrError.unwrap();
element; element = element->GetParentElement()) {
// We are in a cell or selected table
element->GetAttr(nsGkAtoms::bgcolor, aOutColor);
// Done if we have a color explicitly set
if (!aOutColor.IsEmpty()) {
return NS_OK;
}
// Once we hit the body, we're done
if (element->IsHTMLElement(nsGkAtoms::body)) {
return NS_OK;
}
// No color is set, but we need to report visible color inherited
// from nested cells/tables, so search up parent chain so that
// let's keep checking the ancestors.
}
// If no table or cell found, get page body
Element* rootElement = GetRoot();
if (NS_WARN_IF(!rootElement)) {
return NS_ERROR_FAILURE;
}
rootElement->GetAttr(nsGkAtoms::bgcolor, aOutColor);
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::GetListState(bool* aMixed, bool* aOL, bool* aUL,
bool* aDL) {
if (NS_WARN_IF(!aMixed) || NS_WARN_IF(!aOL) || NS_WARN_IF(!aUL) ||
NS_WARN_IF(!aDL)) {
return NS_ERROR_INVALID_ARG;
}
if (!mInitSucceeded) {
return NS_ERROR_NOT_INITIALIZED;
}
ErrorResult error;
ListElementSelectionState state(*this, error);
if (error.Failed()) {
NS_WARNING("ListElementSelectionState failed");
return error.StealNSResult();
}
*aMixed = state.IsNotOneTypeListElementSelected();
*aOL = state.IsOLElementSelected();
*aUL = state.IsULElementSelected();
*aDL = state.IsDLElementSelected();
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::GetListItemState(bool* aMixed, bool* aLI, bool* aDT,
bool* aDD) {
if (NS_WARN_IF(!aMixed) || NS_WARN_IF(!aLI) || NS_WARN_IF(!aDT) ||
NS_WARN_IF(!aDD)) {
return NS_ERROR_INVALID_ARG;
}
if (!mInitSucceeded) {
return NS_ERROR_NOT_INITIALIZED;
}
ErrorResult error;
ListItemElementSelectionState state(*this, error);
if (error.Failed()) {
NS_WARNING("ListItemElementSelectionState failed");
return error.StealNSResult();
}
// XXX Why do we ignore `<li>` element selected state?
*aMixed = state.IsNotOneTypeDefinitionListItemElementSelected();
*aLI = state.IsLIElementSelected();
*aDT = state.IsDTElementSelected();
*aDD = state.IsDDElementSelected();
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::GetAlignment(bool* aMixed,
nsIHTMLEditor::EAlignment* aAlign) {
if (NS_WARN_IF(!aMixed) || NS_WARN_IF(!aAlign)) {
return NS_ERROR_INVALID_ARG;
}
if (!mInitSucceeded) {
return NS_ERROR_NOT_INITIALIZED;
}
ErrorResult error;
AlignStateAtSelection state(*this, error);
if (error.Failed()) {
NS_WARNING("AlignStateAtSelection failed");
return error.StealNSResult();
}
*aMixed = false;
*aAlign = state.AlignmentAtSelectionStart();
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::MakeOrChangeList(const nsAString& aListType,
bool aEntireList,
const nsAString& aBulletType) {
RefPtr<nsAtom> listTagName = NS_Atomize(aListType);
if (NS_WARN_IF(!listTagName) || NS_WARN_IF(!listTagName->IsStatic())) {
return NS_ERROR_INVALID_ARG;
}
// MOZ_KnownLive(listTagName->AsStatic()) because nsStaticAtom instances live
// while the process is running.
nsresult rv = MakeOrChangeListAsAction(
MOZ_KnownLive(*listTagName->AsStatic()), aBulletType,
aEntireList ? SelectAllOfCurrentList::Yes : SelectAllOfCurrentList::No);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::MakeOrChangeListAsAction() failed");
return rv;
}
nsresult HTMLEditor::MakeOrChangeListAsAction(
const nsStaticAtom& aListElementTagName, const nsAString& aBulletType,
SelectAllOfCurrentList aSelectAllOfCurrentList, nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
AutoEditActionDataSetter editActionData(
*this, HTMLEditUtils::GetEditActionForInsert(aListElementTagName),
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
Result<EditActionResult, nsresult> result =
MakeOrChangeListAndListItemAsSubAction(aListElementTagName, aBulletType,
aSelectAllOfCurrentList,
*editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::MakeOrChangeListAndListItemAsSubAction() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::RemoveList(const nsAString& aListType) {
nsresult rv = RemoveListAsAction(aListType);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::RemoveListAsAction() failed");
return rv;
}
nsresult HTMLEditor::RemoveListAsAction(const nsAString& aListType,
nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
// Note that we ignore aListType when we actually remove parent list elements.
// However, we need to set InputEvent.inputType to "insertOrderedList" or
// "insertedUnorderedList" when this is called for
// execCommand("insertorderedlist") or execCommand("insertunorderedlist").
// Otherwise, comm-central UI may call this methods with "dl" or "".
// So, it's okay to use mismatched EditAction here if this is called in
// comm-central.
RefPtr<nsAtom> listAtom = NS_Atomize(aListType);
if (NS_WARN_IF(!listAtom)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(
*this, HTMLEditUtils::GetEditActionForRemoveList(*listAtom), aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
const RefPtr<Element> editingHost = ComputeEditingHost();
if (!editingHost) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
rv = RemoveListAtSelectionAsSubAction(*editingHost);
NS_WARNING_ASSERTION(NS_FAILED(rv),
"HTMLEditor::RemoveListAtSelectionAsSubAction() failed");
return rv;
}
nsresult HTMLEditor::FormatBlockContainerAsSubAction(
const nsStaticAtom& aTagName, FormatBlockMode aFormatBlockMode,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
MOZ_ASSERT(&aTagName != nsGkAtoms::dd && &aTagName != nsGkAtoms::dt);
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eCreateOrRemoveBlock, nsIEditor::eNext,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result.unwrapErr();
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
if (IsSelectionRangeContainerNotContent()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && SelectionRef().IsCollapsed()) {
nsresult rv = EnsureCaretNotAfterInvisibleBRElement(aEditingHost);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
// FormatBlockContainerWithTransaction() creates AutoSelectionRestorer.
// Therefore, even if it returns NS_OK, editor might have been destroyed
// at restoring Selection.
AutoClonedSelectionRangeArray selectionRanges(SelectionRef());
Result<RefPtr<Element>, nsresult> suggestBlockElementToPutCaretOrError =
FormatBlockContainerWithTransaction(selectionRanges, aTagName,
aFormatBlockMode, aEditingHost);
if (suggestBlockElementToPutCaretOrError.isErr()) {
NS_WARNING("HTMLEditor::FormatBlockContainerWithTransaction() failed");
return suggestBlockElementToPutCaretOrError.unwrapErr();
}
if (selectionRanges.HasSavedRanges()) {
selectionRanges.RestoreFromSavedRanges();
}
if (selectionRanges.IsCollapsed()) {
// FIXME: If we get rid of the legacy mutation events, we should be able to
// just insert a line break without empty check.
Result<CreateLineBreakResult, nsresult>
insertPaddingBRElementResultOrError =
InsertPaddingBRElementIfInEmptyBlock(
selectionRanges.GetFirstRangeStartPoint<EditorDOMPoint>(),
eNoStrip);
if (MOZ_UNLIKELY(insertPaddingBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertPaddingBRElementIfInEmptyBlock(eNoStrip) failed");
return insertPaddingBRElementResultOrError.unwrapErr();
}
EditorDOMPoint pointToPutCaret;
insertPaddingBRElementResultOrError.unwrap().MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (pointToPutCaret.IsSet()) {
nsresult rv = selectionRanges.Collapse(pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING("AutoClonedRangeArray::Collapse() failed");
return rv;
}
}
}
if (!suggestBlockElementToPutCaretOrError.inspect() ||
!selectionRanges.IsCollapsed()) {
nsresult rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoClonedSelectionRangeArray::ApplyTo() failed, but ignored");
return rv;
}
const auto firstSelectionStartPoint =
selectionRanges.GetFirstRangeStartPoint<EditorRawDOMPoint>();
if (NS_WARN_IF(!firstSelectionStartPoint.IsSetAndValidInComposedDoc())) {
return NS_ERROR_FAILURE;
}
Result<EditorRawDOMPoint, nsresult> pointInBlockElementOrError =
HTMLEditUtils::ComputePointToPutCaretInElementIfOutside<
EditorRawDOMPoint>(*suggestBlockElementToPutCaretOrError.inspect(),
firstSelectionStartPoint);
NS_WARNING_ASSERTION(
pointInBlockElementOrError.isOk(),
"HTMLEditUtils::ComputePointToPutCaretInElementIfOutside() failed, but "
"ignored");
// Note that if the point is unset, it means that firstSelectionStartPoint is
// in the block element.
if (MOZ_LIKELY(pointInBlockElementOrError.isOk()) &&
pointInBlockElementOrError.inspect().IsSet()) {
nsresult rv =
selectionRanges.Collapse(pointInBlockElementOrError.inspect());
if (NS_FAILED(rv)) {
NS_WARNING("AutoClonedRangeArray::Collapse() failed");
return rv;
}
}
rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"AutoClonedSelectionRangeArray::ApplyTo() failed, but ignored");
return rv;
}
nsresult HTMLEditor::IndentAsAction(nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eIndent,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
Result<EditActionResult, nsresult> result = IndentAsSubAction(*editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::IndentAsSubAction() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
nsresult HTMLEditor::OutdentAsAction(nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eOutdent,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
Result<EditActionResult, nsresult> result = OutdentAsSubAction(*editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::OutdentAsSubAction() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
// TODO: IMPLEMENT ALIGNMENT!
nsresult HTMLEditor::AlignAsAction(const nsAString& aAlignType,
nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(
*this, HTMLEditUtils::GetEditActionForAlignment(aAlignType), aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
Result<EditActionResult, nsresult> result =
AlignAsSubAction(aAlignType, *editingHost);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::AlignAsSubAction() failed");
return EditorBase::ToGenericNSResult(result.unwrapErr());
}
return NS_OK;
}
Element* HTMLEditor::GetInclusiveAncestorByTagName(const nsStaticAtom& aTagName,
nsIContent& aContent) const {
MOZ_ASSERT(&aTagName != nsGkAtoms::_empty);
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return nullptr;
}
return GetInclusiveAncestorByTagNameInternal(aTagName, aContent);
}
Element* HTMLEditor::GetInclusiveAncestorByTagNameAtSelection(
const nsStaticAtom& aTagName) const {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(&aTagName != nsGkAtoms::_empty);
// If no node supplied, get it from anchor node of current selection
const EditorRawDOMPoint atAnchor(SelectionRef().AnchorRef());
if (NS_WARN_IF(!atAnchor.IsInContentNode())) {
return nullptr;
}
// Try to get the actual selected node
nsIContent* content = nullptr;
if (atAnchor.GetContainer()->HasChildNodes() &&
atAnchor.ContainerAs<nsIContent>()) {
content = atAnchor.GetChild();
}
// Anchor node is probably a text node - just use that
if (!content) {
content = atAnchor.ContainerAs<nsIContent>();
if (NS_WARN_IF(!content)) {
return nullptr;
}
}
return GetInclusiveAncestorByTagNameInternal(aTagName, *content);
}
Element* HTMLEditor::GetInclusiveAncestorByTagNameInternal(
const nsStaticAtom& aTagName, const nsIContent& aContent) const {
MOZ_ASSERT(&aTagName != nsGkAtoms::_empty);
Element* currentElement = aContent.GetAsElementOrParentElement();
if (NS_WARN_IF(!currentElement)) {
MOZ_ASSERT(!aContent.GetParentNode());
return nullptr;
}
bool lookForLink = IsLinkTag(aTagName);
bool lookForNamedAnchor = IsNamedAnchorTag(aTagName);
for (Element* const element :
currentElement->InclusiveAncestorsOfType<Element>()) {
// Stop searching if parent is a body element. Note: Originally used
// IsRoot() to/ stop at table cells, but that's too messy when you are
// trying to find the parent table.
if (element->IsHTMLElement(nsGkAtoms::body)) {
return nullptr;
}
if (lookForLink) {
// Test if we have a link (an anchor with href set)
if (HTMLEditUtils::IsHyperlinkElement(*element)) {
return element;
}
} else if (lookForNamedAnchor) {
// Test if we have a named anchor (an anchor with name set)
if (HTMLEditUtils::IsNamedAnchorElement(*element)) {
return element;
}
} else if (&aTagName == nsGkAtoms::list) {
// Match "ol", "ul", or "dl" for lists
if (HTMLEditUtils::IsListElement(*element)) {
return element;
}
} else if (&aTagName == nsGkAtoms::td) {
// Table cells are another special case: match either "td" or "th"
if (HTMLEditUtils::IsTableCellElement(*element)) {
return element;
}
} else if (&aTagName == element->NodeInfo()->NameAtom()) {
return element;
}
}
return nullptr;
}
NS_IMETHODIMP HTMLEditor::GetElementOrParentByTagName(const nsAString& aTagName,
nsINode* aNode,
Element** aReturn) {
if (NS_WARN_IF(aTagName.IsEmpty()) || NS_WARN_IF(!aReturn)) {
return NS_ERROR_INVALID_ARG;
}
nsStaticAtom* tagName = EditorUtils::GetTagNameAtom(aTagName);
if (NS_WARN_IF(!tagName)) {
// We don't need to support custom elements since this is an internal API.
return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
}
if (NS_WARN_IF(tagName == nsGkAtoms::_empty)) {
return NS_ERROR_INVALID_ARG;
}
if (!aNode) {
AutoEditActionDataSetter dummyEditAction(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!dummyEditAction.CanHandle())) {
return NS_ERROR_NOT_AVAILABLE;
}
RefPtr<Element> parentElement =
GetInclusiveAncestorByTagNameAtSelection(*tagName);
if (!parentElement) {
return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
}
parentElement.forget(aReturn);
return NS_OK;
}
if (!aNode->IsContent() || !aNode->GetAsElementOrParentElement()) {
return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
}
RefPtr<Element> parentElement =
GetInclusiveAncestorByTagName(*tagName, *aNode->AsContent());
if (!parentElement) {
return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
}
parentElement.forget(aReturn);
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::GetSelectedElement(const nsAString& aTagName,
nsISupports** aReturn) {
if (NS_WARN_IF(!aReturn)) {
return NS_ERROR_INVALID_ARG;
}
*aReturn = nullptr;
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
ErrorResult error;
nsStaticAtom* tagName = EditorUtils::GetTagNameAtom(aTagName);
if (!aTagName.IsEmpty() && !tagName) {
// We don't need to support custom elements becaus of internal API.
return NS_OK;
}
RefPtr<nsINode> selectedNode = GetSelectedElement(tagName, error);
NS_WARNING_ASSERTION(!error.Failed(),
"HTMLEditor::GetSelectedElement() failed");
selectedNode.forget(aReturn);
return error.StealNSResult();
}
already_AddRefed<Element> HTMLEditor::GetSelectedElement(const nsAtom* aTagName,
ErrorResult& aRv) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!aRv.Failed());
// If there is no Selection or two or more selection ranges, that means that
// not only one element is selected so that return nullptr.
if (SelectionRef().RangeCount() != 1) {
return nullptr;
}
bool isLinkTag = aTagName && IsLinkTag(*aTagName);
bool isNamedAnchorTag = aTagName && IsNamedAnchorTag(*aTagName);
RefPtr<nsRange> firstRange = SelectionRef().GetRangeAt(0);
MOZ_ASSERT(firstRange);
const RangeBoundary& startRef = firstRange->StartRef();
if (NS_WARN_IF(!startRef.IsSet())) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
const RangeBoundary& endRef = firstRange->EndRef();
if (NS_WARN_IF(!endRef.IsSet())) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
// Optimization for a single selected element
if (startRef.GetContainer() == endRef.GetContainer()) {
nsIContent* const startContent = startRef.GetChildAtOffset();
nsIContent* const endContent = endRef.GetChildAtOffset();
if (startContent && endContent &&
startContent->GetNextSibling() == endContent) {
if (!aTagName) {
if (!startContent->IsElement()) {
// This means only a text node or something is selected. We should
// return nullptr in this case since no other elements are selected.
return nullptr;
}
return do_AddRef(startContent->AsElement());
}
// Test for appropriate node type requested
if (aTagName == startContent->NodeInfo()->NameAtom() ||
(isLinkTag && HTMLEditUtils::IsHyperlinkElement(*startContent)) ||
(isNamedAnchorTag &&
HTMLEditUtils::IsNamedAnchorElement(*startContent))) {
MOZ_ASSERT(startContent->IsElement());
return do_AddRef(startContent->AsElement());
}
}
}
if (isLinkTag && startRef.GetContainer()->IsContent() &&
endRef.GetContainer()->IsContent()) {
// Link node must be the same for both ends of selection.
Element* parentLinkOfStart = GetInclusiveAncestorByTagNameInternal(
*nsGkAtoms::href, *startRef.GetContainer()->AsContent());
if (parentLinkOfStart) {
if (SelectionRef().IsCollapsed()) {
// We have just a caret in the link.
return do_AddRef(parentLinkOfStart);
}
// Link node must be the same for both ends of selection.
Element* parentLinkOfEnd = GetInclusiveAncestorByTagNameInternal(
*nsGkAtoms::href, *endRef.GetContainer()->AsContent());
if (parentLinkOfStart == parentLinkOfEnd) {
return do_AddRef(parentLinkOfStart);
}
}
}
if (SelectionRef().IsCollapsed()) {
return nullptr;
}
PostContentIterator postOrderIter;
nsresult rv = postOrderIter.Init(firstRange);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return nullptr;
}
RefPtr<Element> lastElementInRange;
for (nsINode* lastNodeInRange = nullptr; !postOrderIter.IsDone();
postOrderIter.Next()) {
if (lastElementInRange) {
// When any node follows an element node, not only one element is
// selected so that return nullptr.
return nullptr;
}
// This loop ignors any non-element nodes before first element node.
// Its purpose must be that this method treats this case as selecting
// the <b> element:
// - <p>abc <b>d[ef</b>}</p>
// because children of an element node is listed up before the element.
// However, this case must not be expected by the initial developer:
// - <p>a[bc <b>def</b>}</p>
// When we meet non-parent and non-next-sibling node of previous node,
// it means that the range across element boundary (open tag in HTML
// source). So, in this case, we should not say only the following
// element is selected.
nsINode* currentNode = postOrderIter.GetCurrentNode();
MOZ_ASSERT(currentNode);
if (lastNodeInRange && lastNodeInRange->GetParentNode() != currentNode &&
lastNodeInRange->GetNextSibling() != currentNode) {
return nullptr;
}
lastNodeInRange = currentNode;
lastElementInRange = Element::FromNodeOrNull(lastNodeInRange);
if (!lastElementInRange) {
continue;
}
// And also, if it's followed by a <br> element, we shouldn't treat the
// the element is selected like this case:
// - <p><b>[def</b>}<br></p>
// Note that we don't need special handling for <a href> because double
// clicking it selects the element and we use the first path to handle it.
// Additionally, we have this case too:
// - <p><b>[def</b><b>}<br></b></p>
// In these cases, the <br> element is not listed up by PostContentIterator.
// So, we should return nullptr if next sibling is a `<br>` element or
// next sibling starts with `<br>` element.
if (nsIContent* nextSibling = lastElementInRange->GetNextSibling()) {
if (nextSibling->IsHTMLElement(nsGkAtoms::br)) {
return nullptr;
}
nsIContent* firstEditableLeaf = HTMLEditUtils::GetFirstLeafContent(
*nextSibling, {LeafNodeType::OnlyLeafNode});
if (firstEditableLeaf &&
firstEditableLeaf->IsHTMLElement(nsGkAtoms::br)) {
return nullptr;
}
}
if (!aTagName) {
continue;
}
if (isLinkTag && HTMLEditUtils::IsHyperlinkElement(*lastElementInRange)) {
continue;
}
if (isNamedAnchorTag &&
HTMLEditUtils::IsNamedAnchorElement(*lastElementInRange)) {
continue;
}
if (aTagName == lastElementInRange->NodeInfo()->NameAtom()) {
continue;
}
// First element in the range does not match what the caller is looking
// for.
return nullptr;
}
return lastElementInRange.forget();
}
Result<CreateElementResult, nsresult> HTMLEditor::CreateAndInsertElement(
WithTransaction aWithTransaction, const nsAtom& aTagName,
const EditorDOMPoint& aPointToInsert,
const InitializeInsertingElement& aInitializer) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
// XXX We need offset at new node for RangeUpdaterRef(). Therefore, we need
// to compute the offset now but this is expensive. So, if it's possible,
// we need to redesign RangeUpdaterRef() as avoiding using indices.
(void)aPointToInsert.Offset();
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eCreateNode, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// TODO: This method should have a callback function which is called
// immediately after creating an element but before it's inserted into
// the DOM tree. Then, caller can init the new element's attributes
// and children **without** transactions (it'll reduce the number of
// legacy mutation events). Finally, we can get rid of
// CreatElementTransaction since we can use InsertNodeTransaction
// instead.
auto createNewElementResult =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<CreateElementResult, nsresult> {
RefPtr<Element> newElement = CreateHTMLContent(&aTagName);
if (MOZ_UNLIKELY(!newElement)) {
NS_WARNING("EditorBase::CreateHTMLContent() failed");
return Err(NS_ERROR_FAILURE);
}
nsresult rv = MarkElementDirty(*newElement);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING("EditorBase::MarkElementDirty() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::MarkElementDirty() failed, but ignored");
rv = aInitializer(*this, *newElement, aPointToInsert);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "aInitializer failed");
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
RefPtr<InsertNodeTransaction> transaction =
InsertNodeTransaction::Create(*this, *newElement, aPointToInsert);
rv = aWithTransaction == WithTransaction::Yes
? DoTransactionInternal(transaction)
: transaction->DoTransaction();
// FYI: Transaction::DoTransaction never returns NS_ERROR_EDITOR_*.
if (MOZ_UNLIKELY(Destroyed())) {
NS_WARNING(
"InsertNodeTransaction::DoTransaction() caused destroying the "
"editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("InsertNodeTransaction::DoTransaction() failed");
return Err(rv);
}
// Override the success code if new element was moved by the web apps.
if (newElement &&
newElement->GetParentNode() != aPointToInsert.GetContainer()) {
NS_WARNING("The new element was not inserted into the expected node");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return CreateElementResult(
std::move(newElement),
transaction->SuggestPointToPutCaret<EditorDOMPoint>());
}();
if (MOZ_UNLIKELY(createNewElementResult.isErr())) {
NS_WARNING("EditorBase::DoTransactionInternal() failed");
// XXX Why do we do this even when DoTransaction() returned error?
DebugOnly<nsresult> rvIgnored =
RangeUpdaterRef().SelAdjCreateNode(aPointToInsert);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"RangeUpdater::SelAdjCreateNode() failed");
return createNewElementResult;
}
// If we succeeded to create and insert new element, we need to adjust
// ranges in RangeUpdaterRef(). It currently requires offset of the new
// node. So, let's call it with original offset. Note that if
// aPointToInsert stores child node, it may not be at the offset since new
// element must be inserted before the old child. Although, mutation
// observer can do anything, but currently, we don't check it.
DebugOnly<nsresult> rvIgnored =
RangeUpdaterRef().SelAdjCreateNode(EditorRawDOMPoint(
aPointToInsert.GetContainer(), aPointToInsert.Offset()));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"RangeUpdater::SelAdjCreateNode() failed, but ignored");
if (MOZ_LIKELY(createNewElementResult.inspect().GetNewNode())) {
TopLevelEditSubActionDataRef().DidCreateElement(
*this, *createNewElementResult.inspect().GetNewNode());
}
return createNewElementResult;
}
nsresult HTMLEditor::CopyAttributes(WithTransaction aWithTransaction,
Element& aDestElement, Element& aSrcElement,
const AttributeFilter& aFilterFunc) {
if (!aSrcElement.GetAttrCount()) {
return NS_OK;
}
struct MOZ_STACK_CLASS AttrCache {
int32_t mNamespaceID;
const OwningNonNull<nsAtom> mName;
nsString mValue;
};
AutoTArray<AttrCache, 16> srcAttrs;
srcAttrs.SetCapacity(aSrcElement.GetAttrCount());
for (const uint32_t i : IntegerRange(aSrcElement.GetAttrCount())) {
const BorrowedAttrInfo attrInfo = aSrcElement.GetAttrInfoAt(i);
if (const nsAttrName* attrName = attrInfo.mName) {
MOZ_ASSERT(attrName->LocalName());
MOZ_ASSERT(attrInfo.mValue);
nsString attrValue;
attrInfo.mValue->ToString(attrValue);
srcAttrs.AppendElement(AttrCache{attrInfo.mName->NamespaceID(),
*attrName->LocalName(), attrValue});
}
}
if (aWithTransaction == WithTransaction::No) {
for (auto& attr : srcAttrs) {
if (!aFilterFunc(*this, aSrcElement, aDestElement, attr.mNamespaceID,
attr.mName, attr.mValue)) {
continue;
}
DebugOnly<nsresult> rvIgnored =
AutoElementAttrAPIWrapper(*this, aDestElement)
.SetAttr(MOZ_KnownLive(attr.mName), attr.mValue, false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored) && rvIgnored != NS_ERROR_EDITOR_DESTROYED,
"AutoElementAttrAPIWrapper::SetAttr() failed, but ignored");
}
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
return NS_OK;
}
MOZ_ASSERT_UNREACHABLE("Not implemented yet, but you try to use this");
return NS_ERROR_NOT_IMPLEMENTED;
}
already_AddRefed<Element> HTMLEditor::CreateElementWithDefaults(
const nsAtom& aTagName) {
// NOTE: Despite of public method, this can be called for internal use.
// Although this creates an element, but won't change the DOM tree nor
// transaction. So, EditAction::eNotEditing is proper value here. If
// this is called for internal when there is already AutoEditActionDataSetter
// instance, this would be initialized with its EditAction value.
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return nullptr;
}
const nsAtom* realTagName = IsLinkTag(aTagName) || IsNamedAnchorTag(aTagName)
? nsGkAtoms::a
: &aTagName;
// We don't use editor's CreateElement because we don't want to go through
// the transaction system
// New call to use instead to get proper HTML element, bug 39919
RefPtr<Element> newElement = CreateHTMLContent(realTagName);
if (!newElement) {
return nullptr;
}
// Mark the new element dirty, so it will be formatted
// XXX Don't we need to check the error result of setting _moz_dirty attr?
IgnoredErrorResult ignoredError;
newElement->SetAttribute(u"_moz_dirty"_ns, u""_ns, ignoredError);
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"Element::SetAttribute(_moz_dirty) failed, but ignored");
ignoredError.SuppressException();
// Set default values for new elements
if (realTagName == nsGkAtoms::table) {
newElement->SetAttr(nsGkAtoms::cellpadding, u"2"_ns, ignoredError);
if (ignoredError.Failed()) {
NS_WARNING("Element::SetAttr(nsGkAtoms::cellpadding, 2) failed");
return nullptr;
}
ignoredError.SuppressException();
newElement->SetAttr(nsGkAtoms::cellspacing, u"2"_ns, ignoredError);
if (ignoredError.Failed()) {
NS_WARNING("Element::SetAttr(nsGkAtoms::cellspacing, 2) failed");
return nullptr;
}
ignoredError.SuppressException();
newElement->SetAttr(nsGkAtoms::border, u"1"_ns, ignoredError);
if (ignoredError.Failed()) {
NS_WARNING("Element::SetAttr(nsGkAtoms::border, 1) failed");
return nullptr;
}
} else if (realTagName == nsGkAtoms::td) {
nsresult rv = SetAttributeOrEquivalent(newElement, nsGkAtoms::valign,
u"top"_ns, true);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::SetAttributeOrEquivalent(nsGkAtoms::valign, top) "
"failed");
return nullptr;
}
}
// ADD OTHER TAGS HERE
return newElement.forget();
}
NS_IMETHODIMP HTMLEditor::CreateElementWithDefaults(const nsAString& aTagName,
Element** aReturn) {
if (NS_WARN_IF(aTagName.IsEmpty()) || NS_WARN_IF(!aReturn)) {
return NS_ERROR_INVALID_ARG;
}
*aReturn = nullptr;
nsStaticAtom* tagName = EditorUtils::GetTagNameAtom(aTagName);
if (NS_WARN_IF(!tagName)) {
return NS_ERROR_INVALID_ARG;
}
RefPtr<Element> newElement =
CreateElementWithDefaults(MOZ_KnownLive(*tagName));
if (!newElement) {
NS_WARNING("HTMLEditor::CreateElementWithDefaults() failed");
return NS_ERROR_FAILURE;
}
newElement.forget(aReturn);
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::InsertLinkAroundSelection(Element* aAnchorElement) {
nsresult rv = InsertLinkAroundSelectionAsAction(aAnchorElement);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::InsertLinkAroundSelectionAsAction() failed");
return rv;
}
nsresult HTMLEditor::InsertLinkAroundSelectionAsAction(
Element* aAnchorElement, nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(!aAnchorElement)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertLinkElement,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
RefPtr<Element> const editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
if (SelectionRef().IsCollapsed()) {
NS_WARNING("Selection was collapsed");
return NS_OK;
}
// Be sure we were given an anchor element
RefPtr<HTMLAnchorElement> anchor =
HTMLAnchorElement::FromNodeOrNull(aAnchorElement);
if (!anchor) {
return NS_OK;
}
nsAutoString rawHref;
anchor->GetAttr(nsGkAtoms::href, rawHref);
editActionData.SetData(rawHref);
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
// XXX Is this ok? Does this just want to check that we're a link? If so
// there are faster ways to do this.
{
nsAutoCString href;
anchor->GetHref(href);
if (href.IsEmpty()) {
return NS_OK;
}
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
// Set all attributes found on the supplied anchor element
// TODO: We should stop using this loop for adding attributes to newly created
// `<a href="...">` elements. Then, we can avoid to increate the ref-
// counter of attribute names since we can use nsStaticAtom if we don't
// need to support unknown attributes.
AutoTArray<EditorInlineStyleAndValue, 32> stylesToSet;
if (const uint32_t attrCount = anchor->GetAttrCount()) {
stylesToSet.SetCapacity(attrCount);
for (const uint32_t i : IntegerRange(attrCount)) {
const BorrowedAttrInfo attrInfo = anchor->GetAttrInfoAt(i);
if (const nsAttrName* attrName = attrInfo.mName) {
// We don't need to handle _moz_dirty attribute. If it's required, the
// handler should add it to the new element.
if (attrName->IsAtom() && attrName->Equals(nsGkAtoms::mozdirty)) {
continue;
}
RefPtr<nsAtom> attributeName = attrName->LocalName();
MOZ_ASSERT(attrInfo.mValue);
nsString attrValue;
attrInfo.mValue->ToString(attrValue);
stylesToSet.AppendElement(EditorInlineStyleAndValue(
*nsGkAtoms::a, std::move(attributeName), std::move(attrValue)));
}
}
}
rv = SetInlinePropertiesAsSubAction(stylesToSet, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::SetInlinePropertiesAsSubAction() failed");
return rv;
}
nsresult HTMLEditor::SetHTMLBackgroundColorWithTransaction(
const nsAString& aColor) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Find a selected or enclosing table element to set background on
bool isCellSelected = false;
Result<RefPtr<Element>, nsresult> cellOrRowOrTableElementOrError =
GetSelectedOrParentTableElement(&isCellSelected);
if (cellOrRowOrTableElementOrError.isErr()) {
NS_WARNING("HTMLEditor::GetSelectedOrParentTableElement() failed");
return cellOrRowOrTableElementOrError.unwrapErr();
}
bool setColor = !aColor.IsEmpty();
RefPtr<Element> rootElementOfBackgroundColor =
cellOrRowOrTableElementOrError.unwrap();
if (rootElementOfBackgroundColor) {
// Needs to set or remove background color of each selected cell elements.
// Therefore, just the cell contains selection range, we don't need to
// do this. Note that users can select each cell, but with Selection API,
// web apps can select <tr> and <td> at same time. With <table>, looks
// odd, though.
if (isCellSelected || rootElementOfBackgroundColor->IsAnyOfHTMLElements(
nsGkAtoms::table, nsGkAtoms::tr)) {
SelectedTableCellScanner scanner(SelectionRef());
if (scanner.IsInTableCellSelectionMode()) {
if (setColor) {
for (const OwningNonNull<Element>& cellElement :
scanner.ElementsRef()) {
// `MOZ_KnownLive(cellElement)` is safe because of `scanner`
// is stack only class and keeps grabbing it until it's destroyed.
nsresult rv = SetAttributeWithTransaction(
MOZ_KnownLive(cellElement), *nsGkAtoms::bgcolor, aColor);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::::SetAttributeWithTransaction(nsGkAtoms::"
"bgcolor) failed");
return rv;
}
}
return NS_OK;
}
for (const OwningNonNull<Element>& cellElement :
scanner.ElementsRef()) {
// `MOZ_KnownLive(cellElement)` is safe because of `scanner`
// is stack only class and keeps grabbing it until it's destroyed.
nsresult rv = RemoveAttributeWithTransaction(
MOZ_KnownLive(cellElement), *nsGkAtoms::bgcolor);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::RemoveAttributeWithTransaction(nsGkAtoms::bgcolor)"
" failed");
return rv;
}
}
return NS_OK;
}
}
// If we failed to find a cell, fall through to use originally-found element
} else {
// No table element -- set the background color on the body tag
rootElementOfBackgroundColor = GetRoot();
if (NS_WARN_IF(!rootElementOfBackgroundColor)) {
return NS_ERROR_FAILURE;
}
}
// Use the editor method that goes through the transaction system
if (setColor) {
nsresult rv = SetAttributeWithTransaction(*rootElementOfBackgroundColor,
*nsGkAtoms::bgcolor, aColor);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction(nsGkAtoms::bgcolor) failed");
return rv;
}
nsresult rv = RemoveAttributeWithTransaction(*rootElementOfBackgroundColor,
*nsGkAtoms::bgcolor);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::RemoveAttributeWithTransaction(nsGkAtoms::bgcolor) failed");
return rv;
}
Result<CaretPoint, nsresult>
HTMLEditor::DeleteEmptyInclusiveAncestorInlineElements(
nsIContent& aContent, const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(HTMLEditUtils::IsRemovableFromParentNode(aContent));
constexpr static HTMLEditUtils::EmptyCheckOptions kOptionsToCheckInline =
HTMLEditUtils::EmptyCheckOptions{
EmptyCheckOption::TreatBlockAsVisible,
EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatSingleBRElementAsVisible,
EmptyCheckOption::TreatTableCellAsVisible};
if (&aContent == &aEditingHost ||
HTMLEditUtils::IsBlockElement(
aContent, BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
!HTMLEditUtils::IsRemovableFromParentNode(aContent) ||
!aContent.GetParent() ||
!HTMLEditUtils::IsEmptyNode(aContent, kOptionsToCheckInline)) {
return CaretPoint(EditorDOMPoint());
}
OwningNonNull<nsIContent> content = aContent;
for (nsIContent* parentContent : aContent.AncestorsOfType<nsIContent>()) {
if (HTMLEditUtils::IsBlockElement(
*parentContent, BlockInlineCheck::UseComputedDisplayStyle) ||
!HTMLEditUtils::IsRemovableFromParentNode(*parentContent) ||
parentContent == &aEditingHost) {
break;
}
bool parentIsEmpty = true;
if (parentContent->GetChildCount() > 1) {
for (nsIContent* sibling = parentContent->GetFirstChild(); sibling;
sibling = sibling->GetNextSibling()) {
if (sibling == content) {
continue;
}
if (!HTMLEditUtils::IsEmptyNode(*sibling, kOptionsToCheckInline)) {
parentIsEmpty = false;
break;
}
}
}
if (!parentIsEmpty) {
break;
}
content = *parentContent;
}
const nsCOMPtr<nsIContent> nextSibling = content->GetNextSibling();
const nsCOMPtr<nsINode> parentNode = content->GetParentNode();
MOZ_ASSERT(parentNode);
nsresult rv = DeleteNodeWithTransaction(content);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
if (NS_WARN_IF(nextSibling && nextSibling->GetParentNode() != parentNode) ||
NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(*parentNode))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// Note that even if nextSibling is not editable, we can put caret before it
// unless parentNode is not editable.
return CaretPoint(nextSibling ? EditorDOMPoint(nextSibling)
: EditorDOMPoint::AtEndOf(*parentNode));
}
nsresult HTMLEditor::DeleteAllChildrenWithTransaction(Element& aElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Prevent rules testing until we're done
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eDeleteNode, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"OnStartToHandleTopLevelEditSubAction() failed, but ignored");
while (nsCOMPtr<nsIContent> child = aElement.GetLastChild()) {
nsresult rv = DeleteNodeWithTransaction(*child);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
}
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::DeleteNode(nsINode* aNode, bool aPreserveSelection,
uint8_t aOptionalArgCount) {
if (NS_WARN_IF(!aNode) || NS_WARN_IF(!aNode->IsContent())) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eRemoveNode);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
// Make dispatch `input` event after stopping preserving selection.
AutoPlaceholderBatch treatAsOneTransaction(
*this,
ScrollSelectionIntoView::No, // not a user interaction
__FUNCTION__);
Maybe<AutoTransactionsConserveSelection> preserveSelection;
if (aOptionalArgCount && aPreserveSelection) {
preserveSelection.emplace(*this);
}
rv = DeleteNodeWithTransaction(MOZ_KnownLive(*aNode->AsContent()));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteNodeWithTransaction() failed");
return rv;
}
Result<CaretPoint, nsresult> HTMLEditor::DeleteTextWithTransaction(
Text& aTextNode, uint32_t aOffset, uint32_t aLength) {
if (NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(aTextNode))) {
return Err(NS_ERROR_FAILURE);
}
Result<CaretPoint, nsresult> caretPointOrError =
EditorBase::DeleteTextWithTransaction(aTextNode, aOffset, aLength);
NS_WARNING_ASSERTION(caretPointOrError.isOk(),
"EditorBase::DeleteTextWithTransaction() failed");
return caretPointOrError;
}
Result<InsertTextResult, nsresult> HTMLEditor::ReplaceTextWithTransaction(
dom::Text& aTextNode, const ReplaceWhiteSpacesData& aData) {
Result<InsertTextResult, nsresult> insertTextResultOrError =
ReplaceTextWithTransaction(aTextNode, aData.mReplaceStartOffset,
aData.ReplaceLength(),
aData.mNormalizedString);
if (MOZ_UNLIKELY(insertTextResultOrError.isErr()) ||
aData.mNewOffsetAfterReplace > aTextNode.TextDataLength()) {
return insertTextResultOrError;
}
InsertTextResult insertTextResult = insertTextResultOrError.unwrap();
insertTextResult.IgnoreCaretPointSuggestion();
EditorDOMPoint pointToPutCaret(&aTextNode, aData.mNewOffsetAfterReplace);
return InsertTextResult(std::move(insertTextResult),
std::move(pointToPutCaret));
}
Result<InsertTextResult, nsresult> HTMLEditor::ReplaceTextWithTransaction(
Text& aTextNode, uint32_t aOffset, uint32_t aLength,
const nsAString& aStringToInsert) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(aLength > 0 || !aStringToInsert.IsEmpty());
if (aStringToInsert.IsEmpty()) {
Result<CaretPoint, nsresult> caretPointOrError =
DeleteTextWithTransaction(aTextNode, aOffset, aLength);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING("HTMLEditor::DeleteTextWithTransaction() failed");
return caretPointOrError.propagateErr();
}
return InsertTextResult(EditorDOMPoint(&aTextNode, aOffset),
caretPointOrError.unwrap());
}
if (!aLength) {
Result<InsertTextResult, nsresult> insertTextResult =
InsertTextWithTransaction(aStringToInsert,
EditorDOMPoint(&aTextNode, aOffset),
InsertTextTo::ExistingTextNodeIfAvailable);
NS_WARNING_ASSERTION(insertTextResult.isOk(),
"HTMLEditor::InsertTextWithTransaction() failed");
return insertTextResult;
}
if (NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(aTextNode))) {
return Err(NS_ERROR_FAILURE);
}
// This should emulates inserting text for better undo/redo behavior.
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertText, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// FYI: Create the insertion point before changing the DOM tree because
// the point may become invalid offset after that.
EditorDOMPointInText pointToInsert(&aTextNode, aOffset);
RefPtr<ReplaceTextTransaction> transaction = ReplaceTextTransaction::Create(
*this, aStringToInsert, aTextNode, aOffset, aLength);
MOZ_ASSERT(transaction);
if (aLength && !mActionListeners.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored =
listener->WillDeleteText(&aTextNode, aOffset, aLength);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::WillDeleteText() failed, but ignored");
}
}
nsresult rv = DoTransactionInternal(transaction);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DoTransactionInternal() failed");
// Don't check whether we've been destroyed here because we need to notify
// listeners and observers below even if we've already destroyed.
EditorDOMPoint endOfInsertedText(&aTextNode,
aOffset + aStringToInsert.Length());
if (pointToInsert.IsSet()) {
auto [begin, end] = ComputeInsertedRange(pointToInsert, aStringToInsert);
if (begin.IsSet() && end.IsSet()) {
TopLevelEditSubActionDataRef().DidDeleteText(
*this, begin.RefOrTo<EditorRawDOMPoint>());
TopLevelEditSubActionDataRef().DidInsertText(
*this, begin.RefOrTo<EditorRawDOMPoint>(),
end.RefOrTo<EditorRawDOMPoint>());
}
// XXX Should we update endOfInsertedText here?
}
if (!mActionListeners.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored =
listener->DidInsertText(&aTextNode, aOffset, aStringToInsert, rv);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidInsertText() failed, but ignored");
}
}
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
return InsertTextResult(
std::move(endOfInsertedText),
transaction->SuggestPointToPutCaret<EditorDOMPoint>());
}
Result<InsertTextResult, nsresult>
HTMLEditor::InsertOrReplaceTextWithTransaction(
const EditorDOMPoint& aPointToInsert,
const NormalizedStringToInsertText& aData) {
MOZ_ASSERT(aPointToInsert.IsInContentNodeAndValid());
MOZ_ASSERT_IF(aData.ReplaceLength(), aPointToInsert.IsInTextNode());
Result<InsertTextResult, nsresult> insertTextResultOrError =
!aData.ReplaceLength()
? InsertTextWithTransaction(aData.mNormalizedString, aPointToInsert,
InsertTextTo::SpecifiedPoint)
: ReplaceTextWithTransaction(
MOZ_KnownLive(*aPointToInsert.ContainerAs<Text>()),
aData.mReplaceStartOffset, aData.ReplaceLength(),
aData.mNormalizedString);
if (MOZ_UNLIKELY(insertTextResultOrError.isErr())) {
NS_WARNING(!aData.ReplaceLength()
? "HTMLEditor::InsertTextWithTransaction() failed"
: "HTMLEditor::ReplaceTextWithTransaction() failed");
return insertTextResultOrError;
}
InsertTextResult insertTextResult = insertTextResultOrError.unwrap();
if (!aData.ReplaceLength()) {
auto pointToPutCaret = [&]() -> EditorDOMPoint {
return insertTextResult.HasCaretPointSuggestion()
? insertTextResult.UnwrapCaretPoint()
: insertTextResult.EndOfInsertedTextRef();
}();
return InsertTextResult(std::move(insertTextResult),
std::move(pointToPutCaret));
}
insertTextResult.IgnoreCaretPointSuggestion();
Text* const insertedTextNode =
insertTextResult.EndOfInsertedTextRef().GetContainerAs<Text>();
if (NS_WARN_IF(!insertedTextNode) ||
NS_WARN_IF(!insertedTextNode->IsInComposedDoc()) ||
NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(*insertedTextNode))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
const uint32_t expectedEndOffset = aData.EndOffsetOfInsertedText();
if (NS_WARN_IF(expectedEndOffset > insertedTextNode->TextDataLength())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// We need to return end point of the insertion string instead of end of
// replaced following white-spaces.
EditorDOMPoint endOfNewString(insertedTextNode, expectedEndOffset);
EditorDOMPoint pointToPutCaret = endOfNewString;
return InsertTextResult(std::move(endOfNewString),
CaretPoint(std::move(pointToPutCaret)));
}
Result<InsertTextResult, nsresult> HTMLEditor::InsertTextWithTransaction(
const nsAString& aStringToInsert, const EditorDOMPoint& aPointToInsert,
InsertTextTo aInsertTextTo) {
if (NS_WARN_IF(!aPointToInsert.IsSet())) {
return Err(NS_ERROR_INVALID_ARG);
}
// Do nothing if the node is read-only
if (NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(
*aPointToInsert.GetContainer()))) {
return Err(NS_ERROR_FAILURE);
}
return EditorBase::InsertTextWithTransaction(aStringToInsert, aPointToInsert,
aInsertTextTo);
}
Result<EditorDOMPoint, nsresult> HTMLEditor::PrepareToInsertLineBreak(
LineBreakType aLineBreakType, const EditorDOMPoint& aPointToInsert) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!aPointToInsert.IsInContentNode())) {
return Err(NS_ERROR_FAILURE);
}
const auto CanInsertLineBreak = [aLineBreakType](const nsIContent& aContent) {
if (aLineBreakType == LineBreakType::BRElement) {
return HTMLEditUtils::CanNodeContain(aContent, *nsGkAtoms::br);
}
MOZ_ASSERT(aLineBreakType == LineBreakType::Linefeed);
return HTMLEditUtils::CanNodeContain(aContent, *nsGkAtoms::textTagName) &&
EditorUtils::IsNewLinePreformatted(aContent);
};
// If we're being initialized, we cannot normalize white-spaces because the
// normalizer may remove invisible `Text`, but it's not allowed during the
// initialization.
// FIXME: Anyway, we should not do this at initialization. This is required
// only for making users can put caret into empty table cells and list items.
const bool canNormalizeWhiteSpaces = mInitSucceeded;
if (!aPointToInsert.IsInTextNode()) {
if (NS_WARN_IF(
!CanInsertLineBreak(*aPointToInsert.ContainerAs<nsIContent>()))) {
return Err(NS_ERROR_FAILURE);
}
if (!canNormalizeWhiteSpaces) {
return aPointToInsert;
}
Result<EditorDOMPoint, nsresult> pointToInsertOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt(
*this, aPointToInsert,
{WhiteSpaceVisibilityKeeper::NormalizeOption::
StopIfPrecedingWhiteSpacesEndsWithNBP});
if (NS_WARN_IF(pointToInsertOrError.isErr())) {
return pointToInsertOrError.propagateErr();
}
return pointToInsertOrError.unwrap();
}
// If the text node is not in an element node, we cannot insert a line break
// around the text node.
const Element* const containerOrNewLineBreak =
aPointToInsert.GetContainerParentAs<Element>();
if (NS_WARN_IF(!containerOrNewLineBreak) ||
NS_WARN_IF(!CanInsertLineBreak(*containerOrNewLineBreak))) {
return Err(NS_ERROR_FAILURE);
}
Result<EditorDOMPoint, nsresult> pointToInsertOrError =
canNormalizeWhiteSpaces
? WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt(
*this, aPointToInsert,
{WhiteSpaceVisibilityKeeper::NormalizeOption::
StopIfPrecedingWhiteSpacesEndsWithNBP})
: aPointToInsert;
if (NS_WARN_IF(pointToInsertOrError.isErr())) {
return pointToInsertOrError.propagateErr();
}
const EditorDOMPoint pointToInsert = pointToInsertOrError.unwrap();
if (!pointToInsert.IsInTextNode()) {
return pointToInsert.ParentPoint();
}
if (pointToInsert.IsStartOfContainer()) {
// Insert before the text node.
return pointToInsert.ParentPoint();
}
if (pointToInsert.IsEndOfContainer()) {
// Insert after the text node.
return EditorDOMPoint::After(*pointToInsert.ContainerAs<Text>());
}
MOZ_DIAGNOSTIC_ASSERT(pointToInsert.IsSetAndValid());
// Unfortunately, we need to split the text node at the offset.
Result<SplitNodeResult, nsresult> splitTextNodeResult =
SplitNodeWithTransaction(pointToInsert);
if (MOZ_UNLIKELY(splitTextNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitTextNodeResult.propagateErr();
}
// TODO: Stop updating `Selection`.
nsresult rv = splitTextNodeResult.inspect().SuggestCaretPointTo(
*this, {SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (NS_FAILED(rv)) {
NS_WARNING("SplitNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
// Insert new line break before the right node.
auto atNextContent =
splitTextNodeResult.inspect().AtNextContent<EditorDOMPoint>();
if (MOZ_UNLIKELY(!atNextContent.IsInContentNode())) {
NS_WARNING("The next node seems not in the DOM tree");
return Err(NS_ERROR_FAILURE);
}
return atNextContent;
}
Maybe<HTMLEditor::LineBreakType> HTMLEditor::GetPreferredLineBreakType(
const nsINode& aNode, const Element& aEditingHost) const {
const Element* const container = aNode.GetAsElementOrParentElement();
if (MOZ_UNLIKELY(!container)) {
return Nothing();
}
// For backward compatibility, we should not insert a linefeed if
// paragraph separator is set to "br" which is Gecko-specific mode.
if (GetDefaultParagraphSeparator() == ParagraphSeparator::br) {
return Some(LineBreakType::BRElement);
}
// And also if we're the mail composer, the content needs to be serialized.
// Therefore, we should always use <br> for the serializer.
if (IsMailEditor() || IsPlaintextMailComposer()) {
return Some(LineBreakType::BRElement);
}
if (HTMLEditUtils::ShouldInsertLinefeedCharacter(EditorDOMPoint(container, 0),
aEditingHost) &&
HTMLEditUtils::CanNodeContain(*container, *nsGkAtoms::textTagName)) {
return Some(LineBreakType::Linefeed);
}
if (MOZ_UNLIKELY(
!HTMLEditUtils::CanNodeContain(*container, *nsGkAtoms::br))) {
return Nothing();
}
return Some(LineBreakType::BRElement);
}
Result<CreateLineBreakResult, nsresult> HTMLEditor::InsertLineBreak(
WithTransaction aWithTransaction, LineBreakType aLineBreakType,
const EditorDOMPoint& aPointToInsert, EDirection aSelect /* = eNone */) {
MOZ_ASSERT(IsEditActionDataAvailable());
Result<EditorDOMPoint, nsresult> pointToInsertOrError =
PrepareToInsertLineBreak(aLineBreakType, aPointToInsert);
if (MOZ_UNLIKELY(pointToInsertOrError.isErr())) {
NS_WARNING(
nsPrintfCString("HTMLEditor::PrepareToInsertLineBreak(%s) failed",
ToString(aWithTransaction).c_str())
.get());
return pointToInsertOrError.propagateErr();
}
EditorDOMPoint pointToInsert = pointToInsertOrError.unwrap();
MOZ_ASSERT(pointToInsert.IsInContentNode());
MOZ_ASSERT(pointToInsert.IsSetAndValid());
auto lineBreakOrError = [&]() MOZ_NEVER_INLINE_DEBUG MOZ_CAN_RUN_SCRIPT
-> Result<EditorLineBreak, nsresult> {
if (aLineBreakType == LineBreakType::BRElement) {
Result<CreateElementResult, nsresult> insertBRElementResultOrError =
InsertBRElement(aWithTransaction, BRElementType::Normal,
pointToInsert);
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
nsPrintfCString(
"EditorBase::InsertBRElement(%s, BRElementType::Normal) failed",
ToString(aWithTransaction).c_str())
.get());
return insertBRElementResultOrError.propagateErr();
}
CreateElementResult insertBRElementResult =
insertBRElementResultOrError.unwrap();
MOZ_ASSERT(insertBRElementResult.Handled());
insertBRElementResult.IgnoreCaretPointSuggestion();
return EditorLineBreak(insertBRElementResult.UnwrapNewNode());
}
MOZ_ASSERT(aLineBreakType == LineBreakType::Linefeed);
RefPtr<Text> newTextNode = CreateTextNode(u"\n"_ns);
if (NS_WARN_IF(!newTextNode)) {
return Err(NS_ERROR_FAILURE);
}
if (aWithTransaction == WithTransaction::Yes) {
Result<CreateTextResult, nsresult> insertTextNodeResult =
InsertNodeWithTransaction<Text>(*newTextNode, pointToInsert);
if (MOZ_UNLIKELY(insertTextNodeResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return insertTextNodeResult.propagateErr();
}
insertTextNodeResult.unwrap().IgnoreCaretPointSuggestion();
} else {
(void)pointToInsert.Offset();
RefPtr<InsertNodeTransaction> transaction =
InsertNodeTransaction::Create(*this, *newTextNode, pointToInsert);
nsresult rv = transaction->DoTransaction();
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("InsertNodeTransaction::DoTransaction() failed");
return Err(rv);
}
if (NS_WARN_IF(newTextNode->GetParentNode() !=
pointToInsert.GetContainer())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
RangeUpdaterRef().SelAdjInsertNode(EditorRawDOMPoint(
pointToInsert.GetContainer(), pointToInsert.Offset()));
}
if (NS_WARN_IF(!newTextNode->TextDataLength() ||
newTextNode->DataBuffer().CharAt(0) != '\n')) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return EditorLineBreak(std::move(newTextNode), 0u);
}();
if (MOZ_UNLIKELY(lineBreakOrError.isErr())) {
return lineBreakOrError.propagateErr();
}
EditorLineBreak lineBreak = lineBreakOrError.unwrap();
auto pointToPutCaret = [&]() -> EditorDOMPoint {
switch (aSelect) {
case eNext: {
return lineBreak.After<EditorDOMPoint>();
}
case ePrevious: {
return lineBreak.Before<EditorDOMPoint>();
}
default:
NS_WARNING(
"aSelect has invalid value, the caller need to set selection "
"by itself");
[[fallthrough]];
case eNone:
return lineBreak.To<EditorDOMPoint>();
}
}();
return CreateLineBreakResult(std::move(lineBreak),
std::move(pointToPutCaret));
}
nsresult HTMLEditor::EnsureNoFollowingUnnecessaryLineBreak(
const EditorDOMPoint& aNextOrAfterModifiedPoint) {
MOZ_ASSERT(aNextOrAfterModifiedPoint.IsInContentNode());
// If the point is in a mailcite in plaintext mail composer (it is a <span>
// styled as block), we should not treat its padding <br> as unnecessary
// because it's required by the serializer to give next content of the
// mailcite has its own line.
if (IsPlaintextMailComposer()) {
const Element* const blockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
*aNextOrAfterModifiedPoint.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayStyle);
if (blockElement && HTMLEditUtils::IsMailCiteElement(*blockElement) &&
HTMLEditUtils::IsInlineContent(*blockElement,
BlockInlineCheck::UseHTMLDefaultStyle)) {
return NS_OK;
}
}
const bool isWhiteSpacePreformatted = EditorUtils::IsWhiteSpacePreformatted(
*aNextOrAfterModifiedPoint.ContainerAs<nsIContent>());
const DebugOnly<bool> isNewLinePreformatted =
EditorUtils::IsNewLinePreformatted(
*aNextOrAfterModifiedPoint.ContainerAs<nsIContent>());
const Maybe<EditorLineBreak> unnecessaryLineBreak =
HTMLEditUtils::GetFollowingUnnecessaryLineBreak<EditorLineBreak>(
aNextOrAfterModifiedPoint);
if (MOZ_LIKELY(unnecessaryLineBreak.isNothing() ||
!unnecessaryLineBreak->IsDeletableFromComposedDoc())) {
return NS_OK;
}
if (unnecessaryLineBreak->IsHTMLBRElement()) {
// If the found unnecessary <br> is a preceding one of a mailcite which is a
// <span> styled as block, we need to preserve the <br> element for the
// serializer to cause a line break before the mailcite.
if (IsPlaintextMailComposer()) {
const WSScanResult nextThing =
WSRunScanner::ScanInclusiveNextVisibleNodeOrBlockBoundary(
{}, unnecessaryLineBreak->After<EditorRawDOMPoint>());
if (nextThing.ReachedOtherBlockElement() &&
HTMLEditUtils::IsMailCiteElement(*nextThing.ElementPtr()) &&
HTMLEditUtils::IsInlineContent(
*nextThing.ElementPtr(), BlockInlineCheck::UseHTMLDefaultStyle)) {
return NS_OK;
}
}
// If the invisible break is a placeholder of ancestor inline elements, we
// should not delete it to allow users to insert text with the format
// specified by them.
if (HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
unnecessaryLineBreak->BRElementRef(),
BlockInlineCheck::UseComputedDisplayStyle)) {
return NS_OK;
}
nsresult rv = DeleteNodeWithTransaction(
MOZ_KnownLive(unnecessaryLineBreak->BRElementRef()));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteNodeWithTransaction() failed "
"to delete unnecessary <br>");
return rv;
}
MOZ_ASSERT(isNewLinePreformatted);
const auto IsVisibleChar = [&](char16_t aChar) {
switch (aChar) {
case HTMLEditUtils::kNewLine:
return true;
case HTMLEditUtils::kSpace:
case HTMLEditUtils::kTab:
case HTMLEditUtils::kCarriageReturn:
return isWhiteSpacePreformatted;
default:
return true;
}
};
const CharacterDataBuffer& characterDataBuffer =
unnecessaryLineBreak->TextRef().DataBuffer();
const uint32_t length = characterDataBuffer.GetLength();
const DebugOnly<const char16_t> lastChar =
characterDataBuffer.CharAt(length - 1);
MOZ_ASSERT(lastChar == HTMLEditUtils::kNewLine);
const bool textNodeHasVisibleChar = [&]() {
if (length == 1u) {
return false;
}
for (const uint32_t offset : Reversed(IntegerRange(length - 1))) {
if (IsVisibleChar(characterDataBuffer.CharAt(offset))) {
return true;
}
}
return false;
}();
if (!textNodeHasVisibleChar) {
// If the invisible break is a placeholder of ancestor inline elements, we
// should not delete it to allow users to insert text with the format
// specified by them.
if (HTMLEditUtils::GetMostDistantAncestorEditableEmptyInlineElement(
unnecessaryLineBreak->TextRef(),
BlockInlineCheck::UseComputedDisplayStyle)) {
return NS_OK;
}
nsresult rv = DeleteNodeWithTransaction(
MOZ_KnownLive(unnecessaryLineBreak->TextRef()));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteNodeWithTransaction() failed "
"to delete unnecessary Text node");
return rv;
}
Result<CaretPoint, nsresult> result =
DeleteTextWithTransaction(MOZ_KnownLive(unnecessaryLineBreak->TextRef()),
unnecessaryLineBreak->Offset(), 1);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::DeleteTextWithTransaction() failed");
return result.unwrapErr();
}
result.unwrap().IgnoreCaretPointSuggestion();
return NS_OK;
}
Result<CreateElementResult, nsresult>
HTMLEditor::InsertContainerWithTransaction(
nsIContent& aContentToBeWrapped, const nsAtom& aWrapperTagName,
const InitializeInsertingElement& aInitializer) {
EditorDOMPoint pointToInsertNewContainer(&aContentToBeWrapped);
if (NS_WARN_IF(!pointToInsertNewContainer.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
// aContentToBeWrapped will be moved to the new container before inserting the
// new container. So, when we insert the container, the insertion point is
// before the next sibling of aContentToBeWrapped.
// XXX If pointerToInsertNewContainer stores offset here, the offset and
// referring child node become mismatched. Although, currently this
// is not a problem since InsertNodeTransaction refers only child node.
MOZ_ALWAYS_TRUE(pointToInsertNewContainer.AdvanceOffset());
// Create new container.
RefPtr<Element> newContainer = CreateHTMLContent(&aWrapperTagName);
if (NS_WARN_IF(!newContainer)) {
return Err(NS_ERROR_FAILURE);
}
if (&aInitializer != &HTMLEditor::DoNothingForNewElement) {
nsresult rv = aInitializer(*this, *newContainer,
EditorDOMPoint(&aContentToBeWrapped));
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("aInitializer() failed");
return Err(rv);
}
}
// Notify our internal selection state listener
AutoInsertContainerSelNotify selNotify(RangeUpdaterRef());
// Put aNode in the new container, first.
// XXX Perhaps, we should not remove the container if it's not editable.
nsresult rv = DeleteNodeWithTransaction(aContentToBeWrapped);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
{
// TODO: Remove AutoTransactionsConserveSelection here. It's not necessary
// in normal cases. However, it may be required for nested edit
// actions which may be caused by legacy mutation event listeners or
// chrome script.
AutoTransactionsConserveSelection conserveSelection(*this);
Result<CreateContentResult, nsresult> insertContentNodeResult =
InsertNodeWithTransaction(aContentToBeWrapped,
EditorDOMPoint(newContainer, 0u));
if (MOZ_UNLIKELY(insertContentNodeResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return insertContentNodeResult.propagateErr();
}
insertContentNodeResult.inspect().IgnoreCaretPointSuggestion();
}
// Put the new container where aNode was.
Result<CreateElementResult, nsresult> insertNewContainerElementResult =
InsertNodeWithTransaction<Element>(*newContainer,
pointToInsertNewContainer);
NS_WARNING_ASSERTION(insertNewContainerElementResult.isOk(),
"EditorBase::InsertNodeWithTransaction() failed");
return insertNewContainerElementResult;
}
Result<CreateElementResult, nsresult>
HTMLEditor::ReplaceContainerWithTransactionInternal(
Element& aOldContainer, const nsAtom& aTagName, const nsAtom& aAttribute,
const nsAString& aAttributeValue, bool aCloneAllAttributes) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(aOldContainer)) ||
NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(aOldContainer))) {
return Err(NS_ERROR_FAILURE);
}
// If we're replacing <dd> or <dt> with different type of element, we need to
// split the parent <dl>.
OwningNonNull<Element> containerElementToDelete = aOldContainer;
if (aOldContainer.IsAnyOfHTMLElements(nsGkAtoms::dd, nsGkAtoms::dt) &&
&aTagName != nsGkAtoms::dt && &aTagName != nsGkAtoms::dd &&
// aOldContainer always has a parent node because of removable.
aOldContainer.GetParentNode()->IsHTMLElement(nsGkAtoms::dl)) {
OwningNonNull<Element> const dlElement = *aOldContainer.GetParentElement();
if (NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(dlElement)) ||
NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(dlElement))) {
return Err(NS_ERROR_FAILURE);
}
Result<SplitRangeOffFromNodeResult, nsresult> splitDLElementResult =
SplitRangeOffFromElement(dlElement, aOldContainer, aOldContainer);
if (MOZ_UNLIKELY(splitDLElementResult.isErr())) {
NS_WARNING("HTMLEditor::SplitRangeOffFromElement() failed");
return splitDLElementResult.propagateErr();
}
splitDLElementResult.inspect().IgnoreCaretPointSuggestion();
RefPtr<Element> middleDLElement = aOldContainer.GetParentElement();
if (NS_WARN_IF(!middleDLElement) ||
NS_WARN_IF(!middleDLElement->IsHTMLElement(nsGkAtoms::dl)) ||
NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(*middleDLElement))) {
NS_WARNING("The parent <dl> was lost at splitting it");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
containerElementToDelete = std::move(middleDLElement);
}
const RefPtr<Element> newContainer = CreateHTMLContent(&aTagName);
if (NS_WARN_IF(!newContainer)) {
return Err(NS_ERROR_FAILURE);
}
// Set or clone attribute if needed.
// FIXME: What should we do attributes of <dl> elements if we removed it
// above?
if (aCloneAllAttributes) {
MOZ_ASSERT(&aAttribute == nsGkAtoms::_empty);
CloneAttributesWithTransaction(*newContainer, aOldContainer);
} else if (&aAttribute != nsGkAtoms::_empty) {
nsresult rv = newContainer->SetAttr(kNameSpaceID_None,
const_cast<nsAtom*>(&aAttribute),
aAttributeValue, true);
if (NS_FAILED(rv)) {
NS_WARNING("Element::SetAttr() failed");
return Err(NS_ERROR_FAILURE);
}
}
const OwningNonNull<nsINode> parentNode =
*containerElementToDelete->GetParentNode();
const nsCOMPtr<nsINode> referenceNode =
containerElementToDelete->GetNextSibling();
AutoReplaceContainerSelNotify selStateNotify(RangeUpdaterRef(), aOldContainer,
*newContainer);
if (aOldContainer.HasChildren()) {
// TODO: Remove AutoTransactionsConserveSelection here. It's not necessary
// in normal cases. However, it may be required for nested edit
// actions which may be caused by legacy mutation event listeners or
// chrome script.
// Move non-editable children too because its container, aElement, is
// editable so that all children must be removable node.
const OwningNonNull<nsIContent> firstChild = *aOldContainer.GetFirstChild();
const OwningNonNull<nsIContent> lastChild = *aOldContainer.GetLastChild();
Result<MoveNodeResult, nsresult> moveChildrenResultOrError =
MoveSiblingsWithTransaction(firstChild, lastChild,
EditorDOMPoint(newContainer, 0));
if (MOZ_UNLIKELY(moveChildrenResultOrError.isErr())) {
NS_WARNING("HTMLEditor::MoveSiblingsWithTransaction() failed");
return moveChildrenResultOrError.propagateErr();
}
// We'll suggest new caret point which is suggested by new container
// element insertion result. Therefore, we need to do nothing here.
moveChildrenResultOrError.inspect().IgnoreCaretPointSuggestion();
}
// Delete containerElementToDelete from the DOM tree to make it not referred
// by InsertNodeTransaction.
nsresult rv = DeleteNodeWithTransaction(containerElementToDelete);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
if (referenceNode && (!referenceNode->GetParentNode() ||
parentNode != referenceNode->GetParentNode())) {
NS_WARNING(
"The reference node for insertion has been moved to different parent, "
"so we got lost the insertion point");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// Finally, insert the new node to where probably aOldContainer was.
Result<CreateElementResult, nsresult> insertNewContainerElementResult =
InsertNodeWithTransaction<Element>(
*newContainer, referenceNode ? EditorDOMPoint(referenceNode)
: EditorDOMPoint::AtEndOf(*parentNode));
NS_WARNING_ASSERTION(insertNewContainerElementResult.isOk(),
"EditorBase::InsertNodeWithTransaction() failed");
MOZ_ASSERT_IF(
insertNewContainerElementResult.isOk(),
insertNewContainerElementResult.inspect().GetNewNode() == newContainer);
return insertNewContainerElementResult;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::RemoveContainerWithTransaction(
Element& aElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(aElement)) ||
NS_WARN_IF(!HTMLEditUtils::IsSimplyEditableNode(aElement))) {
return Err(NS_ERROR_FAILURE);
}
// Notify our internal selection state listener.
AutoRemoveContainerSelNotify selNotify(RangeUpdaterRef(),
EditorRawDOMPoint(&aElement));
const nsCOMPtr<nsINode> parentNode = aElement.GetParentNode();
const nsCOMPtr<nsIContent> nextSibling = aElement.GetNextSibling();
EditorDOMPoint pointToPutCaret;
// FIXME: If we'd improve the range updater to be able to track moving nodes
// after removing the container first, we should do that because
// IMEContentObserver can run faster.
if (aElement.HasChildren()) {
const OwningNonNull<nsIContent> firstChild = *aElement.GetFirstChild();
const OwningNonNull<nsIContent> lastChild = *aElement.GetLastChild();
Result<MoveNodeResult, nsresult> moveChildrenResultOrError =
MoveSiblingsWithTransaction(firstChild, lastChild,
nextSibling
? EditorDOMPoint(nextSibling)
: EditorDOMPoint::AtEndOf(*parentNode));
if (MOZ_UNLIKELY(moveChildrenResultOrError.isErr())) {
NS_WARNING("HTMLEditor::MoveSiblingsWithTransaction() failed");
return moveChildrenResultOrError.propagateErr();
}
pointToPutCaret = moveChildrenResultOrError.unwrap().UnwrapCaretPoint();
}
{
AutoTrackDOMPoint trackPointToPutCaret(RangeUpdaterRef(), &pointToPutCaret);
nsresult rv = DeleteNodeWithTransaction(aElement);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
if (NS_WARN_IF(nextSibling && nextSibling->GetParentNode() != parentNode)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
}
if (pointToPutCaret.IsSetAndValidInComposedDoc()) {
return pointToPutCaret;
}
return nextSibling && nextSibling->GetParentNode() == parentNode
? EditorDOMPoint(nextSibling)
: EditorDOMPoint::AtEndOf(*parentNode);
}
nsresult HTMLEditor::SelectEntireDocument() {
MOZ_ASSERT(IsEditActionDataAvailable());
if (!mInitSucceeded) {
return NS_ERROR_NOT_INITIALIZED;
}
// XXX It's odd to select all of the document body if an contenteditable
// element has focus.
RefPtr<Element> bodyOrDocumentElement = GetRoot();
if (NS_WARN_IF(!bodyOrDocumentElement)) {
return NS_ERROR_NOT_INITIALIZED;
}
// If we're empty, don't select all children because that would select the
// padding <br> element for empty editor.
if (IsEmpty()) {
nsresult rv = CollapseSelectionToStartOf(*bodyOrDocumentElement);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
return rv;
}
// Otherwise, select all children.
ErrorResult error;
SelectionRef().SelectAllChildren(*bodyOrDocumentElement, error);
if (NS_WARN_IF(Destroyed())) {
error.SuppressException();
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(!error.Failed(),
"Selection::SelectAllChildren() failed");
return error.StealNSResult();
}
nsresult HTMLEditor::SelectAllInternal() {
MOZ_ASSERT(IsEditActionDataAvailable());
CommitComposition();
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
auto GetBodyElementIfElementIsParentOfHTMLBody =
[](const Element& aElement) -> Element* {
if (!aElement.OwnerDoc()->IsHTMLDocument()) {
return const_cast<Element*>(&aElement);
}
HTMLBodyElement* bodyElement = aElement.OwnerDoc()->GetBodyElement();
return bodyElement && nsContentUtils::ContentIsFlattenedTreeDescendantOf(
bodyElement, &aElement)
? bodyElement
: const_cast<Element*>(&aElement);
};
nsCOMPtr<nsIContent> selectionRootContent =
[&]() MOZ_CAN_RUN_SCRIPT -> nsIContent* {
RefPtr<Element> elementToBeSelected = [&]() -> Element* {
// If there is at least one selection range, we should compute the
// selection root from the anchor node.
if (SelectionRef().RangeCount()) {
if (nsIContent* content =
nsIContent::FromNodeOrNull(SelectionRef().GetAnchorNode())) {
if (content->IsElement()) {
return content->AsElement();
}
if (Element* parentElement =
content->GetParentElementCrossingShadowRoot()) {
return parentElement;
}
}
}
// If no element contains a selection range, we should select all children
// of the focused element at least.
if (Element* focusedElement = GetFocusedElement()) {
return focusedElement;
}
// of the body or document element.
Element* bodyOrDocumentElement = GetRoot();
NS_WARNING_ASSERTION(bodyOrDocumentElement,
"There was no element in the document");
return bodyOrDocumentElement;
}();
// Then, compute the selection root content to select all including
// elementToBeSelected.
RefPtr<PresShell> presShell = GetPresShell();
nsIContent* computedSelectionRootContent =
elementToBeSelected->GetSelectionRootContent(
presShell, nsINode::IgnoreOwnIndependentSelection::Yes,
nsINode::AllowCrossShadowBoundary::No);
if (NS_WARN_IF(!computedSelectionRootContent)) {
return nullptr;
}
if (MOZ_UNLIKELY(!computedSelectionRootContent->IsElement())) {
return computedSelectionRootContent;
}
return GetBodyElementIfElementIsParentOfHTMLBody(
*computedSelectionRootContent->AsElement());
}();
if (NS_WARN_IF(!selectionRootContent)) {
return NS_ERROR_FAILURE;
}
Maybe<Selection::AutoUserInitiated> userSelection;
// XXX Do we need to mark it as "user initiated" for
// `Document.execCommand("selectAll")`?
if (!selectionRootContent->IsEditable()) {
userSelection.emplace(SelectionRef());
}
ErrorResult error;
SelectionRef().SelectAllChildren(*selectionRootContent, error);
NS_WARNING_ASSERTION(!error.Failed(),
"Selection::SelectAllChildren() failed");
return error.StealNSResult();
}
bool HTMLEditor::SetCaretInTableCell(Element* aElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (!aElement || !aElement->IsHTMLElement() ||
!HTMLEditUtils::IsAnyTableElementExceptColumnElement(*aElement)) {
return false;
}
const RefPtr<Element> editingHost = ComputeEditingHost();
if (!editingHost || !aElement->IsInclusiveDescendantOf(editingHost)) {
return false;
}
nsCOMPtr<nsIContent> deepestFirstChild = aElement;
while (deepestFirstChild->HasChildren()) {
deepestFirstChild = deepestFirstChild->GetFirstChild();
}
// Set selection at beginning of the found node
nsresult rv = CollapseSelectionToStartOf(*deepestFirstChild);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
return NS_SUCCEEDED(rv);
}
/**
* This method scans the selection for adjacent text nodes
* and collapses them into a single text node.
* "adjacent" means literally adjacent siblings of the same parent.
* Uses HTMLEditor::JoinNodesWithTransaction() so action is undoable.
* Should be called within the context of a batch transaction.
*/
nsresult HTMLEditor::CollapseAdjacentTextNodes(nsRange& aRange) {
AutoTransactionsConserveSelection dontChangeMySelection(*this);
// we can't actually do anything during iteration, so store the text nodes in
// an array first.
DOMSubtreeIterator subtreeIter;
if (NS_FAILED(subtreeIter.Init(aRange))) {
NS_WARNING("DOMSubtreeIterator::Init() failed");
return NS_ERROR_FAILURE;
}
AutoTArray<OwningNonNull<Text>, 8> textNodes;
subtreeIter.AppendNodesToArray(
+[](nsINode& aNode, void*) -> bool {
return EditorUtils::IsEditableContent(*aNode.AsText(),
EditorType::HTML);
},
textNodes);
if (textNodes.Length() < 2) {
return NS_OK;
}
OwningNonNull<Text> leftTextNode = textNodes[0];
for (size_t rightTextNodeIndex = 1; rightTextNodeIndex < textNodes.Length();
rightTextNodeIndex++) {
OwningNonNull<Text>& rightTextNode = textNodes[rightTextNodeIndex];
// If the leftTextNode has only preformatted line break, keep it as-is.
if (HTMLEditUtils::TextHasOnlyOnePreformattedLinefeed(leftTextNode)) {
leftTextNode = rightTextNode;
continue;
}
// If the rightTextNode has only preformatted line break, keep it as-is, and
// advance the loop next to the rightTextNode.
if (HTMLEditUtils::TextHasOnlyOnePreformattedLinefeed(rightTextNode)) {
if (++rightTextNodeIndex == textNodes.Length()) {
break;
}
leftTextNode = textNodes[rightTextNodeIndex];
continue;
}
// If the text nodes are not direct siblings, we shouldn't join them, and
// we don't need to handle the left one anymore.
if (leftTextNode->GetNextSibling() != rightTextNode) {
leftTextNode = rightTextNode;
continue;
}
Result<JoinNodesResult, nsresult> joinNodesResultOrError =
JoinTextNodesWithNormalizeWhiteSpaces(MOZ_KnownLive(leftTextNode),
MOZ_KnownLive(rightTextNode));
if (MOZ_UNLIKELY(joinNodesResultOrError.isErr())) {
NS_WARNING("HTMLEditor::JoinTextNodesWithNormalizeWhiteSpaces() failed");
return joinNodesResultOrError.unwrapErr();
}
}
return NS_OK;
}
nsresult HTMLEditor::SetSelectionAtDocumentStart() {
MOZ_ASSERT(IsEditActionDataAvailable());
RefPtr<Element> rootElement = GetRoot();
if (NS_WARN_IF(!rootElement)) {
return NS_ERROR_FAILURE;
}
nsresult rv = CollapseSelectionToStartOf(*rootElement);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed");
return rv;
}
/**
* Remove aNode, re-parenting any children into the parent of aNode. In
* addition, insert any br's needed to preserve identity of removed block.
*/
Result<EditorDOMPoint, nsresult>
HTMLEditor::RemoveBlockContainerWithTransaction(Element& aElement) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Two possibilities: the container could be empty of editable content. If
// that is the case, we need to compare what is before and after aNode to
// determine if we need a br.
//
// Or it could be not empty, in which case we have to compare previous
// sibling and first child to determine if we need a leading br, and compare
// following sibling and last child to determine if we need a trailing br.
const RefPtr<Element> parentElement = aElement.GetParentElement();
if (NS_WARN_IF((!parentElement))) {
return Err(NS_ERROR_FAILURE);
}
EditorDOMPoint pointToPutCaret;
if (HTMLEditUtils::CanNodeContain(*parentElement, *nsGkAtoms::br)) {
if (nsCOMPtr<nsIContent> child = HTMLEditUtils::GetFirstChild(
aElement, {WalkTreeOption::IgnoreNonEditableNode})) {
// The case of aNode not being empty. We need a br at start unless:
// 1) previous sibling of aNode is a block, OR
// 2) previous sibling of aNode is a br, OR
// 3) first child of aNode is a block OR
// 4) either is null
if (nsIContent* previousSibling = HTMLEditUtils::GetPreviousSibling(
aElement, {WalkTreeOption::IgnoreNonEditableNode})) {
if (!HTMLEditUtils::IsBlockElement(
*previousSibling,
BlockInlineCheck::UseComputedDisplayOutsideStyle) &&
!previousSibling->IsHTMLElement(nsGkAtoms::br) &&
!HTMLEditUtils::IsBlockElement(
*child, BlockInlineCheck::UseComputedDisplayOutsideStyle)) {
Result<CreateLineBreakResult, nsresult> insertBRElementResultOrError =
InsertLineBreak(WithTransaction::Yes, LineBreakType::BRElement,
EditorDOMPoint(&aElement));
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertLineBreak(WithTransaction::Yes, "
"LineBreakType::BRElement) failed");
return insertBRElementResultOrError.propagateErr();
}
CreateLineBreakResult insertBRElementResult =
insertBRElementResultOrError.unwrap();
MOZ_ASSERT(insertBRElementResult.Handled());
insertBRElementResult.IgnoreCaretPointSuggestion();
pointToPutCaret = EditorDOMPoint(&aElement, 0);
}
}
// We need a br at end unless:
// 1) following sibling of aNode is a block, OR
// 2) last child of aNode is a block, OR
// 3) last child of aNode is a br OR
// 4) either is null
if (nsIContent* nextSibling = HTMLEditUtils::GetNextSibling(
aElement, {WalkTreeOption::IgnoreNonEditableNode})) {
if (nextSibling &&
!HTMLEditUtils::IsBlockElement(
*nextSibling, BlockInlineCheck::UseComputedDisplayStyle)) {
if (nsIContent* lastChild = HTMLEditUtils::GetLastChild(
aElement, {WalkTreeOption::IgnoreNonEditableNode},
BlockInlineCheck::Unused)) {
if (!HTMLEditUtils::IsBlockElement(
*lastChild, BlockInlineCheck::UseComputedDisplayStyle) &&
!lastChild->IsHTMLElement(nsGkAtoms::br)) {
Result<CreateLineBreakResult, nsresult>
insertBRElementResultOrError = InsertLineBreak(
WithTransaction::Yes, LineBreakType::BRElement,
EditorDOMPoint::After(aElement));
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertLineBreak(WithTransaction::Yes, "
"LineBreakType::BRElement) failed");
return insertBRElementResultOrError.propagateErr();
}
CreateLineBreakResult insertBRElementResult =
insertBRElementResultOrError.unwrap();
MOZ_ASSERT(insertBRElementResult.Handled());
insertBRElementResult.IgnoreCaretPointSuggestion();
pointToPutCaret = EditorDOMPoint::AtEndOf(aElement);
}
}
}
}
} else if (nsIContent* previousSibling = HTMLEditUtils::GetPreviousSibling(
aElement, {WalkTreeOption::IgnoreNonEditableNode})) {
// The case of aNode being empty. We need a br at start unless:
// 1) previous sibling of aNode is a block, OR
// 2) previous sibling of aNode is a br, OR
// 3) following sibling of aNode is a block, OR
// 4) following sibling of aNode is a br OR
// 5) either is null
if (!HTMLEditUtils::IsBlockElement(
*previousSibling, BlockInlineCheck::UseComputedDisplayStyle) &&
!previousSibling->IsHTMLElement(nsGkAtoms::br)) {
if (nsIContent* nextSibling = HTMLEditUtils::GetNextSibling(
aElement, {WalkTreeOption::IgnoreNonEditableNode})) {
if (!HTMLEditUtils::IsBlockElement(
*nextSibling, BlockInlineCheck::UseComputedDisplayStyle) &&
!nextSibling->IsHTMLElement(nsGkAtoms::br)) {
Result<CreateLineBreakResult, nsresult>
insertBRElementResultOrError = InsertLineBreak(
WithTransaction::Yes, LineBreakType::BRElement,
EditorDOMPoint(&aElement));
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertLineBreak(WithTransaction::Yes, "
"LineBreakType::BRElement) failed");
return insertBRElementResultOrError.propagateErr();
}
CreateLineBreakResult insertBRElementResult =
insertBRElementResultOrError.unwrap();
MOZ_ASSERT(insertBRElementResult.Handled());
insertBRElementResult.IgnoreCaretPointSuggestion();
pointToPutCaret = EditorDOMPoint(&aElement, 0);
}
}
}
}
}
// Now remove container
AutoTrackDOMPoint trackPointToPutCaret(RangeUpdaterRef(), &pointToPutCaret);
Result<EditorDOMPoint, nsresult> unwrapBlockElementResult =
RemoveContainerWithTransaction(aElement);
if (MOZ_UNLIKELY(unwrapBlockElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveContainerWithTransaction() failed");
return unwrapBlockElementResult;
}
trackPointToPutCaret.FlushAndStopTracking();
if (AllowsTransactionsToChangeSelection() &&
unwrapBlockElementResult.inspect().IsSet()) {
pointToPutCaret = unwrapBlockElementResult.unwrap();
}
return pointToPutCaret; // May be unset
}
Result<SplitNodeResult, nsresult> HTMLEditor::SplitNodeWithTransaction(
const EditorDOMPoint& aStartOfRightNode) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!aStartOfRightNode.IsInContentNode())) {
return Err(NS_ERROR_INVALID_ARG);
}
MOZ_ASSERT(aStartOfRightNode.IsSetAndValid());
if (NS_WARN_IF(!HTMLEditUtils::IsSplittableNode(
*aStartOfRightNode.ContainerAs<nsIContent>()))) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eSplitNode, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"OnStartToHandleTopLevelEditSubAction() failed, but ignored");
RefPtr<SplitNodeTransaction> transaction =
SplitNodeTransaction::Create(*this, aStartOfRightNode);
nsresult rv = DoTransactionInternal(transaction);
if (NS_WARN_IF(Destroyed())) {
NS_WARNING(
"EditorBase::DoTransactionInternal() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DoTransactionInternal() failed");
return Err(rv);
}
nsIContent* newContent = transaction->GetNewContent();
nsIContent* splitContent = transaction->GetSplitContent();
if (NS_WARN_IF(!newContent) || NS_WARN_IF(!splitContent)) {
return Err(NS_ERROR_FAILURE);
}
TopLevelEditSubActionDataRef().DidSplitContent(*this, *splitContent,
*newContent);
if (NS_WARN_IF(!newContent->IsInComposedDoc()) ||
NS_WARN_IF(!splitContent->IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return SplitNodeResult(*newContent, *splitContent);
}
Result<SplitNodeResult, nsresult> HTMLEditor::SplitNodeDeepWithTransaction(
nsIContent& aMostAncestorToSplit,
const EditorDOMPoint& aDeepestStartOfRightNode,
SplitAtEdges aSplitAtEdges) {
MOZ_ASSERT(aDeepestStartOfRightNode.IsSetAndValidInComposedDoc());
MOZ_ASSERT(
aDeepestStartOfRightNode.GetContainer() == &aMostAncestorToSplit ||
EditorUtils::IsDescendantOf(*aDeepestStartOfRightNode.GetContainer(),
aMostAncestorToSplit));
if (NS_WARN_IF(!aDeepestStartOfRightNode.IsInComposedDoc())) {
return Err(NS_ERROR_INVALID_ARG);
}
nsCOMPtr<nsIContent> newLeftNodeOfMostAncestor;
EditorDOMPoint atStartOfRightNode(aDeepestStartOfRightNode);
// lastResult is as explained by its name, the last result which may not be
// split a node actually.
SplitNodeResult lastResult = SplitNodeResult::NotHandled(atStartOfRightNode);
MOZ_ASSERT(lastResult.AtSplitPoint<EditorRawDOMPoint>()
.IsSetAndValidInComposedDoc());
while (true) {
// Need to insert rules code call here to do things like not split a list
// if you are after the last <li> or before the first, etc. For now we
// just have some smarts about unnecessarily splitting text nodes, which
// should be universal enough to put straight in this EditorBase routine.
auto* splittingContent = atStartOfRightNode.GetContainerAs<nsIContent>();
if (NS_WARN_IF(!splittingContent)) {
lastResult.IgnoreCaretPointSuggestion();
return Err(NS_ERROR_FAILURE);
}
// If we meet an orphan node before meeting aMostAncestorToSplit, we need
// to stop splitting. This is a bug of the caller.
if (NS_WARN_IF(splittingContent != &aMostAncestorToSplit &&
!atStartOfRightNode.GetContainerParentAs<nsIContent>())) {
lastResult.IgnoreCaretPointSuggestion();
return Err(NS_ERROR_FAILURE);
}
// If the container is not splitable node such as comment node, atomic
// element, etc, we should keep it as-is, and try to split its parents.
if (!HTMLEditUtils::IsSplittableNode(*splittingContent)) {
if (splittingContent == &aMostAncestorToSplit) {
return lastResult;
}
atStartOfRightNode.Set(splittingContent);
continue;
}
// If the split point is middle of the node or the node is not a text node
// and we're allowed to create empty element node, split it.
if ((aSplitAtEdges == SplitAtEdges::eAllowToCreateEmptyContainer &&
!atStartOfRightNode.IsInTextNode()) ||
(!atStartOfRightNode.IsStartOfContainer() &&
!atStartOfRightNode.IsEndOfContainer())) {
Result<SplitNodeResult, nsresult> splitNodeResult =
SplitNodeWithTransaction(atStartOfRightNode);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
lastResult.IgnoreCaretPointSuggestion();
return splitNodeResult;
}
lastResult = SplitNodeResult::MergeWithDeeperSplitNodeResult(
splitNodeResult.unwrap(), lastResult);
if (NS_WARN_IF(!lastResult.AtSplitPoint<EditorRawDOMPoint>()
.IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
MOZ_ASSERT(lastResult.HasCaretPointSuggestion());
MOZ_ASSERT(lastResult.GetOriginalContent() == splittingContent);
if (splittingContent == &aMostAncestorToSplit) {
// Actually, we split aMostAncestorToSplit.
return lastResult;
}
// Then, try to split its parent before current node.
atStartOfRightNode = lastResult.AtNextContent<EditorDOMPoint>();
}
// If the split point is end of the node and it is a text node or we're not
// allowed to create empty container node, try to split its parent after it.
else if (!atStartOfRightNode.IsStartOfContainer()) {
lastResult = SplitNodeResult::HandledButDidNotSplitDueToEndOfContainer(
*splittingContent, &lastResult);
MOZ_ASSERT(lastResult.AtSplitPoint<EditorRawDOMPoint>()
.IsSetAndValidInComposedDoc());
if (splittingContent == &aMostAncestorToSplit) {
return lastResult;
}
// Try to split its parent after current node.
atStartOfRightNode.SetAfter(splittingContent);
}
// If the split point is start of the node and it is a text node or we're
// not allowed to create empty container node, try to split its parent.
else {
if (splittingContent == &aMostAncestorToSplit) {
return SplitNodeResult::HandledButDidNotSplitDueToStartOfContainer(
*splittingContent, &lastResult);
}
// Try to split its parent before current node.
// XXX This is logically wrong. If we've already split something but
// this is the last splitable content node in the limiter, this
// method will return "not handled".
lastResult = SplitNodeResult::NotHandled(atStartOfRightNode, &lastResult);
MOZ_ASSERT(lastResult.AtSplitPoint<EditorRawDOMPoint>()
.IsSetAndValidInComposedDoc());
atStartOfRightNode.Set(splittingContent);
MOZ_ASSERT(atStartOfRightNode.IsSetAndValidInComposedDoc());
}
}
// Not reached because while (true) loop never breaks.
}
Result<SplitNodeResult, nsresult> HTMLEditor::DoSplitNode(
const EditorDOMPoint& aStartOfRightNode, nsIContent& aNewNode) {
// Ensure computing the offset if it's initialized with a child content node.
(void)aStartOfRightNode.Offset();
// XXX Perhaps, aStartOfRightNode may be invalid if this is a redo
// operation after modifying DOM node with JS.
if (NS_WARN_IF(!aStartOfRightNode.IsInContentNode())) {
return Err(NS_ERROR_INVALID_ARG);
}
MOZ_DIAGNOSTIC_ASSERT(aStartOfRightNode.IsSetAndValid());
// Remember all selection points.
AutoTArray<SavedRange, 10> savedRanges;
for (SelectionType selectionType : kPresentSelectionTypes) {
SavedRange savingRange;
savingRange.mSelection = GetSelection(selectionType);
if (NS_WARN_IF(!savingRange.mSelection &&
selectionType == SelectionType::eNormal)) {
return Err(NS_ERROR_FAILURE);
}
if (!savingRange.mSelection) {
// For non-normal selections, skip over the non-existing ones.
continue;
}
for (uint32_t j : IntegerRange(savingRange.mSelection->RangeCount())) {
const nsRange* r = savingRange.mSelection->GetRangeAt(j);
MOZ_ASSERT(r);
MOZ_ASSERT(r->IsPositioned());
// XXX Looks like that SavedRange should have mStart and mEnd which
// are RangeBoundary. Then, we can avoid to compute offset here.
savingRange.mStartContainer = r->GetStartContainer();
savingRange.mStartOffset = r->StartOffset();
savingRange.mEndContainer = r->GetEndContainer();
savingRange.mEndOffset = r->EndOffset();
savedRanges.AppendElement(savingRange);
}
}
const nsCOMPtr<nsINode> containerParentNode =
aStartOfRightNode.GetContainerParent();
if (NS_WARN_IF(!containerParentNode)) {
return Err(NS_ERROR_FAILURE);
}
// For the performance of IMEContentObserver, we should move all data into
// aNewNode first because IMEContentObserver needs to compute moved content
// length only once when aNewNode is connected.
// If we are splitting a text node, we need to move its some data to the
// new text node.
MOZ_DIAGNOSTIC_ASSERT_IF(aStartOfRightNode.IsInTextNode(), aNewNode.IsText());
MOZ_DIAGNOSTIC_ASSERT_IF(!aStartOfRightNode.IsInTextNode(),
!aNewNode.IsText());
const nsCOMPtr<nsIContent> firstChildOfRightNode =
aStartOfRightNode.GetChild();
nsresult rv = [&]() MOZ_NEVER_INLINE_DEBUG MOZ_CAN_RUN_SCRIPT {
if (aStartOfRightNode.IsEndOfContainer()) {
return NS_OK; // No content which should be moved into aNewNode.
}
if (aStartOfRightNode.IsInTextNode()) {
Text* originalTextNode = aStartOfRightNode.ContainerAs<Text>();
Text* newTextNode = aNewNode.AsText();
nsAutoString movingText;
const uint32_t cutStartOffset = aStartOfRightNode.Offset();
const uint32_t cutLength =
originalTextNode->Length() - aStartOfRightNode.Offset();
IgnoredErrorResult error;
originalTextNode->SubstringData(cutStartOffset, cutLength, movingText,
error);
NS_WARNING_ASSERTION(!error.Failed(),
"Text::SubstringData() failed, but ignored");
error.SuppressException();
// XXX This call may destroy us.
DoDeleteText(MOZ_KnownLive(*originalTextNode), cutStartOffset, cutLength,
error);
NS_WARNING_ASSERTION(!error.Failed(),
"EditorBase::DoDeleteText() failed, but ignored");
error.SuppressException();
// XXX This call may destroy us.
DoSetText(MOZ_KnownLive(*newTextNode), movingText, error);
NS_WARNING_ASSERTION(!error.Failed(),
"EditorBase::DoSetText() failed, but ignored");
return NS_OK;
}
// If the right node is new one and splitting at start of the container,
// we need to move all children to the new right node.
if (!firstChildOfRightNode->GetPreviousSibling()) {
// XXX Why do we ignore an error while moving nodes from the right
// node to the left node?
nsresult rv = MoveAllChildren(
// MOZ_KnownLive because aStartOfRightNode grabs the container.
MOZ_KnownLive(*aStartOfRightNode.GetContainer()),
EditorRawDOMPoint(&aNewNode, 0u));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::MoveAllChildren() failed");
return rv;
}
// If the right node is new one and splitting at middle of the node, we need
// to move inclusive next siblings of the split point to the new right node.
// XXX Why do we ignore an error while moving nodes from the right node
// to the left node?
nsresult rv = MoveInclusiveNextSiblings(*firstChildOfRightNode,
EditorRawDOMPoint(&aNewNode, 0u));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::MoveInclusiveNextSiblings() failed");
return rv;
}();
// To avoid a dataloss bug, we should try to insert aNewNode even if we've
// already been destroyed.
if (NS_WARN_IF(!aStartOfRightNode.GetContainerParent())) {
return NS_WARN_IF(Destroyed()) ? Err(NS_ERROR_EDITOR_DESTROYED)
: Err(NS_ERROR_FAILURE);
}
// Finally, we should insert aNewNode which already has proper data or
// children.
{
const nsCOMPtr<nsIContent> nextSibling =
aStartOfRightNode.GetContainer()->GetNextSibling();
AutoNodeAPIWrapper nodeWrapper(*this, *containerParentNode);
nsresult rv = nodeWrapper.InsertBefore(aNewNode, nextSibling);
if (NS_FAILED(rv)) {
NS_WARNING("AutoNodeAPIWrapper::InsertBefore() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
nodeWrapper.IsExpectedResult(),
"Inserting new node caused other mutations, but ignored");
}
if (NS_FAILED(rv)) {
NS_WARNING("Moving children from left node to right node failed");
return Err(rv);
}
// Handle selection
// TODO: Stop doing this, this shouldn't be necessary to update selection.
if (RefPtr<PresShell> presShell = GetPresShell()) {
presShell->FlushPendingNotifications(FlushType::Frames);
}
NS_WARNING_ASSERTION(!Destroyed(),
"The editor is destroyed during splitting a node");
const bool allowedTransactionsToChangeSelection =
AllowsTransactionsToChangeSelection();
IgnoredErrorResult error;
RefPtr<Selection> previousSelection;
for (SavedRange& savedRange : savedRanges) {
// If we have not seen the selection yet, clear all of its ranges.
if (savedRange.mSelection != previousSelection) {
MOZ_KnownLive(savedRange.mSelection)->RemoveAllRanges(error);
if (MOZ_UNLIKELY(error.Failed())) {
NS_WARNING("Selection::RemoveAllRanges() failed");
return Err(error.StealNSResult());
}
previousSelection = savedRange.mSelection;
}
// XXX Looks like that we don't need to modify normal selection here
// because selection will be modified by the caller if
// AllowsTransactionsToChangeSelection() will return true.
if (allowedTransactionsToChangeSelection &&
savedRange.mSelection->Type() == SelectionType::eNormal) {
// If the editor should adjust the selection, don't bother restoring
// the ranges for the normal selection here.
continue;
}
auto AdjustDOMPoint = [&](nsCOMPtr<nsINode>& aContainer,
uint32_t& aOffset) {
if (aContainer != aStartOfRightNode.GetContainer()) {
return;
}
// If the container is the left node and offset is after the split
// point, the content was moved from the right node to aNewNode.
// So, we need to change the container to aNewNode and decrease the
// offset.
if (aOffset >= aStartOfRightNode.Offset()) {
aContainer = &aNewNode;
aOffset -= aStartOfRightNode.Offset();
}
};
AdjustDOMPoint(savedRange.mStartContainer, savedRange.mStartOffset);
AdjustDOMPoint(savedRange.mEndContainer, savedRange.mEndOffset);
RefPtr<nsRange> newRange =
nsRange::Create(savedRange.mStartContainer, savedRange.mStartOffset,
savedRange.mEndContainer, savedRange.mEndOffset, error);
if (MOZ_UNLIKELY(error.Failed())) {
NS_WARNING("nsRange::Create() failed");
return Err(error.StealNSResult());
}
// The `MOZ_KnownLive` annotation is only necessary because of a bug
// (https://bugzilla.mozilla.org/show_bug.cgi?id=1622253) in the
// static analyzer.
MOZ_KnownLive(savedRange.mSelection)
->AddRangeAndSelectFramesAndNotifyListeners(*newRange, error);
if (MOZ_UNLIKELY(error.Failed())) {
NS_WARNING(
"Selection::AddRangeAndSelectFramesAndNotifyListeners() failed");
return Err(error.StealNSResult());
}
}
// We don't need to set selection here because the caller should do that
// in any case.
// If splitting the node causes running mutation event listener and we've
// got unexpected result, we should return error because callers will
// continue to do their work without complicated DOM tree result.
// NOTE: Perhaps, we shouldn't do this immediately after each DOM tree change
// because stopping handling it causes some data loss. E.g., user
// may loose the text which is moved to the new text node.
// XXX We cannot check all descendants in the right node and the new left
// node for performance reason. I think that if caller needs to access
// some of the descendants, they should check by themselves.
if (NS_WARN_IF(containerParentNode !=
aStartOfRightNode.GetContainer()->GetParentNode()) ||
NS_WARN_IF(containerParentNode != aNewNode.GetParentNode()) ||
NS_WARN_IF(aNewNode.GetPreviousSibling() !=
aStartOfRightNode.GetContainer())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
DebugOnly<nsresult> rvIgnored = RangeUpdaterRef().SelAdjSplitNode(
*aStartOfRightNode.ContainerAs<nsIContent>(), aStartOfRightNode.Offset(),
aNewNode);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"RangeUpdater::SelAdjSplitNode() failed, but ignored");
return SplitNodeResult(aNewNode,
*aStartOfRightNode.ContainerAs<nsIContent>());
}
Result<JoinNodesResult, nsresult> HTMLEditor::JoinNodesWithTransaction(
nsIContent& aLeftContent, nsIContent& aRightContent) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(&aLeftContent != &aRightContent);
MOZ_ASSERT(aLeftContent.GetParentNode());
MOZ_ASSERT(aRightContent.GetParentNode());
MOZ_ASSERT(aLeftContent.GetParentNode() == aRightContent.GetParentNode());
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eJoinNodes, nsIEditor::ePrevious, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
if (NS_WARN_IF(!aRightContent.GetParentNode())) {
return Err(NS_ERROR_FAILURE);
}
RefPtr<JoinNodesTransaction> transaction =
JoinNodesTransaction::MaybeCreate(*this, aLeftContent, aRightContent);
if (MOZ_UNLIKELY(!transaction)) {
NS_WARNING("JoinNodesTransaction::MaybeCreate() failed");
return Err(NS_ERROR_FAILURE);
}
const nsresult rv = DoTransactionInternal(transaction);
// FYI: Now, DidJoinNodesTransaction() must have been run if succeeded.
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
// This shouldn't occur unless the cycle collector runs by chrome script
// forcibly.
if (NS_WARN_IF(!transaction->GetRemovedContent()) ||
NS_WARN_IF(!transaction->GetExistingContent())) {
return Err(NS_ERROR_UNEXPECTED);
}
// If joined node is moved to different place, offset may not have any
// meaning. In this case, the web app modified the DOM tree takes on the
// responsibility for the remaning things.
if (NS_WARN_IF(transaction->GetExistingContent()->GetParent() !=
transaction->GetParentNode())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DoTransactionInternal() failed");
return Err(rv);
}
return JoinNodesResult(transaction->CreateJoinedPoint<EditorDOMPoint>(),
*transaction->GetRemovedContent());
}
void HTMLEditor::DidJoinNodesTransaction(
const JoinNodesTransaction& aTransaction, nsresult aDoJoinNodesResult) {
// This shouldn't occur unless the cycle collector runs by chrome script
// forcibly.
if (MOZ_UNLIKELY(NS_WARN_IF(!aTransaction.GetRemovedContent()) ||
NS_WARN_IF(!aTransaction.GetExistingContent()))) {
return;
}
// If joined node is moved to different place, offset may not have any
// meaning. In this case, the web app modified the DOM tree takes on the
// responsibility for the remaning things.
if (MOZ_UNLIKELY(aTransaction.GetExistingContent()->GetParentNode() !=
aTransaction.GetParentNode())) {
return;
}
// Be aware, the joined point should be created for each call because
// they may refer the child node, but some of them may change the DOM tree
// after that, thus we need to avoid invalid point (Although it shouldn't
// occur).
TopLevelEditSubActionDataRef().DidJoinContents(
*this, aTransaction.CreateJoinedPoint<EditorRawDOMPoint>());
if (NS_SUCCEEDED(aDoJoinNodesResult)) {
if (RefPtr<TextServicesDocument> textServicesDocument =
mTextServicesDocument) {
textServicesDocument->DidJoinContents(
aTransaction.CreateJoinedPoint<EditorRawDOMPoint>(),
*aTransaction.GetRemovedContent());
}
}
if (!mActionListeners.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored = listener->DidJoinContents(
aTransaction.CreateJoinedPoint<EditorRawDOMPoint>(),
aTransaction.GetRemovedContent());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidJoinContents() failed, but ignored");
}
}
}
nsresult HTMLEditor::DoJoinNodes(nsIContent& aContentToKeep,
nsIContent& aContentToRemove) {
MOZ_ASSERT(IsEditActionDataAvailable());
const uint32_t keepingContentLength = aContentToKeep.Length();
const EditorDOMPoint oldPointAtRightContent(&aContentToRemove);
if (MOZ_LIKELY(oldPointAtRightContent.IsSet())) {
(void)oldPointAtRightContent.Offset(); // Fix the offset
}
// Remember all selection points.
// XXX Do we need to restore all types of selections by ourselves? Normal
// selection should be modified later as result of handling edit action.
// IME selections shouldn't be there when nodes are joined. Spellcheck
// selections should be recreated with newer text. URL selections
// shouldn't be there because of used only by the URL bar.
AutoTArray<SavedRange, 10> savedRanges;
{
EditorRawDOMPoint atRemovingNode(&aContentToRemove);
EditorRawDOMPoint atNodeToKeep(&aContentToKeep);
for (SelectionType selectionType : kPresentSelectionTypes) {
SavedRange savingRange;
savingRange.mSelection = GetSelection(selectionType);
if (selectionType == SelectionType::eNormal) {
if (NS_WARN_IF(!savingRange.mSelection)) {
return NS_ERROR_FAILURE;
}
} else if (!savingRange.mSelection) {
// For non-normal selections, skip over the non-existing ones.
continue;
}
const uint32_t rangeCount = savingRange.mSelection->RangeCount();
for (const uint32_t j : IntegerRange(rangeCount)) {
MOZ_ASSERT(savingRange.mSelection->RangeCount() == rangeCount);
const RefPtr<nsRange> r = savingRange.mSelection->GetRangeAt(j);
MOZ_ASSERT(r);
MOZ_ASSERT(r->IsPositioned());
savingRange.mStartContainer = r->GetStartContainer();
savingRange.mStartOffset = r->StartOffset();
savingRange.mEndContainer = r->GetEndContainer();
savingRange.mEndOffset = r->EndOffset();
// If selection endpoint is between the nodes, remember it as being
// in the one that is going away instead. This simplifies later
// selection adjustment logic at end of this method.
if (savingRange.mStartContainer) {
MOZ_ASSERT(savingRange.mEndContainer);
auto AdjustDOMPoint = [&](nsCOMPtr<nsINode>& aContainer,
uint32_t& aOffset) {
// If range boundary points aContentToRemove and aContentToKeep is
// its left node, remember it as being at end of aContentToKeep.
// Then, it will point start of the first content of moved content
// from aContentToRemove.
if (aContainer == atRemovingNode.GetContainer() &&
atNodeToKeep.Offset() < aOffset &&
aOffset <= atRemovingNode.Offset()) {
aContainer = &aContentToKeep;
aOffset = keepingContentLength;
}
};
AdjustDOMPoint(savingRange.mStartContainer, savingRange.mStartOffset);
AdjustDOMPoint(savingRange.mEndContainer, savingRange.mEndOffset);
}
savedRanges.AppendElement(savingRange);
}
}
}
// OK, ready to do join now.
nsresult rv = [&]() MOZ_NEVER_INLINE_DEBUG MOZ_CAN_RUN_SCRIPT {
// If it's a text node, just shuffle around some text.
if (aContentToKeep.IsText() && aContentToRemove.IsText()) {
nsAutoString rightText;
aContentToRemove.AsText()->GetData(rightText);
// Delete the node first to minimize the text change range from
// IMEContentObserver of view.
{
AutoNodeAPIWrapper nodeWrapper(*this, aContentToRemove);
if (NS_FAILED(nodeWrapper.Remove())) {
NS_WARNING("AutoNodeAPIWrapper::Remove() failed, but ignored");
} else {
NS_WARNING_ASSERTION(
nodeWrapper.IsExpectedResult(),
"Deleting node caused other mutations, but ignored");
}
}
// Even if we've already destroyed, let's update aContentToKeep for
// avoiding a dataloss bug.
IgnoredErrorResult ignoredError;
DoInsertText(MOZ_KnownLive(*aContentToKeep.AsText()),
aContentToKeep.AsText()->TextDataLength(), rightText,
ignoredError);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"EditorBase::DoSetText() failed, but ignored");
return NS_OK;
}
// Otherwise it's an interior node, so shuffle around the children.
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfChildContents;
HTMLEditUtils::CollectAllChildren(aContentToRemove, arrayOfChildContents);
// Delete the node first to minimize the text change range from
// IMEContentObserver of view.
{
AutoNodeAPIWrapper nodeWrapper(*this, aContentToRemove);
if (NS_FAILED(nodeWrapper.Remove())) {
NS_WARNING("AutoNodeAPIWrapper::Remove() failed, but ignored");
} else {
NS_WARNING_ASSERTION(
nodeWrapper.IsExpectedResult(),
"Deleting node caused other mutations, but ignored");
}
}
// Even if we've already destroyed, let's update aContentToKeep for avoiding
// a dataloss bug.
nsresult rv = NS_OK;
for (const OwningNonNull<nsIContent>& child : arrayOfChildContents) {
AutoNodeAPIWrapper nodeWrapper(*this, aContentToKeep);
nsresult rvInner = nodeWrapper.AppendChild(MOZ_KnownLive(child));
if (NS_FAILED(rvInner)) {
NS_WARNING("AutoNodeAPIWrapper::AppendChild() failed");
rv = rvInner;
} else {
NS_WARNING_ASSERTION(
nodeWrapper.IsExpectedResult(),
"Appending child caused other mutations, but ignored");
}
}
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
return rv;
}();
if (MOZ_LIKELY(oldPointAtRightContent.IsSet())) {
DebugOnly<nsresult> rvIgnored = RangeUpdaterRef().SelAdjJoinNodes(
EditorRawDOMPoint(&aContentToKeep, std::min(keepingContentLength,
aContentToKeep.Length())),
aContentToRemove, oldPointAtRightContent);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"RangeUpdater::SelAdjJoinNodes() failed, but ignored");
}
if (MOZ_UNLIKELY(NS_FAILED(rv))) {
return rv;
}
const bool allowedTransactionsToChangeSelection =
AllowsTransactionsToChangeSelection();
// And adjust the selection if needed.
RefPtr<Selection> previousSelection;
for (SavedRange& savedRange : savedRanges) {
// If we have not seen the selection yet, clear all of its ranges.
if (savedRange.mSelection != previousSelection) {
IgnoredErrorResult error;
MOZ_KnownLive(savedRange.mSelection)->RemoveAllRanges(error);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (error.Failed()) {
NS_WARNING("Selection::RemoveAllRanges() failed");
return error.StealNSResult();
}
previousSelection = savedRange.mSelection;
}
if (allowedTransactionsToChangeSelection &&
savedRange.mSelection->Type() == SelectionType::eNormal) {
// If the editor should adjust the selection, don't bother restoring
// the ranges for the normal selection here.
continue;
}
auto AdjustDOMPoint = [&](nsCOMPtr<nsINode>& aContainer,
uint32_t& aOffset) {
// Now, all content of aContentToRemove are moved to end of
// aContentToKeep. Therefore, if a range boundary was in
// aContentToRemove, we need to change the container to aContentToKeep and
// adjust the offset to after the original content of aContentToKeep.
if (aContainer == &aContentToRemove) {
aContainer = &aContentToKeep;
aOffset += keepingContentLength;
}
};
AdjustDOMPoint(savedRange.mStartContainer, savedRange.mStartOffset);
AdjustDOMPoint(savedRange.mEndContainer, savedRange.mEndOffset);
const RefPtr<nsRange> newRange = nsRange::Create(
savedRange.mStartContainer, savedRange.mStartOffset,
savedRange.mEndContainer, savedRange.mEndOffset, IgnoreErrors());
if (!newRange) {
NS_WARNING("nsRange::Create() failed");
return NS_ERROR_FAILURE;
}
IgnoredErrorResult error;
// The `MOZ_KnownLive` annotation is only necessary because of a bug
// (https://bugzilla.mozilla.org/show_bug.cgi?id=1622253) in the
// static analyzer.
MOZ_KnownLive(savedRange.mSelection)
->AddRangeAndSelectFramesAndNotifyListeners(*newRange, error);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
}
if (allowedTransactionsToChangeSelection) {
// Editor wants us to set selection at join point.
DebugOnly<nsresult> rvIgnored = CollapseSelectionToStartOf(aContentToKeep);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionTo() caused destroying the editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBases::CollapseSelectionTos() failed, but ignored");
}
return NS_OK;
}
Result<MoveNodeResult, nsresult> HTMLEditor::MoveNodeWithTransaction(
nsIContent& aContentToMove, const EditorDOMPoint& aPointToInsert) {
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
EditorDOMPoint oldPoint(&aContentToMove);
if (NS_WARN_IF(!oldPoint.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
// Don't do anything if it's already in right place.
if (aPointToInsert == oldPoint) {
return MoveNodeResult::IgnoredResult(aPointToInsert.NextPoint());
}
RefPtr<MoveNodeTransaction> moveNodeTransaction =
MoveNodeTransaction::MaybeCreate(*this, aContentToMove, aPointToInsert);
if (MOZ_UNLIKELY(!moveNodeTransaction)) {
NS_WARNING("MoveNodeTransaction::MaybeCreate() failed");
return Err(NS_ERROR_FAILURE);
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eMoveNode, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
TopLevelEditSubActionDataRef().WillDeleteContent(*this, aContentToMove);
nsresult rv = DoTransactionInternal(moveNodeTransaction);
if (NS_SUCCEEDED(rv)) {
if (mTextServicesDocument) {
const OwningNonNull<TextServicesDocument> textServicesDocument =
*mTextServicesDocument;
textServicesDocument->DidDeleteContent(aContentToMove);
}
}
if (!mActionListeners.IsEmpty()) {
for (auto& listener : mActionListeners.Clone()) {
DebugOnly<nsresult> rvIgnored =
listener->DidDeleteNode(&aContentToMove, rv);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidDeleteNode() failed, but ignored");
}
}
if (MOZ_UNLIKELY(Destroyed())) {
NS_WARNING(
"MoveNodeTransaction::DoTransaction() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeTransaction::DoTransaction() failed");
return Err(rv);
}
TopLevelEditSubActionDataRef().DidInsertContent(*this, aContentToMove);
return MoveNodeResult::HandledResult(
moveNodeTransaction->SuggestNextInsertionPoint().To<EditorDOMPoint>(),
moveNodeTransaction->SuggestPointToPutCaret().To<EditorDOMPoint>());
}
Result<MoveNodeResult, nsresult> HTMLEditor::MoveSiblingsWithTransaction(
nsIContent& aFirstContentToMove, nsIContent& aLastContentToMove,
const EditorDOMPoint& aPointToInsert) {
MOZ_ASSERT(aPointToInsert.IsSetAndValid());
MOZ_ASSERT(aFirstContentToMove.GetParentNode() ==
aLastContentToMove.GetParentNode());
if (&aFirstContentToMove == &aLastContentToMove) {
Result<MoveNodeResult, nsresult> moveNodeResultOrError =
MoveNodeWithTransaction(aFirstContentToMove, aPointToInsert);
NS_WARNING_ASSERTION(moveNodeResultOrError.isOk(),
"HTMLEditor::MoveNodeWithTransaction() failed");
return moveNodeResultOrError;
}
MOZ_ASSERT(*aFirstContentToMove.ComputeIndexInParentNode() <
*aLastContentToMove.ComputeIndexInParentNode());
// Don't do anything if it's already in right place.
{
const EditorDOMPoint atFirstContent(&aFirstContentToMove);
if (NS_WARN_IF(!atFirstContent.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
const EditorDOMPoint atLastContent(&aLastContentToMove);
if (NS_WARN_IF(!atLastContent.IsSet())) {
return Err(NS_ERROR_FAILURE);
}
if (aPointToInsert.GetContainer() == atFirstContent.GetContainer() &&
atFirstContent.EqualsOrIsBefore(aPointToInsert) &&
aPointToInsert.EqualsOrIsBefore(
atLastContent.NextPoint<EditorRawDOMPoint>())) {
return MoveNodeResult::IgnoredResult(atLastContent.NextPoint());
}
}
const RefPtr<MoveSiblingsTransaction> moveSiblingsTransaction =
MoveSiblingsTransaction::MaybeCreate(*this, aFirstContentToMove,
aLastContentToMove, aPointToInsert);
if (MOZ_UNLIKELY(!moveSiblingsTransaction)) {
NS_WARNING("MoveNodeTransaction::MaybeCreate() failed");
return Err(NS_ERROR_FAILURE);
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eMoveNode, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return Err(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"TextEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// WillDeleteContent will extend the changed range to contain all points where
// the moved nodes were. Therefore, we need to call it only for the first and
// and the last one.
TopLevelEditSubActionDataRef().WillDeleteContent(*this, aFirstContentToMove);
TopLevelEditSubActionDataRef().WillDeleteContent(*this, aLastContentToMove);
nsresult rv = DoTransactionInternal(moveSiblingsTransaction);
Maybe<CopyableAutoTArray<OwningNonNull<nsIContent>, 64>> movedSiblings;
if (NS_SUCCEEDED(rv)) {
if (mTextServicesDocument) {
movedSiblings.emplace(moveSiblingsTransaction->TargetSiblings());
const OwningNonNull<TextServicesDocument> textServicesDocument =
*mTextServicesDocument;
for (const OwningNonNull<nsIContent>& movedContent :
movedSiblings.ref()) {
textServicesDocument->DidDeleteContent(MOZ_KnownLive(*movedContent));
}
}
}
if (!mActionListeners.IsEmpty()) {
if (!movedSiblings) {
movedSiblings.emplace(moveSiblingsTransaction->TargetSiblings());
}
for (auto& listener : mActionListeners.Clone()) {
for (const OwningNonNull<nsIContent>& movedContent :
movedSiblings.ref()) {
DebugOnly<nsresult> rvIgnored =
listener->DidDeleteNode(MOZ_KnownLive(movedContent), rv);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIEditActionListener::DidDeleteNode() failed, but ignored");
}
}
}
if (MOZ_UNLIKELY(Destroyed())) {
NS_WARNING(
"MoveNodeTransaction::DoTransaction() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("MoveNodeTransaction::DoTransaction() failed");
return Err(rv);
}
nsIContent* const firstMovedContentInExpectedContainer =
moveSiblingsTransaction->GetFirstMovedContent();
nsIContent* const lastMovedContentInExpectedContainer =
moveSiblingsTransaction->GetLastMovedContent();
if (!firstMovedContentInExpectedContainer) {
return MoveNodeResult::IgnoredResult(aPointToInsert);
}
MOZ_ASSERT(lastMovedContentInExpectedContainer);
// DidInsertContent will extend the changed range to contain all moved
// contents. Therefore, we need to call it only for the first and and the
// last one.
TopLevelEditSubActionDataRef().DidInsertContent(
*this, *firstMovedContentInExpectedContainer);
if (firstMovedContentInExpectedContainer ==
lastMovedContentInExpectedContainer) {
// Only one node was moved.
return MoveNodeResult::HandledResult(
moveSiblingsTransaction->SuggestNextInsertionPoint()
.To<EditorDOMPoint>(),
moveSiblingsTransaction->SuggestPointToPutCaret().To<EditorDOMPoint>());
}
TopLevelEditSubActionDataRef().DidInsertContent(
*this, *lastMovedContentInExpectedContainer);
return MoveNodeResult::HandledResult(
*firstMovedContentInExpectedContainer,
moveSiblingsTransaction->SuggestNextInsertionPoint().To<EditorDOMPoint>(),
moveSiblingsTransaction->SuggestPointToPutCaret().To<EditorDOMPoint>());
}
Result<RefPtr<Element>, nsresult> HTMLEditor::DeleteSelectionAndCreateElement(
nsAtom& aTag, const InitializeInsertingElement& aInitializer) {
MOZ_ASSERT(IsEditActionDataAvailable());
nsresult rv = DeleteSelectionAndPrepareToCreateNode();
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteSelectionAndPrepareToCreateNode() failed");
return Err(rv);
}
EditorDOMPoint pointToInsert(SelectionRef().AnchorRef());
if (!pointToInsert.IsSet()) {
return Err(NS_ERROR_FAILURE);
}
Result<CreateElementResult, nsresult> createNewElementResult =
CreateAndInsertElement(WithTransaction::Yes, aTag, pointToInsert,
aInitializer);
if (MOZ_UNLIKELY(createNewElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) failed");
return createNewElementResult.propagateErr();
}
MOZ_ASSERT(createNewElementResult.inspect().GetNewNode());
// We want the selection to be just after the new node
createNewElementResult.inspect().IgnoreCaretPointSuggestion();
rv = CollapseSelectionTo(
EditorRawDOMPoint::After(*createNewElementResult.inspect().GetNewNode()));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
return createNewElementResult.unwrap().UnwrapNewNode();
}
nsresult HTMLEditor::DeleteSelectionAndPrepareToCreateNode() {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!SelectionRef().GetAnchorFocusRange())) {
return NS_OK;
}
if (!SelectionRef().GetAnchorFocusRange()->Collapsed()) {
nsresult rv =
DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eStrip);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteSelectionAsSubAction() failed");
return rv;
}
MOZ_ASSERT(SelectionRef().GetAnchorFocusRange() &&
SelectionRef().GetAnchorFocusRange()->Collapsed(),
"Selection not collapsed after delete");
}
// If the selection is a chardata node, split it if necessary and compute
// where to put the new node
EditorDOMPoint atAnchor(SelectionRef().AnchorRef());
if (NS_WARN_IF(!atAnchor.IsSet()) || !atAnchor.IsInDataNode()) {
return NS_OK;
}
if (NS_WARN_IF(!atAnchor.GetContainerParent())) {
return NS_ERROR_FAILURE;
}
if (atAnchor.IsStartOfContainer()) {
const EditorRawDOMPoint atAnchorContainer(atAnchor.GetContainer());
if (NS_WARN_IF(!atAnchorContainer.IsSetAndValid())) {
return NS_ERROR_FAILURE;
}
nsresult rv = CollapseSelectionTo(atAnchorContainer);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
if (atAnchor.IsEndOfContainer()) {
EditorRawDOMPoint afterAnchorContainer(atAnchor.GetContainer());
if (NS_WARN_IF(!afterAnchorContainer.AdvanceOffset())) {
return NS_ERROR_FAILURE;
}
nsresult rv = CollapseSelectionTo(afterAnchorContainer);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
Result<SplitNodeResult, nsresult> splitAtAnchorResult =
SplitNodeWithTransaction(atAnchor);
if (MOZ_UNLIKELY(splitAtAnchorResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitAtAnchorResult.unwrapErr();
}
splitAtAnchorResult.inspect().IgnoreCaretPointSuggestion();
const auto atRightContent =
splitAtAnchorResult.inspect().AtNextContent<EditorRawDOMPoint>();
if (NS_WARN_IF(!atRightContent.IsSet())) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(atRightContent.IsSetAndValid());
nsresult rv = CollapseSelectionTo(atRightContent);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed");
return rv;
}
bool HTMLEditor::IsEmpty() const {
if (mPaddingBRElementForEmptyEditor) {
return true;
}
const Element* activeElement =
GetDocument() ? GetDocument()->GetActiveElement() : nullptr;
const Element* editingHostOrBodyOrRootElement =
activeElement && activeElement->IsEditable()
? ComputeEditingHost(*activeElement, LimitInBodyElement::No)
: ComputeEditingHost(LimitInBodyElement::No);
if (MOZ_UNLIKELY(!editingHostOrBodyOrRootElement)) {
// If there is no active element nor no selection range in the document,
// let's check entire the document as what we do traditionally.
editingHostOrBodyOrRootElement = GetRoot();
if (!editingHostOrBodyOrRootElement) {
return true;
}
}
for (nsIContent* childContent =
editingHostOrBodyOrRootElement->GetFirstChild();
childContent; childContent = childContent->GetNextSibling()) {
if (!childContent->IsText() || childContent->Length()) {
return false;
}
}
return true;
}
// add to aElement the CSS inline styles corresponding to the HTML attribute
// aAttribute with its value aValue
nsresult HTMLEditor::SetAttributeOrEquivalent(Element* aElement,
nsAtom* aAttribute,
const nsAString& aValue,
bool aSuppressTransaction) {
MOZ_ASSERT(aElement);
MOZ_ASSERT(aAttribute);
nsAutoScriptBlocker scriptBlocker;
nsStyledElement* styledElement = nsStyledElement::FromNodeOrNull(aElement);
if (!IsCSSEnabled()) {
// we are not in an HTML+CSS editor; let's set the attribute the HTML way
if (EditorElementStyle::IsHTMLStyle(aAttribute)) {
const EditorElementStyle elementStyle =
EditorElementStyle::Create(*aAttribute);
if (styledElement && elementStyle.IsCSSRemovable(*styledElement)) {
// MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
// be guaranteed by the caller because of MOZ_CAN_RUN_SCRIPT method.
nsresult rv = CSSEditUtils::RemoveCSSEquivalentToStyle(
aSuppressTransaction ? WithTransaction::No : WithTransaction::Yes,
*this, MOZ_KnownLive(*styledElement), elementStyle, nullptr);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"CSSEditUtils::RemoveCSSEquivalentToStyle() failed, but ignored");
}
}
if (aSuppressTransaction) {
AutoElementAttrAPIWrapper elementWrapper(*this, *aElement);
nsresult rv = elementWrapper.SetAttr(aAttribute, aValue, true);
if (NS_FAILED(rv)) {
NS_WARNING("AutoElementAttrAPIWrapper::SetAttr() failed");
return rv;
}
NS_WARNING_ASSERTION(
elementWrapper.IsExpectedResult(aValue),
"Setting attribute caused other mutations, but ignored");
return NS_OK;
}
nsresult rv = SetAttributeWithTransaction(*aElement, *aAttribute, aValue);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction() failed");
return rv;
}
if (EditorElementStyle::IsHTMLStyle(aAttribute)) {
const EditorElementStyle elementStyle =
EditorElementStyle::Create(*aAttribute);
if (styledElement && elementStyle.IsCSSSettable(*styledElement)) {
// MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
// be guaranteed by the caller because of MOZ_CAN_RUN_SCRIPT method.
Result<size_t, nsresult> count = CSSEditUtils::SetCSSEquivalentToStyle(
aSuppressTransaction ? WithTransaction::No : WithTransaction::Yes,
*this, MOZ_KnownLive(*styledElement), elementStyle, &aValue);
if (MOZ_UNLIKELY(count.isErr())) {
if (NS_WARN_IF(count.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle() failed, but ignored");
}
if (count.inspect()) {
// we found an equivalence ; let's remove the HTML attribute itself if
// it is set
nsAutoString existingValue;
if (!aElement->GetAttr(aAttribute, existingValue)) {
return NS_OK;
}
if (aSuppressTransaction) {
AutoElementAttrAPIWrapper elementWrapper(*this, *aElement);
nsresult rv = elementWrapper.UnsetAttr(aAttribute, true);
if (NS_FAILED(rv)) {
NS_WARNING("AutoElementAttrAPIWrapper::UnsetAttr() failed");
return rv;
}
NS_WARNING_ASSERTION(
elementWrapper.IsExpectedResult(EmptyString()),
"Removing attribute caused other mutations, but ignored");
return NS_OK;
}
nsresult rv = RemoveAttributeWithTransaction(*aElement, *aAttribute);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::RemoveAttributeWithTransaction() failed");
return rv;
}
}
}
// count is an integer that represents the number of CSS declarations
// applied to the element. If it is zero, we found no equivalence in this
// implementation for the attribute
if (aAttribute == nsGkAtoms::style) {
// if it is the style attribute, just add the new value to the existing
// style attribute's value
nsString existingValue; // Use nsString to avoid copying the string
// buffer at setting the attribute below.
aElement->GetAttr(nsGkAtoms::style, existingValue);
if (!existingValue.IsEmpty()) {
existingValue.Append(HTMLEditUtils::kSpace);
}
existingValue.Append(aValue);
if (aSuppressTransaction) {
AutoElementAttrAPIWrapper elementWrapper(*this, *aElement);
nsresult rv =
elementWrapper.SetAttr(nsGkAtoms::style, existingValue, true);
if (NS_FAILED(rv)) {
NS_WARNING("AutoElementAttrAPIWrapper::SetAttr() failed");
return rv;
}
NS_WARNING_ASSERTION(
elementWrapper.IsExpectedResult(existingValue),
"Setting style attribute caused other mutations, but ignored");
return NS_OK;
}
nsresult rv = SetAttributeWithTransaction(*aElement, *nsGkAtoms::style,
existingValue);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction(nsGkAtoms::style) failed");
return rv;
}
// we have no CSS equivalence for this attribute and it is not the style
// attribute; let's set it the good'n'old HTML way
if (aSuppressTransaction) {
AutoElementAttrAPIWrapper elementWrapper(*this, *aElement);
nsresult rv = elementWrapper.SetAttr(aAttribute, aValue, true);
if (NS_FAILED(rv)) {
NS_WARNING("AutoElementAttrAPIWrapper::SetAttr() failed");
return rv;
}
NS_WARNING_ASSERTION(
elementWrapper.IsExpectedResult(aValue),
"Setting attribute caused other mutations, but ignored");
return NS_OK;
}
nsresult rv = SetAttributeWithTransaction(*aElement, *aAttribute, aValue);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::SetAttributeWithTransaction() failed");
return rv;
}
nsresult HTMLEditor::RemoveAttributeOrEquivalent(Element* aElement,
nsAtom* aAttribute,
bool aSuppressTransaction) {
MOZ_ASSERT(aElement);
MOZ_ASSERT(aAttribute);
if (IsCSSEnabled() && EditorElementStyle::IsHTMLStyle(aAttribute)) {
const EditorElementStyle elementStyle =
EditorElementStyle::Create(*aAttribute);
if (elementStyle.IsCSSRemovable(*aElement)) {
// XXX It might be keep handling attribute even if aElement is not
// an nsStyledElement instance.
nsStyledElement* styledElement =
nsStyledElement::FromNodeOrNull(aElement);
if (NS_WARN_IF(!styledElement)) {
return NS_ERROR_INVALID_ARG;
}
// MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
// be guaranteed by the caller because of MOZ_CAN_RUN_SCRIPT method.
nsresult rv = CSSEditUtils::RemoveCSSEquivalentToStyle(
aSuppressTransaction ? WithTransaction::No : WithTransaction::Yes,
*this, MOZ_KnownLive(*styledElement), elementStyle, nullptr);
if (NS_FAILED(rv)) {
NS_WARNING("CSSEditUtils::RemoveCSSEquivalentToStyle() failed");
return rv;
}
}
}
if (!aElement->HasAttr(aAttribute)) {
return NS_OK;
}
if (aSuppressTransaction) {
AutoElementAttrAPIWrapper elementWrapper(*this, *aElement);
nsresult rv = elementWrapper.UnsetAttr(aAttribute, true);
if (NS_FAILED(rv)) {
NS_WARNING("AutoElementAttrAPIWrapper::UnsetAttr() failed");
return rv;
}
NS_WARNING_ASSERTION(
elementWrapper.IsExpectedResult(EmptyString()),
"Removing attribute caused other mutations, but ignored");
return NS_OK;
}
nsresult rv = RemoveAttributeWithTransaction(*aElement, *aAttribute);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::RemoveAttributeWithTransaction() failed");
return rv;
}
NS_IMETHODIMP HTMLEditor::SetIsCSSEnabled(bool aIsCSSPrefChecked) {
AutoEditActionDataSetter editActionData(*this,
EditAction::eEnableOrDisableCSS);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
mIsCSSPrefChecked = aIsCSSPrefChecked;
return NS_OK;
}
// Set the block background color
nsresult HTMLEditor::SetBlockBackgroundColorWithCSSAsSubAction(
const nsAString& aColor) {
MOZ_ASSERT(IsEditActionDataAvailable());
// background-color change and committing composition should be undone
// together
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
CommitComposition();
// XXX Shouldn't we do this before calling `CommitComposition()`?
if (IsPlaintextMailComposer()) {
return NS_OK;
}
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result.unwrapErr();
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertElement, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() "
"failed, but ignored");
// TODO: We don't need AutoTransactionsConserveSelection here in the normal
// cases, but removing this may cause the behavior with the legacy
// mutation event listeners. We should try to delete this in a bug.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
AutoClonedSelectionRangeArray selectionRanges(SelectionRef());
MOZ_ALWAYS_TRUE(selectionRanges.SaveAndTrackRanges(*this));
for (const OwningNonNull<nsRange>& domRange : selectionRanges.Ranges()) {
EditorDOMRange range(domRange);
if (NS_WARN_IF(!range.IsPositioned())) {
continue;
}
if (range.InSameContainer()) {
// If the range is in a text node, set background color of its parent
// block.
if (range.StartRef().IsInTextNode()) {
const RefPtr<nsStyledElement> editableBlockStyledElement =
nsStyledElement::FromNodeOrNull(HTMLEditUtils::GetAncestorElement(
*range.StartRef().ContainerAs<Text>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle));
if (!editableBlockStyledElement ||
!EditorElementStyle::BGColor().IsCSSSettable(
*editableBlockStyledElement)) {
continue;
}
Result<size_t, nsresult> result = CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, *this, *editableBlockStyledElement,
EditorElementStyle::BGColor(), &aColor);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle(EditorElementStyle::"
"BGColor()) failed, but ignored");
}
continue;
}
// If `Selection` is collapsed in a `<body>` element, set background
// color of the `<body>` element.
if (range.Collapsed() &&
range.StartRef().IsContainerHTMLElement(nsGkAtoms::body)) {
const RefPtr<nsStyledElement> styledElement =
range.StartRef().GetContainerAs<nsStyledElement>();
if (!styledElement ||
!EditorElementStyle::BGColor().IsCSSSettable(*styledElement)) {
continue;
}
Result<size_t, nsresult> result = CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, *this, *styledElement,
EditorElementStyle::BGColor(), &aColor);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle(EditorElementStyle::"
"BGColor()) failed, but ignored");
}
continue;
}
// If one node is selected, set background color of it if it's a
// block, or of its parent block otherwise.
if ((range.StartRef().IsStartOfContainer() &&
range.EndRef().IsStartOfContainer()) ||
range.StartRef().Offset() + 1 == range.EndRef().Offset()) {
if (NS_WARN_IF(range.StartRef().IsInDataNode())) {
continue;
}
const RefPtr<nsStyledElement> editableBlockStyledElement =
nsStyledElement::FromNodeOrNull(
HTMLEditUtils::GetInclusiveAncestorElement(
*range.StartRef().GetChild(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle));
if (!editableBlockStyledElement ||
!EditorElementStyle::BGColor().IsCSSSettable(
*editableBlockStyledElement)) {
continue;
}
Result<size_t, nsresult> result = CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, *this, *editableBlockStyledElement,
EditorElementStyle::BGColor(), &aColor);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle(EditorElementStyle::"
"BGColor()) failed, but ignored");
}
continue;
}
} // if (range.InSameContainer())
// Collect editable nodes which are entirely contained in the range.
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContents;
{
ContentSubtreeIterator subtreeIter;
// If there is no node which is entirely in the range,
// `ContentSubtreeIterator::Init()` fails, but this is possible case,
// don't warn it.
nsresult rv = subtreeIter.Init(range.StartRef().ToRawRangeBoundary(),
range.EndRef().ToRawRangeBoundary());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"ContentSubtreeIterator::Init() failed, but ignored");
if (NS_SUCCEEDED(rv)) {
for (; !subtreeIter.IsDone(); subtreeIter.Next()) {
nsINode* node = subtreeIter.GetCurrentNode();
if (NS_WARN_IF(!node)) {
return NS_ERROR_FAILURE;
}
if (node->IsContent() && EditorUtils::IsEditableContent(
*node->AsContent(), EditorType::HTML)) {
arrayOfContents.AppendElement(*node->AsContent());
}
}
}
}
// This caches block parent if we set its background color.
RefPtr<Element> handledBlockParent;
// If start node is a text node, set background color of its parent
// block.
if (range.StartRef().IsInTextNode() &&
EditorUtils::IsEditableContent(*range.StartRef().ContainerAs<Text>(),
EditorType::HTML)) {
Element* const editableBlockElement = HTMLEditUtils::GetAncestorElement(
*range.StartRef().ContainerAs<Text>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle);
if (editableBlockElement && handledBlockParent != editableBlockElement) {
handledBlockParent = editableBlockElement;
nsStyledElement* const blockStyledElement =
nsStyledElement::FromNode(handledBlockParent);
if (blockStyledElement &&
EditorElementStyle::BGColor().IsCSSSettable(*blockStyledElement)) {
// MOZ_KnownLive(*blockStyledElement): It's handledBlockParent
// whose type is RefPtr.
Result<size_t, nsresult> result =
CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, *this,
MOZ_KnownLive(*blockStyledElement),
EditorElementStyle::BGColor(), &aColor);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle(EditorElementStyle::"
"BGColor()) failed, but ignored");
}
}
}
}
// Then, set background color of each block or block parent of all nodes
// in the range entirely.
for (OwningNonNull<nsIContent>& content : arrayOfContents) {
Element* const editableBlockElement =
HTMLEditUtils::GetInclusiveAncestorElement(
content, HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle);
if (editableBlockElement && handledBlockParent != editableBlockElement) {
handledBlockParent = editableBlockElement;
nsStyledElement* const blockStyledElement =
nsStyledElement::FromNode(handledBlockParent);
if (blockStyledElement &&
EditorElementStyle::BGColor().IsCSSSettable(*blockStyledElement)) {
// MOZ_KnownLive(*blockStyledElement): It's handledBlockParent whose
// type is RefPtr.
Result<size_t, nsresult> result =
CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, *this,
MOZ_KnownLive(*blockStyledElement),
EditorElementStyle::BGColor(), &aColor);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle(EditorElementStyle::"
"BGColor()) failed, but ignored");
}
}
}
}
// Finally, if end node is a text node, set background color of its
// parent block.
if (range.EndRef().IsInTextNode() &&
EditorUtils::IsEditableContent(*range.EndRef().ContainerAs<Text>(),
EditorType::HTML)) {
Element* const editableBlockElement = HTMLEditUtils::GetAncestorElement(
*range.EndRef().ContainerAs<Text>(),
HTMLEditUtils::ClosestEditableBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle);
if (editableBlockElement && handledBlockParent != editableBlockElement) {
const RefPtr<nsStyledElement> blockStyledElement =
nsStyledElement::FromNode(editableBlockElement);
if (blockStyledElement &&
EditorElementStyle::BGColor().IsCSSSettable(*blockStyledElement)) {
Result<size_t, nsresult> result =
CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, *this, *blockStyledElement,
EditorElementStyle::BGColor(), &aColor);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle(EditorElementStyle::"
"BGColor()) failed, but ignored");
}
}
}
}
} // for-loop of selectionRanges
MOZ_ASSERT(selectionRanges.HasSavedRanges());
selectionRanges.RestoreFromSavedRanges();
nsresult rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"AutoClonedSelectionRangeArray::ApplyTo() failed");
return rv;
}
NS_IMETHODIMP HTMLEditor::SetBackgroundColor(const nsAString& aColor) {
nsresult rv = SetBackgroundColorAsAction(aColor);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::SetBackgroundColorAsAction() failed");
return rv;
}
nsresult HTMLEditor::SetBackgroundColorAsAction(const nsAString& aColor,
nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(
*this, EditAction::eSetBackgroundColor, aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
if (IsCSSEnabled()) {
// if we are in CSS mode, we have to apply the background color to the
// containing block (or the body if we have no block-level element in
// the document)
nsresult rv = SetBlockBackgroundColorWithCSSAsSubAction(aColor);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::SetBlockBackgroundColorWithCSSAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
// but in HTML mode, we can only set the document's background color
rv = SetHTMLBackgroundColorWithTransaction(aColor);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::SetHTMLBackgroundColorWithTransaction() failed");
return EditorBase::ToGenericNSResult(rv);
}
Result<EditorDOMPoint, nsresult>
HTMLEditor::CopyLastEditableChildStylesWithTransaction(
Element& aPreviousBlock, Element& aNewBlock, const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
// First, clear out aNewBlock. Contract is that we want only the styles
// from aPreviousBlock.
AutoTArray<OwningNonNull<nsIContent>, 32> newBlockChildren;
HTMLEditUtils::CollectAllChildren(aNewBlock, newBlockChildren);
for (const OwningNonNull<nsIContent>& child : newBlockChildren) {
// MOZ_KNownLive(child) because of bug 1622253
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(child));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
if (MOZ_UNLIKELY(aNewBlock.GetFirstChild())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
// XXX aNewBlock may be moved or removed. Even in such case, we should
// keep cloning the styles?
// Look for the deepest last editable leaf node in aPreviousBlock.
// Then, if found one is a <br> element, look for non-<br> element.
nsIContent* deepestEditableContent = nullptr;
for (nsCOMPtr<nsIContent> child = &aPreviousBlock; child;
child = HTMLEditUtils::GetLastChild(
*child, {WalkTreeOption::IgnoreNonEditableNode})) {
deepestEditableContent = child;
}
while (deepestEditableContent &&
deepestEditableContent->IsHTMLElement(nsGkAtoms::br)) {
deepestEditableContent = HTMLEditUtils::GetPreviousContent(
*deepestEditableContent, {WalkTreeOption::IgnoreNonEditableNode},
BlockInlineCheck::UseComputedDisplayOutsideStyle, &aEditingHost);
}
if (!deepestEditableContent) {
return EditorDOMPoint(&aNewBlock, 0u);
}
Element* deepestVisibleEditableElement =
deepestEditableContent->GetAsElementOrParentElement();
if (!deepestVisibleEditableElement) {
return EditorDOMPoint(&aNewBlock, 0u);
}
// Clone inline elements to keep current style in the new block.
// XXX Looks like that this is really slow if lastEditableDescendant is
// far from aPreviousBlock. Probably, we should clone inline containers
// from ancestor to descendants without transactions, then, insert it
// after that with transaction.
RefPtr<Element> lastClonedElement, firstClonedElement;
for (RefPtr<Element> elementInPreviousBlock = deepestVisibleEditableElement;
elementInPreviousBlock && elementInPreviousBlock != &aPreviousBlock;
elementInPreviousBlock = elementInPreviousBlock->GetParentElement()) {
if (!HTMLEditUtils::IsInlineStyleElement(*elementInPreviousBlock) &&
!elementInPreviousBlock->IsHTMLElement(nsGkAtoms::span)) {
continue;
}
OwningNonNull<nsAtom> tagName =
*elementInPreviousBlock->NodeInfo()->NameAtom();
// At first time, just create the most descendant inline container
// element.
if (!firstClonedElement) {
Result<CreateElementResult, nsresult> createNewElementResult =
CreateAndInsertElement(
WithTransaction::Yes, tagName, EditorDOMPoint(&aNewBlock, 0u),
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
[&elementInPreviousBlock](
HTMLEditor& aHTMLEditor, Element& aNewElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
// Clone all attributes. Note that despite the method name,
// CloneAttributesWithTransaction does not create
// transactions in this case because aNewElement has not
// been connected yet.
// XXX Looks like that this clones id attribute too.
aHTMLEditor.CloneAttributesWithTransaction(
aNewElement, *elementInPreviousBlock);
return NS_OK;
});
if (MOZ_UNLIKELY(createNewElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::CreateAndInsertElement(WithTransaction::Yes) failed");
return createNewElementResult.propagateErr();
}
CreateElementResult unwrappedCreateNewElementResult =
createNewElementResult.unwrap();
// We'll return with a point suggesting new caret position and the
// following path does not require an update of selection here.
// Therefore, we don't need to update selection here.
unwrappedCreateNewElementResult.IgnoreCaretPointSuggestion();
firstClonedElement = lastClonedElement =
unwrappedCreateNewElementResult.UnwrapNewNode();
continue;
}
// Otherwise, inserts new parent inline container to the previous inserted
// inline container.
Result<CreateElementResult, nsresult> wrapClonedElementResult =
InsertContainerWithTransaction(*lastClonedElement, tagName);
if (MOZ_UNLIKELY(wrapClonedElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertContainerWithTransaction() failed");
return wrapClonedElementResult.propagateErr();
}
CreateElementResult unwrappedWrapClonedElementResult =
wrapClonedElementResult.unwrap();
// We'll return with a point suggesting new caret so that we don't need to
// update selection here.
unwrappedWrapClonedElementResult.IgnoreCaretPointSuggestion();
MOZ_ASSERT(unwrappedWrapClonedElementResult.GetNewNode());
lastClonedElement = unwrappedWrapClonedElementResult.UnwrapNewNode();
CloneAttributesWithTransaction(*lastClonedElement, *elementInPreviousBlock);
if (NS_WARN_IF(Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
}
if (!firstClonedElement) {
// XXX Even if no inline elements are cloned, shouldn't we create new
// <br> element for aNewBlock?
return EditorDOMPoint(&aNewBlock, 0u);
}
Result<CreateLineBreakResult, nsresult> insertBRElementResultOrError =
InsertLineBreak(WithTransaction::Yes, LineBreakType::BRElement,
EditorDOMPoint(firstClonedElement, 0u));
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertLineBreak(WithTransaction::Yes, "
"LineBreakType::BRElement) failed");
return insertBRElementResultOrError.propagateErr();
}
CreateLineBreakResult insertBRElementResult =
insertBRElementResultOrError.unwrap();
MOZ_ASSERT(insertBRElementResult.Handled());
insertBRElementResult.IgnoreCaretPointSuggestion();
return insertBRElementResult.AtLineBreak<EditorDOMPoint>();
}
nsresult HTMLEditor::GetElementOrigin(Element& aElement, int32_t& aX,
int32_t& aY) {
aX = 0;
aY = 0;
if (NS_WARN_IF(!IsInitialized())) {
return NS_ERROR_NOT_INITIALIZED;
}
PresShell* presShell = GetPresShell();
if (NS_WARN_IF(!presShell)) {
return NS_ERROR_NOT_INITIALIZED;
}
nsIFrame* frame = aElement.GetPrimaryFrame();
if (NS_WARN_IF(!frame)) {
return NS_OK;
}
nsIFrame* absoluteContainerBlockFrame =
presShell->GetAbsoluteContainingBlock(frame);
if (NS_WARN_IF(!absoluteContainerBlockFrame)) {
return NS_OK;
}
nsPoint off = frame->GetOffsetTo(absoluteContainerBlockFrame);
aX = nsPresContext::AppUnitsToIntCSSPixels(off.x);
aY = nsPresContext::AppUnitsToIntCSSPixels(off.y);
return NS_OK;
}
Element* HTMLEditor::GetSelectionContainerElement() const {
MOZ_ASSERT(IsEditActionDataAvailable());
nsINode* focusNode = nullptr;
if (SelectionRef().IsCollapsed()) {
focusNode = SelectionRef().GetFocusNode();
if (NS_WARN_IF(!focusNode)) {
return nullptr;
}
} else {
const uint32_t rangeCount = SelectionRef().RangeCount();
MOZ_ASSERT(rangeCount, "If 0, Selection::IsCollapsed() should return true");
if (rangeCount == 1) {
const nsRange* range = SelectionRef().GetRangeAt(0);
const RangeBoundary& startRef = range->StartRef();
const RangeBoundary& endRef = range->EndRef();
// This method called GetSelectedElement() to retrieve proper container
// when only one node is selected. However, it simply returns start
// node of Selection with additional cost. So, we do not need to call
// it anymore.
if (startRef.GetContainer()->IsElement() &&
startRef.GetContainer() == endRef.GetContainer() &&
startRef.GetChildAtOffset() &&
startRef.GetChildAtOffset()->GetNextSibling() ==
endRef.GetChildAtOffset()) {
focusNode = startRef.GetChildAtOffset();
MOZ_ASSERT(focusNode, "Start container must not be nullptr");
} else {
focusNode = range->GetClosestCommonInclusiveAncestor();
if (!focusNode) {
NS_WARNING(
"AbstractRange::GetClosestCommonInclusiveAncestor() returned "
"nullptr");
return nullptr;
}
}
} else {
for (const uint32_t i : IntegerRange(rangeCount)) {
MOZ_ASSERT(SelectionRef().RangeCount() == rangeCount);
const nsRange* range = SelectionRef().GetRangeAt(i);
MOZ_ASSERT(range);
nsINode* startContainer = range->GetStartContainer();
if (!focusNode) {
focusNode = startContainer;
} else if (focusNode != startContainer) {
// XXX Looks odd to use parent of startContainer because previous
// range may not be in the parent node of current
// startContainer.
focusNode = startContainer->GetParentNode();
// XXX Looks odd to break the for-loop here because we refer only
// first range and another range which starts from different
// container, and the latter range is preferred. Why?
break;
}
}
if (!focusNode) {
NS_WARNING("Focused node of selection was not found");
return nullptr;
}
}
}
if (focusNode->IsText()) {
focusNode = focusNode->GetParentNode();
if (NS_WARN_IF(!focusNode)) {
return nullptr;
}
}
if (NS_WARN_IF(!focusNode->IsElement())) {
return nullptr;
}
return focusNode->AsElement();
}
NS_IMETHODIMP HTMLEditor::IsAnonymousElement(Element* aElement, bool* aReturn) {
if (NS_WARN_IF(!aElement)) {
return NS_ERROR_INVALID_ARG;
}
*aReturn = aElement->IsRootOfNativeAnonymousSubtree();
return NS_OK;
}
nsresult HTMLEditor::SetReturnInParagraphCreatesNewParagraph(
bool aCreatesNewParagraph) {
mCRInParagraphCreatesParagraph = aCreatesNewParagraph;
return NS_OK;
}
bool HTMLEditor::GetReturnInParagraphCreatesNewParagraph() const {
return mCRInParagraphCreatesParagraph;
}
nsresult HTMLEditor::GetReturnInParagraphCreatesNewParagraph(
bool* aCreatesNewParagraph) {
*aCreatesNewParagraph = mCRInParagraphCreatesParagraph;
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::GetWrapWidth(int32_t* aWrapColumn) {
if (NS_WARN_IF(!aWrapColumn)) {
return NS_ERROR_INVALID_ARG;
}
*aWrapColumn = WrapWidth();
return NS_OK;
}
//
// See if the style value includes this attribute, and if it does,
// cut out everything from the attribute to the next semicolon.
//
static void CutStyle(const char* stylename, nsString& styleValue) {
// Find the current wrapping type:
int32_t styleStart = styleValue.LowerCaseFindASCII(stylename);
if (styleStart >= 0) {
int32_t styleEnd = styleValue.Find(u";", styleStart);
if (styleEnd > styleStart) {
styleValue.Cut(styleStart, styleEnd - styleStart + 1);
} else {
styleValue.Cut(styleStart, styleValue.Length() - styleStart);
}
}
}
NS_IMETHODIMP HTMLEditor::SetWrapWidth(int32_t aWrapColumn) {
AutoEditActionDataSetter editActionData(*this, EditAction::eSetWrapWidth);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
mWrapColumn = aWrapColumn;
// Make sure we're a plaintext editor, otherwise we shouldn't
// do the rest of this.
if (!IsPlaintextMailComposer()) {
return NS_OK;
}
// Ought to set a style sheet here...
const RefPtr<Element> rootElement = GetRoot();
if (NS_WARN_IF(!rootElement)) {
return NS_ERROR_NOT_INITIALIZED;
}
// Get the current style for this root element:
nsAutoString styleValue;
rootElement->GetAttr(nsGkAtoms::style, styleValue);
// We'll replace styles for these values:
CutStyle("white-space", styleValue);
CutStyle("width", styleValue);
CutStyle("font-family", styleValue);
// If we have other style left, trim off any existing semicolons
// or white-space, then add a known semicolon-space:
if (!styleValue.IsEmpty()) {
styleValue.Trim("; \t", false, true);
styleValue.AppendLiteral("; ");
}
// Make sure we have fixed-width font. This should be done for us,
// but it isn't, see bug 22502, so we have to add "font: -moz-fixed;".
// Only do this if we're wrapping.
if (IsWrapHackEnabled() && aWrapColumn >= 0) {
styleValue.AppendLiteral("font-family: -moz-fixed; ");
}
// and now we're ready to set the new white-space/wrapping style.
if (aWrapColumn > 0) {
// Wrap to a fixed column.
styleValue.AppendLiteral("white-space: pre-wrap; width: ");
styleValue.AppendInt(aWrapColumn);
styleValue.AppendLiteral("ch;");
} else if (!aWrapColumn) {
styleValue.AppendLiteral("white-space: pre-wrap;");
} else {
styleValue.AppendLiteral("white-space: pre;");
}
AutoElementAttrAPIWrapper elementWrapper(*this, *rootElement);
nsresult rv = elementWrapper.SetAttr(nsGkAtoms::style, styleValue, true);
if (NS_FAILED(rv)) {
NS_WARNING("AutoElementAttrAPIWrapper::SetAttr() failed");
return rv;
}
NS_WARNING_ASSERTION(
elementWrapper.IsExpectedResult(styleValue),
"Setting style attribute caused other mutations, but ignored");
return NS_OK;
}
Element* HTMLEditor::GetFocusedElement() const {
Element* const focusedElement = nsFocusManager::GetFocusedElementStatic();
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return nullptr;
}
const bool inDesignMode = focusedElement ? focusedElement->IsInDesignMode()
: document->IsInDesignMode();
if (!focusedElement) {
// in designMode, nobody gets focus in most cases.
if (inDesignMode && OurWindowHasFocus()) {
return document->GetRootElement();
}
return nullptr;
}
if (inDesignMode) {
return OurWindowHasFocus() &&
focusedElement->IsInclusiveDescendantOf(document)
? focusedElement
: nullptr;
}
// We're HTML editor for contenteditable
// If the focused content isn't editable, or it has independent selection,
// we don't have focus.
if (!focusedElement->HasFlag(NODE_IS_EDITABLE) ||
focusedElement->HasIndependentSelection()) {
return nullptr;
}
// If our window is focused, we're focused.
return OurWindowHasFocus() ? focusedElement : nullptr;
}
bool HTMLEditor::IsActiveInDOMWindow() const {
nsFocusManager* focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return false;
}
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return false;
}
// If we're in designMode, we're always active in the DOM window.
if (IsInDesignMode()) {
return true;
}
nsPIDOMWindowOuter* ourWindow = document->GetWindow();
nsCOMPtr<nsPIDOMWindowOuter> win;
nsIContent* content = nsFocusManager::GetFocusedDescendant(
ourWindow, nsFocusManager::eOnlyCurrentWindow, getter_AddRefs(win));
if (!content) {
return false;
}
if (content->IsInDesignMode()) {
return true;
}
// We're HTML editor for contenteditable
// If the active content isn't editable, or it has independent selection,
// we're not active).
if (!content->HasFlag(NODE_IS_EDITABLE) ||
content->HasIndependentSelection()) {
return false;
}
return true;
}
Element* HTMLEditor::ComputeEditingHostInternal(
const nsIContent* aContent, LimitInBodyElement aLimitInBodyElement) const {
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return nullptr;
}
auto MaybeLimitInBodyElement =
[&](const Element* aCandidateEditingHost) -> Element* {
if (!aCandidateEditingHost) {
return nullptr;
}
if (aLimitInBodyElement != LimitInBodyElement::Yes) {
return const_cast<Element*>(aCandidateEditingHost);
}
// By default, we should limit editing host to the <body> element for
// avoiding deleting or creating unexpected elements outside the <body>.
// However, this is incompatible with Chrome so that we should stop
// doing this with adding safety checks more.
if (document->GetBodyElement() &&
nsContentUtils::ContentIsFlattenedTreeDescendantOf(
aCandidateEditingHost, document->GetBodyElement())) {
return const_cast<Element*>(aCandidateEditingHost);
}
// XXX If aContent is an editing host and has no parent node, we reach here,
// but returning the <body> which is not connected to aContent is odd.
return document->GetBodyElement();
};
// We're HTML editor for contenteditable
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return nullptr;
}
const nsIContent* const content = [&]() -> const nsIContent* {
if (aContent) {
return aContent;
}
// If there are selection ranges, let's look for their common ancestor's
// editing host because selection ranges may be visible for users.
nsIContent* selectionCommonAncestor = nullptr;
for (uint32_t i : IntegerRange(SelectionRef().RangeCount())) {
nsRange* range = SelectionRef().GetRangeAt(i);
MOZ_ASSERT(range);
nsIContent* commonAncestor =
nsIContent::FromNodeOrNull(range->GetCommonAncestorContainer(
IgnoreErrors(), AllowRangeCrossShadowBoundary::Yes));
if (MOZ_UNLIKELY(!commonAncestor)) {
continue;
}
if (!selectionCommonAncestor) {
selectionCommonAncestor = commonAncestor;
} else {
selectionCommonAncestor =
nsContentUtils::GetCommonFlattenedTreeAncestorForSelection(
commonAncestor, selectionCommonAncestor);
}
}
if (selectionCommonAncestor) {
return selectionCommonAncestor;
}
// Otherwise, let's use the focused element in the window.
nsPIDOMWindowInner* const innerWindow = document->GetInnerWindow();
if (MOZ_UNLIKELY(!innerWindow)) {
return nullptr;
}
if (Element* focusedElementInWindow = innerWindow->GetFocusedElement()) {
if (focusedElementInWindow->ChromeOnlyAccess()) {
focusedElementInWindow = Element::FromNodeOrNull(
// XXX Should we use
// nsIContent::FindFirstNonChromeOnlyAccessContent() instead of
// nsINode::GetClosestNativeAnonymousSubtreeRootParentOrHost()?
focusedElementInWindow
->GetClosestNativeAnonymousSubtreeRootParentOrHost());
}
if (focusedElementInWindow) {
return focusedElementInWindow->IsEditable() ? focusedElementInWindow
: nullptr;
}
}
// If there is no focused element and the document is in the design mode,
// let's return the <body>.
if (document->IsInDesignMode()) {
return document->GetBodyElement();
}
// Otherwise, we cannot find the editing host...
return nullptr;
}();
if ((content && content->IsInDesignMode()) ||
(!content && document->IsInDesignMode())) {
// FIXME: There may be no <body>. In such case and aLimitInBodyElement is
// "No", we should use root element instead.
return document->GetBodyElement();
}
if (NS_WARN_IF(!content)) {
return nullptr;
}
// If the active content isn't editable, we're not active.
if (!content->HasFlag(NODE_IS_EDITABLE)) {
return nullptr;
}
// Although the content shouldn't be in a native anonymous subtree, but
// perhaps due to a bug of Selection or Range API, it may occur. HTMLEditor
// shouldn't touch native anonymous subtree so that return nullptr in such
// case.
if (MOZ_UNLIKELY(content->IsInNativeAnonymousSubtree())) {
return nullptr;
}
// Note that `Selection` can be in <input> or <textarea>. In the case, we
// need to look for an ancestor which does not have editable parent.
return MaybeLimitInBodyElement(
const_cast<nsIContent*>(content)->GetEditingHost());
}
void HTMLEditor::NotifyEditingHostMaybeChanged() {
// Note that even if the document is in design mode, a contenteditable element
// in a shadow tree is focusable. Therefore, we may need to update editing
// host even when the document is in design mode.
if (MOZ_UNLIKELY(NS_WARN_IF(!GetDocument()))) {
return;
}
// We're HTML editor for contenteditable
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return;
}
// Get selection ancestor limit which may be old editing host.
nsIContent* ancestorLimiter = SelectionRef().GetAncestorLimiter();
if (!ancestorLimiter) {
// If we've not initialized selection ancestor limit, we should wait focus
// event to set proper limiter.
return;
}
// Compute current editing host.
Element* const editingHost = ComputeEditingHost();
if (NS_WARN_IF(!editingHost)) {
return;
}
// Update selection ancestor limit if current editing host includes the
// previous editing host.
// Additionally, the editing host may be an element in shadow DOM and the
// shadow host is in designMode. In this case, we need to set the editing
// host as the new selection limiter.
if (ancestorLimiter->IsInclusiveDescendantOf(editingHost) ||
(ancestorLimiter->IsInDesignMode() != editingHost->IsInDesignMode())) {
// Note that don't call HTMLEditor::InitializeSelectionAncestorLimit()
// here because it may collapse selection to the first editable node.
EditorBase::InitializeSelectionAncestorLimit(*editingHost);
}
}
EventTarget* HTMLEditor::GetDOMEventTarget() const {
// Don't use getDocument here, because we have no way of knowing
// whether Init() was ever called. So we need to get the document
// ourselves, if it exists.
Document* doc = GetDocument();
MOZ_ASSERT(doc, "The HTMLEditor has not been initialized yet");
if (!doc) {
return nullptr;
}
// Register the EditorEventListener to the parent of window.
//
// The advantage of this approach is HTMLEditor can still
// receive events when shadow dom is involved.
if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
return win->GetParentTarget();
}
return nullptr;
}
Element* HTMLEditor::GetBodyElement() const {
Document* document = GetDocument();
MOZ_ASSERT(document, "The HTMLEditor hasn't been initialized yet");
if (NS_WARN_IF(!document)) {
return nullptr;
}
return document->GetBody();
}
nsINode* HTMLEditor::GetFocusedNode() const {
Element* focusedElement = GetFocusedElement();
if (!focusedElement) {
return nullptr;
}
// focusedElement might be non-null even
// nsFocusManager::GetFocusedElementStatic() returns null. That's the
// designMode case, and in that case our GetFocusedElement() returns the root
// element, but we want to return the document.
if ((focusedElement = nsFocusManager::GetFocusedElementStatic())) {
return focusedElement;
}
return GetDocument();
}
bool HTMLEditor::OurWindowHasFocus() const {
nsFocusManager* focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return false;
}
nsPIDOMWindowOuter* focusedWindow = focusManager->GetFocusedWindow();
if (!focusedWindow) {
return false;
}
Document* document = GetDocument();
if (NS_WARN_IF(!document)) {
return false;
}
nsPIDOMWindowOuter* ourWindow = document->GetWindow();
return ourWindow == focusedWindow;
}
bool HTMLEditor::IsAcceptableInputEvent(WidgetGUIEvent* aGUIEvent) const {
if (!EditorBase::IsAcceptableInputEvent(aGUIEvent)) {
return false;
}
// While there is composition, all composition events in its top level
// window are always fired on the composing editor. Therefore, if this
// editor has composition, the composition events should be handled in this
// editor.
if (mComposition && aGUIEvent->AsCompositionEvent()) {
return true;
}
nsCOMPtr<nsINode> eventTargetNode =
nsINode::FromEventTargetOrNull(aGUIEvent->GetOriginalDOMEventTarget());
if (NS_WARN_IF(!eventTargetNode)) {
return false;
}
if (eventTargetNode->IsContent()) {
eventTargetNode =
eventTargetNode->AsContent()->FindFirstNonChromeOnlyAccessContent();
if (NS_WARN_IF(!eventTargetNode)) {
return false;
}
}
RefPtr<Document> document = GetDocument();
if (NS_WARN_IF(!document)) {
return false;
}
if (eventTargetNode->IsInDesignMode()) {
// If this editor is in designMode and the event target is the document,
// the event is for this editor.
if (eventTargetNode->IsDocument()) {
return eventTargetNode == document;
}
// Otherwise, check whether the event target is in this document or not.
if (NS_WARN_IF(!eventTargetNode->IsContent())) {
return false;
}
if (document == eventTargetNode->GetUncomposedDoc()) {
return true;
}
}
// Space event for <button> and <summary> with contenteditable
// should be handle by the themselves.
if (aGUIEvent->mMessage == eKeyPress &&
aGUIEvent->AsKeyboardEvent()->ShouldWorkAsSpaceKey()) {
nsGenericHTMLElement* element =
HTMLButtonElement::FromNode(eventTargetNode);
if (!element) {
element = HTMLSummaryElement::FromNode(eventTargetNode);
}
if (element && element->IsContentEditable()) {
return false;
}
}
// This HTML editor is for contenteditable. We need to check the validity
// of the target.
if (NS_WARN_IF(!eventTargetNode->IsContent())) {
return false;
}
// If the event is a mouse event, we need to check if the target content is
// the focused editing host or its descendant.
if (aGUIEvent->AsMouseEventBase()) {
nsIContent* editingHost = ComputeEditingHost();
// If there is no active editing host, we cannot handle the mouse event
// correctly.
if (!editingHost) {
return false;
}
// If clicked on non-editable root element but the body element is the
// active editing host, we should assume that the click event is
// targetted.
if (eventTargetNode == document->GetRootElement() &&
!eventTargetNode->HasFlag(NODE_IS_EDITABLE) &&
editingHost == document->GetBodyElement()) {
eventTargetNode = editingHost;
}
// If the target element is neither the active editing host nor a
// descendant of it, we may not be able to handle the event.
if (!eventTargetNode->IsInclusiveDescendantOf(editingHost)) {
return false;
}
// If the clicked element has an independent selection, we shouldn't
// handle this click event.
if (eventTargetNode->AsContent()->HasIndependentSelection()) {
return false;
}
// If the target content is editable, we should handle this event.
return eventTargetNode->HasFlag(NODE_IS_EDITABLE);
}
// If the target of the other events which target focused element isn't
// editable or has an independent selection, this editor shouldn't handle
// the event.
if (!eventTargetNode->HasFlag(NODE_IS_EDITABLE) ||
eventTargetNode->AsContent()->HasIndependentSelection()) {
return false;
}
// Finally, check whether we're actually focused or not. When we're not
// focused, we should ignore the dispatched event by script (or something)
// because content editable element needs selection in itself for editing.
// However, when we're not focused, it's not guaranteed.
return IsActiveInDOMWindow();
}
nsresult HTMLEditor::GetPreferredIMEState(IMEState* aState) {
// HTML editor don't prefer the CSS ime-mode because IE didn't do so too.
aState->mOpen = IMEState::DONT_CHANGE_OPEN_STATE;
if (IsReadonly()) {
aState->mEnabled = IMEEnabled::Disabled;
} else {
aState->mEnabled = IMEEnabled::Enabled;
}
return NS_OK;
}
already_AddRefed<Element> HTMLEditor::GetInputEventTargetElement() const {
// If there is no selection ranges, we'll do nothing. Therefore,
// `beforeinput` event should not be fired.
// FIXME: If there is no selection but we've already modified the DOM,
// we should fire `input` event on the editing host. However, we cannot
// know which one was the editing host when we touched the DOM.
if (MOZ_UNLIKELY(!SelectionRef().RangeCount())) {
return nullptr;
}
RefPtr<Element> target = ComputeEditingHost(LimitInBodyElement::No);
if (target) {
return target.forget();
}
// When there is no active editing host due to focus node is a
// non-editable node, we should look for its editable parent to
// dispatch `beforeinput` event.
nsIContent* focusContent =
nsIContent::FromNodeOrNull(SelectionRef().GetFocusNode());
if (!focusContent || focusContent->IsEditable()) {
return nullptr;
}
for (Element* element : focusContent->AncestorsOfType<Element>()) {
if (element->IsEditable()) {
target = element->GetEditingHost();
return target.forget();
}
}
return nullptr;
}
} // namespace mozilla
|