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
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=78: */
/* 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 <string.h>
#include "AutoSelectionRestorer.h"
#include "EditAction.h"
#include "EditorBase.h"
#include "EditorDOMPoint.h"
#include "EditorUtils.h"
#include "HTMLEditHelpers.h"
#include "HTMLEditUtils.h"
#include "InternetCiter.h"
#include "PendingStyles.h"
#include "SelectionState.h"
#include "WhiteSpaceVisibilityKeeper.h"
#include "WSRunScanner.h"
#include "ErrorList.h"
#include "mozilla/dom/Comment.h"
#include "mozilla/dom/DataTransfer.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/DOMStringList.h"
#include "mozilla/dom/DOMStringList.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ElementInlines.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/FileBlobImpl.h"
#include "mozilla/dom/FileReader.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/StaticRange.h"
#include "mozilla/dom/WorkerRef.h"
#include "mozilla/Attributes.h"
#include "mozilla/Base64.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Maybe.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/Preferences.h"
#include "mozilla/Result.h"
#include "mozilla/StaticPrefs_editor.h"
#include "mozilla/TextComposition.h"
#include "nsAString.h"
#include "nsCOMPtr.h"
#include "nsCRTGlue.h" // for CRLF
#include "nsComponentManagerUtils.h"
#include "nsIScriptError.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsDependentSubstring.h"
#include "nsError.h"
#include "nsFocusManager.h"
#include "nsGkAtoms.h"
#include "nsIClipboard.h"
#include "nsIContent.h"
#include "nsIDocumentEncoder.h"
#include "nsIFile.h"
#include "nsIInputStream.h"
#include "nsIMIMEService.h"
#include "nsINode.h"
#include "nsIParserUtils.h"
#include "nsIPrincipal.h"
#include "nsISupportsImpl.h"
#include "nsISupportsPrimitives.h"
#include "nsISupportsUtils.h"
#include "nsITransferable.h"
#include "nsIVariant.h"
#include "nsLinebreakConverter.h"
#include "nsLiteralString.h"
#include "nsNameSpaceManager.h"
#include "nsNetUtil.h"
#include "nsPrintfCString.h"
#include "nsRange.h"
#include "nsReadableUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsStreamUtils.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsStringIterator.h"
#include "nsTreeSanitizer.h"
#include "nsXPCOM.h"
#include "nscore.h"
#include "nsContentUtils.h"
#include "nsQueryObject.h"
class nsAtom;
class nsILoadContext;
namespace mozilla {
using namespace dom;
using EmptyCheckOption = HTMLEditUtils::EmptyCheckOption;
using LeafNodeType = HTMLEditUtils::LeafNodeType;
#define kInsertCookie "_moz_Insert Here_moz_"
// some little helpers
static bool FindIntegerAfterString(const char* aLeadingString,
const nsCString& aCStr,
int32_t& foundNumber);
static void RemoveFragComments(nsCString& aStr);
nsresult HTMLEditor::InsertDroppedDataTransferAsAction(
AutoEditActionDataSetter& aEditActionData, DataTransfer& aDataTransfer,
const EditorDOMPoint& aDroppedAt, nsIPrincipal* aSourcePrincipal) {
MOZ_ASSERT(aEditActionData.GetEditAction() == EditAction::eDrop);
MOZ_ASSERT(GetEditAction() == EditAction::eDrop);
MOZ_ASSERT(aDroppedAt.IsSet());
MOZ_ASSERT(aDataTransfer.MozItemCount() > 0);
if (IsReadonly()) {
return NS_OK;
}
aEditActionData.InitializeDataTransfer(&aDataTransfer);
RefPtr<StaticRange> targetRange = StaticRange::Create(
aDroppedAt.GetContainer(), aDroppedAt.Offset(), aDroppedAt.GetContainer(),
aDroppedAt.Offset(), IgnoreErrors());
NS_WARNING_ASSERTION(targetRange && targetRange->IsPositioned(),
"Why did we fail to create collapsed static range at "
"dropped position?");
if (targetRange && targetRange->IsPositioned()) {
aEditActionData.AppendTargetRange(*targetRange);
}
nsresult rv = aEditActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent() failed");
return rv;
}
if (MOZ_UNLIKELY(!aDroppedAt.IsInContentNode())) {
NS_WARNING("Dropped into non-content node");
return NS_OK;
}
const RefPtr<Element> editingHost = ComputeEditingHost(
*aDroppedAt.ContainerAs<nsIContent>(), LimitInBodyElement::No);
if (MOZ_UNLIKELY(!editingHost)) {
NS_WARNING("Dropped onto non-editable node");
return NS_OK;
}
uint32_t numItems = aDataTransfer.MozItemCount();
for (uint32_t i = 0; i < numItems; ++i) {
DebugOnly<nsresult> rvIgnored =
InsertFromDataTransfer(&aDataTransfer, i, aSourcePrincipal, aDroppedAt,
DeleteSelectedContent::No, *editingHost);
if (NS_WARN_IF(Destroyed())) {
return NS_OK;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"HTMLEditor::InsertFromDataTransfer("
"DeleteSelectedContent::No) failed, but ignored");
}
return NS_OK;
}
nsresult HTMLEditor::LoadHTML(const nsAString& aInputString) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
// force IME commit; set up rules sniffing and batching
DebugOnly<nsresult> rvIgnored = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertHTMLSource, 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");
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::EnsureNoPaddingBRElementForEmptyEditor() failed");
return rv;
}
// Delete Selection, but only if it isn't collapsed, see bug #106269
if (!SelectionRef().IsCollapsed()) {
nsresult rv = DeleteSelectionAsSubAction(eNone, eStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(eNone, eStrip) failed");
return rv;
}
}
// Get the first range in the selection, for context:
RefPtr<const nsRange> range = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!range)) {
return NS_ERROR_FAILURE;
}
// Create fragment for pasted HTML.
ErrorResult error;
RefPtr<DocumentFragment> documentFragment =
range->CreateContextualFragment(aInputString, error);
if (error.Failed()) {
NS_WARNING("nsRange::CreateContextualFragment() failed");
return error.StealNSResult();
}
// Put the fragment into the document at start of selection.
EditorDOMPoint pointToInsert(range->StartRef());
// XXX We need to make pointToInsert store offset for keeping traditional
// behavior since using only child node to pointing insertion point
// changes the behavior when inserted child is moved by mutation
// observer. We need to investigate what we should do here.
(void)pointToInsert.Offset();
EditorDOMPoint pointToPutCaret;
for (nsCOMPtr<nsIContent> contentToInsert = documentFragment->GetFirstChild();
contentToInsert; contentToInsert = documentFragment->GetFirstChild()) {
Result<CreateContentResult, nsresult> insertChildContentNodeResult =
InsertNodeWithTransaction(*contentToInsert, pointToInsert);
if (MOZ_UNLIKELY(insertChildContentNodeResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return insertChildContentNodeResult.unwrapErr();
}
CreateContentResult unwrappedInsertChildContentNodeResult =
insertChildContentNodeResult.unwrap();
unwrappedInsertChildContentNodeResult.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
// XXX If the inserted node has been moved by mutation observer,
// incrementing offset will cause odd result. Next new node
// will be inserted after existing node and the offset will be
// overflown from the container node.
pointToInsert.Set(pointToInsert.GetContainer(), pointToInsert.Offset() + 1);
if (NS_WARN_IF(!pointToInsert.Offset())) {
// Append the remaining children to the container if offset is
// overflown.
pointToInsert.SetToEndOf(pointToInsert.GetContainer());
}
}
if (pointToPutCaret.IsSet()) {
nsresult rv = CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed, but ignored");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::InsertHTML(const nsAString& aInString) {
nsresult rv = InsertHTMLAsAction(aInString);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLAsAction() failed");
return rv;
}
nsresult HTMLEditor::InsertHTMLAsAction(const nsAString& aInString,
nsIPrincipal* aPrincipal) {
// FIXME: This should keep handling inserting HTML if the caller is
// nsIHTMLEditor::InsertHTML.
if (IsReadonly()) {
return NS_OK;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertHTML,
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 (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
if (editingHost->IsContentEditablePlainTextOnly()) {
nsAutoString plaintextString;
nsresult rv = nsContentUtils::ConvertToPlainText(
aInString, plaintextString, nsIDocumentEncoder::OutputLFLineBreak,
0u /* never wrap lines*/);
if (NS_FAILED(rv)) {
NS_WARNING("nsContentUtils::ConvertToPlainText() failed");
return EditorBase::ToGenericNSResult(rv);
}
Maybe<AutoPlaceholderBatch> treatAsOneTransaction;
const auto EnsureAutoPlaceholderBatch = [&]() {
if (treatAsOneTransaction.isNothing()) {
treatAsOneTransaction.emplace(*this, ScrollSelectionIntoView::Yes,
__FUNCTION__);
}
};
if (mComposition &&
mComposition->CanRequsetIMEToCommitOrCancelComposition()) {
EnsureAutoPlaceholderBatch();
CommitComposition();
if (NS_WARN_IF(Destroyed())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_WARN_IF(editingHost !=
ComputeEditingHost(LimitInBodyElement::No))) {
return EditorBase::ToGenericNSResult(
NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
if (MOZ_LIKELY(!plaintextString.IsEmpty())) {
EnsureAutoPlaceholderBatch();
rv = InsertTextAsSubAction(plaintextString, InsertTextFor::NormalText);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed");
} else if (!SelectionRef().IsCollapsed()) {
EnsureAutoPlaceholderBatch();
rv = DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eNoStrip);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteSelectionAsSubAction() failed");
}
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertHTMLWithContextAsSubAction(
aInString, u""_ns, u""_ns, u""_ns, SafeToInsertData::Yes,
EditorDOMPoint(), DeleteSelectedContent::Yes,
InlineStylesAtInsertionPoint::Clear, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"SafeToInsertData::Yes, DeleteSelectedContent::Yes, "
"InlineStylesAtInsertionPoint::Clear) failed");
return EditorBase::ToGenericNSResult(rv);
}
class MOZ_STACK_CLASS HTMLEditor::HTMLWithContextInserter final {
public:
MOZ_CAN_RUN_SCRIPT HTMLWithContextInserter(HTMLEditor& aHTMLEditor,
const Element& aEditingHost)
: mHTMLEditor(aHTMLEditor), mEditingHost(aEditingHost) {}
HTMLWithContextInserter() = delete;
HTMLWithContextInserter(const HTMLWithContextInserter&) = delete;
HTMLWithContextInserter(HTMLWithContextInserter&&) = delete;
[[nodiscard]] MOZ_CAN_RUN_SCRIPT Result<EditActionResult, nsresult> Run(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, SafeToInsertData aSafeToInsertData,
InlineStylesAtInsertionPoint aInlineStylesAtInsertionPoint);
private:
class FragmentFromPasteCreator;
class FragmentParser;
/**
* CollectTopMostChildContentsCompletelyInRange() collects topmost child
* contents which are completely in the given range.
* For example, if the range points a node with its container node, the
* result is only the node (meaning does not include its descendants).
* If the range starts start of a node and ends end of it, and if the node
* does not have children, returns no nodes, otherwise, if the node has
* some children, the result includes its all children (not including their
* descendants).
*
* @param aStartPoint Start point of the range.
* @param aEndPoint End point of the range.
* @param aOutArrayOfContents [Out] Topmost children which are completely in
* the range.
*/
static void CollectTopMostChildContentsCompletelyInRange(
const EditorRawDOMPoint& aStartPoint, const EditorRawDOMPoint& aEndPoint,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents);
EditorDOMPoint GetNewCaretPointAfterInsertingHTML(
const EditorDOMPoint& aLastInsertedPoint) const;
/**
* @return error result or the last inserted point. The latter is only set, if
* content was inserted.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT Result<EditorDOMPoint, nsresult>
InsertContents(
const EditorDOMPoint& aPointToInsert,
nsTArray<OwningNonNull<nsIContent>>& aArrayOfTopMostChildContents,
const nsINode* aFragmentAsNode);
/**
* @param aContextStr as indicated by nsITransferable's kHTMLContext.
* @param aInfoStr as indicated by nsITransferable's kHTMLInfo.
*/
nsresult CreateDOMFragmentFromPaste(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, nsCOMPtr<nsINode>* aOutFragNode,
nsCOMPtr<nsINode>* aOutStartNode, nsCOMPtr<nsINode>* aOutEndNode,
uint32_t* aOutStartOffset, uint32_t* aOutEndOffset,
SafeToInsertData aSafeToInsertData) const;
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult MoveCaretOutsideOfLink(
Element& aLinkElement, const EditorDOMPoint& aPointToPutCaret);
// MOZ_KNOWN_LIVE because this is set only by the constructor which is
// marked as MOZ_CAN_RUN_SCRIPT and this is allocated only in the stack.
MOZ_KNOWN_LIVE HTMLEditor& mHTMLEditor;
MOZ_KNOWN_LIVE const Element& mEditingHost;
};
class MOZ_STACK_CLASS
HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator final {
public:
nsresult Run(const Document& aDocument, const nsAString& aInputString,
const nsAString& aContextStr, const nsAString& aInfoStr,
nsCOMPtr<nsINode>* aOutFragNode,
nsCOMPtr<nsINode>* aOutStartNode, nsCOMPtr<nsINode>* aOutEndNode,
SafeToInsertData aSafeToInsertData) const;
private:
nsresult CreateDocumentFragmentAndGetParentOfPastedHTMLInContext(
const Document& aDocument, const nsAString& aInputString,
const nsAString& aContextStr, SafeToInsertData aSafeToInsertData,
nsCOMPtr<nsINode>& aParentNodeOfPastedHTMLInContext,
RefPtr<DocumentFragment>& aDocumentFragmentToInsert) const;
static nsAtom* DetermineContextLocalNameForParsingPastedHTML(
const nsIContent* aParentContentOfPastedHTMLInContext);
static bool FindTargetNodeOfContextForPastedHTMLAndRemoveInsertionCookie(
nsINode& aStart, nsCOMPtr<nsINode>& aResult);
static bool IsInsertionCookie(const nsIContent& aContent);
/**
* @param aDocumentFragmentForContext contains the merged result.
*/
static nsresult MergeAndPostProcessFragmentsForPastedHTMLAndContext(
DocumentFragment& aDocumentFragmentForPastedHTML,
DocumentFragment& aDocumentFragmentForContext,
nsIContent& aTargetContentOfContextForPastedHTML);
/**
* @param aInfoStr as indicated by nsITransferable's kHTMLInfo.
*/
[[nodiscard]] static nsresult MoveStartAndEndAccordingToHTMLInfo(
const nsAString& aInfoStr, nsCOMPtr<nsINode>* aOutStartNode,
nsCOMPtr<nsINode>* aOutEndNode);
static nsresult PostProcessFragmentForPastedHTMLWithoutContext(
DocumentFragment& aDocumentFragmentForPastedHTML);
static nsresult PreProcessContextDocumentFragmentForMerging(
DocumentFragment& aDocumentFragmentForContext);
static void RemoveHeadChildAndStealBodyChildsChildren(nsINode& aNode);
/**
* This is designed for a helper class to remove disturbing nodes at inserting
* the HTML fragment into the DOM tree. This walks the children and if some
* elements do not have enough children, e.g., list elements not having
* another visible list elements nor list item elements,
* will be removed.
*
* @param aNode Should not be a node whose mutation may be observed by
* JS.
*/
static void RemoveIncompleteDescendantsFromInsertingFragment(nsINode& aNode);
enum class NodesToRemove {
eAll,
eOnlyListItems /*!< List items are always block-level elements, hence such
whitespace-only nodes are always invisible. */
};
static nsresult
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
nsIContent& aNode, NodesToRemove aNodesToRemove);
};
EditorDOMPoint
HTMLEditor::HTMLWithContextInserter::GetNewCaretPointAfterInsertingHTML(
const EditorDOMPoint& aLastInsertedPoint) const {
EditorDOMPoint pointToPutCaret;
// but don't cross tables
nsIContent* containerContent = nullptr;
// FIXME: GetChild() might be nullptr, but it's referred as non-null in the
// block!
if (!aLastInsertedPoint.GetChild() ||
!aLastInsertedPoint.GetChild()->IsHTMLElement(nsGkAtoms::table)) {
containerContent = HTMLEditUtils::GetLastLeafContent(
*aLastInsertedPoint.GetChild(), {LeafNodeType::OnlyEditableLeafNode},
BlockInlineCheck::Unused,
aLastInsertedPoint.GetChild()->GetAsElementOrParentElement());
if (containerContent) {
Element* mostDistantInclusiveAncestorTableElement = nullptr;
for (Element* maybeTableElement =
containerContent->GetAsElementOrParentElement();
maybeTableElement &&
maybeTableElement != aLastInsertedPoint.GetChild();
maybeTableElement = maybeTableElement->GetParentElement()) {
if (maybeTableElement->IsHTMLElement(nsGkAtoms::table)) {
mostDistantInclusiveAncestorTableElement = maybeTableElement;
}
}
// If we're in table elements, we should put caret into the most ancestor
// table element.
if (mostDistantInclusiveAncestorTableElement) {
containerContent = mostDistantInclusiveAncestorTableElement;
}
}
}
// If we are not in table elements, we should put caret in the last inserted
// node.
if (!containerContent) {
containerContent = aLastInsertedPoint.GetChild();
}
// If the container is a text node or a container element except `<table>`
// element, put caret a end of it.
if (containerContent->IsText() ||
(HTMLEditUtils::IsContainerNode(*containerContent) &&
!containerContent->IsHTMLElement(nsGkAtoms::table))) {
pointToPutCaret.SetToEndOf(containerContent);
}
// Otherwise, i.e., it's an atomic element, `<table>` element or data node,
// put caret after it.
else {
pointToPutCaret.SetAfter(containerContent);
}
// Make sure we don't end up with selection collapsed after an invisible
// `<br>` element.
const WSScanResult prevVisibleThing =
WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundary(
// We want to put caret to an editable point so that we need to scan
// only editable nodes.
{WSRunScanner::Option::OnlyEditableNodes}, pointToPutCaret);
if (prevVisibleThing.ReachedInvisibleBRElement()) {
const WSScanResult prevVisibleThingOfBRElement =
WSRunScanner::ScanPreviousVisibleNodeOrBlockBoundary(
{WSRunScanner::Option::OnlyEditableNodes},
EditorRawDOMPoint(prevVisibleThing.BRElementPtr()));
if (prevVisibleThingOfBRElement.InVisibleOrCollapsibleCharacters()) {
pointToPutCaret = prevVisibleThingOfBRElement
.PointAfterReachedContent<EditorDOMPoint>();
} else if (prevVisibleThingOfBRElement.ReachedSpecialContent()) {
pointToPutCaret = prevVisibleThingOfBRElement
.PointAfterReachedContentNode<EditorDOMPoint>();
}
}
return pointToPutCaret;
}
nsresult HTMLEditor::InsertHTMLWithContextAsSubAction(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, const nsAString& aFlavor,
SafeToInsertData aSafeToInsertData, const EditorDOMPoint& aPointToInsert,
DeleteSelectedContent aDeleteSelectedContent,
InlineStylesAtInsertionPoint aInlineStylesAtInsertionPoint,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
CommitComposition();
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::ePasteHTMLContent, 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");
ignoredError.SuppressException();
{
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 we have a destination / target node, we want to insert there rather than
// in place of the selection. Ignore aDeleteSelectedContent here if
// aPointToInsert is not set since deletion will also occur later in
// HTMLWithContextInserter and will be collapsed around there; this block
// is intended to cover the various scenarios where we are dropping in an
// editor (and may want to delete the selection before collapsing the
// selection in the new destination)
if (aPointToInsert.IsSet()) {
nsresult rv =
PrepareToInsertContent(aPointToInsert, aDeleteSelectedContent);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::PrepareToInsertContent() failed");
return rv;
}
aDeleteSelectedContent = DeleteSelectedContent::No;
}
HTMLWithContextInserter htmlWithContextInserter(*this, aEditingHost);
Result<EditActionResult, nsresult> result = htmlWithContextInserter.Run(
aInputString, aContextStr, aInfoStr, aSafeToInsertData,
aInlineStylesAtInsertionPoint);
if (MOZ_UNLIKELY(result.isErr())) {
return result.unwrapErr();
}
// If nothing is inserted and delete selection is required, we need to
// delete selection right now.
if (result.inspect().Ignored() &&
aDeleteSelectedContent == DeleteSelectedContent::Yes) {
nsresult rv = DeleteSelectionAsSubAction(eNone, eStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(eNone, eStrip) failed");
return rv;
}
}
return NS_OK;
}
Result<EditActionResult, nsresult> HTMLEditor::HTMLWithContextInserter::Run(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, SafeToInsertData aSafeToInsertData,
InlineStylesAtInsertionPoint aInlineStylesAtInsertionPoint) {
MOZ_ASSERT(mHTMLEditor.IsEditActionDataAvailable());
// create a dom document fragment that represents the structure to paste
nsCOMPtr<nsINode> fragmentAsNode, streamStartParent, streamEndParent;
uint32_t streamStartOffset = 0, streamEndOffset = 0;
nsresult rv = CreateDOMFragmentFromPaste(
aInputString, aContextStr, aInfoStr, address_of(fragmentAsNode),
address_of(streamStartParent), address_of(streamEndParent),
&streamStartOffset, &streamEndOffset, aSafeToInsertData);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::CreateDOMFragmentFromPaste() "
"failed");
return Err(rv);
}
// we need to recalculate various things based on potentially new offsets
// this is work to be completed at a later date (probably by jfrancis)
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfTopMostChildContents;
// If we have stream start point information, lets use it and end point.
// Otherwise, we should make a range all over the document fragment.
EditorRawDOMPoint streamStartPoint =
streamStartParent
? EditorRawDOMPoint(streamStartParent,
AssertedCast<uint32_t>(streamStartOffset))
: EditorRawDOMPoint(fragmentAsNode, 0);
EditorRawDOMPoint streamEndPoint =
streamStartParent ? EditorRawDOMPoint(streamEndParent, streamEndOffset)
: EditorRawDOMPoint::AtEndOf(fragmentAsNode);
(void)streamStartPoint;
(void)streamEndPoint;
HTMLWithContextInserter::CollectTopMostChildContentsCompletelyInRange(
EditorRawDOMPoint(streamStartParent,
AssertedCast<uint32_t>(streamStartOffset)),
EditorRawDOMPoint(streamEndParent,
AssertedCast<uint32_t>(streamEndOffset)),
arrayOfTopMostChildContents);
if (arrayOfTopMostChildContents.IsEmpty()) {
return EditActionResult::IgnoredResult(); // Nothing to insert.
}
// Are there any table elements in the list?
// check for table cell selection mode
bool cellSelectionMode =
HTMLEditUtils::IsInTableCellSelectionMode(mHTMLEditor.SelectionRef());
if (cellSelectionMode) {
// do we have table content to paste? If so, we want to delete
// the selected table cells and replace with new table elements;
// but if not we want to delete _contents_ of cells and replace
// with non-table elements. Use cellSelectionMode bool to
// indicate results.
if (!HTMLEditUtils::IsAnyTableElementExceptColumnElement(
*arrayOfTopMostChildContents[0])) {
cellSelectionMode = false;
}
}
if (!cellSelectionMode) {
rv = mHTMLEditor.DeleteSelectionAndPrepareToCreateNode();
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteSelectionAndPrepareToCreateNode() failed");
return Err(rv);
}
if (aInlineStylesAtInsertionPoint == InlineStylesAtInsertionPoint::Clear) {
// pasting does not inherit local inline styles
Result<EditorDOMPoint, nsresult> pointToPutCaretOrError =
mHTMLEditor.ClearStyleAt(
EditorDOMPoint(mHTMLEditor.SelectionRef().AnchorRef()),
EditorInlineStyle::RemoveAllStyles(), SpecifiedStyle::Preserve,
mEditingHost);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("HTMLEditor::ClearStyleAt() failed");
return pointToPutCaretOrError.propagateErr();
}
if (pointToPutCaretOrError.inspect().IsSetAndValid()) {
nsresult rv =
mHTMLEditor.CollapseSelectionTo(pointToPutCaretOrError.unwrap());
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionTo() failed");
return Err(rv);
}
}
}
} else {
// Delete whole cells: we will replace with new table content.
// Braces for artificial block to scope AutoSelectionRestorer.
// Save current selection since DeleteTableCellWithTransaction() perturbs
// it.
{
AutoSelectionRestorer restoreSelectionLater(&mHTMLEditor);
rv = mHTMLEditor.DeleteTableCellWithTransaction(1);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteTableCellWithTransaction(1) failed");
return Err(rv);
}
}
// collapse selection to beginning of deleted table content
IgnoredErrorResult ignoredError;
mHTMLEditor.SelectionRef().CollapseToStart(ignoredError);
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"Selection::Collapse() failed, but ignored");
}
{
Result<EditActionResult, nsresult> result =
mHTMLEditor.CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result;
}
if (result.inspect().Canceled()) {
return result;
}
}
mHTMLEditor.UndefineCaretBidiLevel();
rv = mHTMLEditor.EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && mHTMLEditor.SelectionRef().IsCollapsed()) {
nsresult rv =
mHTMLEditor.EnsureCaretNotAfterInvisibleBRElement(mEditingHost);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterInvisibleBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = mHTMLEditor.PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
// Adjust position based on the first node we are going to insert.
const auto candidatePointToInsert =
mHTMLEditor.GetFirstSelectionStartPoint<EditorRawDOMPoint>();
if (NS_WARN_IF(!candidatePointToInsert.IsSet()) ||
NS_WARN_IF(
!candidatePointToInsert.GetContainer()->IsInclusiveDescendantOf(
&mEditingHost))) {
return Err(NS_ERROR_FAILURE);
}
EditorDOMPoint pointToInsert =
HTMLEditUtils::GetBetterInsertionPointFor<EditorDOMPoint>(
arrayOfTopMostChildContents[0],
mHTMLEditor.GetFirstSelectionStartPoint<EditorRawDOMPoint>());
if (!pointToInsert.IsSet()) {
NS_WARNING("HTMLEditor::GetBetterInsertionPointFor() failed");
return Err(NS_ERROR_FAILURE);
}
Result<EditorDOMPoint, nsresult> pointToInsertOrError =
WhiteSpaceVisibilityKeeper::NormalizeWhiteSpacesToSplitAt(
mHTMLEditor, 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);
}
const bool insertionPointWasInLink =
!!HTMLEditor::GetLinkElement(pointToInsert.GetContainer());
if (pointToInsert.IsInTextNode()) {
Result<SplitNodeResult, nsresult> splitNodeResult =
mHTMLEditor.SplitNodeDeepWithTransaction(
MOZ_KnownLive(*pointToInsert.ContainerAs<nsIContent>()),
pointToInsert, SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitNodeResult.propagateErr();
}
nsresult rv = splitNodeResult.inspect().SuggestCaretPointTo(
mHTMLEditor, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (NS_FAILED(rv)) {
NS_WARNING("SplitNodeResult::SuggestCaretPointTo() failed");
return Err(rv);
}
pointToInsert = splitNodeResult.inspect().AtSplitPoint<EditorDOMPoint>();
if (MOZ_UNLIKELY(!pointToInsert.IsSet())) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction() didn't return split "
"point");
return Err(NS_ERROR_FAILURE);
}
}
{ // Block only for AutoHTMLFragmentBoundariesFixer to hide it from the
// following code. Note that it may modify arrayOfTopMostChildContents.
AutoHTMLFragmentBoundariesFixer fixPiecesOfTablesAndLists(
arrayOfTopMostChildContents);
}
MOZ_ASSERT(pointToInsert.GetContainer()->GetChildAt_Deprecated(
pointToInsert.Offset()) == pointToInsert.GetChild());
Result<EditorDOMPoint, nsresult> lastInsertedPoint = InsertContents(
pointToInsert, arrayOfTopMostChildContents, fragmentAsNode);
if (lastInsertedPoint.isErr()) {
NS_WARNING("HTMLWithContextInserter::InsertContents() failed.");
return lastInsertedPoint.propagateErr();
}
mHTMLEditor.TopLevelEditSubActionDataRef().mNeedsToCleanUpEmptyElements =
false;
if (MOZ_UNLIKELY(!lastInsertedPoint.inspect().IsInComposedDoc())) {
return EditActionResult::HandledResult();
}
if (MOZ_LIKELY(lastInsertedPoint.inspect().IsInContentNode())) {
const auto afterLastInsertedContent =
lastInsertedPoint.inspect().NextPointOrAfterContainer();
if (MOZ_LIKELY(afterLastInsertedContent.IsInContentNode())) {
nsresult rv = mHTMLEditor.EnsureNoFollowingUnnecessaryLineBreak(
afterLastInsertedContent);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::EnsureNoFollowingUnnecessaryLineBreak() failed");
return Err(rv);
}
}
}
const EditorDOMPoint pointToPutCaret =
GetNewCaretPointAfterInsertingHTML(lastInsertedPoint.inspect());
// Now collapse the selection to the end of what we just inserted.
rv = mHTMLEditor.CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionTo() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
// If we didn't start from an `<a href>` element, we should not keep
// caret in the link to make users type something outside the link.
if (insertionPointWasInLink) {
return EditActionResult::HandledResult();
}
RefPtr<Element> linkElement = GetLinkElement(pointToPutCaret.GetContainer());
if (!linkElement) {
return EditActionResult::HandledResult();
}
rv = MoveCaretOutsideOfLink(*linkElement, pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::MoveCaretOutsideOfLink "
"failed.");
return Err(rv);
}
return EditActionResult::HandledResult();
}
Result<EditorDOMPoint, nsresult>
HTMLEditor::HTMLWithContextInserter::InsertContents(
const EditorDOMPoint& aPointToInsert,
nsTArray<OwningNonNull<nsIContent>>& aArrayOfTopMostChildContents,
const nsINode* aFragmentAsNode) {
MOZ_ASSERT(aPointToInsert.IsSetAndValidInComposedDoc());
EditorDOMPoint pointToInsert{aPointToInsert};
// Loop over the node list and paste the nodes:
const RefPtr<const Element> maybeNonEditableBlockElement =
pointToInsert.IsInContentNode()
? HTMLEditUtils::GetInclusiveAncestorElement(
*pointToInsert.ContainerAs<nsIContent>(),
HTMLEditUtils::ClosestBlockElement,
BlockInlineCheck::UseComputedDisplayOutsideStyle)
: nullptr;
EditorDOMPoint lastInsertedPoint;
nsCOMPtr<nsIContent> insertedContextParentContent;
for (const OwningNonNull<nsIContent>& content :
aArrayOfTopMostChildContents) {
if (NS_WARN_IF(content == aFragmentAsNode) ||
NS_WARN_IF(content->IsHTMLElement(nsGkAtoms::body))) {
return Err(NS_ERROR_FAILURE);
}
if (insertedContextParentContent) {
// If we had to insert something higher up in the paste hierarchy,
// we want to skip any further paste nodes that descend from that.
// Else we will paste twice.
// XXX This check may be really expensive. Cannot we check whether
// the node's `ownerDocument` is the `aFragmentAsNode` or not?
// XXX If content was moved to outside of insertedContextParentContent
// by mutation event listeners, we will anyway duplicate it.
if (EditorUtils::IsDescendantOf(*content,
*insertedContextParentContent)) {
continue;
}
}
// If a `<table>` or `<tr>` element on the clipboard, and pasting it into
// a `<table>` or `<tr>` element, insert only the appropriate children
// instead.
bool inserted = false;
if (HTMLEditUtils::IsTableRowElement(*content) &&
HTMLEditUtils::IsTableRowElement(
pointToInsert.GetContainerAs<nsIContent>()) &&
(content->IsHTMLElement(nsGkAtoms::table) ||
pointToInsert.IsContainerHTMLElement(nsGkAtoms::table))) {
// Move children of current node to the insertion point.
AutoTArray<OwningNonNull<nsIContent>, 24> children;
HTMLEditUtils::CollectAllChildren(*content, children);
EditorDOMPoint pointToPutCaret;
for (const OwningNonNull<nsIContent>& child : children) {
// MOZ_KnownLive(child) because of bug 1622253
Result<CreateContentResult, nsresult> moveChildResult =
mHTMLEditor.InsertNodeIntoProperAncestorWithTransaction<nsIContent>(
MOZ_KnownLive(child), pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(moveChildResult.isErr())) {
// If moving node is moved to different place, we should ignore
// this result and keep trying to insert next content node to same
// position.
if (moveChildResult.inspectErr() ==
NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE) {
inserted = true;
continue; // the inner `for` loop
}
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed, maybe "
"ignored");
break; // from the inner `for` loop
}
if (MOZ_UNLIKELY(!moveChildResult.inspect().Handled())) {
continue;
}
inserted = true;
lastInsertedPoint.Set(child);
pointToInsert = lastInsertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
CreateContentResult unwrappedMoveChildResult = moveChildResult.unwrap();
unwrappedMoveChildResult.MoveCaretPointTo(
pointToPutCaret, mHTMLEditor,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
} // end of the inner `for` loop
if (pointToPutCaret.IsSet()) {
nsresult rv = mHTMLEditor.CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionTo() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
}
// If a list element on the clipboard, and pasting it into a list or
// list item element, insert the appropriate children instead. I.e.,
// merge the list elements instead of pasting as a sublist.
else if (HTMLEditUtils::IsListElement(*content) &&
(HTMLEditUtils::IsListElement(
pointToInsert.GetContainerAs<nsIContent>()) ||
HTMLEditUtils::IsListItemElement(
pointToInsert.GetContainerAs<nsIContent>()))) {
AutoTArray<OwningNonNull<nsIContent>, 24> children;
HTMLEditUtils::CollectAllChildren(*content, children);
EditorDOMPoint pointToPutCaret;
for (const OwningNonNull<nsIContent>& child : children) {
if (HTMLEditUtils::IsListItemElement(*child) ||
HTMLEditUtils::IsListElement(*child)) {
// If we're pasting into empty list item, we should remove it
// and past current node into the parent list directly.
// XXX This creates invalid structure if current list item element
// is not proper child of the parent element, or current node
// is a list element.
if (HTMLEditUtils::IsListItemElement(
pointToInsert.GetContainerAs<nsIContent>()) &&
HTMLEditUtils::IsEmptyNode(
*pointToInsert.GetContainer(),
{EmptyCheckOption::TreatNonEditableContentAsInvisible})) {
NS_WARNING_ASSERTION(pointToInsert.GetContainerParent(),
"Insertion point is out of the DOM tree");
if (pointToInsert.GetContainerParent()) {
pointToInsert.Set(pointToInsert.GetContainer());
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
AutoEditorDOMPointChildInvalidator lockOffset(pointToInsert);
nsresult rv = mHTMLEditor.DeleteNodeWithTransaction(
MOZ_KnownLive(*pointToInsert.GetChild()));
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::DeleteNodeWithTransaction() "
"failed, but ignored");
}
}
// MOZ_KnownLive(child) because of bug 1622253
Result<CreateContentResult, nsresult> moveChildResult =
mHTMLEditor
.InsertNodeIntoProperAncestorWithTransaction<nsIContent>(
MOZ_KnownLive(child), pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(moveChildResult.isErr())) {
// If moving node is moved to different place, we should ignore
// this result and keep trying to insert next content node to
// same position.
if (moveChildResult.inspectErr() ==
NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE) {
inserted = true;
continue; // the inner `for` loop
}
if (NS_WARN_IF(moveChildResult.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed, but maybe "
"ignored");
break; // from the inner `for` loop
}
if (MOZ_UNLIKELY(!moveChildResult.inspect().Handled())) {
continue;
}
inserted = true;
lastInsertedPoint.Set(child);
pointToInsert = lastInsertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
CreateContentResult unwrappedMoveChildResult =
moveChildResult.unwrap();
unwrappedMoveChildResult.MoveCaretPointTo(
pointToPutCaret, mHTMLEditor,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
}
// If the child of current node is not list item nor list element,
// we should remove it from the DOM tree.
else if (HTMLEditUtils::IsRemovableNode(child)) {
AutoEditorDOMPointChildInvalidator lockOffset(pointToInsert);
IgnoredErrorResult ignoredError;
content->RemoveChild(child, ignoredError);
if (MOZ_UNLIKELY(mHTMLEditor.Destroyed())) {
NS_WARNING(
"nsIContent::RemoveChild() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"nsINode::RemoveChild() failed, but ignored");
} else {
NS_WARNING(
"Failed to delete the first child of a list element because the "
"list element non-editable");
break; // from the inner `for` loop
}
} // end of the inner `for` loop
if (MOZ_UNLIKELY(mHTMLEditor.Destroyed())) {
NS_WARNING("The editor has been destroyed");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (pointToPutCaret.IsSet()) {
nsresult rv = mHTMLEditor.CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionTo() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
}
// If pasting into a `<pre>` element and current node is a `<pre>` element,
// move only its children.
else if (maybeNonEditableBlockElement &&
maybeNonEditableBlockElement->IsHTMLElement(nsGkAtoms::pre) &&
content->IsHTMLElement(nsGkAtoms::pre)) {
// Check for pre's going into pre's.
AutoTArray<OwningNonNull<nsIContent>, 24> children;
HTMLEditUtils::CollectAllChildren(*content, children);
EditorDOMPoint pointToPutCaret;
for (const OwningNonNull<nsIContent>& child : children) {
// MOZ_KnownLive(child) because of bug 1622253
Result<CreateContentResult, nsresult> moveChildResult =
mHTMLEditor.InsertNodeIntoProperAncestorWithTransaction<nsIContent>(
MOZ_KnownLive(child), pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(moveChildResult.isErr())) {
// If moving node is moved to different place, we should ignore
// this result and keep trying to insert next content node there.
if (moveChildResult.inspectErr() ==
NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE) {
inserted = true;
continue; // the inner `for` loop
}
if (NS_WARN_IF(moveChildResult.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return moveChildResult.propagateErr();
}
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed, but maybe "
"ignored");
break; // from the inner `for` loop
}
if (MOZ_UNLIKELY(!moveChildResult.inspect().Handled())) {
continue;
}
CreateContentResult unwrappedMoveChildResult = moveChildResult.unwrap();
inserted = true;
lastInsertedPoint.Set(child);
pointToInsert = lastInsertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
unwrappedMoveChildResult.MoveCaretPointTo(
pointToPutCaret, mHTMLEditor,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
} // end of the inner `for` loop
if (pointToPutCaret.IsSet()) {
nsresult rv = mHTMLEditor.CollapseSelectionTo(pointToPutCaret);
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionTo() caused destroying the editor");
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
}
// TODO: For making the above code clearer, we should move this fallback
// path into a lambda and call it in each if/else-if block.
// If we haven't inserted current node nor its children, move current node
// to the insertion point.
if (!inserted) {
// MOZ_KnownLive(content) because 'aArrayOfTopMostChildContents' is
// guaranteed to keep it alive.
Result<CreateContentResult, nsresult> moveContentResult =
mHTMLEditor.InsertNodeIntoProperAncestorWithTransaction<nsIContent>(
MOZ_KnownLive(content), pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_LIKELY(moveContentResult.isOk())) {
if (MOZ_UNLIKELY(!moveContentResult.inspect().Handled())) {
continue;
}
lastInsertedPoint.Set(content);
pointToInsert = lastInsertedPoint;
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
nsresult rv = moveContentResult.inspect().SuggestCaretPointTo(
mHTMLEditor, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateContentResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateContentResult::SuggestCaretPointTo() failed, but ignored");
} else if (moveContentResult.inspectErr() ==
NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE) {
// Moving node is moved to different place, we should keep trying to
// insert the next content to same position.
} else {
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed, but ignored");
// Assume failure means no legal parent in the document hierarchy,
// try again with the parent of content in the paste hierarchy.
// FYI: We cannot use `InclusiveAncestorOfType` here because of
// calling `InsertNodeIntoProperAncestorWithTransaction()`.
for (nsCOMPtr<nsIContent> childContent = content; childContent;
childContent = childContent->GetParent()) {
if (NS_WARN_IF(!childContent->GetParent()) ||
NS_WARN_IF(
childContent->GetParent()->IsHTMLElement(nsGkAtoms::body))) {
break; // for the inner `for` loop
}
const OwningNonNull<nsIContent> oldParentContent =
*childContent->GetParent();
Result<CreateContentResult, nsresult> moveParentResult =
mHTMLEditor
.InsertNodeIntoProperAncestorWithTransaction<nsIContent>(
oldParentContent, pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(moveParentResult.isErr())) {
// Moving node is moved to different place, we should keep trying to
// insert the next content to same position.
if (moveParentResult.inspectErr() ==
NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE) {
break; // from the inner `for` loop
}
if (NS_WARN_IF(moveParentResult.inspectErr() ==
NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"HTMLEditor::InsertNodeInToProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed, but "
"ignored");
continue; // the inner `for` loop
}
if (MOZ_UNLIKELY(!moveParentResult.inspect().Handled())) {
continue;
}
insertedContextParentContent = oldParentContent;
pointToInsert.Set(oldParentContent);
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
nsresult rv = moveParentResult.inspect().SuggestCaretPointTo(
mHTMLEditor, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt,
SuggestCaret::AndIgnoreTrivialError});
if (NS_FAILED(rv)) {
NS_WARNING("CreateContentResult::SuggestCaretPointTo() failed");
return Err(rv);
}
NS_WARNING_ASSERTION(
rv != NS_SUCCESS_EDITOR_BUT_IGNORED_TRIVIAL_ERROR,
"CreateContentResult::SuggestCaretPointTo() failed, but ignored");
break; // from the inner `for` loop
} // end of the inner `for` loop
}
}
if (lastInsertedPoint.IsSet()) {
if (MOZ_UNLIKELY(lastInsertedPoint.GetContainer() !=
lastInsertedPoint.GetChild()->GetParentNode())) {
NS_WARNING(
"HTMLEditor::InsertHTMLWithContextAsSubAction() got lost insertion "
"point");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
pointToInsert = lastInsertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSetAndValidInComposedDoc());
}
} // end of the `for` loop
return lastInsertedPoint;
}
nsresult HTMLEditor::HTMLWithContextInserter::MoveCaretOutsideOfLink(
Element& aLinkElement, const EditorDOMPoint& aPointToPutCaret) {
MOZ_ASSERT(HTMLEditUtils::IsHyperlinkElement(aLinkElement));
// The reason why do that instead of just moving caret after it is, the
// link might have ended in an invisible `<br>` element. If so, the code
// above just placed selection inside that. So we need to split it instead.
// XXX Sounds like that it's not really expensive comparing with the reason
// to use SplitNodeDeepWithTransaction() here.
Result<SplitNodeResult, nsresult> splitLinkResult =
mHTMLEditor.SplitNodeDeepWithTransaction(
aLinkElement, aPointToPutCaret,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitLinkResult.isErr())) {
if (splitLinkResult.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction() failed, but ignored");
}
if (nsIContent* previousContentOfSplitPoint =
splitLinkResult.inspect().GetPreviousContent()) {
splitLinkResult.inspect().IgnoreCaretPointSuggestion();
nsresult rv = mHTMLEditor.CollapseSelectionTo(
EditorRawDOMPoint::After(*previousContentOfSplitPoint));
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionTo() failed, but ignored");
return NS_OK;
}
nsresult rv = splitLinkResult.inspect().SuggestCaretPointTo(
mHTMLEditor, {SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"SplitNodeResult::SuggestCaretPointTo() failed");
return rv;
}
// static
Element* HTMLEditor::GetLinkElement(nsINode* aNode) {
if (NS_WARN_IF(!aNode)) {
return nullptr;
}
nsINode* node = aNode;
while (node) {
if (node->IsElement() &&
HTMLEditUtils::IsHyperlinkElement(*node->AsElement())) {
return node->AsElement();
}
node = node->GetParentNode();
}
return nullptr;
}
// static
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
nsIContent& aNode, NodesToRemove aNodesToRemove) {
if (aNode.TextIsOnlyWhitespace()) {
nsCOMPtr<nsINode> parent = aNode.GetParentNode();
// TODO: presumably, if the parent is a `<pre>` element, the node
// shouldn't be removed.
if (parent) {
if (aNodesToRemove == NodesToRemove::eAll ||
HTMLEditUtils::IsListElement(nsIContent::FromNode(parent))) {
ErrorResult error;
parent->RemoveChild(aNode, error);
NS_WARNING_ASSERTION(!error.Failed(), "nsINode::RemoveChild() failed");
return error.StealNSResult();
}
return NS_OK;
}
}
if (!aNode.IsHTMLElement(nsGkAtoms::pre)) {
nsCOMPtr<nsIContent> child = aNode.GetLastChild();
while (child) {
nsCOMPtr<nsIContent> previous = child->GetPreviousSibling();
nsresult rv = FragmentFromPasteCreator::
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
*child, aNodesToRemove);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces"
"() "
"failed");
return rv;
}
child = std::move(previous);
}
}
return NS_OK;
}
class MOZ_STACK_CLASS HTMLEditor::HTMLTransferablePreparer {
public:
HTMLTransferablePreparer(const HTMLEditor& aHTMLEditor,
nsITransferable** aTransferable,
const Element* aEditingHost);
nsresult Run();
private:
void AddDataFlavorsInBestOrder(nsITransferable& aTransferable) const;
const HTMLEditor& mHTMLEditor;
const Element* const mEditingHost;
nsITransferable** mTransferable;
};
HTMLEditor::HTMLTransferablePreparer::HTMLTransferablePreparer(
const HTMLEditor& aHTMLEditor, nsITransferable** aTransferable,
const Element* aEditingHost)
: mHTMLEditor{aHTMLEditor},
mEditingHost(aEditingHost),
mTransferable{aTransferable} {
MOZ_ASSERT(mTransferable);
MOZ_ASSERT(!*mTransferable);
}
nsresult HTMLEditor::PrepareHTMLTransferable(
nsITransferable** aTransferable, const Element* aEditingHost) const {
HTMLTransferablePreparer htmlTransferablePreparer{*this, aTransferable,
aEditingHost};
return htmlTransferablePreparer.Run();
}
nsresult HTMLEditor::HTMLTransferablePreparer::Run() {
// Create generic Transferable for getting the data
nsresult rv;
RefPtr<nsITransferable> transferable =
do_CreateInstance("@mozilla.org/widget/transferable;1", &rv);
if (NS_FAILED(rv)) {
NS_WARNING("do_CreateInstance() failed to create nsITransferable instance");
return rv;
}
if (!transferable) {
NS_WARNING("do_CreateInstance() returned nullptr, but ignored");
return NS_OK;
}
// Get the nsITransferable interface for getting the data from the clipboard
RefPtr<Document> destdoc = mHTMLEditor.GetDocument();
nsILoadContext* loadContext = destdoc ? destdoc->GetLoadContext() : nullptr;
DebugOnly<nsresult> rvIgnored = transferable->Init(loadContext);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::Init() failed, but ignored");
// See `HTMLEditor::InsertFromTransferableAtSelection`.
AddDataFlavorsInBestOrder(*transferable);
transferable.forget(mTransferable);
return NS_OK;
}
void HTMLEditor::HTMLTransferablePreparer::AddDataFlavorsInBestOrder(
nsITransferable& aTransferable) const {
// Create the desired DataFlavor for the type of data
// we want to get out of the transferable
// This should only happen in html editors, not plaintext
// Note that if you add more flavors here you will need to add them
// to DataTransfer::GetExternalClipboardFormats as well.
if (!mHTMLEditor.IsPlaintextMailComposer() &&
!(mEditingHost && mEditingHost->IsContentEditablePlainTextOnly())) {
DebugOnly<nsresult> rvIgnored =
aTransferable.AddDataFlavor(kNativeHTMLMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kNativeHTMLMime) failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kHTMLMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kHTMLMime) failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kFileMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kFileMime) failed, but ignored");
switch (Preferences::GetInt("clipboard.paste_image_type", 1)) {
case 0: // prefer JPEG over PNG over GIF encoding
rvIgnored = aTransferable.AddDataFlavor(kJPEGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPEGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kPNGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kPNGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kGIFImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kGIFImageMime) "
"failed, but ignored");
break;
case 1: // prefer PNG over JPEG over GIF encoding (default)
default:
rvIgnored = aTransferable.AddDataFlavor(kPNGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kPNGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPEGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPEGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kGIFImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kGIFImageMime) "
"failed, but ignored");
break;
case 2: // prefer GIF over JPEG over PNG encoding
rvIgnored = aTransferable.AddDataFlavor(kGIFImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kGIFImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPEGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPEGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kPNGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kPNGImageMime) "
"failed, but ignored");
break;
}
}
DebugOnly<nsresult> rvIgnored = aTransferable.AddDataFlavor(kTextMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kTextMime) failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kMozTextInternal);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kMozTextInternal) failed, but ignored");
}
bool FindIntegerAfterString(const char* aLeadingString, const nsCString& aCStr,
int32_t& foundNumber) {
// first obtain offsets from cfhtml str
int32_t numFront = aCStr.Find(aLeadingString);
if (numFront == -1) {
return false;
}
numFront += strlen(aLeadingString);
int32_t numBack = aCStr.FindCharInSet(CRLF, numFront);
if (numBack == -1) {
return false;
}
nsAutoCString numStr(Substring(aCStr, numFront, numBack - numFront));
nsresult errorCode;
foundNumber = numStr.ToInteger(&errorCode);
return true;
}
void RemoveFragComments(nsCString& aStr) {
// remove the StartFragment/EndFragment comments from the str, if present
int32_t startCommentIndx = aStr.Find("<!--StartFragment");
if (startCommentIndx >= 0) {
int32_t startCommentEnd = aStr.Find("-->", startCommentIndx);
if (startCommentEnd > startCommentIndx) {
aStr.Cut(startCommentIndx, (startCommentEnd + 3) - startCommentIndx);
}
}
int32_t endCommentIndx = aStr.Find("<!--EndFragment");
if (endCommentIndx >= 0) {
int32_t endCommentEnd = aStr.Find("-->", endCommentIndx);
if (endCommentEnd > endCommentIndx) {
aStr.Cut(endCommentIndx, (endCommentEnd + 3) - endCommentIndx);
}
}
}
nsresult HTMLEditor::ParseCFHTML(const nsCString& aCfhtml,
char16_t** aStuffToPaste,
char16_t** aCfcontext) {
// First obtain offsets from cfhtml str.
int32_t startHTML, endHTML, startFragment, endFragment;
if (!FindIntegerAfterString("StartHTML:", aCfhtml, startHTML) ||
startHTML < -1) {
return NS_ERROR_FAILURE;
}
if (!FindIntegerAfterString("EndHTML:", aCfhtml, endHTML) || endHTML < -1) {
return NS_ERROR_FAILURE;
}
if (!FindIntegerAfterString("StartFragment:", aCfhtml, startFragment) ||
startFragment < 0) {
return NS_ERROR_FAILURE;
}
if (!FindIntegerAfterString("EndFragment:", aCfhtml, endFragment) ||
startFragment < 0) {
return NS_ERROR_FAILURE;
}
// The StartHTML and EndHTML markers are allowed to be -1 to include
// everything.
// See Reference: MSDN doc entitled "HTML Clipboard Format"
// http://msdn.microsoft.com/en-us/library/aa767917(VS.85).aspx#unknown_854
if (startHTML == -1) {
startHTML = aCfhtml.Find("<!--StartFragment-->");
if (startHTML == -1) {
return NS_OK;
}
}
if (endHTML == -1) {
const char endFragmentMarker[] = "<!--EndFragment-->";
endHTML = aCfhtml.Find(endFragmentMarker);
if (endHTML == -1) {
return NS_OK;
}
endHTML += std::size(endFragmentMarker) - 1;
}
// create context string
nsAutoCString contextUTF8(
Substring(aCfhtml, startHTML, startFragment - startHTML) +
"<!--" kInsertCookie "-->"_ns +
Substring(aCfhtml, endFragment, endHTML - endFragment));
// validate startFragment
// make sure it's not in the middle of a HTML tag
// see bug #228879 for more details
int32_t curPos = startFragment;
while (curPos > startHTML) {
if (aCfhtml[curPos] == '>') {
// working backwards, the first thing we see is the end of a tag
// so StartFragment is good, so do nothing.
break;
}
if (aCfhtml[curPos] == '<') {
// if we are at the start, then we want to see the '<'
if (curPos != startFragment) {
// working backwards, the first thing we see is the start of a tag
// so StartFragment is bad, so we need to update it.
NS_ERROR(
"StartFragment byte count in the clipboard looks bad, see bug "
"#228879");
startFragment = curPos - 1;
}
break;
}
curPos--;
}
// create fragment string
nsAutoCString fragmentUTF8(
Substring(aCfhtml, startFragment, endFragment - startFragment));
// remove the StartFragment/EndFragment comments from the fragment, if present
RemoveFragComments(fragmentUTF8);
// remove the StartFragment/EndFragment comments from the context, if present
RemoveFragComments(contextUTF8);
// convert both strings to usc2
const nsString& fragUcs2Str = NS_ConvertUTF8toUTF16(fragmentUTF8);
const nsString& cntxtUcs2Str = NS_ConvertUTF8toUTF16(contextUTF8);
// translate platform linebreaks for fragment
int32_t oldLengthInChars =
fragUcs2Str.Length() + 1; // +1 to include null terminator
int32_t newLengthInChars = 0;
*aStuffToPaste = nsLinebreakConverter::ConvertUnicharLineBreaks(
fragUcs2Str.get(), nsLinebreakConverter::eLinebreakAny,
nsLinebreakConverter::eLinebreakContent, oldLengthInChars,
&newLengthInChars);
if (!*aStuffToPaste) {
NS_WARNING("nsLinebreakConverter::ConvertUnicharLineBreaks() failed");
return NS_ERROR_FAILURE;
}
// translate platform linebreaks for context
oldLengthInChars =
cntxtUcs2Str.Length() + 1; // +1 to include null terminator
newLengthInChars = 0;
*aCfcontext = nsLinebreakConverter::ConvertUnicharLineBreaks(
cntxtUcs2Str.get(), nsLinebreakConverter::eLinebreakAny,
nsLinebreakConverter::eLinebreakContent, oldLengthInChars,
&newLengthInChars);
// it's ok for context to be empty. frag might be whole doc and contain all
// its context.
// we're done!
return NS_OK;
}
static nsresult ImgFromData(const nsACString& aType, const nsACString& aData,
nsString& aOutput) {
aOutput.AssignLiteral("<IMG src=\"data:");
AppendUTF8toUTF16(aType, aOutput);
aOutput.AppendLiteral(";base64,");
nsresult rv = Base64EncodeAppend(aData, aOutput);
if (NS_FAILED(rv)) {
NS_WARNING("Base64Encode() failed");
return rv;
}
aOutput.AppendLiteral("\" alt=\"\" >");
return NS_OK;
}
NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLEditor::BlobReader)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(HTMLEditor::BlobReader)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBlob)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mHTMLEditor)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPointToInsert)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(HTMLEditor::BlobReader)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBlob)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mHTMLEditor)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPointToInsert)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
HTMLEditor::BlobReader::BlobReader(BlobImpl* aBlob, HTMLEditor* aHTMLEditor,
SafeToInsertData aSafeToInsertData,
const EditorDOMPoint& aPointToInsert,
DeleteSelectedContent aDeleteSelectedContent,
const Element& aEditingHost)
: mBlob(aBlob),
mHTMLEditor(aHTMLEditor),
mEditingHost(&aEditingHost),
// "beforeinput" event should've been dispatched before we read blob,
// but anyway, we need to clone dataTransfer for "input" event.
mDataTransfer(mHTMLEditor->GetInputEventDataTransfer()),
mPointToInsert(aPointToInsert),
mEditAction(aHTMLEditor->GetEditAction()),
mSafeToInsertData(aSafeToInsertData),
mDeleteSelectedContent(aDeleteSelectedContent),
mNeedsToDispatchBeforeInputEvent(
!mHTMLEditor->HasTriedToDispatchBeforeInputEvent()) {
MOZ_ASSERT(mBlob);
MOZ_ASSERT(mHTMLEditor);
MOZ_ASSERT(mHTMLEditor->IsEditActionDataAvailable());
MOZ_ASSERT(mDataTransfer);
// Take only offset here since it's our traditional behavior.
if (mPointToInsert.IsSet()) {
AutoEditorDOMPointChildInvalidator storeOnlyWithOffset(mPointToInsert);
}
}
nsresult HTMLEditor::BlobReader::OnResult(const nsACString& aResult) {
if (NS_WARN_IF(!mEditingHost)) {
return NS_ERROR_FAILURE;
}
AutoEditActionDataSetter editActionData(*mHTMLEditor, mEditAction);
editActionData.InitializeDataTransfer(mDataTransfer);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_FAILURE;
}
if (NS_WARN_IF(mNeedsToDispatchBeforeInputEvent)) {
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
} else {
editActionData.MarkAsBeforeInputHasBeenDispatched();
}
nsString blobType;
mBlob->GetType(blobType);
// TODO: This does not work well.
// * If the data is not an image file, this inserts <img> element with odd
// data URI (bug 1610220).
// * If the data is valid image file data, an <img> file is inserted with
// data URI, but it's not loaded (bug 1610219).
NS_ConvertUTF16toUTF8 type(blobType);
nsAutoString stuffToPaste;
nsresult rv = ImgFromData(type, aResult, stuffToPaste);
if (NS_FAILED(rv)) {
NS_WARNING("ImgFormData() failed");
return EditorBase::ToGenericNSResult(rv);
}
RefPtr<HTMLEditor> htmlEditor = std::move(mHTMLEditor);
AutoPlaceholderBatch treatAsOneTransaction(
*htmlEditor, ScrollSelectionIntoView::Yes, __FUNCTION__);
EditorDOMPoint pointToInsert = std::move(mPointToInsert);
const RefPtr<const Element> editingHost = std::move(mEditingHost);
rv = htmlEditor->InsertHTMLWithContextAsSubAction(
stuffToPaste, u""_ns, u""_ns, NS_LITERAL_STRING_FROM_CSTRING(kFileMime),
mSafeToInsertData, pointToInsert, mDeleteSelectedContent,
InlineStylesAtInsertionPoint::Preserve, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"InlineStylesAtInsertionPoint::Preserve) failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::BlobReader::OnError(const nsAString& aError) {
AutoTArray<nsString, 1> error;
error.AppendElement(aError);
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "Editor"_ns, mHTMLEditor->GetDocument(),
nsContentUtils::eDOM_PROPERTIES, "EditorFileDropFailed", error);
return NS_OK;
}
class SlurpBlobEventListener final : public nsIDOMEventListener {
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(SlurpBlobEventListener)
explicit SlurpBlobEventListener(HTMLEditor::BlobReader* aListener)
: mListener(aListener) {}
MOZ_CAN_RUN_SCRIPT NS_IMETHOD HandleEvent(Event* aEvent) override;
private:
~SlurpBlobEventListener() = default;
RefPtr<HTMLEditor::BlobReader> mListener;
};
NS_IMPL_CYCLE_COLLECTION(SlurpBlobEventListener, mListener)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(SlurpBlobEventListener)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(SlurpBlobEventListener)
NS_IMPL_CYCLE_COLLECTING_RELEASE(SlurpBlobEventListener)
NS_IMETHODIMP SlurpBlobEventListener::HandleEvent(Event* aEvent) {
EventTarget* target = aEvent->GetTarget();
if (!target || !mListener) {
return NS_OK;
}
RefPtr<FileReader> reader = do_QueryObject(target);
if (!reader) {
return NS_OK;
}
EventMessage message = aEvent->WidgetEventPtr()->mMessage;
RefPtr<HTMLEditor::BlobReader> listener(mListener);
if (message == eLoad) {
MOZ_ASSERT(reader->DataFormat() == FileReader::FILE_AS_BINARY);
// The original data has been converted from Latin1 to UTF-16, this just
// undoes that conversion.
DebugOnly<nsresult> rvIgnored =
listener->OnResult(NS_LossyConvertUTF16toASCII(reader->Result()));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"HTMLEditor::BlobReader::OnResult() failed, but ignored");
return NS_OK;
}
if (message == eLoadError) {
nsAutoString errorMessage;
reader->GetError()->GetErrorMessage(errorMessage);
DebugOnly<nsresult> rvIgnored = listener->OnError(errorMessage);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"HTMLEditor::BlobReader::OnError() failed, but ignored");
return NS_OK;
}
return NS_OK;
}
// static
nsresult HTMLEditor::SlurpBlob(Blob* aBlob, nsIGlobalObject* aGlobal,
BlobReader* aBlobReader) {
MOZ_ASSERT(aBlob);
MOZ_ASSERT(aGlobal);
MOZ_ASSERT(aBlobReader);
RefPtr<WeakWorkerRef> workerRef;
RefPtr<FileReader> reader = new FileReader(aGlobal, workerRef);
RefPtr<SlurpBlobEventListener> eventListener =
new SlurpBlobEventListener(aBlobReader);
nsresult rv = reader->AddEventListener(u"load"_ns, eventListener, false);
if (NS_FAILED(rv)) {
NS_WARNING("FileReader::AddEventListener(load) failed");
return rv;
}
rv = reader->AddEventListener(u"error"_ns, eventListener, false);
if (NS_FAILED(rv)) {
NS_WARNING("FileReader::AddEventListener(error) failed");
return rv;
}
ErrorResult error;
reader->ReadAsBinaryString(*aBlob, error);
NS_WARNING_ASSERTION(!error.Failed(),
"FileReader::ReadAsBinaryString() failed");
return error.StealNSResult();
}
nsresult HTMLEditor::InsertObject(const nsACString& aType, nsISupports* aObject,
SafeToInsertData aSafeToInsertData,
const EditorDOMPoint& aPointToInsert,
DeleteSelectedContent aDeleteSelectedContent,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Check to see if we the file is actually an image.
nsAutoCString type(aType);
if (type.EqualsLiteral(kFileMime)) {
if (nsCOMPtr<nsIFile> file = do_QueryInterface(aObject)) {
nsCOMPtr<nsIMIMEService> mime = do_GetService("@mozilla.org/mime;1");
if (NS_WARN_IF(!mime)) {
return NS_ERROR_FAILURE;
}
nsresult rv = mime->GetTypeFromFile(file, type);
if (NS_FAILED(rv)) {
NS_WARNING("nsIMIMEService::GetTypeFromFile() failed");
return rv;
}
}
}
nsCOMPtr<nsISupports> object = aObject;
if (type.EqualsLiteral(kJPEGImageMime) || type.EqualsLiteral(kJPGImageMime) ||
type.EqualsLiteral(kPNGImageMime) || type.EqualsLiteral(kGIFImageMime)) {
if (nsCOMPtr<nsIFile> file = do_QueryInterface(object)) {
object = new FileBlobImpl(file);
// Fallthrough to BlobImpl code below.
} else if (RefPtr<Blob> blob = do_QueryObject(object)) {
object = blob->Impl();
// Fallthrough.
} else if (nsCOMPtr<nsIInputStream> imageStream =
do_QueryInterface(object)) {
nsCString imageData;
nsresult rv = NS_ConsumeStream(imageStream, UINT32_MAX, imageData);
if (NS_FAILED(rv)) {
NS_WARNING("NS_ConsumeStream() failed");
return rv;
}
rv = imageStream->Close();
if (NS_FAILED(rv)) {
NS_WARNING("nsIInputStream::Close() failed");
return rv;
}
nsAutoString stuffToPaste;
rv = ImgFromData(type, imageData, stuffToPaste);
if (NS_FAILED(rv)) {
NS_WARNING("ImgFromData() failed");
return rv;
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertHTMLWithContextAsSubAction(
stuffToPaste, u""_ns, u""_ns,
NS_LITERAL_STRING_FROM_CSTRING(kFileMime), aSafeToInsertData,
aPointToInsert, aDeleteSelectedContent,
InlineStylesAtInsertionPoint::Preserve, aEditingHost);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"InlineStylesAtInsertionPoint::Preserve) failed, but ignored");
return NS_OK;
} else {
NS_WARNING("HTMLEditor::InsertObject: Unexpected type for image mime");
return NS_OK;
}
}
// We always try to insert BlobImpl even without a known image mime.
nsCOMPtr<BlobImpl> blob = do_QueryInterface(object);
if (!blob) {
return NS_OK;
}
RefPtr<BlobReader> br =
new BlobReader(blob, this, aSafeToInsertData, aPointToInsert,
aDeleteSelectedContent, aEditingHost);
nsCOMPtr<nsPIDOMWindowInner> inner = GetInnerWindow();
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(inner);
if (!global) {
NS_WARNING("Could not get global");
return NS_ERROR_FAILURE;
}
RefPtr<Blob> domBlob = Blob::Create(global, blob);
if (!domBlob) {
NS_WARNING("Blob::Create() failed");
return NS_ERROR_FAILURE;
}
nsresult rv = SlurpBlob(domBlob, global, br);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::::SlurpBlob() failed");
return rv;
}
static bool GetString(nsISupports* aData, nsAString& aText) {
if (nsCOMPtr<nsISupportsString> str = do_QueryInterface(aData)) {
DebugOnly<nsresult> rvIgnored = str->GetData(aText);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsISupportsString::GetData() failed, but ignored");
return !aText.IsEmpty();
}
return false;
}
static bool GetCString(nsISupports* aData, nsACString& aText) {
if (nsCOMPtr<nsISupportsCString> str = do_QueryInterface(aData)) {
DebugOnly<nsresult> rvIgnored = str->GetData(aText);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsISupportsString::GetData() failed, but ignored");
return !aText.IsEmpty();
}
return false;
}
nsresult HTMLEditor::InsertFromTransferableAtSelection(
nsITransferable* aTransferable, const nsAString& aContextStr,
const nsAString& aInfoStr, HavePrivateHTMLFlavor aHavePrivateHTMLFlavor,
const Element& aEditingHost) {
nsAutoCString bestFlavor;
nsCOMPtr<nsISupports> genericDataObj;
// See `HTMLTransferablePreparer::AddDataFlavorsInBestOrder`.
nsresult rv = aTransferable->GetAnyTransferData(
bestFlavor, getter_AddRefs(genericDataObj));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"nsITransferable::GetAnyTransferData() failed, but ignored");
if (NS_SUCCEEDED(rv)) {
AutoTransactionsConserveSelection dontChangeMySelection(*this);
nsAutoString flavor;
CopyASCIItoUTF16(bestFlavor, flavor);
const SafeToInsertData safeToInsertData = IsSafeToInsertData(nullptr);
if (bestFlavor.EqualsLiteral(kFileMime) ||
bestFlavor.EqualsLiteral(kJPEGImageMime) ||
bestFlavor.EqualsLiteral(kJPGImageMime) ||
bestFlavor.EqualsLiteral(kPNGImageMime) ||
bestFlavor.EqualsLiteral(kGIFImageMime)) {
nsresult rv = InsertObject(bestFlavor, genericDataObj, safeToInsertData,
EditorDOMPoint(), DeleteSelectedContent::Yes,
aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::InsertObject() failed");
return rv;
}
} else if (bestFlavor.EqualsLiteral(kNativeHTMLMime)) {
// note cf_html uses utf8
nsAutoCString cfhtml;
if (GetCString(genericDataObj, cfhtml)) {
// cfselection left emtpy for now.
nsString cfcontext, cffragment, cfselection;
nsresult rv = ParseCFHTML(cfhtml, getter_Copies(cffragment),
getter_Copies(cfcontext));
if (NS_SUCCEEDED(rv) && !cffragment.IsEmpty()) {
// If we have our private HTML flavor, we will only use the fragment
// from the CF_HTML. The rest comes from the clipboard.
if (aHavePrivateHTMLFlavor == HavePrivateHTMLFlavor::Yes) {
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertHTMLWithContextAsSubAction(
cffragment, aContextStr, aInfoStr, flavor, safeToInsertData,
EditorDOMPoint(), DeleteSelectedContent::Yes,
InlineStylesAtInsertionPoint::Clear, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"DeleteSelectedContent::Yes, "
"InlineStylesAtInsertionPoint::Clear) failed");
return rv;
}
} else {
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertHTMLWithContextAsSubAction(
cffragment, cfcontext, cfselection, flavor, safeToInsertData,
EditorDOMPoint(), DeleteSelectedContent::Yes,
InlineStylesAtInsertionPoint::Clear, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"DeleteSelectedContent::Yes, "
"InlineStylesAtInsertionPoint::Clear) failed");
return rv;
}
}
} else {
// In some platforms (like Linux), the clipboard might return data
// requested for unknown flavors (for example:
// application/x-moz-nativehtml). In this case, treat the data
// to be pasted as mere HTML to get the best chance of pasting it
// correctly.
bestFlavor.AssignLiteral(kHTMLMime);
// Fall through the next case
}
}
}
if (bestFlavor.EqualsLiteral(kHTMLMime) ||
bestFlavor.EqualsLiteral(kTextMime) ||
bestFlavor.EqualsLiteral(kMozTextInternal)) {
nsAutoString stuffToPaste;
if (!GetString(genericDataObj, stuffToPaste)) {
nsAutoCString text;
if (GetCString(genericDataObj, text)) {
CopyUTF8toUTF16(text, stuffToPaste);
}
}
if (!stuffToPaste.IsEmpty()) {
if (bestFlavor.EqualsLiteral(kHTMLMime)) {
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
nsresult rv = InsertHTMLWithContextAsSubAction(
stuffToPaste, aContextStr, aInfoStr, flavor, safeToInsertData,
EditorDOMPoint(), DeleteSelectedContent::Yes,
InlineStylesAtInsertionPoint::Clear, aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"DeleteSelectedContent::Yes, "
"InlineStylesAtInsertionPoint::Clear) failed");
return rv;
}
} else {
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
nsresult rv =
InsertTextAsSubAction(stuffToPaste, InsertTextFor::NormalText);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::InsertTextAsSubAction() failed");
return rv;
}
}
}
}
}
// Try to scroll the selection into view if the paste succeeded
DebugOnly<nsresult> rvIgnored = ScrollSelectionFocusIntoView();
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"EditorBase::ScrollSelectionFocusIntoView() failed, but ignored");
return NS_OK;
}
static void GetStringFromDataTransfer(const DataTransfer* aDataTransfer,
const nsAString& aType, uint32_t aIndex,
nsString& aOutputString) {
nsCOMPtr<nsIVariant> variant;
DebugOnly<nsresult> rvIgnored = aDataTransfer->GetDataAtNoSecurityCheck(
aType, aIndex, getter_AddRefs(variant));
if (!variant) {
MOZ_ASSERT(aOutputString.IsEmpty());
return;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"DataTransfer::GetDataAtNoSecurityCheck() failed, but ignored");
variant->GetAsAString(aOutputString);
nsContentUtils::PlatformToDOMLineBreaks(aOutputString);
}
nsresult HTMLEditor::InsertFromDataTransfer(
const DataTransfer* aDataTransfer, uint32_t aIndex,
nsIPrincipal* aSourcePrincipal, const EditorDOMPoint& aDroppedAt,
DeleteSelectedContent aDeleteSelectedContent, const Element& aEditingHost) {
MOZ_ASSERT(GetEditAction() == EditAction::eDrop ||
GetEditAction() == EditAction::ePaste);
MOZ_ASSERT(mPlaceholderBatch,
"HTMLEditor::InsertFromDataTransfer() should be called by "
"HandleDropEvent() or paste action and there should've already "
"been placeholder transaction");
MOZ_ASSERT_IF(GetEditAction() == EditAction::eDrop, aDroppedAt.IsSet());
ErrorResult error;
RefPtr<DOMStringList> types = aDataTransfer->MozTypesAt(aIndex, error);
if (error.Failed()) {
NS_WARNING("DataTransfer::MozTypesAt() failed");
return error.StealNSResult();
}
const bool hasPrivateHTMLFlavor =
types->Contains(NS_LITERAL_STRING_FROM_CSTRING(kHTMLContext));
const bool isPlaintextEditor = IsPlaintextMailComposer() ||
aEditingHost.IsContentEditablePlainTextOnly();
const SafeToInsertData safeToInsertData =
IsSafeToInsertData(aSourcePrincipal);
uint32_t length = types->Length();
for (uint32_t i = 0; i < length; i++) {
nsAutoString type;
types->Item(i, type);
if (!isPlaintextEditor) {
if (type.EqualsLiteral(kFileMime) || type.EqualsLiteral(kJPEGImageMime) ||
type.EqualsLiteral(kJPGImageMime) ||
type.EqualsLiteral(kPNGImageMime) ||
type.EqualsLiteral(kGIFImageMime)) {
nsCOMPtr<nsIVariant> variant;
DebugOnly<nsresult> rvIgnored = aDataTransfer->GetDataAtNoSecurityCheck(
type, aIndex, getter_AddRefs(variant));
if (variant) {
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"DataTransfer::GetDataAtNoSecurityCheck() failed, but ignored");
nsCOMPtr<nsISupports> object;
rvIgnored = variant->GetAsISupports(getter_AddRefs(object));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIVariant::GetAsISupports() failed, but ignored");
nsresult rv = InsertObject(NS_ConvertUTF16toUTF8(type), object,
safeToInsertData, aDroppedAt,
aDeleteSelectedContent, aEditingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertObject() failed");
return rv;
}
} else if (type.EqualsLiteral(kNativeHTMLMime)) {
// Windows only clipboard parsing.
nsAutoString text;
GetStringFromDataTransfer(aDataTransfer, type, aIndex, text);
NS_ConvertUTF16toUTF8 cfhtml(text);
nsString cfcontext, cffragment,
cfselection; // cfselection left emtpy for now
nsresult rv = ParseCFHTML(cfhtml, getter_Copies(cffragment),
getter_Copies(cfcontext));
if (NS_SUCCEEDED(rv) && !cffragment.IsEmpty()) {
if (hasPrivateHTMLFlavor) {
// If we have our private HTML flavor, we will only use the fragment
// from the CF_HTML. The rest comes from the clipboard.
nsAutoString contextString, infoString;
GetStringFromDataTransfer(
aDataTransfer, NS_LITERAL_STRING_FROM_CSTRING(kHTMLContext),
aIndex, contextString);
GetStringFromDataTransfer(aDataTransfer,
NS_LITERAL_STRING_FROM_CSTRING(kHTMLInfo),
aIndex, infoString);
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
nsresult rv = InsertHTMLWithContextAsSubAction(
cffragment, contextString, infoString, type, safeToInsertData,
aDroppedAt, aDeleteSelectedContent,
InlineStylesAtInsertionPoint::Clear, aEditingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"InlineStylesAtInsertionPoint::Clear) failed");
return rv;
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
nsresult rv = InsertHTMLWithContextAsSubAction(
cffragment, cfcontext, cfselection, type, safeToInsertData,
aDroppedAt, aDeleteSelectedContent,
InlineStylesAtInsertionPoint::Clear, aEditingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"InlineStylesAtInsertionPoint::Clear) failed");
return rv;
}
} else if (type.EqualsLiteral(kHTMLMime)) {
nsAutoString text, contextString, infoString;
GetStringFromDataTransfer(aDataTransfer, type, aIndex, text);
GetStringFromDataTransfer(aDataTransfer,
NS_LITERAL_STRING_FROM_CSTRING(kHTMLContext),
aIndex, contextString);
GetStringFromDataTransfer(aDataTransfer,
NS_LITERAL_STRING_FROM_CSTRING(kHTMLInfo),
aIndex, infoString);
if (type.EqualsLiteral(kHTMLMime)) {
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
nsresult rv = InsertHTMLWithContextAsSubAction(
text, contextString, infoString, type, safeToInsertData,
aDroppedAt, aDeleteSelectedContent,
InlineStylesAtInsertionPoint::Clear, aEditingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLWithContextAsSubAction("
"InlineStylesAtInsertionPoint::Clear) failed");
return rv;
}
}
}
if (type.EqualsLiteral(kTextMime) || type.EqualsLiteral(kMozTextInternal)) {
nsAutoString text;
GetStringFromDataTransfer(aDataTransfer, type, aIndex, text);
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
nsresult rv = InsertTextAt(text, aDroppedAt, aDeleteSelectedContent);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAt() failed");
return rv;
}
}
return NS_OK;
}
// static
HTMLEditor::HavePrivateHTMLFlavor
HTMLEditor::DataTransferOrClipboardHasPrivateHTMLFlavor(
DataTransfer* aDataTransfer, nsIClipboard* aClipboard) {
nsresult rv;
if (aDataTransfer) {
return aDataTransfer->HasPrivateHTMLFlavor() ? HavePrivateHTMLFlavor::Yes
: HavePrivateHTMLFlavor::No;
}
// otherwise, fall back to clipboard
if (NS_WARN_IF(!aClipboard)) {
return HavePrivateHTMLFlavor::No;
}
// check the clipboard for our special kHTMLContext flavor. If that is there,
// we know we have our own internal html format on clipboard.
bool hasPrivateHTMLFlavor = false;
AutoTArray<nsCString, 1> flavArray = {nsDependentCString(kHTMLContext)};
rv = aClipboard->HasDataMatchingFlavors(
flavArray, nsIClipboard::kGlobalClipboard, &hasPrivateHTMLFlavor);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"nsIClipboard::HasDataMatchingFlavors(nsIClipboard::"
"kGlobalClipboard) failed");
return NS_SUCCEEDED(rv) && hasPrivateHTMLFlavor ? HavePrivateHTMLFlavor::Yes
: HavePrivateHTMLFlavor::No;
}
nsresult HTMLEditor::HandlePaste(AutoEditActionDataSetter& aEditActionData,
nsIClipboard::ClipboardType aClipboardType,
DataTransfer* aDataTransfer) {
aEditActionData.InitializeDataTransferWithClipboard(
SettingDataTransfer::eWithFormat, aDataTransfer, aClipboardType);
nsresult rv = aEditActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent() failed");
return rv;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
rv = PasteInternal(aClipboardType, aDataTransfer, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::PasteInternal() failed");
return rv;
}
nsresult HTMLEditor::PasteInternal(nsIClipboard::ClipboardType aClipboardType,
DataTransfer* aDataTransfer,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (MOZ_UNLIKELY(!IsModifiable())) {
return NS_OK;
}
// Get Clipboard Service
nsresult rv = NS_OK;
nsCOMPtr<nsIClipboard> clipboard =
do_GetService("@mozilla.org/widget/clipboard;1", &rv);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to get nsIClipboard service");
return rv;
}
// Get the nsITransferable interface for getting the data from the clipboard
nsCOMPtr<nsITransferable> transferable;
rv = PrepareHTMLTransferable(getter_AddRefs(transferable), &aEditingHost);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::PrepareHTMLTransferable() failed");
return rv;
}
if (!transferable) {
NS_WARNING("HTMLEditor::PrepareHTMLTransferable() returned nullptr");
return NS_ERROR_FAILURE;
}
// Get the Data from the clipboard
rv = GetDataFromDataTransferOrClipboard(aDataTransfer, transferable,
aClipboardType);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::GetDataFromDataTransferOrClipboard() failed");
return rv;
}
// also get additional html copy hints, if present
nsAutoString contextStr, infoStr;
// If we have our internal html flavor on the clipboard, there is special
// context to use instead of cfhtml context.
const HavePrivateHTMLFlavor clipboardHasPrivateHTMLFlavor =
DataTransferOrClipboardHasPrivateHTMLFlavor(aDataTransfer, clipboard);
if (clipboardHasPrivateHTMLFlavor == HavePrivateHTMLFlavor::Yes) {
nsCOMPtr<nsITransferable> contextTransferable =
do_CreateInstance("@mozilla.org/widget/transferable;1");
if (!contextTransferable) {
NS_WARNING(
"do_CreateInstance() failed to create nsITransferable instance");
return NS_ERROR_FAILURE;
}
DebugOnly<nsresult> rvIgnored = contextTransferable->Init(nullptr);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::Init() failed, but ignored");
contextTransferable->SetIsPrivateData(transferable->GetIsPrivateData());
rvIgnored = contextTransferable->AddDataFlavor(kHTMLContext);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kHTMLContext) failed, but ignored");
GetDataFromDataTransferOrClipboard(aDataTransfer, contextTransferable,
aClipboardType);
nsCOMPtr<nsISupports> contextDataObj;
rv = contextTransferable->GetTransferData(kHTMLContext,
getter_AddRefs(contextDataObj));
if (NS_SUCCEEDED(rv) && contextDataObj) {
if (nsCOMPtr<nsISupportsString> str = do_QueryInterface(contextDataObj)) {
DebugOnly<nsresult> rvIgnored = str->GetData(contextStr);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISupportsString::GetData() failed, but ignored");
}
}
nsCOMPtr<nsITransferable> infoTransferable =
do_CreateInstance("@mozilla.org/widget/transferable;1");
if (!infoTransferable) {
NS_WARNING(
"do_CreateInstance() failed to create nsITransferable instance");
return NS_ERROR_FAILURE;
}
rvIgnored = infoTransferable->Init(nullptr);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"nsITransferable::Init() failed, but ignored");
contextTransferable->SetIsPrivateData(transferable->GetIsPrivateData());
rvIgnored = infoTransferable->AddDataFlavor(kHTMLInfo);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kHTMLInfo) failed, but ignored");
GetDataFromDataTransferOrClipboard(aDataTransfer, infoTransferable,
aClipboardType);
nsCOMPtr<nsISupports> infoDataObj;
rv = infoTransferable->GetTransferData(kHTMLInfo,
getter_AddRefs(infoDataObj));
if (NS_SUCCEEDED(rv) && infoDataObj) {
if (nsCOMPtr<nsISupportsString> str = do_QueryInterface(infoDataObj)) {
DebugOnly<nsresult> rvIgnored = str->GetData(infoStr);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsISupportsString::GetData() failed, but ignored");
}
}
}
rv = InsertFromTransferableAtSelection(transferable, contextStr, infoStr,
clipboardHasPrivateHTMLFlavor,
aEditingHost);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::InsertFromTransferableAtSelection() failed");
return rv;
}
nsresult HTMLEditor::HandlePasteTransferable(
AutoEditActionDataSetter& aEditActionData, nsITransferable& aTransferable) {
// InitializeDataTransfer may fetch input stream in aTransferable, so it
// may be invalid after calling this.
aEditActionData.InitializeDataTransfer(&aTransferable);
nsresult rv = aEditActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return rv;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
RefPtr<DataTransfer> dataTransfer = GetInputEventDataTransfer();
if (dataTransfer->HasFile() && dataTransfer->MozItemCount() > 0) {
// Now aTransferable has moved to DataTransfer. Use DataTransfer.
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertFromDataTransfer(dataTransfer, 0, nullptr, EditorDOMPoint(),
DeleteSelectedContent::Yes, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertFromDataTransfer("
"DeleteSelectedContent::Yes) failed");
return rv;
}
nsAutoString contextStr, infoStr;
rv = InsertFromTransferableAtSelection(&aTransferable, contextStr, infoStr,
HavePrivateHTMLFlavor::No,
*editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertFromTransferableAtSelection("
"HavePrivateHTMLFlavor::No) failed");
return rv;
}
nsresult HTMLEditor::PasteNoFormattingAsAction(
nsIClipboard::ClipboardType aClipboardType,
DispatchPasteEvent aDispatchPasteEvent,
DataTransfer* aDataTransfer /* = nullptr */,
nsIPrincipal* aPrincipal /* = nullptr */) {
if (IsReadonly()) {
return NS_OK;
}
// Create the same DataTransfer object here so we can share it between
// the clipboard event and its data with the call to
// InsertFromTransferableWithSelection below. This prevents
// race conditions with Content Analysis on like we see in bug 1918027.
RefPtr<DataTransfer> dataTransfer =
aDataTransfer ? RefPtr<DataTransfer>(aDataTransfer)
: RefPtr<DataTransfer>(CreateDataTransferForPaste(
ePasteNoFormatting, aClipboardType));
auto clearDataTransfer = MakeScopeExit([&] {
// If the caller passed in aDataTransfer, they are responsible for clearing
// this.
if (!aDataTransfer && dataTransfer) {
dataTransfer->ClearForPaste();
}
});
AutoEditActionDataSetter editActionData(*this, EditAction::ePaste,
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
editActionData.InitializeDataTransferWithClipboard(
SettingDataTransfer::eWithoutFormat, dataTransfer, aClipboardType);
if (aDispatchPasteEvent == DispatchPasteEvent::Yes) {
RefPtr<nsFocusManager> focusManager = nsFocusManager::GetFocusManager();
if (NS_WARN_IF(!focusManager)) {
return NS_ERROR_UNEXPECTED;
}
const RefPtr<Element> focusedElement = focusManager->GetFocusedElement();
Result<ClipboardEventResult, nsresult> ret = Err(NS_ERROR_FAILURE);
{
// This method is not set up to pass back the new aDataTransfer
// if it changes. If we need this in the future, we can change
// aDataTransfer to be a RefPtr<DataTransfer>*.
MOZ_ASSERT(!aDataTransfer);
AutoTrackDataTransferForPaste trackDataTransfer(*this, dataTransfer);
ret = DispatchClipboardEventAndUpdateClipboard(
ePasteNoFormatting, Some(aClipboardType), dataTransfer);
if (MOZ_UNLIKELY(ret.isErr())) {
NS_WARNING(
"EditorBase::DispatchClipboardEventAndUpdateClipboard("
"ePasteNoFormatting) failed");
return EditorBase::ToGenericNSResult(ret.unwrapErr());
}
}
switch (ret.inspect()) {
case ClipboardEventResult::DoDefault:
break;
case ClipboardEventResult::DefaultPreventedOfPaste:
case ClipboardEventResult::IgnoredOrError:
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
case ClipboardEventResult::CopyOrCutHandled:
MOZ_ASSERT_UNREACHABLE("Invalid result for ePaste");
}
// If focus is changed by a "paste" event listener, we should keep handling
// the "pasting" in new focused editor because Chrome works as so.
const RefPtr<Element> newFocusedElement = focusManager->GetFocusedElement();
if (MOZ_UNLIKELY(focusedElement != newFocusedElement)) {
// For the privacy reason, let's top handling it if new focused element is
// in different document.
if (focusManager->GetFocusedWindow() != GetWindow()) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
RefPtr<EditorBase> editorBase =
nsContentUtils::GetActiveEditor(GetPresContext());
if (!editorBase || (editorBase->IsHTMLEditor() &&
!editorBase->AsHTMLEditor()->IsActiveInDOMWindow())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
}
if (editorBase != this) {
if (editorBase->IsHTMLEditor()) {
nsresult rv = MOZ_KnownLive(editorBase->AsHTMLEditor())
->PasteNoFormattingAsAction(
aClipboardType, DispatchPasteEvent::No,
dataTransfer, aPrincipal);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::PasteNoFormattingAsAction("
"DispatchPasteEvent::No) failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult rv = editorBase->PasteAsAction(
aClipboardType, DispatchPasteEvent::No, dataTransfer, aPrincipal);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::PasteAsAction(DispatchPasteEvent::No) failed");
return EditorBase::ToGenericNSResult(rv);
}
}
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
// Dispatch "beforeinput" event after "paste" event. And perhaps, before
// committing composition because if pasting is canceled, we don't need to
// commit the active composition.
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
DebugOnly<nsresult> rvIgnored = CommitComposition();
if (NS_WARN_IF(Destroyed())) {
return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::CommitComposition() failed, but ignored");
if (MOZ_UNLIKELY(!IsModifiable())) {
return NS_OK;
}
Result<nsCOMPtr<nsITransferable>, nsresult> maybeTransferable =
EditorUtils::CreateTransferableForPlainText(*GetDocument());
if (maybeTransferable.isErr()) {
NS_WARNING("EditorUtils::CreateTransferableForPlainText() failed");
return EditorBase::ToGenericNSResult(maybeTransferable.unwrapErr());
}
nsCOMPtr<nsITransferable> transferable(maybeTransferable.unwrap());
if (!transferable) {
NS_WARNING(
"EditorUtils::CreateTransferableForPlainText() returned nullptr, but "
"ignored");
return NS_OK;
}
rv = GetDataFromDataTransferOrClipboard(dataTransfer, transferable,
aClipboardType);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::GetDataFromDataTransferOrClipboard() failed");
return rv;
}
rv = InsertFromTransferableAtSelection(
transferable, u""_ns, u""_ns, HavePrivateHTMLFlavor::No, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertFromTransferableAtSelection("
"HavePrivateHTMLFlavor::No) failed");
return EditorBase::ToGenericNSResult(rv);
}
// The following arrays contain the MIME types that we can paste. The arrays
// are used by CanPaste() and CanPasteTransferable() below.
static const char* textEditorFlavors[] = {kTextMime};
static const char* textHtmlEditorFlavors[] = {kTextMime, kHTMLMime,
kJPEGImageMime, kJPGImageMime,
kPNGImageMime, kGIFImageMime};
bool HTMLEditor::CanPaste(nsIClipboard::ClipboardType aClipboardType) const {
if (AreClipboardCommandsUnconditionallyEnabled()) {
return true;
}
// can't paste if readonly
if (!IsModifiable()) {
return false;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost) {
return false;
}
nsresult rv;
nsCOMPtr<nsIClipboard> clipboard(
do_GetService("@mozilla.org/widget/clipboard;1", &rv));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to get nsIClipboard service");
return false;
}
// Use the flavors depending on the current editor mask
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
AutoTArray<nsCString, std::size(textEditorFlavors)> flavors;
flavors.AppendElements<const char*>(Span<const char*>(textEditorFlavors));
bool haveFlavors;
nsresult rv = clipboard->HasDataMatchingFlavors(flavors, aClipboardType,
&haveFlavors);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"nsIClipboard::HasDataMatchingFlavors() failed");
return NS_SUCCEEDED(rv) && haveFlavors;
}
AutoTArray<nsCString, std::size(textHtmlEditorFlavors)> flavors;
flavors.AppendElements<const char*>(Span<const char*>(textHtmlEditorFlavors));
bool haveFlavors;
rv = clipboard->HasDataMatchingFlavors(flavors, aClipboardType, &haveFlavors);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"nsIClipboard::HasDataMatchingFlavors() failed");
return NS_SUCCEEDED(rv) && haveFlavors;
}
bool HTMLEditor::CanPasteTransferable(nsITransferable* aTransferable) {
// can't paste if readonly
if (!IsModifiable()) {
return false;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost) {
return false;
}
// If |aTransferable| is null, assume that a paste will succeed.
if (!aTransferable) {
return true;
}
// Peek in |aTransferable| to see if it contains a supported MIME type.
// Use the flavors depending on the current editor mask
const char** flavors;
size_t length;
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
flavors = textEditorFlavors;
length = std::size(textEditorFlavors);
} else {
flavors = textHtmlEditorFlavors;
length = std::size(textHtmlEditorFlavors);
}
for (size_t i = 0; i < length; i++, flavors++) {
nsCOMPtr<nsISupports> data;
nsresult rv =
aTransferable->GetTransferData(*flavors, getter_AddRefs(data));
if (NS_SUCCEEDED(rv) && data) {
return true;
}
}
return false;
}
nsresult HTMLEditor::HandlePasteAsQuotation(
AutoEditActionDataSetter& aEditActionData,
nsIClipboard::ClipboardType aClipboardType, DataTransfer* aDataTransfer) {
MOZ_ASSERT(aClipboardType == nsIClipboard::kGlobalClipboard ||
aClipboardType == nsIClipboard::kSelectionClipboard);
aEditActionData.InitializeDataTransferWithClipboard(
SettingDataTransfer::eWithFormat, aDataTransfer, aClipboardType);
if (NS_WARN_IF(!aEditActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult rv = aEditActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return rv;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
nsresult rv =
PasteAsPlaintextQuotation(aClipboardType, aDataTransfer, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::PasteAsPlaintextQuotation() failed");
return rv;
}
// If it's not in plain text edit mode, paste text into new
// <blockquote type="cite"> element after removing selection.
{
// XXX Why don't we test these first?
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;
}
}
UndefineCaretBidiLevel();
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertQuotation, 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");
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(*editingHost);
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");
}
}
// Remove Selection and create `<blockquote type="cite">` now.
// XXX Why don't we insert the `<blockquote>` into the DOM tree after
// pasting the content in clipboard into it?
Result<RefPtr<Element>, nsresult> blockquoteElementOrError =
DeleteSelectionAndCreateElement(
*nsGkAtoms::blockquote,
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
[](HTMLEditor&, Element& aBlockquoteElement, const EditorDOMPoint&)
MOZ_CAN_RUN_SCRIPT_BOUNDARY {
DebugOnly<nsresult> rvIgnored = aBlockquoteElement.SetAttr(
kNameSpaceID_None, nsGkAtoms::type, u"cite"_ns,
aBlockquoteElement.IsInComposedDoc());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
nsPrintfCString(
"Element::SetAttr(nsGkAtoms::type, \"cite\", %s) "
"failed, but ignored",
aBlockquoteElement.IsInComposedDoc() ? "true" : "false")
.get());
return NS_OK;
});
if (MOZ_UNLIKELY(blockquoteElementOrError.isErr()) ||
NS_WARN_IF(Destroyed())) {
NS_WARNING(
"HTMLEditor::DeleteSelectionAndCreateElement(nsGkAtoms::blockquote) "
"failed");
return Destroyed() ? NS_ERROR_EDITOR_DESTROYED
: blockquoteElementOrError.unwrapErr();
}
MOZ_ASSERT(blockquoteElementOrError.inspect());
// Collapse Selection in the new `<blockquote>` element.
rv = CollapseSelectionToStartOf(
MOZ_KnownLive(*blockquoteElementOrError.inspect()));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::CollapseSelectionToStartOf() failed");
return rv;
}
rv = PasteInternal(aClipboardType, aDataTransfer, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::PasteInternal() failed");
return rv;
}
nsresult HTMLEditor::PasteAsPlaintextQuotation(
nsIClipboard::ClipboardType aSelectionType, DataTransfer* aDataTransfer,
const Element& aEditingHost) {
nsresult rv;
// Create generic Transferable for getting the data
nsCOMPtr<nsITransferable> transferable =
do_CreateInstance("@mozilla.org/widget/transferable;1", &rv);
if (NS_FAILED(rv)) {
NS_WARNING("do_CreateInstance() failed to create nsITransferable instance");
return rv;
}
if (!transferable) {
NS_WARNING("do_CreateInstance() returned nullptr");
return NS_ERROR_FAILURE;
}
RefPtr<Document> destdoc = GetDocument();
auto* windowContext = GetDocument()->GetWindowContext();
if (!windowContext) {
NS_WARNING("Editor didn't have document window context");
return NS_ERROR_FAILURE;
}
nsILoadContext* loadContext = destdoc ? destdoc->GetLoadContext() : nullptr;
DebugOnly<nsresult> rvIgnored = transferable->Init(loadContext);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::Init() failed, but ignored");
// We only handle plaintext pastes here
rvIgnored = transferable->AddDataFlavor(kTextMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kTextMime) failed, but ignored");
// Get the Data from the clipboard
GetDataFromDataTransferOrClipboard(aDataTransfer, transferable,
aSelectionType);
// Now we ask the transferable for the data
// it still owns the data, we just have a pointer to it.
// If it can't support a "text" output of the data the call will fail
nsCOMPtr<nsISupports> genericDataObj;
nsAutoCString flavor;
rv = transferable->GetAnyTransferData(flavor, getter_AddRefs(genericDataObj));
if (NS_FAILED(rv)) {
NS_WARNING("nsITransferable::GetAnyTransferData() failed");
return rv;
}
if (!flavor.EqualsLiteral(kTextMime)) {
return NS_OK;
}
nsAutoString stuffToPaste;
if (!GetString(genericDataObj, stuffToPaste)) {
return NS_OK;
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertAsPlaintextQuotation(stuffToPaste, AddCites::Yes, aEditingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertAsPlaintextQuotation() failed");
return rv;
}
nsresult HTMLEditor::InsertWithQuotationsAsSubAction(
const nsAString& aQuotedText) {
MOZ_ASSERT(IsEditActionDataAvailable());
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
{
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;
}
}
UndefineCaretBidiLevel();
// Let the citer quote it for us:
nsString quotedStuff;
InternetCiter::GetCiteString(aQuotedText, quotedStuff);
// It's best to put a blank line after the quoted text so that mails
// written without thinking won't be so ugly.
if (!aQuotedText.IsEmpty() &&
(aQuotedText.Last() != HTMLEditUtils::kNewLine)) {
quotedStuff.Append(HTMLEditUtils::kNewLine);
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertText, 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");
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(*editingHost);
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");
}
}
rv = InsertTextAsSubAction(quotedStuff, InsertTextFor::NormalText);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed");
return rv;
}
NS_IMETHODIMP HTMLEditor::InsertTextWithQuotations(
const nsAString& aStringToInsert) {
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertText);
MOZ_ASSERT(!aStringToInsert.IsVoid());
editActionData.SetData(aStringToInsert);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
if (aStringToInsert.IsEmpty()) {
return NS_OK;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
// The whole operation should be undoable in one transaction:
// XXX Why isn't enough to use only AutoPlaceholderBatch here?
AutoTransactionBatch bundleAllTransactions(*this, __FUNCTION__);
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertTextWithQuotationsInternal(aStringToInsert, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertTextWithQuotationsInternal() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::InsertTextWithQuotationsInternal(
const nsAString& aStringToInsert, const Element& aEditingHost) {
MOZ_ASSERT(!aStringToInsert.IsEmpty());
// We're going to loop over the string, collecting up a "hunk"
// that's all the same type (quoted or not),
// Whenever the quotedness changes (or we reach the string's end)
// we will insert the hunk all at once, quoted or non.
static const char16_t cite('>');
bool curHunkIsQuoted = (aStringToInsert.First() == cite);
nsAString::const_iterator hunkStart, strEnd;
aStringToInsert.BeginReading(hunkStart);
aStringToInsert.EndReading(strEnd);
// In the loop below, we only look for DOM newlines (\n),
// because we don't have a FindChars method that can look
// for both \r and \n. \r is illegal in the dom anyway,
// but in debug builds, let's take the time to verify that
// there aren't any there:
#ifdef DEBUG
nsAString::const_iterator dbgStart(hunkStart);
if (FindCharInReadable(HTMLEditUtils::kCarriageReturn, dbgStart, strEnd)) {
NS_ASSERTION(
false,
"Return characters in DOM! InsertTextWithQuotations may be wrong");
}
#endif /* DEBUG */
// Loop over lines:
nsresult rv = NS_OK;
nsAString::const_iterator lineStart(hunkStart);
// We will break from inside when we run out of newlines.
for (;;) {
// Search for the end of this line (dom newlines, see above):
bool found = FindCharInReadable(HTMLEditUtils::kNewLine, lineStart, strEnd);
bool quoted = false;
if (found) {
// if there's another newline, lineStart now points there.
// Loop over any consecutive newline chars:
nsAString::const_iterator firstNewline(lineStart);
while (*lineStart == HTMLEditUtils::kNewLine) {
++lineStart;
}
quoted = (*lineStart == cite);
if (quoted == curHunkIsQuoted) {
continue;
}
// else we're changing state, so we need to insert
// from curHunk to lineStart then loop around.
// But if the current hunk is quoted, then we want to make sure
// that any extra newlines on the end do not get included in
// the quoted section: blank lines flaking a quoted section
// should be considered unquoted, so that if the user clicks
// there and starts typing, the new text will be outside of
// the quoted block.
if (curHunkIsQuoted) {
lineStart = firstNewline;
// 'firstNewline' points to the first '\n'. We want to
// ensure that this first newline goes into the hunk
// since quoted hunks can be displayed as blocks
// (and the newline should become invisible in this case).
// So the next line needs to start at the next character.
lineStart++;
}
}
// If no newline found, lineStart is now strEnd and we can finish up,
// inserting from curHunk to lineStart then returning.
const nsAString& curHunk = Substring(hunkStart, lineStart);
if (curHunkIsQuoted) {
rv = InsertAsPlaintextQuotation(curHunk, AddCites::No, aEditingHost);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertAsPlaintextQuotation() failed, "
"but might be ignored");
} else {
rv = InsertTextAsSubAction(curHunk, InsertTextFor::NormalText);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::InsertTextAsSubAction() failed, but might be ignored");
}
if (!found) {
break;
}
curHunkIsQuoted = quoted;
hunkStart = lineStart;
}
// XXX This returns the last result of InsertAsPlaintextQuotation() or
// InsertTextAsSubAction() in the loop. This must be a bug.
return rv;
}
nsresult HTMLEditor::InsertAsQuotation(const nsAString& aQuotedText,
nsINode** aNodeInserted) {
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertText);
MOZ_ASSERT(!aQuotedText.IsVoid());
editActionData.SetData(aQuotedText);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(
rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertAsPlaintextQuotation(aQuotedText, AddCites::Yes, *editingHost,
aNodeInserted);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertAsPlaintextQuotation() failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoEditActionDataSetter editActionData(*this,
EditAction::eInsertBlockquoteElement);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
nsAutoString citation;
rv = InsertAsCitedQuotationInternal(aQuotedText, citation, false,
*editingHost, aNodeInserted);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertAsCitedQuotationInternal() failed");
return EditorBase::ToGenericNSResult(rv);
}
// Insert plaintext as a quotation, with cite marks (e.g. "> ").
// This differs from its corresponding method in TextEditor
// in that here, quoted material is enclosed in a <pre> tag
// in order to preserve the original line wrapping.
nsresult HTMLEditor::InsertAsPlaintextQuotation(const nsAString& aQuotedText,
AddCites aAddCites,
const Element& aEditingHost,
nsINode** aNodeInserted) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (aNodeInserted) {
*aNodeInserted = nullptr;
}
{
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;
}
}
UndefineCaretBidiLevel();
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertQuotation, 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");
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");
}
}
RefPtr<Element> containerSpanElement;
if (!aEditingHost.IsContentEditablePlainTextOnly()) {
// Wrap the inserted quote in a <span> so we can distinguish it. If we're
// inserting into the <body>, we use a <span> which is displayed as a block
// and sized to the screen using 98 viewport width units.
// We could use 100vw, but 98vw avoids a horizontal scroll bar where
// possible. All this is done to wrap overlong lines to the screen and not
// to the container element, the width-restricted body.
// XXX I think that we don't need to do this in the web. This should be
// done only for Thunderbird.
Result<RefPtr<Element>, nsresult> spanElementOrError =
DeleteSelectionAndCreateElement(
*nsGkAtoms::span, [](HTMLEditor&, Element& aSpanElement,
const EditorDOMPoint& aPointToInsert) {
// Add an attribute on the pre node so we'll know it's a
// quotation.
DebugOnly<nsresult> rvIgnored = aSpanElement.SetAttr(
kNameSpaceID_None, nsGkAtoms::mozquote, u"true"_ns,
aSpanElement.IsInComposedDoc());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
nsPrintfCString(
"Element::SetAttr(nsGkAtoms::mozquote, \"true\", %s) "
"failed",
aSpanElement.IsInComposedDoc() ? "true" : "false")
.get());
// Allow wrapping on spans so long lines get wrapped to the
// screen.
if (aPointToInsert.IsContainerHTMLElement(nsGkAtoms::body)) {
DebugOnly<nsresult> rvIgnored = aSpanElement.SetAttr(
kNameSpaceID_None, nsGkAtoms::style,
nsLiteralString(u"white-space: pre-wrap; display: block; "
u"width: 98vw;"),
false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"Element::SetAttr(nsGkAtoms::style, \"pre-wrap, block\", "
"false) failed, but ignored");
} else {
DebugOnly<nsresult> rvIgnored =
aSpanElement.SetAttr(kNameSpaceID_None, nsGkAtoms::style,
u"white-space: pre-wrap;"_ns, false);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"Element::SetAttr(nsGkAtoms::style, "
"\"pre-wrap\", false) failed, but ignored");
}
return NS_OK;
});
if (MOZ_UNLIKELY(spanElementOrError.isErr())) {
NS_WARNING(
"HTMLEditor::DeleteSelectionAndCreateElement(nsGkAtoms::span) "
"failed");
return NS_OK;
}
// If this succeeded, then set selection inside the pre
// so the inserted text will end up there.
// If it failed, we don't care what the return value was,
// but we'll fall through and try to insert the text anyway.
MOZ_ASSERT(spanElementOrError.inspect());
nsresult rv = CollapseSelectionToStartOf(
MOZ_KnownLive(*spanElementOrError.inspect()));
if (MOZ_UNLIKELY(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"EditorBase::CollapseSelectionToStartOf() caused destroying the "
"editor");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"EditorBase::CollapseSelectionToStartOf() failed, but ignored");
containerSpanElement = spanElementOrError.unwrap();
}
// TODO: We should insert text at specific point rather than at selection.
// Then, we can do this before inserting the <span> element.
if (aAddCites == AddCites::Yes) {
nsresult rv = InsertWithQuotationsAsSubAction(aQuotedText);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::InsertWithQuotationsAsSubAction() failed");
return rv;
}
} else {
nsresult rv = InsertTextAsSubAction(aQuotedText, InsertTextFor::NormalText);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::InsertTextAsSubAction() failed");
return rv;
}
}
// Set the selection to after the <span> if and only if we wrap the text into
// it.
if (containerSpanElement) {
EditorRawDOMPoint afterNewSpanElement(
EditorRawDOMPoint::After(*containerSpanElement));
NS_WARNING_ASSERTION(
afterNewSpanElement.IsSet(),
"Failed to set after the new <span> element, but ignored");
if (afterNewSpanElement.IsSet()) {
nsresult rv = CollapseSelectionTo(afterNewSpanElement);
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),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
// Note that if !aAddCites, aNodeInserted isn't set.
// That's okay because the routines that use aAddCites
// don't need to know the inserted node.
if (aNodeInserted) {
containerSpanElement.forget(aNodeInserted);
}
}
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::Rewrap(bool aRespectNewlines) {
AutoEditActionDataSetter editActionData(*this, EditAction::eRewrap);
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 (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
// Rewrap makes no sense if there's no wrap column; default to 72.
int32_t wrapWidth = WrapWidth();
if (wrapWidth <= 0) {
wrapWidth = 72;
}
nsAutoString current;
const bool isCollapsed = SelectionRef().IsCollapsed();
uint32_t flags = nsIDocumentEncoder::OutputFormatted |
nsIDocumentEncoder::OutputLFLineBreak;
if (!isCollapsed) {
flags |= nsIDocumentEncoder::OutputSelectionOnly;
}
rv = ComputeValueInternal(u"text/plain"_ns, flags, current);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::ComputeValueInternal(text/plain) failed");
return EditorBase::ToGenericNSResult(rv);
}
if (current.IsEmpty()) {
return NS_OK;
}
nsString wrapped;
uint32_t firstLineOffset = 0; // XXX need to reset this if there is a
// selection
InternetCiter::Rewrap(current, wrapWidth, firstLineOffset, aRespectNewlines,
wrapped);
if (wrapped.IsEmpty()) {
return NS_OK;
}
if (isCollapsed) {
DebugOnly<nsresult> rvIgnored = SelectAllInternal();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"HTMLEditor::SelectAllInternal() failed");
}
// The whole operation in InsertTextWithQuotationsInternal() should be
// undoable in one transaction.
// XXX Why isn't enough to use only AutoPlaceholderBatch here?
AutoTransactionBatch bundleAllTransactions(*this, __FUNCTION__);
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertTextWithQuotationsInternal(wrapped, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertTextWithQuotationsInternal() failed");
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP HTMLEditor::InsertAsCitedQuotation(const nsAString& aQuotedText,
const nsAString& aCitation,
bool aInsertHTML,
nsINode** aNodeInserted) {
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
// Don't let anyone insert HTML when we're in plaintext mode.
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
NS_ASSERTION(
!aInsertHTML,
"InsertAsCitedQuotation: trying to insert html into plaintext editor");
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertText);
MOZ_ASSERT(!aQuotedText.IsVoid());
editActionData.SetData(aQuotedText);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(
rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertAsPlaintextQuotation(aQuotedText, AddCites::Yes, *editingHost,
aNodeInserted);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertAsPlaintextQuotation() failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoEditActionDataSetter editActionData(*this,
EditAction::eInsertBlockquoteElement);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
rv = InsertAsCitedQuotationInternal(aQuotedText, aCitation, aInsertHTML,
*editingHost, aNodeInserted);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertAsCitedQuotationInternal() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::InsertAsCitedQuotationInternal(
const nsAString& aQuotedText, const nsAString& aCitation, bool aInsertHTML,
const Element& aEditingHost, nsINode** aNodeInserted) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!IsPlaintextMailComposer());
{
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;
}
}
UndefineCaretBidiLevel();
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertQuotation, 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");
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");
}
}
Result<RefPtr<Element>, nsresult> blockquoteElementOrError =
DeleteSelectionAndCreateElement(
*nsGkAtoms::blockquote,
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
[&aCitation](HTMLEditor&, Element& aBlockquoteElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
// Try to set type=cite. Ignore it if this fails.
DebugOnly<nsresult> rvIgnored = aBlockquoteElement.SetAttr(
kNameSpaceID_None, nsGkAtoms::type, u"cite"_ns,
aBlockquoteElement.IsInComposedDoc());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
nsPrintfCString(
"Element::SetAttr(nsGkAtoms::type, \"cite\", %s) failed, "
"but ignored",
aBlockquoteElement.IsInComposedDoc() ? "true" : "false")
.get());
if (!aCitation.IsEmpty()) {
DebugOnly<nsresult> rvIgnored = aBlockquoteElement.SetAttr(
kNameSpaceID_None, nsGkAtoms::cite, aCitation,
aBlockquoteElement.IsInComposedDoc());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
nsPrintfCString(
"Element::SetAttr(nsGkAtoms::cite, \"...\", %s) failed, "
"but ignored",
aBlockquoteElement.IsInComposedDoc() ? "true" : "false")
.get());
}
return NS_OK;
});
if (MOZ_UNLIKELY(blockquoteElementOrError.isErr() ||
NS_WARN_IF(Destroyed()))) {
NS_WARNING(
"HTMLEditor::DeleteSelectionAndCreateElement(nsGkAtoms::blockquote) "
"failed");
return Destroyed() ? NS_ERROR_EDITOR_DESTROYED
: blockquoteElementOrError.unwrapErr();
}
MOZ_ASSERT(blockquoteElementOrError.inspect());
// Set the selection inside the blockquote so aQuotedText will go there:
rv = CollapseSelectionTo(
EditorRawDOMPoint(blockquoteElementOrError.inspect(), 0u));
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),
"EditorBase::CollapseSelectionTo() failed, but ignored");
// TODO: We should insert text at specific point rather than at selection.
// Then, we can do this before inserting the <blockquote> element.
if (aInsertHTML) {
rv = LoadHTML(aQuotedText);
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::LoadHTML() failed");
return rv;
}
} else {
rv = InsertTextAsSubAction(
aQuotedText, InsertTextFor::NormalText); // XXX ignore charset
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::LoadHTML() failed");
return rv;
}
}
// Set the selection to just after the inserted node:
EditorRawDOMPoint afterNewBlockquoteElement(
EditorRawDOMPoint::After(blockquoteElementOrError.inspect()));
NS_WARNING_ASSERTION(
afterNewBlockquoteElement.IsSet(),
"Failed to set after new <blockquote> element, but ignored");
if (afterNewBlockquoteElement.IsSet()) {
nsresult rv = CollapseSelectionTo(afterNewBlockquoteElement);
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),
"EditorBase::CollapseSelectionTo() failed, but ignored");
}
if (aNodeInserted) {
blockquoteElementOrError.unwrap().forget(aNodeInserted);
}
return NS_OK;
}
void HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
RemoveHeadChildAndStealBodyChildsChildren(nsINode& aNode) {
nsCOMPtr<nsIContent> body, head;
// find the body and head nodes if any.
// look only at immediate children of aNode.
for (nsCOMPtr<nsIContent> child = aNode.GetFirstChild(); child;
child = child->GetNextSibling()) {
if (child->IsHTMLElement(nsGkAtoms::body)) {
body = child;
} else if (child->IsHTMLElement(nsGkAtoms::head)) {
head = child;
}
}
if (head) {
ErrorResult ignored;
aNode.RemoveChild(*head, ignored);
}
if (body) {
nsCOMPtr<nsIContent> child = body->GetFirstChild();
while (child) {
ErrorResult ignored;
aNode.InsertBefore(*child, body, ignored);
child = body->GetFirstChild();
}
ErrorResult ignored;
aNode.RemoveChild(*body, ignored);
}
}
// static
void HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
RemoveIncompleteDescendantsFromInsertingFragment(nsINode& aNode) {
nsIContent* child = aNode.GetFirstChild();
while (child) {
bool isEmptyNodeShouldNotInserted = false;
if (HTMLEditUtils::IsListElement(*child)) {
// Current limitation of HTMLEditor:
// Cannot put caret in a list element which does not have list item
// element even as a descendant. I.e., HTMLEditor does not support
// editing in such empty list element, and does not support to delete
// it from outside. Therefore, HTMLWithContextInserter should not
// insert empty list element.
isEmptyNodeShouldNotInserted = HTMLEditUtils::IsEmptyNode(
*child,
{
// Although we don't check relation between list item element
// and parent list element, but it should not be a problem in the
// wild because appearing such invalid list element is an edge
// case and anyway HTMLEditor supports editing in them.
EmptyCheckOption::TreatListItemAsVisible,
// A non-editable list item element may make the list element
// visible. Although HTMLEditor does not support to edit list
// elements which have only non-editable list item elements, but
// it should be deleted from outside. Therefore, don't treat
// non-editable things as invisible.
// TODO: Currently, HTMLEditor does not support deleting such list
// element with Backspace. We should fix this issue.
});
}
// TODO: Perhaps, we should delete <table>s if they have no <td>/<th>
// element, or something other elements which must have specific
// children but they don't.
if (isEmptyNodeShouldNotInserted) {
nsIContent* nextChild = child->GetNextSibling();
OwningNonNull<nsIContent> removingChild(*child);
removingChild->Remove();
child = nextChild;
continue;
}
if (child->HasChildNodes()) {
RemoveIncompleteDescendantsFromInsertingFragment(*child);
}
child = child->GetNextSibling();
}
}
// static
bool HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
IsInsertionCookie(const nsIContent& aContent) {
// Is this child the magical cookie?
if (const auto* comment = Comment::FromNode(&aContent)) {
nsAutoString data;
comment->GetData(data);
return data.EqualsLiteral(kInsertCookie);
}
return false;
}
/**
* This function finds the target node that we will be pasting into. aStart is
* the context that we're given and aResult will be the target. Initially,
* *aResult must be nullptr.
*
* The target for a paste is found by either finding the node that contains
* the magical comment node containing kInsertCookie or, failing that, the
* firstChild of the firstChild (until we reach a leaf).
*/
bool HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
FindTargetNodeOfContextForPastedHTMLAndRemoveInsertionCookie(
nsINode& aStart, nsCOMPtr<nsINode>& aResult) {
nsIContent* firstChild = aStart.GetFirstChild();
if (!firstChild) {
// If the current result is nullptr, then aStart is a leaf, and is the
// fallback result.
if (!aResult) {
aResult = &aStart;
}
return false;
}
for (nsCOMPtr<nsIContent> child = firstChild; child;
child = child->GetNextSibling()) {
if (FragmentFromPasteCreator::IsInsertionCookie(*child)) {
// Yes it is! Return an error so we bubble out and short-circuit the
// search.
aResult = &aStart;
child->Remove();
return true;
}
if (FindTargetNodeOfContextForPastedHTMLAndRemoveInsertionCookie(*child,
aResult)) {
return true;
}
}
return false;
}
class MOZ_STACK_CLASS HTMLEditor::HTMLWithContextInserter::FragmentParser
final {
public:
FragmentParser(const Document& aDocument, SafeToInsertData aSafeToInsertData);
[[nodiscard]] nsresult ParseContext(const nsAString& aContextString,
DocumentFragment** aFragment);
[[nodiscard]] nsresult ParsePastedHTML(const nsAString& aInputString,
nsAtom* aContextLocalNameAtom,
DocumentFragment** aFragment);
private:
static nsresult ParseFragment(const nsAString& aStr,
nsAtom* aContextLocalName,
const Document* aTargetDoc,
dom::DocumentFragment** aFragment,
SafeToInsertData aSafeToInsertData);
const Document& mDocument;
const SafeToInsertData mSafeToInsertData;
};
HTMLEditor::HTMLWithContextInserter::FragmentParser::FragmentParser(
const Document& aDocument, SafeToInsertData aSafeToInsertData)
: mDocument{aDocument}, mSafeToInsertData{aSafeToInsertData} {}
nsresult HTMLEditor::HTMLWithContextInserter::FragmentParser::ParseContext(
const nsAString& aContextStr, DocumentFragment** aFragment) {
return FragmentParser::ParseFragment(aContextStr, nullptr, &mDocument,
aFragment, mSafeToInsertData);
}
nsresult HTMLEditor::HTMLWithContextInserter::FragmentParser::ParsePastedHTML(
const nsAString& aInputString, nsAtom* aContextLocalNameAtom,
DocumentFragment** aFragment) {
return FragmentParser::ParseFragment(aInputString, aContextLocalNameAtom,
&mDocument, aFragment,
mSafeToInsertData);
}
nsresult HTMLEditor::HTMLWithContextInserter::CreateDOMFragmentFromPaste(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, nsCOMPtr<nsINode>* aOutFragNode,
nsCOMPtr<nsINode>* aOutStartNode, nsCOMPtr<nsINode>* aOutEndNode,
uint32_t* aOutStartOffset, uint32_t* aOutEndOffset,
SafeToInsertData aSafeToInsertData) const {
if (NS_WARN_IF(!aOutFragNode) || NS_WARN_IF(!aOutStartNode) ||
NS_WARN_IF(!aOutEndNode) || NS_WARN_IF(!aOutStartOffset) ||
NS_WARN_IF(!aOutEndOffset)) {
return NS_ERROR_INVALID_ARG;
}
RefPtr<const Document> document = mHTMLEditor.GetDocument();
if (NS_WARN_IF(!document)) {
return NS_ERROR_FAILURE;
}
FragmentFromPasteCreator fragmentFromPasteCreator;
const nsresult rv = fragmentFromPasteCreator.Run(
*document, aInputString, aContextStr, aInfoStr, aOutFragNode,
aOutStartNode, aOutEndNode, aSafeToInsertData);
*aOutStartOffset = 0;
*aOutEndOffset = (*aOutEndNode)->Length();
return rv;
}
// static
nsAtom* HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
DetermineContextLocalNameForParsingPastedHTML(
const nsIContent* aParentContentOfPastedHTMLInContext) {
if (!aParentContentOfPastedHTMLInContext) {
return nsGkAtoms::body;
}
nsAtom* contextLocalNameAtom =
aParentContentOfPastedHTMLInContext->NodeInfo()->NameAtom();
return (aParentContentOfPastedHTMLInContext->IsHTMLElement(nsGkAtoms::html))
? nsGkAtoms::body
: contextLocalNameAtom;
}
// static
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
MergeAndPostProcessFragmentsForPastedHTMLAndContext(
DocumentFragment& aDocumentFragmentForPastedHTML,
DocumentFragment& aDocumentFragmentForContext,
nsIContent& aTargetContentOfContextForPastedHTML) {
FragmentFromPasteCreator::RemoveHeadChildAndStealBodyChildsChildren(
aDocumentFragmentForPastedHTML);
FragmentFromPasteCreator::RemoveIncompleteDescendantsFromInsertingFragment(
aDocumentFragmentForPastedHTML);
// unite the two trees
IgnoredErrorResult ignoredError;
aTargetContentOfContextForPastedHTML.AppendChild(
aDocumentFragmentForPastedHTML, ignoredError);
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"nsINode::AppendChild() failed, but ignored");
const nsresult rv = FragmentFromPasteCreator::
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
aDocumentFragmentForContext, NodesToRemove::eOnlyListItems);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces()"
" failed");
return rv;
}
return rv;
}
// static
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
PostProcessFragmentForPastedHTMLWithoutContext(
DocumentFragment& aDocumentFragmentForPastedHTML) {
FragmentFromPasteCreator::RemoveHeadChildAndStealBodyChildsChildren(
aDocumentFragmentForPastedHTML);
FragmentFromPasteCreator::RemoveIncompleteDescendantsFromInsertingFragment(
aDocumentFragmentForPastedHTML);
const nsresult rv = FragmentFromPasteCreator::
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
aDocumentFragmentForPastedHTML, NodesToRemove::eOnlyListItems);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces() "
"failed");
return rv;
}
return rv;
}
// static
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
PreProcessContextDocumentFragmentForMerging(
DocumentFragment& aDocumentFragmentForContext) {
// The context is expected to contain text nodes only in block level
// elements. Hence, if they contain only whitespace, they're invisible.
const nsresult rv = FragmentFromPasteCreator::
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
aDocumentFragmentForContext, NodesToRemove::eAll);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces() "
"failed");
return rv;
}
FragmentFromPasteCreator::RemoveHeadChildAndStealBodyChildsChildren(
aDocumentFragmentForContext);
return rv;
}
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
CreateDocumentFragmentAndGetParentOfPastedHTMLInContext(
const Document& aDocument, const nsAString& aInputString,
const nsAString& aContextStr, SafeToInsertData aSafeToInsertData,
nsCOMPtr<nsINode>& aParentNodeOfPastedHTMLInContext,
RefPtr<DocumentFragment>& aDocumentFragmentToInsert) const {
// if we have context info, create a fragment for that
RefPtr<DocumentFragment> documentFragmentForContext;
FragmentParser fragmentParser{aDocument, aSafeToInsertData};
if (!aContextStr.IsEmpty()) {
nsresult rv = fragmentParser.ParseContext(
aContextStr, getter_AddRefs(documentFragmentForContext));
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentParser::ParseContext() "
"failed");
return rv;
}
if (!documentFragmentForContext) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentParser::ParseContext() "
"returned nullptr");
return NS_ERROR_FAILURE;
}
rv = FragmentFromPasteCreator::PreProcessContextDocumentFragmentForMerging(
*documentFragmentForContext);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"PreProcessContextDocumentFragmentForMerging() failed.");
return rv;
}
FragmentFromPasteCreator::
FindTargetNodeOfContextForPastedHTMLAndRemoveInsertionCookie(
*documentFragmentForContext, aParentNodeOfPastedHTMLInContext);
MOZ_ASSERT(aParentNodeOfPastedHTMLInContext);
}
nsCOMPtr<nsIContent> parentContentOfPastedHTMLInContext =
nsIContent::FromNodeOrNull(aParentNodeOfPastedHTMLInContext);
MOZ_ASSERT_IF(aParentNodeOfPastedHTMLInContext,
parentContentOfPastedHTMLInContext);
nsAtom* contextLocalNameAtom =
FragmentFromPasteCreator::DetermineContextLocalNameForParsingPastedHTML(
parentContentOfPastedHTMLInContext);
RefPtr<DocumentFragment> documentFragmentForPastedHTML;
nsresult rv = fragmentParser.ParsePastedHTML(
aInputString, contextLocalNameAtom,
getter_AddRefs(documentFragmentForPastedHTML));
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentParser::ParsePastedHTML()"
" failed");
return rv;
}
if (!documentFragmentForPastedHTML) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentParser::ParsePastedHTML()"
" returned nullptr");
return NS_ERROR_FAILURE;
}
if (aParentNodeOfPastedHTMLInContext) {
const nsresult rv = FragmentFromPasteCreator::
MergeAndPostProcessFragmentsForPastedHTMLAndContext(
*documentFragmentForPastedHTML, *documentFragmentForContext,
*parentContentOfPastedHTMLInContext);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"MergeAndPostProcessFragmentsForPastedHTMLAndContext() failed.");
return rv;
}
aDocumentFragmentToInsert = std::move(documentFragmentForContext);
} else {
const nsresult rv = PostProcessFragmentForPastedHTMLWithoutContext(
*documentFragmentForPastedHTML);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"PostProcessFragmentForPastedHTMLWithoutContext() failed.");
return rv;
}
aDocumentFragmentToInsert = std::move(documentFragmentForPastedHTML);
}
return rv;
}
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::Run(
const Document& aDocument, const nsAString& aInputString,
const nsAString& aContextStr, const nsAString& aInfoStr,
nsCOMPtr<nsINode>* aOutFragNode, nsCOMPtr<nsINode>* aOutStartNode,
nsCOMPtr<nsINode>* aOutEndNode, SafeToInsertData aSafeToInsertData) const {
MOZ_ASSERT(aOutFragNode);
MOZ_ASSERT(aOutStartNode);
MOZ_ASSERT(aOutEndNode);
nsCOMPtr<nsINode> parentNodeOfPastedHTMLInContext;
RefPtr<DocumentFragment> documentFragmentToInsert;
nsresult rv = CreateDocumentFragmentAndGetParentOfPastedHTMLInContext(
aDocument, aInputString, aContextStr, aSafeToInsertData,
parentNodeOfPastedHTMLInContext, documentFragmentToInsert);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"CreateDocumentFragmentAndGetParentOfPastedHTMLInContext() failed.");
return rv;
}
// If there was no context, then treat all of the data we did get as the
// pasted data.
if (parentNodeOfPastedHTMLInContext) {
*aOutEndNode = *aOutStartNode = parentNodeOfPastedHTMLInContext;
} else {
*aOutEndNode = *aOutStartNode = documentFragmentToInsert;
}
*aOutFragNode = std::move(documentFragmentToInsert);
if (!aInfoStr.IsEmpty()) {
const nsresult rv =
FragmentFromPasteCreator::MoveStartAndEndAccordingToHTMLInfo(
aInfoStr, aOutStartNode, aOutEndNode);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"MoveStartAndEndAccordingToHTMLInfo() failed");
return rv;
}
}
return NS_OK;
}
// static
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
MoveStartAndEndAccordingToHTMLInfo(const nsAString& aInfoStr,
nsCOMPtr<nsINode>* aOutStartNode,
nsCOMPtr<nsINode>* aOutEndNode) {
int32_t sep = aInfoStr.FindChar((char16_t)',');
nsAutoString numstr1(Substring(aInfoStr, 0, sep));
nsAutoString numstr2(
Substring(aInfoStr, sep + 1, aInfoStr.Length() - (sep + 1)));
// Move the start and end children.
nsresult rvIgnored;
int32_t num = numstr1.ToInteger(&rvIgnored);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsAString::ToInteger() failed, but ignored");
while (num--) {
nsINode* tmp = (*aOutStartNode)->GetFirstChild();
if (!tmp) {
NS_WARNING("aOutStartNode did not have children");
return NS_ERROR_FAILURE;
}
*aOutStartNode = tmp;
}
num = numstr2.ToInteger(&rvIgnored);
while (num--) {
nsINode* tmp = (*aOutEndNode)->GetLastChild();
if (!tmp) {
NS_WARNING("aOutEndNode did not have children");
return NS_ERROR_FAILURE;
}
*aOutEndNode = tmp;
}
return NS_OK;
}
// static
nsresult HTMLEditor::HTMLWithContextInserter::FragmentParser::ParseFragment(
const nsAString& aFragStr, nsAtom* aContextLocalName,
const Document* aTargetDocument, DocumentFragment** aFragment,
SafeToInsertData aSafeToInsertData) {
nsAutoScriptBlockerSuppressNodeRemoved autoBlocker;
nsCOMPtr<Document> doc =
nsContentUtils::CreateInertHTMLDocument(aTargetDocument);
if (!doc) {
return NS_ERROR_FAILURE;
}
RefPtr<DocumentFragment> fragment =
new (doc->NodeInfoManager()) DocumentFragment(doc->NodeInfoManager());
nsresult rv = nsContentUtils::ParseFragmentHTML(
aFragStr, fragment,
aContextLocalName ? aContextLocalName : nsGkAtoms::body,
kNameSpaceID_XHTML, false, true);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"nsContentUtils::ParseFragmentHTML() failed");
if (aSafeToInsertData == SafeToInsertData::No) {
nsTreeSanitizer sanitizer(aContextLocalName
? nsIParserUtils::SanitizerAllowStyle
: nsIParserUtils::SanitizerAllowComments);
sanitizer.Sanitize(fragment);
}
fragment.forget(aFragment);
return rv;
}
// static
void HTMLEditor::HTMLWithContextInserter::
CollectTopMostChildContentsCompletelyInRange(
const EditorRawDOMPoint& aStartPoint,
const EditorRawDOMPoint& aEndPoint,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents) {
MOZ_ASSERT(aStartPoint.IsSetAndValid());
MOZ_ASSERT(aEndPoint.IsSetAndValid());
RefPtr<nsRange> range =
nsRange::Create(aStartPoint.ToRawRangeBoundary(),
aEndPoint.ToRawRangeBoundary(), IgnoreErrors());
if (!range) {
NS_WARNING("nsRange::Create() failed");
return;
}
DOMSubtreeIterator iter;
if (NS_FAILED(iter.Init(*range))) {
NS_WARNING("DOMSubtreeIterator::Init() failed, but ignored");
return;
}
iter.AppendAllNodesToArray(aOutArrayOfContents);
}
/******************************************************************************
* HTMLEditor::AutoHTMLFragmentBoundariesFixer
******************************************************************************/
HTMLEditor::AutoHTMLFragmentBoundariesFixer::AutoHTMLFragmentBoundariesFixer(
nsTArray<OwningNonNull<nsIContent>>& aArrayOfTopMostChildContents) {
EnsureBeginsOrEndsWithValidContent(StartOrEnd::start,
aArrayOfTopMostChildContents);
EnsureBeginsOrEndsWithValidContent(StartOrEnd::end,
aArrayOfTopMostChildContents);
}
// static
void HTMLEditor::AutoHTMLFragmentBoundariesFixer::
CollectTableAndAnyListElementsOfInclusiveAncestorsAt(
nsIContent& aContent,
nsTArray<OwningNonNull<Element>>& aOutArrayOfListAndTableElements) {
for (Element* element = aContent.GetAsElementOrParentElement(); element;
element = element->GetParentElement()) {
if (HTMLEditUtils::IsListElement(*element) ||
element->IsHTMLElement(nsGkAtoms::table)) {
aOutArrayOfListAndTableElements.AppendElement(*element);
}
}
}
// static
Element* HTMLEditor::AutoHTMLFragmentBoundariesFixer::
GetMostDistantAncestorListOrTableElement(
const nsTArray<OwningNonNull<nsIContent>>& aArrayOfTopMostChildContents,
const nsTArray<OwningNonNull<Element>>&
aInclusiveAncestorsTableOrListElements) {
Element* lastFoundAncestorListOrTableElement = nullptr;
for (const OwningNonNull<nsIContent>& content :
aArrayOfTopMostChildContents) {
if (HTMLEditUtils::IsAnyTableElementExceptTableElementAndColumElement(
content)) {
Element* tableElement =
HTMLEditUtils::GetClosestAncestorTableElement(*content);
if (!tableElement) {
continue;
}
// If we find a `<table>` element which is an ancestor of a table
// related element and is not an acestor of first nor last of
// aArrayOfNodes, return the last found list or `<table>` element.
// XXX Is that really expected that this returns a list element in this
// case?
if (!aInclusiveAncestorsTableOrListElements.Contains(tableElement)) {
return lastFoundAncestorListOrTableElement;
}
// If we find a `<table>` element which is topmost list or `<table>`
// element at first or last of aArrayOfNodes, return it.
if (aInclusiveAncestorsTableOrListElements.LastElement().get() ==
tableElement) {
return tableElement;
}
// Otherwise, store the `<table>` element which is an ancestor but
// not topmost ancestor of first or last of aArrayOfNodes.
lastFoundAncestorListOrTableElement = tableElement;
continue;
}
if (!HTMLEditUtils::IsListItemElement(*content)) {
continue;
}
Element* listElement =
HTMLEditUtils::GetClosestAncestorAnyListElement(*content);
if (!listElement) {
continue;
}
// If we find a list element which is ancestor of a list item element and
// is not an acestor of first nor last of aArrayOfNodes, return the last
// found list or `<table>` element.
// XXX Is that really expected that this returns a `<table>` element in
// this case?
if (!aInclusiveAncestorsTableOrListElements.Contains(listElement)) {
return lastFoundAncestorListOrTableElement;
}
// If we find a list element which is topmost list or `<table>` element at
// first or last of aArrayOfNodes, return it.
if (aInclusiveAncestorsTableOrListElements.LastElement().get() ==
listElement) {
return listElement;
}
// Otherwise, store the list element which is an ancestor but not topmost
// ancestor of first or last of aArrayOfNodes.
lastFoundAncestorListOrTableElement = listElement;
}
// If we find only non-topmost list or `<table>` element, returns the last
// found one (meaning bottommost one). Otherwise, nullptr.
return lastFoundAncestorListOrTableElement;
}
Element*
HTMLEditor::AutoHTMLFragmentBoundariesFixer::FindReplaceableTableElement(
Element& aTableElement, nsIContent& aContentMaybeInTableElement) const {
MOZ_ASSERT(aTableElement.IsHTMLElement(nsGkAtoms::table));
// Perhaps, this is designed for climbing up the DOM tree from
// aContentMaybeInTableElement to aTableElement and making sure that
// aContentMaybeInTableElement itself or its ancestor is a `<td>`, `<th>`,
// `<tr>`, `<thead>`, `<tbody>`, `<tfoot>` or `<caption>`.
// But this looks really buggy because this loop may skip aTableElement
// as the following NS_ASSERTION. We should write automated tests and
// check right behavior.
for (Element* element =
aContentMaybeInTableElement.GetAsElementOrParentElement();
element; element = element->GetParentElement()) {
if (!HTMLEditUtils::IsAnyTableElementExceptColumnElement(*element) ||
element->IsHTMLElement(nsGkAtoms::table)) {
// XXX Perhaps, the original developer of this method assumed that
// aTableElement won't be skipped because if it's assumed, we can
// stop climbing up the tree in that case.
NS_ASSERTION(element != &aTableElement,
"The table element which is looking for is ignored");
continue;
}
Element* tableElement = nullptr;
for (Element* maybeTableElement = element->GetParentElement();
maybeTableElement;
maybeTableElement = maybeTableElement->GetParentElement()) {
if (maybeTableElement->IsHTMLElement(nsGkAtoms::table)) {
tableElement = maybeTableElement;
break;
}
}
if (tableElement == &aTableElement) {
return element;
}
// XXX If we find another `<table>` element, why don't we keep searching
// from its parent?
}
return nullptr;
}
bool HTMLEditor::AutoHTMLFragmentBoundariesFixer::IsReplaceableListElement(
Element& aListElement, nsIContent& aContentMaybeInListElement) const {
MOZ_ASSERT(HTMLEditUtils::IsListElement(aListElement));
// Perhaps, this is designed for climbing up the DOM tree from
// aContentMaybeInListElement to aListElement and making sure that
// aContentMaybeInListElement itself or its ancestor is an list item.
// But this looks really buggy because this loop may skip aListElement
// as the following NS_ASSERTION. We should write automated tests and
// check right behavior.
for (Element* element =
aContentMaybeInListElement.GetAsElementOrParentElement();
element; element = element->GetParentElement()) {
if (!HTMLEditUtils::IsListItemElement(*element)) {
// XXX Perhaps, the original developer of this method assumed that
// aListElement won't be skipped because if it's assumed, we can
// stop climbing up the tree in that case.
NS_ASSERTION(element != &aListElement,
"The list element which is looking for is ignored");
continue;
}
Element* listElement =
HTMLEditUtils::GetClosestAncestorAnyListElement(*element);
if (listElement == &aListElement) {
return true;
}
// XXX If we find another list element, why don't we keep searching
// from its parent?
}
return false;
}
void HTMLEditor::AutoHTMLFragmentBoundariesFixer::
EnsureBeginsOrEndsWithValidContent(StartOrEnd aStartOrEnd,
nsTArray<OwningNonNull<nsIContent>>&
aArrayOfTopMostChildContents) const {
MOZ_ASSERT(!aArrayOfTopMostChildContents.IsEmpty());
// Collect list elements and table related elements at first or last node
// in aArrayOfTopMostChildContents.
AutoTArray<OwningNonNull<Element>, 4> inclusiveAncestorsListOrTableElements;
CollectTableAndAnyListElementsOfInclusiveAncestorsAt(
aStartOrEnd == StartOrEnd::end
? aArrayOfTopMostChildContents.LastElement()
: aArrayOfTopMostChildContents[0],
inclusiveAncestorsListOrTableElements);
if (inclusiveAncestorsListOrTableElements.IsEmpty()) {
return;
}
// Get most ancestor list or `<table>` element in
// inclusiveAncestorsListOrTableElements which contains earlier
// node in aArrayOfTopMostChildContents as far as possible.
// XXX With inclusiveAncestorsListOrTableElements, this returns a
// list or `<table>` element which contains first or last node of
// aArrayOfTopMostChildContents. However, this seems slow when
// aStartOrEnd is StartOrEnd::end and only the last node is in
// different list or `<table>`. But I'm not sure whether it's
// possible case or not. We need to add tests to
// test_content_iterator_subtree.html for checking how
// SubtreeContentIterator works.
Element* listOrTableElement = GetMostDistantAncestorListOrTableElement(
aArrayOfTopMostChildContents, inclusiveAncestorsListOrTableElements);
if (!listOrTableElement) {
return;
}
// If we have pieces of tables or lists to be inserted, let's force the
// insertion to deal with table elements right away, so that it doesn't
// orphan some table or list contents outside the table or list.
OwningNonNull<nsIContent>& firstOrLastChildContent =
aStartOrEnd == StartOrEnd::end
? aArrayOfTopMostChildContents.LastElement()
: aArrayOfTopMostChildContents[0];
// Find substructure of list or table that must be included in paste.
Element* replaceElement;
if (HTMLEditUtils::IsListElement(*listOrTableElement)) {
if (!IsReplaceableListElement(*listOrTableElement,
firstOrLastChildContent)) {
return;
}
replaceElement = listOrTableElement;
} else {
MOZ_ASSERT(listOrTableElement->IsHTMLElement(nsGkAtoms::table));
replaceElement = FindReplaceableTableElement(*listOrTableElement,
firstOrLastChildContent);
if (!replaceElement) {
return;
}
}
// If we can replace the given list element or found a table related element
// in the `<table>` element, insert it into aArrayOfTopMostChildContents which
// is tompost children to be inserted instead of descendants of them in
// aArrayOfTopMostChildContents.
for (size_t i = 0; i < aArrayOfTopMostChildContents.Length();) {
OwningNonNull<nsIContent>& content = aArrayOfTopMostChildContents[i];
if (content == replaceElement) {
// If the element is n aArrayOfTopMostChildContents, its descendants must
// not be in the array. Therefore, we don't need to optimize this case.
// XXX Perhaps, we can break this loop right now.
aArrayOfTopMostChildContents.RemoveElementAt(i);
continue;
}
if (!EditorUtils::IsDescendantOf(content, *replaceElement)) {
i++;
continue;
}
// For saving number of calls of EditorUtils::IsDescendantOf(), we should
// remove its siblings in the array.
nsIContent* parent = content->GetParent();
aArrayOfTopMostChildContents.RemoveElementAt(i);
while (i < aArrayOfTopMostChildContents.Length() &&
aArrayOfTopMostChildContents[i]->GetParent() == parent) {
aArrayOfTopMostChildContents.RemoveElementAt(i);
}
}
// Now replace the removed nodes with the structural parent
if (aStartOrEnd == StartOrEnd::end) {
aArrayOfTopMostChildContents.AppendElement(*replaceElement);
} else {
aArrayOfTopMostChildContents.InsertElementAt(0, *replaceElement);
}
}
} // namespace mozilla
|