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
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ErrorList.h"
#include "HTMLEditor.h"
#include "HTMLEditorInlines.h"
#include "HTMLEditorNestedClasses.h"
#include "AutoClonedRangeArray.h"
#include "CSSEditUtils.h"
#include "EditAction.h"
#include "EditorLineBreak.h"
#include "EditorUtils.h"
#include "HTMLEditHelpers.h"
#include "HTMLEditUtils.h"
#include "PendingStyles.h"
#include "SelectionState.h"
#include "WSRunScanner.h"
#include "mozilla/Assertions.h"
#include "mozilla/ContentIterator.h"
#include "mozilla/EditorForwards.h"
#include "mozilla/mozalloc.h"
#include "mozilla/SelectionState.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ElementInlines.h"
#include "mozilla/dom/HTMLBRElement.h"
#include "mozilla/dom/NameSpaceConstants.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/Text.h"
#include "nsAString.h"
#include "nsAtom.h"
#include "nsAttrName.h"
#include "nsAttrValue.h"
#include "nsCaseTreatment.h"
#include "nsColor.h"
#include "nsComponentManagerUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsGkAtoms.h"
#include "nsIContent.h"
#include "nsINode.h"
#include "nsIPrincipal.h"
#include "nsISupportsImpl.h"
#include "nsLiteralString.h"
#include "nsNameSpaceManager.h"
#include "nsRange.h"
#include "nsReadableUtils.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsStyledElement.h"
#include "nsTArray.h"
#include "nsTextNode.h"
#include "nsUnicharUtils.h"
namespace mozilla {
using namespace dom;
using EditablePointOption = HTMLEditUtils::EditablePointOption;
using EditablePointOptions = HTMLEditUtils::EditablePointOptions;
using EmptyCheckOption = HTMLEditUtils::EmptyCheckOption;
using LeafNodeType = HTMLEditUtils::LeafNodeType;
using LeafNodeTypes = HTMLEditUtils::LeafNodeTypes;
using WalkTreeOption = HTMLEditUtils::WalkTreeOption;
template nsresult HTMLEditor::SetInlinePropertiesAsSubAction(
const AutoTArray<EditorInlineStyleAndValue, 1>& aStylesToSet,
const Element& aEditingHost);
template nsresult HTMLEditor::SetInlinePropertiesAsSubAction(
const AutoTArray<EditorInlineStyleAndValue, 32>& aStylesToSet,
const Element& aEditingHost);
template nsresult HTMLEditor::SetInlinePropertiesAroundRanges(
AutoClonedRangeArray& aRanges,
const AutoTArray<EditorInlineStyleAndValue, 1>& aStylesToSet);
template nsresult HTMLEditor::SetInlinePropertiesAroundRanges(
AutoClonedRangeArray& aRanges,
const AutoTArray<EditorInlineStyleAndValue, 32>& aStylesToSet);
nsresult HTMLEditor::SetInlinePropertyAsAction(nsStaticAtom& aProperty,
nsStaticAtom* aAttribute,
const nsAString& aValue,
nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(
*this,
HTMLEditUtils::GetEditActionForFormatText(aProperty, aAttribute, true),
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
switch (editActionData.GetEditAction()) {
case EditAction::eSetFontFamilyProperty:
MOZ_ASSERT(!aValue.IsVoid());
// XXX Should we trim unnecessary white-spaces?
editActionData.SetData(aValue);
break;
case EditAction::eSetColorProperty:
case EditAction::eSetBackgroundColorPropertyInline:
editActionData.SetColorData(aValue);
break;
default:
break;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
// XXX Due to bug 1659276 and bug 1659924, we should not scroll selection
// into view after setting the new style.
AutoPlaceholderBatch treatAsOneTransaction(*this, ScrollSelectionIntoView::No,
__FUNCTION__);
nsStaticAtom* property = &aProperty;
nsStaticAtom* attribute = aAttribute;
nsString value(aValue);
if (attribute == nsGkAtoms::color || attribute == nsGkAtoms::bgcolor) {
if (!IsCSSEnabled()) {
// We allow CSS style color value even in the HTML mode. In the cases,
// we will apply the style with CSS. For considering it in the value
// as-is if it's a known CSS keyboard, `rgb()` or `rgba()` style.
// NOTE: It may be later that we set the color into the DOM tree and at
// that time, IsCSSEnabled() may return true. E.g., setting color value
// to collapsed selection, then, change the CSS enabled, finally, user
// types text there.
if (!HTMLEditUtils::MaybeCSSSpecificColorValue(value)) {
HTMLEditUtils::GetNormalizedHTMLColorValue(value, value);
}
} else {
HTMLEditUtils::GetNormalizedCSSColorValue(
value, HTMLEditUtils::ZeroAlphaColor::RGBAValue, value);
}
}
AutoTArray<EditorInlineStyle, 1> stylesToRemove;
if (&aProperty == nsGkAtoms::sup) {
// Superscript and Subscript styles are mutually exclusive.
stylesToRemove.AppendElement(EditorInlineStyle(*nsGkAtoms::sub));
} else if (&aProperty == nsGkAtoms::sub) {
// Superscript and Subscript styles are mutually exclusive.
stylesToRemove.AppendElement(EditorInlineStyle(*nsGkAtoms::sup));
}
// Handling `<tt>` element code was implemented for composer (bug 115922).
// This shouldn't work with `Document.execCommand()`. Currently, aPrincipal
// is set only when the root caller is Document::ExecCommand() so that
// we should handle `<tt>` element only when aPrincipal is nullptr that
// must be only when XUL command is executed on composer.
else if (!aPrincipal) {
if (&aProperty == nsGkAtoms::tt) {
stylesToRemove.AppendElement(
EditorInlineStyle(*nsGkAtoms::font, nsGkAtoms::face));
} else if (&aProperty == nsGkAtoms::font && aAttribute == nsGkAtoms::face) {
if (!value.LowerCaseEqualsASCII("tt")) {
stylesToRemove.AppendElement(EditorInlineStyle(*nsGkAtoms::tt));
} else {
stylesToRemove.AppendElement(
EditorInlineStyle(*nsGkAtoms::font, nsGkAtoms::face));
// Override property, attribute and value if the new font face value is
// "tt".
property = nsGkAtoms::tt;
attribute = nullptr;
value.Truncate();
}
}
}
if (!stylesToRemove.IsEmpty()) {
nsresult rv =
RemoveInlinePropertiesAsSubAction(stylesToRemove, *editingHost);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::RemoveInlinePropertiesAsSubAction() failed");
return rv;
}
}
AutoTArray<EditorInlineStyleAndValue, 1> styleToSet;
styleToSet.AppendElement(
attribute
? EditorInlineStyleAndValue(*property, *attribute, std::move(value))
: EditorInlineStyleAndValue(*property));
rv = SetInlinePropertiesAsSubAction(styleToSet, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::SetInlinePropertiesAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP HTMLEditor::SetInlineProperty(const nsAString& aProperty,
const nsAString& aAttribute,
const nsAString& aValue) {
nsStaticAtom* property = NS_GetStaticAtom(aProperty);
if (NS_WARN_IF(!property)) {
return NS_ERROR_INVALID_ARG;
}
nsStaticAtom* attribute = EditorUtils::GetAttributeAtom(aAttribute);
AutoEditActionDataSetter editActionData(
*this,
HTMLEditUtils::GetEditActionForFormatText(*property, attribute, true));
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (NS_WARN_IF(!editingHost)) {
return NS_ERROR_FAILURE;
}
if (IsPlaintextMailComposer() ||
editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
switch (editActionData.GetEditAction()) {
case EditAction::eSetFontFamilyProperty:
MOZ_ASSERT(!aValue.IsVoid());
// XXX Should we trim unnecessary white-spaces?
editActionData.SetData(aValue);
break;
case EditAction::eSetColorProperty:
case EditAction::eSetBackgroundColorPropertyInline:
editActionData.SetColorData(aValue);
break;
default:
break;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoTArray<EditorInlineStyleAndValue, 1> styleToSet;
styleToSet.AppendElement(
attribute ? EditorInlineStyleAndValue(*property, *attribute, aValue)
: EditorInlineStyleAndValue(*property));
rv = SetInlinePropertiesAsSubAction(styleToSet, *editingHost);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::SetInlinePropertiesAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
template <size_t N>
nsresult HTMLEditor::SetInlinePropertiesAsSubAction(
const AutoTArray<EditorInlineStyleAndValue, N>& aStylesToSet,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!aStylesToSet.IsEmpty());
DebugOnly<nsresult> rvIgnored = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
if (MOZ_UNLIKELY(&aEditingHost !=
ComputeEditingHost(LimitInBodyElement::No))) {
NS_WARNING("Editing host has been changed during committing composition");
return NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE;
}
if (SelectionRef().IsCollapsed()) {
// Manipulating text attributes on a collapsed selection only sets state
// for the next text insertion
mPendingStylesToApplyToNewContent->PreserveStyles(aStylesToSet);
return NS_OK;
}
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result.unwrapErr();
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertElement, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// TODO: We don't need AutoTransactionsConserveSelection here in the normal
// cases, but removing this may cause the behavior with the legacy
// mutation event listeners. We should try to delete this in a bug.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
AutoClonedSelectionRangeArray selectionRanges(SelectionRef());
nsresult rv = SetInlinePropertiesAroundRanges(selectionRanges, aStylesToSet);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::SetInlinePropertiesAroundRanges() failed");
return rv;
}
MOZ_ASSERT(!selectionRanges.HasSavedRanges());
rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"AutoClonedSelectionRangeArray::ApplyTo() failed");
return rv;
}
template <size_t N>
nsresult HTMLEditor::SetInlinePropertiesAroundRanges(
AutoClonedRangeArray& aRanges,
const AutoTArray<EditorInlineStyleAndValue, N>& aStylesToSet) {
MOZ_ASSERT(!aRanges.HasSavedRanges());
for (const EditorInlineStyleAndValue& styleToSet : aStylesToSet) {
AutoInlineStyleSetter inlineStyleSetter(styleToSet);
for (OwningNonNull<nsRange>& domRange : aRanges.Ranges()) {
inlineStyleSetter.Reset();
auto rangeOrError =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<EditorDOMRange, nsresult> {
EditorDOMRange range(domRange);
// If we're setting <font>, we want to remove ancestors which set
// `font-size` or <font size="..."> recursively. Therefore, for
// extending the ranges to contain all ancestors in the range, we need
// to split ancestors first.
// XXX: Blink and WebKit inserts <font> elements to inner most
// elements, however, we cannot do it under current design because
// once we contain ancestors which have `font-size` or are
// <font size="...">, we lost the original ranges which we wanted to
// apply the style. For fixing this, we need to manage both ranges, but
// it's too expensive especially we allow to run script when we touch
// the DOM tree. Additionally, font-size value affects the height
// of the element, but does not affect the height of ancestor inline
// elements. Therefore, following the behavior may cause similar issue
// as bug 1808906. So at least for now, we should not do this big work.
if (styleToSet.IsStyleOfFontElement()) {
Result<SplitRangeOffResult, nsresult> splitAncestorsResult =
SplitAncestorStyledInlineElementsAtRangeEdges(
range, styleToSet, SplitAtEdges::eDoNotCreateEmptyContainer);
if (MOZ_UNLIKELY(splitAncestorsResult.isErr())) {
NS_WARNING(
"HTMLEditor::SplitAncestorStyledInlineElementsAtRangeEdges() "
"failed");
return splitAncestorsResult.propagateErr();
}
SplitRangeOffResult unwrappedResult = splitAncestorsResult.unwrap();
unwrappedResult.IgnoreCaretPointSuggestion();
range = unwrappedResult.RangeRef();
if (NS_WARN_IF(!range.IsPositionedAndValid())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
}
Result<EditorRawDOMRange, nsresult> rangeOrError =
inlineStyleSetter.ExtendOrShrinkRangeToApplyTheStyle(*this, range);
if (MOZ_UNLIKELY(rangeOrError.isErr())) {
NS_WARNING(
"HTMLEditor::ExtendOrShrinkRangeToApplyTheStyle() failed, but "
"ignored");
return EditorDOMRange();
}
return EditorDOMRange(rangeOrError.unwrap());
}();
if (MOZ_UNLIKELY(rangeOrError.isErr())) {
return rangeOrError.unwrapErr();
}
const EditorDOMRange range = rangeOrError.unwrap();
if (!range.IsPositioned()) {
continue;
}
// If the range is collapsed, we should insert new element there.
if (range.Collapsed()) {
Result<RefPtr<Text>, nsresult> emptyTextNodeOrError =
AutoInlineStyleSetter::GetEmptyTextNodeToApplyNewStyle(
*this, range.StartRef());
if (MOZ_UNLIKELY(emptyTextNodeOrError.isErr())) {
NS_WARNING(
"AutoInlineStyleSetter::GetEmptyTextNodeToApplyNewStyle() "
"failed");
return emptyTextNodeOrError.unwrapErr();
}
if (MOZ_UNLIKELY(!emptyTextNodeOrError.inspect())) {
continue; // Couldn't insert text node there
}
RefPtr<Text> emptyTextNode = emptyTextNodeOrError.unwrap();
Result<CaretPoint, nsresult> caretPointOrError =
inlineStyleSetter
.ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle(
*this, *emptyTextNode);
if (MOZ_UNLIKELY(caretPointOrError.isErr())) {
NS_WARNING(
"AutoInlineStyleSetter::"
"ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle() failed");
return caretPointOrError.unwrapErr();
}
DebugOnly<nsresult> rvIgnored = domRange->CollapseTo(emptyTextNode, 0);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsRange::CollapseTo() failed, but ignored");
continue;
}
// Use const_cast hack here for preventing the others to update the range.
AutoTrackDOMRange trackRange(RangeUpdaterRef(),
const_cast<EditorDOMRange*>(&range));
auto UpdateSelectionRange = [&]() MOZ_CAN_RUN_SCRIPT {
// If inlineStyleSetter creates elements or setting styles, we should
// select between start of first element and end of last element.
if (inlineStyleSetter.FirstHandledPointRef().IsInContentNode()) {
MOZ_ASSERT(inlineStyleSetter.LastHandledPointRef().IsInContentNode());
const auto startPoint =
!inlineStyleSetter.FirstHandledPointRef().IsStartOfContainer()
? inlineStyleSetter.FirstHandledPointRef()
.To<EditorRawDOMPoint>()
: HTMLEditUtils::GetDeepestEditableStartPointOf<
EditorRawDOMPoint>(
*inlineStyleSetter.FirstHandledPointRef()
.ContainerAs<nsIContent>(),
{EditablePointOption::RecognizeInvisibleWhiteSpaces,
EditablePointOption::StopAtComment});
const auto endPoint =
!inlineStyleSetter.LastHandledPointRef().IsEndOfContainer()
? inlineStyleSetter.LastHandledPointRef()
.To<EditorRawDOMPoint>()
: HTMLEditUtils::GetDeepestEditableEndPointOf<
EditorRawDOMPoint>(
*inlineStyleSetter.LastHandledPointRef()
.ContainerAs<nsIContent>(),
{EditablePointOption::RecognizeInvisibleWhiteSpaces,
EditablePointOption::StopAtComment});
nsresult rv = domRange->SetStartAndEnd(
startPoint.ToRawRangeBoundary(), endPoint.ToRawRangeBoundary());
if (NS_SUCCEEDED(rv)) {
trackRange.StopTracking();
return;
}
}
// Otherwise, use the range computed with the tracking original range.
trackRange.FlushAndStopTracking();
domRange->SetStartAndEnd(range.StartRef().ToRawRangeBoundary(),
range.EndRef().ToRawRangeBoundary());
};
// If range is in a text node, apply new style simply.
if (range.InSameContainer() && range.StartRef().IsInTextNode()) {
// MOZ_KnownLive(...ContainerAs<Text>()) because of grabbed by `range`.
// MOZ_KnownLive(styleToSet.*) due to bug 1622253.
Result<SplitRangeOffFromNodeResult, nsresult>
wrapTextInStyledElementResult =
inlineStyleSetter.SplitTextNodeAndApplyStyleToMiddleNode(
*this, MOZ_KnownLive(*range.StartRef().ContainerAs<Text>()),
range.StartRef().Offset(), range.EndRef().Offset());
if (MOZ_UNLIKELY(wrapTextInStyledElementResult.isErr())) {
NS_WARNING("HTMLEditor::SetInlinePropertyOnTextNode() failed");
return wrapTextInStyledElementResult.unwrapErr();
}
// The caller should handle the ranges as Selection if necessary, and we
// don't want to update aRanges with this result.
wrapTextInStyledElementResult.inspect().IgnoreCaretPointSuggestion();
UpdateSelectionRange();
continue;
}
// Collect editable nodes which are entirely contained in the range.
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContentsAroundRange;
{
ContentSubtreeIterator subtreeIter;
// If there is no node which is entirely in the range,
// `ContentSubtreeIterator::Init()` fails, but this is possible case,
// don't warn it.
if (NS_SUCCEEDED(
subtreeIter.Init(range.StartRef().ToRawRangeBoundary(),
range.EndRef().ToRawRangeBoundary()))) {
for (; !subtreeIter.IsDone(); subtreeIter.Next()) {
nsINode* node = subtreeIter.GetCurrentNode();
if (NS_WARN_IF(!node)) {
return NS_ERROR_FAILURE;
}
if (MOZ_UNLIKELY(!node->IsContent())) {
continue;
}
// We don't need to wrap non-editable node in new inline element
// nor shouldn't modify `style` attribute of non-editable element.
if (!EditorUtils::IsEditableContent(*node->AsContent(),
EditorType::HTML)) {
continue;
}
// We shouldn't wrap invisible text node in new inline element.
if (node->IsText() &&
!HTMLEditUtils::IsVisibleTextNode(*node->AsText())) {
continue;
}
arrayOfContentsAroundRange.AppendElement(*node->AsContent());
}
}
}
// If start node is a text node, apply new style to a part of it.
if (range.StartRef().IsInTextNode() &&
EditorUtils::IsEditableContent(*range.StartRef().ContainerAs<Text>(),
EditorType::HTML)) {
// MOZ_KnownLive(...ContainerAs<Text>()) because of grabbed by `range`.
// MOZ_KnownLive(styleToSet.*) due to bug 1622253.
Result<SplitRangeOffFromNodeResult, nsresult>
wrapTextInStyledElementResult =
inlineStyleSetter.SplitTextNodeAndApplyStyleToMiddleNode(
*this, MOZ_KnownLive(*range.StartRef().ContainerAs<Text>()),
range.StartRef().Offset(),
range.StartRef().ContainerAs<Text>()->TextDataLength());
if (MOZ_UNLIKELY(wrapTextInStyledElementResult.isErr())) {
NS_WARNING("HTMLEditor::SetInlinePropertyOnTextNode() failed");
return wrapTextInStyledElementResult.unwrapErr();
}
// The caller should handle the ranges as Selection if necessary, and we
// don't want to update aRanges with this result.
wrapTextInStyledElementResult.inspect().IgnoreCaretPointSuggestion();
}
// Then, apply new style to all nodes in the range entirely.
for (auto& content : arrayOfContentsAroundRange) {
// MOZ_KnownLive due to bug 1622253.
Result<CaretPoint, nsresult> pointToPutCaretOrError =
inlineStyleSetter
.ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle(
*this, MOZ_KnownLive(*content));
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"AutoInlineStyleSetter::"
"ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle() failed");
return pointToPutCaretOrError.unwrapErr();
}
// The caller should handle the ranges as Selection if necessary, and we
// don't want to update aRanges with this result.
pointToPutCaretOrError.inspect().IgnoreCaretPointSuggestion();
}
// Finally, if end node is a text node, apply new style to a part of it.
if (range.EndRef().IsInTextNode() &&
EditorUtils::IsEditableContent(*range.EndRef().ContainerAs<Text>(),
EditorType::HTML)) {
// MOZ_KnownLive(...ContainerAs<Text>()) because of grabbed by `range`.
// MOZ_KnownLive(styleToSet.mAttribute) due to bug 1622253.
Result<SplitRangeOffFromNodeResult, nsresult>
wrapTextInStyledElementResult =
inlineStyleSetter.SplitTextNodeAndApplyStyleToMiddleNode(
*this, MOZ_KnownLive(*range.EndRef().ContainerAs<Text>()),
0, range.EndRef().Offset());
if (MOZ_UNLIKELY(wrapTextInStyledElementResult.isErr())) {
NS_WARNING("HTMLEditor::SetInlinePropertyOnTextNode() failed");
return wrapTextInStyledElementResult.unwrapErr();
}
// The caller should handle the ranges as Selection if necessary, and we
// don't want to update aRanges with this result.
wrapTextInStyledElementResult.inspect().IgnoreCaretPointSuggestion();
}
UpdateSelectionRange();
}
}
return NS_OK;
}
// static
Result<RefPtr<Text>, nsresult>
HTMLEditor::AutoInlineStyleSetter::GetEmptyTextNodeToApplyNewStyle(
HTMLEditor& aHTMLEditor, const EditorDOMPoint& aCandidatePointToInsert) {
auto pointToInsertNewText =
HTMLEditUtils::GetBetterCaretPositionToInsertText<EditorDOMPoint>(
aCandidatePointToInsert);
if (MOZ_UNLIKELY(!pointToInsertNewText.IsSet())) {
return RefPtr<Text>(); // cannot insert text there
}
auto pointToInsertNewStyleOrError =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<EditorDOMPoint, nsresult> {
if (!pointToInsertNewText.IsInTextNode()) {
return pointToInsertNewText;
}
if (!pointToInsertNewText.ContainerAs<Text>()->TextDataLength()) {
return pointToInsertNewText; // Use it
}
if (pointToInsertNewText.IsStartOfContainer()) {
return pointToInsertNewText.ParentPoint();
}
if (pointToInsertNewText.IsEndOfContainer()) {
return EditorDOMPoint::After(*pointToInsertNewText.ContainerAs<Text>());
}
Result<SplitNodeResult, nsresult> splitTextNodeResult =
aHTMLEditor.SplitNodeWithTransaction(pointToInsertNewText);
if (MOZ_UNLIKELY(splitTextNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitTextNodeResult.propagateErr();
}
SplitNodeResult unwrappedSplitTextNodeResult = splitTextNodeResult.unwrap();
unwrappedSplitTextNodeResult.IgnoreCaretPointSuggestion();
return unwrappedSplitTextNodeResult.AtSplitPoint<EditorDOMPoint>();
}();
if (MOZ_UNLIKELY(pointToInsertNewStyleOrError.isErr())) {
return pointToInsertNewStyleOrError.propagateErr();
}
// If we already have empty text node which is available for placeholder in
// new styled element, let's use it.
if (pointToInsertNewStyleOrError.inspect().IsInTextNode()) {
return RefPtr<Text>(
pointToInsertNewStyleOrError.inspect().ContainerAs<Text>());
}
// Otherwise, we need an empty text node to create new inline style.
RefPtr<Text> newEmptyTextNode = aHTMLEditor.CreateTextNode(u""_ns);
if (MOZ_UNLIKELY(!newEmptyTextNode)) {
NS_WARNING("EditorBase::CreateTextNode() failed");
return Err(NS_ERROR_FAILURE);
}
Result<CreateTextResult, nsresult> insertNewTextNodeResult =
aHTMLEditor.InsertNodeWithTransaction<Text>(
*newEmptyTextNode, pointToInsertNewStyleOrError.inspect());
if (MOZ_UNLIKELY(insertNewTextNodeResult.isErr())) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return insertNewTextNodeResult.propagateErr();
}
insertNewTextNodeResult.inspect().IgnoreCaretPointSuggestion();
return newEmptyTextNode;
}
Result<bool, nsresult>
HTMLEditor::AutoInlineStyleSetter::ElementIsGoodContainerForTheStyle(
HTMLEditor& aHTMLEditor, Element& aElement) const {
// If the editor is in the CSS mode and the style can be specified with CSS,
// we should not use existing HTML element as a new container.
const bool isCSSEditable = IsCSSSettable(aElement);
if (!aHTMLEditor.IsCSSEnabled() || !isCSSEditable) {
// First check for <b>, <i>, etc.
if (aElement.IsHTMLElement(&HTMLPropertyRef()) &&
!HTMLEditUtils::ElementHasAttribute(aElement) && !mAttribute) {
return true;
}
// Now look for things like <font>
if (mAttribute) {
nsString attrValue;
if (aElement.IsHTMLElement(&HTMLPropertyRef()) &&
!HTMLEditUtils::ElementHasAttributeExcept(aElement, *mAttribute) &&
aElement.GetAttr(mAttribute, attrValue)) {
if (attrValue.Equals(mAttributeValue,
nsCaseInsensitiveStringComparator)) {
return true;
}
if (mAttribute == nsGkAtoms::color ||
mAttribute == nsGkAtoms::bgcolor) {
if (aHTMLEditor.IsCSSEnabled()) {
if (HTMLEditUtils::IsSameCSSColorValue(mAttributeValue,
attrValue)) {
return true;
}
} else if (HTMLEditUtils::IsSameHTMLColorValue(
mAttributeValue, attrValue,
HTMLEditUtils::TransparentKeyword::Allowed)) {
return true;
}
}
}
}
if (!isCSSEditable) {
return false;
}
}
// No luck so far. Now we check for a <span> with a single style=""
// attribute that sets only the style we're looking for, if this type of
// style supports it
if (!aElement.IsHTMLElement(nsGkAtoms::span) ||
!aElement.HasAttr(nsGkAtoms::style) ||
HTMLEditUtils::ElementHasAttributeExcept(aElement, *nsGkAtoms::style)) {
return false;
}
nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement);
if (MOZ_UNLIKELY(!styledElement)) {
return false;
}
// Some CSS styles are not so simple. For instance, underline is
// "text-decoration: underline", which decomposes into four different text-*
// properties. So for now, we just create a span, add the desired style, and
// see if it matches.
RefPtr<Element> newSpanElement =
aHTMLEditor.CreateHTMLContent(nsGkAtoms::span);
if (MOZ_UNLIKELY(!newSpanElement)) {
NS_WARNING("EditorBase::CreateHTMLContent(nsGkAtoms::span) failed");
return false;
}
nsStyledElement* styledNewSpanElement =
nsStyledElement::FromNode(newSpanElement);
if (MOZ_UNLIKELY(!styledNewSpanElement)) {
return false;
}
// MOZ_KnownLive(*styledNewSpanElement): It's newSpanElement whose type is
// RefPtr.
Result<size_t, nsresult> result = CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::No, aHTMLEditor, MOZ_KnownLive(*styledNewSpanElement),
*this, &mAttributeValue);
if (MOZ_UNLIKELY(result.isErr())) {
// The call shouldn't return destroyed error because it must be
// impossible to run script with modifying the new orphan node.
MOZ_ASSERT_UNREACHABLE("How did you destroy this editor?");
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
return false;
}
return CSSEditUtils::DoStyledElementsHaveSameStyle(*styledNewSpanElement,
*styledElement);
}
bool HTMLEditor::AutoInlineStyleSetter::ElementIsGoodContainerToSetStyle(
nsStyledElement& aStyledElement) const {
if (!HTMLEditUtils::IsContainerNode(aStyledElement) ||
!EditorUtils::IsEditableContent(aStyledElement, EditorType::HTML)) {
return false;
}
// If it has `style` attribute, let's use it.
if (aStyledElement.HasAttr(nsGkAtoms::style)) {
return true;
}
// If it has `class` or `id` attribute, the element may have specific rule.
// For applying the new style, we may need to set `style` attribute to it
// to override the specified rule.
if (aStyledElement.HasAttr(nsGkAtoms::id) ||
aStyledElement.HasAttr(nsGkAtoms::_class)) {
return true;
}
// If we're setting text-decoration and the element represents a value of
// text-decoration, <ins> or <del>, let's use it.
if (IsStyleOfTextDecoration(IgnoreSElement::No) &&
aStyledElement.IsAnyOfHTMLElements(nsGkAtoms::u, nsGkAtoms::s,
nsGkAtoms::strike, nsGkAtoms::ins,
nsGkAtoms::del)) {
return true;
}
// If we're setting font-size, color or background-color, we should use <font>
// for compatibility with the other browsers.
if (&HTMLPropertyRef() == nsGkAtoms::font &&
aStyledElement.IsHTMLElement(nsGkAtoms::font)) {
return true;
}
// If the element has one or more <br> (even if it's invisible), we don't
// want to use the <span> for compatibility with the other browsers.
if (aStyledElement.QuerySelector("br"_ns, IgnoreErrors())) {
return false;
}
// NOTE: The following code does not match with the other browsers not
// completely. Blink considers this with relation with the range.
// However, we cannot do it now. We should fix here after or at
// fixing bug 1792386.
// If it's only visible element child of parent block, let's use it.
// E.g., we don't want to create new <span> when
// `<p>{ <span>abc</span> }</p>`.
if (aStyledElement.GetParentElement() &&
HTMLEditUtils::IsBlockElement(
*aStyledElement.GetParentElement(),
BlockInlineCheck::UseComputedDisplayStyle)) {
for (nsIContent* previousSibling = aStyledElement.GetPreviousSibling();
previousSibling;
previousSibling = previousSibling->GetPreviousSibling()) {
if (previousSibling->IsElement()) {
return false; // Assume any elements visible.
}
if (Text* text = Text::FromNode(previousSibling)) {
if (HTMLEditUtils::IsVisibleTextNode(*text)) {
return false;
}
continue;
}
}
for (nsIContent* nextSibling = aStyledElement.GetNextSibling(); nextSibling;
nextSibling = nextSibling->GetNextSibling()) {
if (nextSibling->IsElement()) {
if (!HTMLEditUtils::IsInvisibleBRElement(*nextSibling)) {
return false;
}
continue; // The invisible <br> element may be followed by a child
// block, let's continue to check it.
}
if (Text* text = Text::FromNode(nextSibling)) {
if (HTMLEditUtils::IsVisibleTextNode(*text)) {
return false;
}
continue;
}
}
return true;
}
// Otherwise, wrap it into new <span> for making
// `<span>[abc</span> <span>def]</span>` become
// `<span style="..."><span>abc</span> <span>def</span></span>` rather
// than `<span style="...">abc <span>def</span></span>`.
return false;
}
Result<SplitRangeOffFromNodeResult, nsresult>
HTMLEditor::AutoInlineStyleSetter::SplitTextNodeAndApplyStyleToMiddleNode(
HTMLEditor& aHTMLEditor, Text& aText, uint32_t aStartOffset,
uint32_t aEndOffset) {
const RefPtr<Element> element = aText.GetParentElement();
if (!element || !HTMLEditUtils::CanNodeContain(*element, HTMLPropertyRef())) {
OnHandled(EditorDOMPoint(&aText, aStartOffset),
EditorDOMPoint(&aText, aEndOffset));
return SplitRangeOffFromNodeResult(nullptr, &aText, nullptr);
}
// Don't need to do anything if no characters actually selected
if (aStartOffset == aEndOffset) {
OnHandled(EditorDOMPoint(&aText, aStartOffset),
EditorDOMPoint(&aText, aEndOffset));
return SplitRangeOffFromNodeResult(nullptr, &aText, nullptr);
}
// Don't need to do anything if property already set on node
if (IsCSSSettable(*element)) {
// The HTML styles defined by this have a CSS equivalence for node;
// let's check if it carries those CSS styles
nsAutoString value(mAttributeValue);
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(aHTMLEditor, *element, *this,
value);
if (MOZ_UNLIKELY(isComputedCSSEquivalentToStyleOrError.isErr())) {
NS_WARNING("CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError.propagateErr();
}
if (isComputedCSSEquivalentToStyleOrError.unwrap()) {
OnHandled(EditorDOMPoint(&aText, aStartOffset),
EditorDOMPoint(&aText, aEndOffset));
return SplitRangeOffFromNodeResult(nullptr, &aText, nullptr);
}
} else if (HTMLEditUtils::IsInlineStyleSetByElement(aText, *this,
&mAttributeValue)) {
OnHandled(EditorDOMPoint(&aText, aStartOffset),
EditorDOMPoint(&aText, aEndOffset));
return SplitRangeOffFromNodeResult(nullptr, &aText, nullptr);
}
// Make the range an independent node.
auto splitAtEndResult =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<SplitNodeResult, nsresult> {
EditorDOMPoint atEnd(&aText, aEndOffset);
if (atEnd.IsEndOfContainer()) {
return SplitNodeResult::NotHandled(atEnd);
}
// We need to split off back of text node
Result<SplitNodeResult, nsresult> splitNodeResult =
aHTMLEditor.SplitNodeWithTransaction(atEnd);
if (splitNodeResult.isErr()) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitNodeResult;
}
if (MOZ_UNLIKELY(!splitNodeResult.inspect().HasCaretPointSuggestion())) {
NS_WARNING(
"HTMLEditor::SplitNodeWithTransaction() didn't suggest caret "
"point");
return Err(NS_ERROR_FAILURE);
}
return splitNodeResult;
}();
if (MOZ_UNLIKELY(splitAtEndResult.isErr())) {
return splitAtEndResult.propagateErr();
}
SplitNodeResult unwrappedSplitAtEndResult = splitAtEndResult.unwrap();
EditorDOMPoint pointToPutCaret = unwrappedSplitAtEndResult.UnwrapCaretPoint();
auto splitAtStartResult =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<SplitNodeResult, nsresult> {
EditorDOMPoint atStart(unwrappedSplitAtEndResult.DidSplit()
? unwrappedSplitAtEndResult.GetPreviousContent()
: &aText,
aStartOffset);
if (atStart.IsStartOfContainer()) {
return SplitNodeResult::NotHandled(atStart);
}
// We need to split off front of text node
Result<SplitNodeResult, nsresult> splitNodeResult =
aHTMLEditor.SplitNodeWithTransaction(atStart);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitNodeResult;
}
if (MOZ_UNLIKELY(!splitNodeResult.inspect().HasCaretPointSuggestion())) {
NS_WARNING(
"HTMLEditor::SplitNodeWithTransaction() didn't suggest caret "
"point");
return Err(NS_ERROR_FAILURE);
}
return splitNodeResult;
}();
if (MOZ_UNLIKELY(splitAtStartResult.isErr())) {
return splitAtStartResult.propagateErr();
}
SplitNodeResult unwrappedSplitAtStartResult = splitAtStartResult.unwrap();
if (unwrappedSplitAtStartResult.HasCaretPointSuggestion()) {
pointToPutCaret = unwrappedSplitAtStartResult.UnwrapCaretPoint();
}
MOZ_ASSERT_IF(unwrappedSplitAtStartResult.DidSplit(),
unwrappedSplitAtStartResult.GetPreviousContent()->IsText());
MOZ_ASSERT_IF(unwrappedSplitAtStartResult.DidSplit(),
unwrappedSplitAtStartResult.GetNextContent()->IsText());
MOZ_ASSERT_IF(unwrappedSplitAtEndResult.DidSplit(),
unwrappedSplitAtEndResult.GetPreviousContent()->IsText());
MOZ_ASSERT_IF(unwrappedSplitAtEndResult.DidSplit(),
unwrappedSplitAtEndResult.GetNextContent()->IsText());
// Note that those text nodes are grabbed by unwrappedSplitAtStartResult,
// unwrappedSplitAtEndResult or the callers. Therefore, we don't need to make
// them strong pointer.
Text* const leftTextNode =
unwrappedSplitAtStartResult.DidSplit()
? unwrappedSplitAtStartResult.GetPreviousContentAs<Text>()
: nullptr;
Text* const middleTextNode =
unwrappedSplitAtStartResult.DidSplit()
? unwrappedSplitAtStartResult.GetNextContentAs<Text>()
: (unwrappedSplitAtEndResult.DidSplit()
? unwrappedSplitAtEndResult.GetPreviousContentAs<Text>()
: &aText);
Text* const rightTextNode =
unwrappedSplitAtEndResult.DidSplit()
? unwrappedSplitAtEndResult.GetNextContentAs<Text>()
: nullptr;
if (mAttribute) {
// Look for siblings that are correct type of node
nsIContent* sibling = HTMLEditUtils::GetPreviousSibling(
*middleTextNode, {WalkTreeOption::IgnoreNonEditableNode});
if (sibling && sibling->IsElement()) {
OwningNonNull<Element> element(*sibling->AsElement());
Result<bool, nsresult> result =
ElementIsGoodContainerForTheStyle(aHTMLEditor, element);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::ElementIsGoodContainerForTheStyle() failed");
return result.propagateErr();
}
if (result.inspect()) {
// Previous sib is already right kind of inline node; slide this over
Result<MoveNodeResult, nsresult> moveTextNodeResult =
aHTMLEditor.MoveNodeToEndWithTransaction(
MOZ_KnownLive(*middleTextNode), element);
if (MOZ_UNLIKELY(moveTextNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveTextNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveTextNodeResult =
moveTextNodeResult.unwrap();
unwrappedMoveTextNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
OnHandled(*middleTextNode);
return SplitRangeOffFromNodeResult(leftTextNode, middleTextNode,
rightTextNode,
std::move(pointToPutCaret));
}
}
sibling = HTMLEditUtils::GetNextSibling(
*middleTextNode, {WalkTreeOption::IgnoreNonEditableNode});
if (sibling && sibling->IsElement()) {
OwningNonNull<Element> element(*sibling->AsElement());
Result<bool, nsresult> result =
ElementIsGoodContainerForTheStyle(aHTMLEditor, element);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::ElementIsGoodContainerForTheStyle() failed");
return result.propagateErr();
}
if (result.inspect()) {
// Following sib is already right kind of inline node; slide this over
Result<MoveNodeResult, nsresult> moveTextNodeResult =
aHTMLEditor.MoveNodeWithTransaction(MOZ_KnownLive(*middleTextNode),
EditorDOMPoint(sibling, 0u));
if (MOZ_UNLIKELY(moveTextNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveTextNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveTextNodeResult =
moveTextNodeResult.unwrap();
unwrappedMoveTextNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
OnHandled(*middleTextNode);
return SplitRangeOffFromNodeResult(leftTextNode, middleTextNode,
rightTextNode,
std::move(pointToPutCaret));
}
}
}
// Wrap the node inside inline node.
Result<CaretPoint, nsresult> setStyleResult =
ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle(
aHTMLEditor, MOZ_KnownLive(*middleTextNode));
if (MOZ_UNLIKELY(setStyleResult.isErr())) {
NS_WARNING(
"AutoInlineStyleSetter::"
"ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle() failed");
return setStyleResult.propagateErr();
}
return SplitRangeOffFromNodeResult(
leftTextNode, middleTextNode, rightTextNode,
setStyleResult.unwrap().UnwrapCaretPoint());
}
Result<CaretPoint, nsresult> HTMLEditor::AutoInlineStyleSetter::ApplyStyle(
HTMLEditor& aHTMLEditor, nsIContent& aContent) {
// If this is an element that can't be contained in a span, we have to
// recurse to its children.
if (!HTMLEditUtils::CanNodeContain(*nsGkAtoms::span, aContent)) {
if (!aContent.HasChildren()) {
return CaretPoint(EditorDOMPoint());
}
AutoTArray<OwningNonNull<nsIContent>, 32> arrayOfContents;
HTMLEditUtils::CollectChildren(
aContent, arrayOfContents,
{CollectChildrenOption::IgnoreNonEditableChildren,
CollectChildrenOption::IgnoreInvisibleTextNodes});
// Then loop through the list, set the property on each node.
EditorDOMPoint pointToPutCaret;
for (const OwningNonNull<nsIContent>& content : arrayOfContents) {
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
Result<CaretPoint, nsresult> setInlinePropertyResult =
ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle(
aHTMLEditor, MOZ_KnownLive(content));
if (MOZ_UNLIKELY(setInlinePropertyResult.isErr())) {
NS_WARNING(
"AutoInlineStyleSetter::"
"ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle() failed");
return setInlinePropertyResult;
}
setInlinePropertyResult.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
}
return CaretPoint(std::move(pointToPutCaret));
}
// First check if there's an adjacent sibling we can put our node into.
nsCOMPtr<nsIContent> previousSibling = HTMLEditUtils::GetPreviousSibling(
aContent, {WalkTreeOption::IgnoreNonEditableNode});
nsCOMPtr<nsIContent> nextSibling = HTMLEditUtils::GetNextSibling(
aContent, {WalkTreeOption::IgnoreNonEditableNode});
if (RefPtr<Element> previousElement =
Element::FromNodeOrNull(previousSibling)) {
Result<bool, nsresult> canMoveIntoPreviousSibling =
ElementIsGoodContainerForTheStyle(aHTMLEditor, *previousElement);
if (MOZ_UNLIKELY(canMoveIntoPreviousSibling.isErr())) {
NS_WARNING("HTMLEditor::ElementIsGoodContainerForTheStyle() failed");
return canMoveIntoPreviousSibling.propagateErr();
}
if (canMoveIntoPreviousSibling.inspect()) {
Result<MoveNodeResult, nsresult> moveNodeResult =
aHTMLEditor.MoveNodeToEndWithTransaction(aContent, *previousSibling);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
RefPtr<Element> nextElement = Element::FromNodeOrNull(nextSibling);
if (!nextElement) {
OnHandled(aContent);
return CaretPoint(unwrappedMoveNodeResult.UnwrapCaretPoint());
}
Result<bool, nsresult> canMoveIntoNextSibling =
ElementIsGoodContainerForTheStyle(aHTMLEditor, *nextElement);
if (MOZ_UNLIKELY(canMoveIntoNextSibling.isErr())) {
NS_WARNING("HTMLEditor::ElementIsGoodContainerForTheStyle() failed");
unwrappedMoveNodeResult.IgnoreCaretPointSuggestion();
return canMoveIntoNextSibling.propagateErr();
}
if (!canMoveIntoNextSibling.inspect()) {
OnHandled(aContent);
return CaretPoint(unwrappedMoveNodeResult.UnwrapCaretPoint());
}
unwrappedMoveNodeResult.IgnoreCaretPointSuggestion();
// JoinNodesWithTransaction (DoJoinNodes) tries to collapse selection to
// the joined point and we want to skip updating `Selection` here.
AutoTransactionsConserveSelection dontChangeMySelection(aHTMLEditor);
Result<JoinNodesResult, nsresult> joinNodesResult =
aHTMLEditor.JoinNodesWithTransaction(*previousElement, *nextElement);
if (MOZ_UNLIKELY(joinNodesResult.isErr())) {
NS_WARNING("HTMLEditor::JoinNodesWithTransaction() failed");
return joinNodesResult.propagateErr();
}
// So, let's take it.
OnHandled(aContent);
return CaretPoint(
joinNodesResult.inspect().AtJoinedPoint<EditorDOMPoint>());
}
}
if (RefPtr<Element> nextElement = Element::FromNodeOrNull(nextSibling)) {
Result<bool, nsresult> canMoveIntoNextSibling =
ElementIsGoodContainerForTheStyle(aHTMLEditor, *nextElement);
if (MOZ_UNLIKELY(canMoveIntoNextSibling.isErr())) {
NS_WARNING("HTMLEditor::ElementIsGoodContainerForTheStyle() failed");
return canMoveIntoNextSibling.propagateErr();
}
if (canMoveIntoNextSibling.inspect()) {
Result<MoveNodeResult, nsresult> moveNodeResult =
aHTMLEditor.MoveNodeWithTransaction(aContent,
EditorDOMPoint(nextElement, 0u));
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveNodeResult.propagateErr();
}
OnHandled(aContent);
return CaretPoint(moveNodeResult.unwrap().UnwrapCaretPoint());
}
}
// Don't need to do anything if property already set on node
if (const RefPtr<Element> element = aContent.GetAsElementOrParentElement()) {
if (IsCSSSettable(*element)) {
nsAutoString value(mAttributeValue);
// MOZ_KnownLive(element) because it's aContent.
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(aHTMLEditor, *element, *this,
value);
if (MOZ_UNLIKELY(isComputedCSSEquivalentToStyleOrError.isErr())) {
NS_WARNING("CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError.propagateErr();
}
if (isComputedCSSEquivalentToStyleOrError.unwrap()) {
OnHandled(aContent);
return CaretPoint(EditorDOMPoint());
}
} else if (HTMLEditUtils::IsInlineStyleSetByElement(*element, *this,
&mAttributeValue)) {
OnHandled(aContent);
return CaretPoint(EditorDOMPoint());
}
}
auto ShouldUseCSS = [&]() {
if (aHTMLEditor.IsCSSEnabled() && aContent.GetAsElementOrParentElement() &&
IsCSSSettable(*aContent.GetAsElementOrParentElement())) {
return true;
}
// bgcolor is always done using CSS
if (mAttribute == nsGkAtoms::bgcolor) {
return true;
}
// called for removing parent style, we should use CSS with <span> element.
if (IsStyleToInvert()) {
return true;
}
// If we set color value, the value may be able to specified only with CSS.
// In that case, we need to use CSS even in the HTML mode.
if (mAttribute == nsGkAtoms::color) {
return mAttributeValue.First() != '#' &&
!HTMLEditUtils::CanConvertToHTMLColorValue(mAttributeValue);
}
return false;
};
if (ShouldUseCSS()) {
// We need special handlings for text-decoration.
if (IsStyleOfTextDecoration(IgnoreSElement::No)) {
Result<CaretPoint, nsresult> result =
ApplyCSSTextDecoration(aHTMLEditor, aContent);
NS_WARNING_ASSERTION(
result.isOk(),
"AutoInlineStyleSetter::ApplyCSSTextDecoration() failed");
return result;
}
EditorDOMPoint pointToPutCaret;
RefPtr<nsStyledElement> styledElement = [&]() -> nsStyledElement* {
auto* const styledElement = nsStyledElement::FromNode(&aContent);
return styledElement && ElementIsGoodContainerToSetStyle(*styledElement)
? styledElement
: nullptr;
}();
// If we don't have good element to set the style, let's create new <span>.
if (!styledElement) {
Result<CreateElementResult, nsresult> wrapInSpanElementResult =
aHTMLEditor.InsertContainerWithTransaction(aContent,
*nsGkAtoms::span);
if (MOZ_UNLIKELY(wrapInSpanElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertContainerWithTransaction(nsGkAtoms::span) "
"failed");
return wrapInSpanElementResult.propagateErr();
}
CreateElementResult unwrappedWrapInSpanElementResult =
wrapInSpanElementResult.unwrap();
MOZ_ASSERT(unwrappedWrapInSpanElementResult.GetNewNode());
unwrappedWrapInSpanElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
styledElement = nsStyledElement::FromNode(
unwrappedWrapInSpanElementResult.GetNewNode());
MOZ_ASSERT(styledElement);
if (MOZ_UNLIKELY(!styledElement)) {
// Don't return error to avoid creating new path to throwing error.
OnHandled(aContent);
return CaretPoint(pointToPutCaret);
}
}
// Add the CSS styles corresponding to the HTML style request
if (IsCSSSettable(*styledElement)) {
Result<size_t, nsresult> result = CSSEditUtils::SetCSSEquivalentToStyle(
WithTransaction::Yes, aHTMLEditor, *styledElement, *this,
&mAttributeValue);
if (MOZ_UNLIKELY(result.isErr())) {
if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING(
"CSSEditUtils::SetCSSEquivalentToStyle() failed, but ignored");
}
}
OnHandled(aContent);
return CaretPoint(pointToPutCaret);
}
nsAutoString attributeValue(mAttributeValue);
if (mAttribute == nsGkAtoms::color && mAttributeValue.First() != '#') {
// At here, all color values should be able to be parsed as a CSS color
// value. Therefore, we need to convert it to normalized HTML color value.
HTMLEditUtils::ConvertToNormalizedHTMLColorValue(attributeValue,
attributeValue);
}
// is it already the right kind of node, but with wrong attribute?
if (aContent.IsHTMLElement(&HTMLPropertyRef())) {
if (NS_WARN_IF(!mAttribute)) {
return Err(NS_ERROR_INVALID_ARG);
}
// Just set the attribute on it.
nsresult rv = aHTMLEditor.SetAttributeWithTransaction(
MOZ_KnownLive(*aContent.AsElement()), *mAttribute, attributeValue);
if (NS_WARN_IF(aHTMLEditor.Destroyed())) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::SetAttributeWithTransaction() failed");
return Err(rv);
}
OnHandled(aContent);
return CaretPoint(EditorDOMPoint());
}
// ok, chuck it in its very own container
Result<CreateElementResult, nsresult> wrapWithNewElementToFormatResult =
aHTMLEditor.InsertContainerWithTransaction(
aContent, MOZ_KnownLive(HTMLPropertyRef()),
!mAttribute ? HTMLEditor::DoNothingForNewElement
// MOZ_CAN_RUN_SCRIPT_BOUNDARY due to bug 1758868
: [&](HTMLEditor& aHTMLEditor, Element& aNewElement,
const EditorDOMPoint&) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
nsresult rv =
aNewElement.SetAttr(kNameSpaceID_None, mAttribute,
attributeValue, false);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Element::SetAttr() failed");
return rv;
});
if (MOZ_UNLIKELY(wrapWithNewElementToFormatResult.isErr())) {
NS_WARNING("HTMLEditor::InsertContainerWithTransaction() failed");
return wrapWithNewElementToFormatResult.propagateErr();
}
OnHandled(aContent);
MOZ_ASSERT(wrapWithNewElementToFormatResult.inspect().GetNewNode());
return CaretPoint(
wrapWithNewElementToFormatResult.unwrap().UnwrapCaretPoint());
}
Result<CaretPoint, nsresult>
HTMLEditor::AutoInlineStyleSetter::ApplyCSSTextDecoration(
HTMLEditor& aHTMLEditor, nsIContent& aContent) {
MOZ_ASSERT(IsStyleOfTextDecoration(IgnoreSElement::No));
EditorDOMPoint pointToPutCaret;
RefPtr<nsStyledElement> styledElement = nsStyledElement::FromNode(aContent);
nsAutoString newTextDecorationValue;
if (&HTMLPropertyRef() == nsGkAtoms::u) {
newTextDecorationValue.AssignLiteral(u"underline");
} else if (&HTMLPropertyRef() == nsGkAtoms::s ||
&HTMLPropertyRef() == nsGkAtoms::strike) {
newTextDecorationValue.AssignLiteral(u"line-through");
} else {
MOZ_ASSERT_UNREACHABLE(
"Was new value added in "
"IsStyleOfTextDecoration(IgnoreSElement::No))?");
}
if (styledElement && IsCSSSettable(*styledElement) &&
ElementIsGoodContainerToSetStyle(*styledElement)) {
nsAutoString textDecorationValue;
nsresult rv = CSSEditUtils::GetSpecifiedProperty(
*styledElement, *nsGkAtoms::text_decoration, textDecorationValue);
if (NS_FAILED(rv)) {
NS_WARNING(
"CSSEditUtils::GetSpecifiedProperty(nsGkAtoms::text_decoration) "
"failed");
return Err(rv);
}
// However, if the element is an element to style the text-decoration,
// replace it with new <span>.
if (styledElement && styledElement->IsAnyOfHTMLElements(
nsGkAtoms::u, nsGkAtoms::s, nsGkAtoms::strike)) {
Result<CreateElementResult, nsresult> replaceResult =
aHTMLEditor.ReplaceContainerAndCloneAttributesWithTransaction(
*styledElement, *nsGkAtoms::span);
if (MOZ_UNLIKELY(replaceResult.isErr())) {
NS_WARNING(
"HTMLEditor::ReplaceContainerAndCloneAttributesWithTransaction() "
"failed");
return replaceResult.propagateErr();
}
CreateElementResult unwrappedReplaceResult = replaceResult.unwrap();
MOZ_ASSERT(unwrappedReplaceResult.GetNewNode());
unwrappedReplaceResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
// The new <span> needs to specify the original element's text-decoration
// style unless it's specified explicitly.
if (textDecorationValue.IsEmpty()) {
if (!newTextDecorationValue.IsEmpty()) {
newTextDecorationValue.Append(HTMLEditUtils::kSpace);
}
if (styledElement->IsHTMLElement(nsGkAtoms::u)) {
newTextDecorationValue.AppendLiteral(u"underline");
} else {
newTextDecorationValue.AppendLiteral(u"line-through");
}
}
styledElement =
nsStyledElement::FromNode(unwrappedReplaceResult.GetNewNode());
if (NS_WARN_IF(!styledElement)) {
OnHandled(aContent);
return CaretPoint(pointToPutCaret);
}
}
// If the element has default style, we need to keep it after specifying
// text-decoration.
else if (textDecorationValue.IsEmpty() &&
styledElement->IsAnyOfHTMLElements(nsGkAtoms::u, nsGkAtoms::ins)) {
if (!newTextDecorationValue.IsEmpty()) {
newTextDecorationValue.Append(HTMLEditUtils::kSpace);
}
newTextDecorationValue.AppendLiteral(u"underline");
} else if (textDecorationValue.IsEmpty() &&
styledElement->IsAnyOfHTMLElements(
nsGkAtoms::s, nsGkAtoms::strike, nsGkAtoms::del)) {
if (!newTextDecorationValue.IsEmpty()) {
newTextDecorationValue.Append(HTMLEditUtils::kSpace);
}
newTextDecorationValue.AppendLiteral(u"line-through");
}
}
// Otherwise, use new <span> element.
else {
Result<CreateElementResult, nsresult> wrapInSpanElementResult =
aHTMLEditor.InsertContainerWithTransaction(aContent, *nsGkAtoms::span);
if (MOZ_UNLIKELY(wrapInSpanElementResult.isErr())) {
NS_WARNING(
"HTMLEditor::InsertContainerWithTransaction(nsGkAtoms::span) failed");
return wrapInSpanElementResult.propagateErr();
}
CreateElementResult unwrappedWrapInSpanElementResult =
wrapInSpanElementResult.unwrap();
MOZ_ASSERT(unwrappedWrapInSpanElementResult.GetNewNode());
unwrappedWrapInSpanElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
styledElement = nsStyledElement::FromNode(
unwrappedWrapInSpanElementResult.GetNewNode());
if (NS_WARN_IF(!styledElement)) {
OnHandled(aContent);
return CaretPoint(pointToPutCaret);
}
}
nsresult rv = CSSEditUtils::SetCSSPropertyWithTransaction(
aHTMLEditor, *styledElement, *nsGkAtoms::text_decoration,
newTextDecorationValue);
if (NS_FAILED(rv)) {
NS_WARNING("CSSEditUtils::SetCSSPropertyWithTransaction() failed");
return Err(rv);
}
OnHandled(aContent);
return CaretPoint(pointToPutCaret);
}
Result<CaretPoint, nsresult> HTMLEditor::AutoInlineStyleSetter::
ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle(HTMLEditor& aHTMLEditor,
nsIContent& aContent) {
if (NS_WARN_IF(!aContent.GetParentNode())) {
return Err(NS_ERROR_FAILURE);
}
OwningNonNull<nsINode> parent = *aContent.GetParentNode();
nsCOMPtr<nsIContent> previousSibling = aContent.GetPreviousSibling(),
nextSibling = aContent.GetNextSibling();
EditorDOMPoint pointToPutCaret;
if (aContent.IsElement()) {
Result<EditorDOMPoint, nsresult> removeStyleResult =
aHTMLEditor.RemoveStyleInside(MOZ_KnownLive(*aContent.AsElement()),
*this, SpecifiedStyle::Preserve);
if (MOZ_UNLIKELY(removeStyleResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveStyleInside() failed");
return removeStyleResult.propagateErr();
}
if (removeStyleResult.inspect().IsSet()) {
pointToPutCaret = removeStyleResult.unwrap();
}
if (nsStaticAtom* similarElementNameAtom = GetSimilarElementNameAtom()) {
Result<EditorDOMPoint, nsresult> removeStyleResult =
aHTMLEditor.RemoveStyleInside(
MOZ_KnownLive(*aContent.AsElement()),
EditorInlineStyle(*similarElementNameAtom),
SpecifiedStyle::Preserve);
if (MOZ_UNLIKELY(removeStyleResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveStyleInside() failed");
return removeStyleResult.propagateErr();
}
if (removeStyleResult.inspect().IsSet()) {
pointToPutCaret = removeStyleResult.unwrap();
}
}
}
if (aContent.GetParentNode()) {
// The node is still where it was
Result<CaretPoint, nsresult> pointToPutCaretOrError =
ApplyStyle(aHTMLEditor, aContent);
NS_WARNING_ASSERTION(pointToPutCaretOrError.isOk(),
"AutoInlineStyleSetter::ApplyStyle() failed");
return pointToPutCaretOrError;
}
// It's vanished. Use the old siblings for reference to construct a
// list. But first, verify that the previous/next siblings are still
// where we expect them; otherwise we have to give up.
if (NS_WARN_IF(previousSibling &&
previousSibling->GetParentNode() != parent) ||
NS_WARN_IF(nextSibling && nextSibling->GetParentNode() != parent) ||
NS_WARN_IF(!parent->IsInComposedDoc())) {
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
AutoTArray<OwningNonNull<nsIContent>, 24> nodesToSet;
for (nsIContent* content = previousSibling ? previousSibling->GetNextSibling()
: parent->GetFirstChild();
content && content != nextSibling; content = content->GetNextSibling()) {
if (EditorUtils::IsEditableContent(*content, EditorType::HTML)) {
nodesToSet.AppendElement(*content);
}
}
for (OwningNonNull<nsIContent>& content : nodesToSet) {
// MOZ_KnownLive because 'nodesToSet' is guaranteed to
// keep it alive.
Result<CaretPoint, nsresult> pointToPutCaretOrError =
ApplyStyle(aHTMLEditor, MOZ_KnownLive(content));
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING("AutoInlineStyleSetter::ApplyStyle() failed");
return pointToPutCaretOrError;
}
pointToPutCaretOrError.unwrap().MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
}
return CaretPoint(pointToPutCaret);
}
bool HTMLEditor::AutoInlineStyleSetter::ContentIsElementSettingTheStyle(
const HTMLEditor& aHTMLEditor, nsIContent& aContent) const {
Element* const element = Element::FromNode(&aContent);
if (!element) {
return false;
}
if (IsRepresentedBy(*element)) {
return true;
}
Result<bool, nsresult> specified = IsSpecifiedBy(aHTMLEditor, *element);
NS_WARNING_ASSERTION(specified.isOk(),
"EditorInlineStyle::IsSpecified() failed, but ignored");
return specified.unwrapOr(false);
}
// static
nsIContent* HTMLEditor::AutoInlineStyleSetter::GetNextEditableInlineContent(
const nsIContent& aContent, const nsINode* aLimiter) {
auto* const nextContentInRange = [&]() -> nsIContent* {
for (nsIContent* parent : aContent.InclusiveAncestorsOfType<nsIContent>()) {
if (parent == aLimiter ||
!EditorUtils::IsEditableContent(*parent, EditorType::HTML) ||
(parent->IsElement() &&
(HTMLEditUtils::IsBlockElement(
*parent->AsElement(),
BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
HTMLEditUtils::IsDisplayInsideFlowRoot(*parent->AsElement())))) {
return nullptr;
}
if (nsIContent* nextSibling = parent->GetNextSibling()) {
return nextSibling;
}
}
return nullptr;
}();
return nextContentInRange &&
EditorUtils::IsEditableContent(*nextContentInRange,
EditorType::HTML) &&
!HTMLEditUtils::IsBlockElement(
*nextContentInRange,
BlockInlineCheck::UseComputedDisplayOutsideStyle)
? nextContentInRange
: nullptr;
}
// static
nsIContent* HTMLEditor::AutoInlineStyleSetter::GetPreviousEditableInlineContent(
const nsIContent& aContent, const nsINode* aLimiter) {
auto* const previousContentInRange = [&]() -> nsIContent* {
for (nsIContent* parent : aContent.InclusiveAncestorsOfType<nsIContent>()) {
if (parent == aLimiter ||
!EditorUtils::IsEditableContent(*parent, EditorType::HTML) ||
(parent->IsElement() &&
(HTMLEditUtils::IsBlockElement(
*parent->AsElement(),
BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
HTMLEditUtils::IsDisplayInsideFlowRoot(*parent->AsElement())))) {
return nullptr;
}
if (nsIContent* previousSibling = parent->GetPreviousSibling()) {
return previousSibling;
}
}
return nullptr;
}();
return previousContentInRange &&
EditorUtils::IsEditableContent(*previousContentInRange,
EditorType::HTML) &&
!HTMLEditUtils::IsBlockElement(
*previousContentInRange,
BlockInlineCheck::UseComputedDisplayOutsideStyle)
? previousContentInRange
: nullptr;
}
EditorRawDOMPoint HTMLEditor::AutoInlineStyleSetter::GetShrunkenRangeStart(
const HTMLEditor& aHTMLEditor, const EditorDOMRange& aRange,
const nsINode& aCommonAncestorOfRange,
const nsIContent* aFirstEntirelySelectedContentNodeInRange) const {
const EditorDOMPoint& startRef = aRange.StartRef();
// <a> cannot be nested and it should be represented with one element as far
// as possible. Therefore, we don't need to shrink the range.
if (IsStyleOfAnchorElement()) {
return startRef.To<EditorRawDOMPoint>();
}
// If the start boundary is at end of a node, we need to shrink the range
// to next content, e.g., `abc[<b>def` should be `abc<b>[def` unless the
// <b> is not entirely selected.
auto* const nextContentOrStartContainer = [&]() -> nsIContent* {
if (!startRef.IsInContentNode()) {
return nullptr;
}
if (!startRef.IsEndOfContainer()) {
return startRef.ContainerAs<nsIContent>();
}
nsIContent* const nextContent =
AutoInlineStyleSetter::GetNextEditableInlineContent(
*startRef.ContainerAs<nsIContent>(), &aCommonAncestorOfRange);
return nextContent ? nextContent : startRef.ContainerAs<nsIContent>();
}();
if (MOZ_UNLIKELY(!nextContentOrStartContainer)) {
return startRef.To<EditorRawDOMPoint>();
}
EditorRawDOMPoint startPoint =
nextContentOrStartContainer != startRef.ContainerAs<nsIContent>()
? EditorRawDOMPoint(nextContentOrStartContainer)
: startRef.To<EditorRawDOMPoint>();
MOZ_ASSERT(startPoint.IsSet());
// If the start point points a content node, let's try to move it down to
// start of the child recursively.
while (nsIContent* child = startPoint.GetChild()) {
// We shouldn't cross editable and block boundary.
if (!EditorUtils::IsEditableContent(*child, EditorType::HTML) ||
HTMLEditUtils::IsBlockElement(
*child, BlockInlineCheck::UseComputedDisplayOutsideStyle)) {
break;
}
// If we reach a text node, the minimized range starts from start of it.
if (child->IsText()) {
startPoint.Set(child, 0u);
break;
}
// Don't shrink the range into element which applies the style to children
// because we want to update the element. E.g., if we are setting
// background color, we want to update style attribute of an element which
// specifies background color with `style` attribute.
if (child == aFirstEntirelySelectedContentNodeInRange) {
break;
}
// We should not start from an atomic element such as <br>, <img>, etc.
if (!HTMLEditUtils::IsContainerNode(*child)) {
break;
}
// If the element specifies the style, we should update it. Therefore, we
// need to wrap it in the range.
if (ContentIsElementSettingTheStyle(aHTMLEditor, *child)) {
break;
}
// If the child is an `<a>`, we should not shrink the range into it
// because user may not want to keep editing in the link except when user
// tries to update selection into it obviously.
if (child->IsHTMLElement(nsGkAtoms::a)) {
break;
}
startPoint.Set(child, 0u);
}
return startPoint;
}
EditorRawDOMPoint HTMLEditor::AutoInlineStyleSetter::GetShrunkenRangeEnd(
const HTMLEditor& aHTMLEditor, const EditorDOMRange& aRange,
const nsINode& aCommonAncestorOfRange,
const nsIContent* aLastEntirelySelectedContentNodeInRange) const {
const EditorDOMPoint& endRef = aRange.EndRef();
// <a> cannot be nested and it should be represented with one element as far
// as possible. Therefore, we don't need to shrink the range.
if (IsStyleOfAnchorElement()) {
return endRef.To<EditorRawDOMPoint>();
}
// If the end boundary is at start of a node, we need to shrink the range
// to previous content, e.g., `abc</b>]def` should be `abc]</b>def` unless
// the <b> is not entirely selected.
auto* const previousContentOrEndContainer = [&]() -> nsIContent* {
if (!endRef.IsInContentNode()) {
return nullptr;
}
if (!endRef.IsStartOfContainer()) {
return endRef.ContainerAs<nsIContent>();
}
nsIContent* const previousContent =
AutoInlineStyleSetter::GetPreviousEditableInlineContent(
*endRef.ContainerAs<nsIContent>(), &aCommonAncestorOfRange);
return previousContent ? previousContent : endRef.ContainerAs<nsIContent>();
}();
if (MOZ_UNLIKELY(!previousContentOrEndContainer)) {
return endRef.To<EditorRawDOMPoint>();
}
EditorRawDOMPoint endPoint =
previousContentOrEndContainer != endRef.ContainerAs<nsIContent>()
? EditorRawDOMPoint::After(*previousContentOrEndContainer)
: endRef.To<EditorRawDOMPoint>();
MOZ_ASSERT(endPoint.IsSet());
// If the end point points after a content node, let's try to move it down
// to end of the child recursively.
while (nsIContent* child = endPoint.GetPreviousSiblingOfChild()) {
// We shouldn't cross editable and block boundary.
if (!EditorUtils::IsEditableContent(*child, EditorType::HTML) ||
HTMLEditUtils::IsBlockElement(
*child, BlockInlineCheck::UseComputedDisplayOutsideStyle)) {
break;
}
// If we reach a text node, the minimized range starts from start of it.
if (child->IsText()) {
endPoint.SetToEndOf(child);
break;
}
// Don't shrink the range into element which applies the style to children
// because we want to update the element. E.g., if we are setting
// background color, we want to update style attribute of an element which
// specifies background color with `style` attribute.
if (child == aLastEntirelySelectedContentNodeInRange) {
break;
}
// We should not end in an atomic element such as <br>, <img>, etc.
if (!HTMLEditUtils::IsContainerNode(*child)) {
break;
}
// If the element specifies the style, we should update it. Therefore, we
// need to wrap it in the range.
if (ContentIsElementSettingTheStyle(aHTMLEditor, *child)) {
break;
}
// If the child is an `<a>`, we should not shrink the range into it
// because user may not want to keep editing in the link except when user
// tries to update selection into it obviously.
if (child->IsHTMLElement(nsGkAtoms::a)) {
break;
}
endPoint.SetToEndOf(child);
}
return endPoint;
}
EditorRawDOMPoint HTMLEditor::AutoInlineStyleSetter::
GetExtendedRangeStartToWrapAncestorApplyingSameStyle(
const HTMLEditor& aHTMLEditor,
const EditorRawDOMPoint& aStartPoint) const {
MOZ_ASSERT(aStartPoint.IsSetAndValid());
EditorRawDOMPoint startPoint = aStartPoint;
// FIXME: This should handle ignore invisible white-spaces before the position
// if it's in a text node or invisible white-spaces.
if (!startPoint.IsStartOfContainer() ||
startPoint.GetContainer()->GetPreviousSibling()) {
return startPoint;
}
// FYI: Currently, we don't support setting `font-size` even in the CSS mode.
// Therefore, if the style is <font size="...">, we always set a <font>.
const bool isSettingFontElement =
IsStyleOfFontSize() ||
(!aHTMLEditor.IsCSSEnabled() && IsStyleOfFontElement());
Element* mostDistantStartParentHavingStyle = nullptr;
for (Element* parent :
startPoint.GetContainer()->InclusiveAncestorsOfType<Element>()) {
if (!EditorUtils::IsEditableContent(*parent, EditorType::HTML) ||
HTMLEditUtils::IsBlockElement(
*parent, BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
HTMLEditUtils::IsDisplayInsideFlowRoot(*parent)) {
break;
}
if (ContentIsElementSettingTheStyle(aHTMLEditor, *parent)) {
mostDistantStartParentHavingStyle = parent;
}
// If we're setting <font> element and there is a <font> element which is
// entirely selected, we should use it.
else if (isSettingFontElement && parent->IsHTMLElement(nsGkAtoms::font)) {
mostDistantStartParentHavingStyle = parent;
}
if (parent->GetPreviousSibling()) {
break; // The parent is not first element in its parent, stop climbing.
}
}
if (mostDistantStartParentHavingStyle) {
startPoint.Set(mostDistantStartParentHavingStyle);
}
return startPoint;
}
EditorRawDOMPoint HTMLEditor::AutoInlineStyleSetter::
GetExtendedRangeEndToWrapAncestorApplyingSameStyle(
const HTMLEditor& aHTMLEditor,
const EditorRawDOMPoint& aEndPoint) const {
MOZ_ASSERT(aEndPoint.IsSetAndValid());
EditorRawDOMPoint endPoint = aEndPoint;
// FIXME: This should ignore invisible white-spaces after the position if it's
// in a text node, invisible <br> or following invisible text nodes.
if (!endPoint.IsEndOfContainer() ||
endPoint.GetContainer()->GetNextSibling()) {
return endPoint;
}
// FYI: Currently, we don't support setting `font-size` even in the CSS mode.
// Therefore, if the style is <font size="...">, we always set a <font>.
const bool isSettingFontElement =
IsStyleOfFontSize() ||
(!aHTMLEditor.IsCSSEnabled() && IsStyleOfFontElement());
Element* mostDistantEndParentHavingStyle = nullptr;
for (Element* parent :
endPoint.GetContainer()->InclusiveAncestorsOfType<Element>()) {
if (!EditorUtils::IsEditableContent(*parent, EditorType::HTML) ||
HTMLEditUtils::IsBlockElement(
*parent, BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
HTMLEditUtils::IsDisplayInsideFlowRoot(*parent)) {
break;
}
if (ContentIsElementSettingTheStyle(aHTMLEditor, *parent)) {
mostDistantEndParentHavingStyle = parent;
}
// If we're setting <font> element and there is a <font> element which is
// entirely selected, we should use it.
else if (isSettingFontElement && parent->IsHTMLElement(nsGkAtoms::font)) {
mostDistantEndParentHavingStyle = parent;
}
if (parent->GetNextSibling()) {
break; // The parent is not last element in its parent, stop climbing.
}
}
if (mostDistantEndParentHavingStyle) {
endPoint.SetAfter(mostDistantEndParentHavingStyle);
}
return endPoint;
}
EditorRawDOMRange HTMLEditor::AutoInlineStyleSetter::
GetExtendedRangeToMinimizeTheNumberOfNewElements(
const HTMLEditor& aHTMLEditor, const nsINode& aCommonAncestor,
EditorRawDOMPoint&& aStartPoint, EditorRawDOMPoint&& aEndPoint) const {
MOZ_ASSERT(aStartPoint.IsSet());
MOZ_ASSERT(aEndPoint.IsSet());
// For minimizing the number of new elements, we should extend the range as
// far as possible. E.g., `<span>[abc</span> <span>def]</span>` should be
// styled as `<b><span>abc</span> <span>def</span></b>`.
// Similarly, if the range crosses a block boundary, we should do same thing.
// I.e., `<p><span>[abc</span></p><p><span>def]</span></p>` should become
// `<p><b><span>abc</span></b></p><p><b><span>def</span></b></p>`.
if (aStartPoint.GetContainer() != aEndPoint.GetContainer()) {
while (aStartPoint.GetContainer() != &aCommonAncestor &&
aStartPoint.IsInContentNode() && aStartPoint.GetContainerParent() &&
aStartPoint.IsStartOfContainer()) {
if (!EditorUtils::IsEditableContent(
*aStartPoint.ContainerAs<nsIContent>(), EditorType::HTML) ||
(aStartPoint.ContainerAs<nsIContent>()->IsElement() &&
(HTMLEditUtils::IsBlockElement(
*aStartPoint.ContainerAs<Element>(),
BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
HTMLEditUtils::IsDisplayInsideFlowRoot(
*aStartPoint.ContainerAs<Element>())))) {
break;
}
aStartPoint = aStartPoint.ParentPoint();
}
while (aEndPoint.GetContainer() != &aCommonAncestor &&
aEndPoint.IsInContentNode() && aEndPoint.GetContainerParent() &&
aEndPoint.IsEndOfContainer()) {
if (!EditorUtils::IsEditableContent(*aEndPoint.ContainerAs<nsIContent>(),
EditorType::HTML) ||
(aEndPoint.ContainerAs<nsIContent>()->IsElement() &&
(HTMLEditUtils::IsBlockElement(
*aEndPoint.ContainerAs<Element>(),
BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
HTMLEditUtils::IsDisplayInsideFlowRoot(
*aEndPoint.ContainerAs<Element>())))) {
break;
}
aEndPoint.SetAfter(aEndPoint.ContainerAs<nsIContent>());
}
}
// Additionally, if we'll set a CSS style, we want to wrap elements which
// should have the new style into the range to avoid creating new <span>
// element.
if (!IsRepresentableWithHTML() ||
(aHTMLEditor.IsCSSEnabled() && IsCSSSettable(*nsGkAtoms::span))) {
// First, if pointing in a text node, use parent point.
if (aStartPoint.IsInContentNode() && aStartPoint.IsStartOfContainer() &&
aStartPoint.GetContainerParentAs<nsIContent>() &&
EditorUtils::IsEditableContent(
*aStartPoint.ContainerParentAs<nsIContent>(), EditorType::HTML) &&
(!aStartPoint.GetContainerAs<Element>() ||
!HTMLEditUtils::IsContainerNode(
*aStartPoint.ContainerAs<nsIContent>())) &&
EditorUtils::IsEditableContent(*aStartPoint.ContainerAs<nsIContent>(),
EditorType::HTML)) {
aStartPoint = aStartPoint.ParentPoint();
MOZ_ASSERT(aStartPoint.IsSet());
}
if (aEndPoint.IsInContentNode() && aEndPoint.IsEndOfContainer() &&
aEndPoint.GetContainerParentAs<nsIContent>() &&
EditorUtils::IsEditableContent(
*aEndPoint.ContainerParentAs<nsIContent>(), EditorType::HTML) &&
(!aEndPoint.GetContainerAs<Element>() ||
!HTMLEditUtils::IsContainerNode(
*aEndPoint.ContainerAs<nsIContent>())) &&
EditorUtils::IsEditableContent(*aEndPoint.ContainerAs<nsIContent>(),
EditorType::HTML)) {
aEndPoint.SetAfter(aEndPoint.GetContainer());
MOZ_ASSERT(aEndPoint.IsSet());
}
// Then, wrap the container if it's a good element to set a CSS property.
if (aStartPoint.IsInContentNode() && aStartPoint.GetContainerParent() &&
// The point must be start of the container
aStartPoint.IsStartOfContainer() &&
// only if the pointing first child node cannot have `style` attribute
(!aStartPoint.GetChildAs<nsStyledElement>() ||
!ElementIsGoodContainerToSetStyle(
*aStartPoint.ChildAs<nsStyledElement>())) &&
// but don't cross block boundary at climbing up the tree
!HTMLEditUtils::IsBlockElement(
*aStartPoint.ContainerAs<nsIContent>(),
BlockInlineCheck::UseComputedDisplayOutsideStyle) &&
// and the container is a good editable element to set CSS style
aStartPoint.GetContainerAs<nsStyledElement>() &&
ElementIsGoodContainerToSetStyle(
*aStartPoint.ContainerAs<nsStyledElement>())) {
aStartPoint = aStartPoint.ParentPoint();
MOZ_ASSERT(aStartPoint.IsSet());
}
if (aEndPoint.IsInContentNode() && aEndPoint.GetContainerParent() &&
// The point must be end of the container
aEndPoint.IsEndOfContainer() &&
// only if the pointing last child node cannot have `style` attribute
(aEndPoint.IsStartOfContainer() ||
!aEndPoint.GetPreviousSiblingOfChildAs<nsStyledElement>() ||
!ElementIsGoodContainerToSetStyle(
*aEndPoint.GetPreviousSiblingOfChildAs<nsStyledElement>())) &&
// but don't cross block boundary at climbing up the tree
!HTMLEditUtils::IsBlockElement(
*aEndPoint.ContainerAs<nsIContent>(),
BlockInlineCheck::UseComputedDisplayOutsideStyle) &&
// and the container is a good editable element to set CSS style
aEndPoint.GetContainerAs<nsStyledElement>() &&
ElementIsGoodContainerToSetStyle(
*aEndPoint.ContainerAs<nsStyledElement>())) {
aEndPoint.SetAfter(aEndPoint.GetContainer());
MOZ_ASSERT(aEndPoint.IsSet());
}
}
return EditorRawDOMRange(std::move(aStartPoint), std::move(aEndPoint));
}
Result<EditorRawDOMRange, nsresult>
HTMLEditor::AutoInlineStyleSetter::ExtendOrShrinkRangeToApplyTheStyle(
const HTMLEditor& aHTMLEditor, const EditorDOMRange& aRange) const {
if (NS_WARN_IF(!aRange.IsPositioned())) {
return Err(NS_ERROR_FAILURE);
}
// For avoiding assertion hits in the utility methods, check whether the
// range is in same subtree, first. Even if the range crosses a subtree
// boundary, it's not a bug of this module.
nsINode* commonAncestor = aRange.GetClosestCommonInclusiveAncestor();
if (NS_WARN_IF(!commonAncestor)) {
return Err(NS_ERROR_FAILURE);
}
// If the range does not select only invisible <br> element, let's extend the
// range to contain the <br> element.
EditorDOMRange range(aRange);
if (range.EndRef().IsInContentNode()) {
const WSScanResult nextContentData =
WSRunScanner::ScanInclusiveNextVisibleNodeOrBlockBoundary(
{WSRunScanner::Option::OnlyEditableNodes}, range.EndRef());
if (nextContentData.ReachedInvisibleBRElement() &&
nextContentData.BRElementPtr()->GetParentElement() &&
HTMLEditUtils::IsInlineContent(
*nextContentData.BRElementPtr()->GetParentElement(),
BlockInlineCheck::UseComputedDisplayOutsideStyle)) {
range.SetEnd(EditorDOMPoint::After(*nextContentData.BRElementPtr()));
MOZ_ASSERT(range.EndRef().IsSet());
commonAncestor = range.GetClosestCommonInclusiveAncestor();
if (NS_WARN_IF(!commonAncestor)) {
return Err(NS_ERROR_FAILURE);
}
}
}
// If the range is collapsed, we don't want to replace ancestors unless it's
// in an empty element.
if (range.Collapsed() && range.StartRef().GetContainer()->Length()) {
return EditorRawDOMRange(range);
}
// First, shrink the given range to minimize new style applied contents.
// However, we should not shrink the range into entirely selected element.
// E.g., if `abc[<i>def</i>]ghi`, shouldn't shrink it as
// `abc<i>[def]</i>ghi`.
EditorRawDOMPoint startPoint, endPoint;
if (range.Collapsed()) {
startPoint = endPoint = range.StartRef().To<EditorRawDOMPoint>();
} else {
ContentSubtreeIterator iter;
if (NS_FAILED(iter.Init(range.StartRef().ToRawRangeBoundary(),
range.EndRef().ToRawRangeBoundary()))) {
NS_WARNING("ContentSubtreeIterator::Init() failed");
return Err(NS_ERROR_FAILURE);
}
nsIContent* const firstContentEntirelyInRange =
nsIContent::FromNodeOrNull(iter.GetCurrentNode());
nsIContent* const lastContentEntirelyInRange = [&]() {
iter.Last();
return nsIContent::FromNodeOrNull(iter.GetCurrentNode());
}();
// Compute the shrunken range boundaries.
startPoint = GetShrunkenRangeStart(aHTMLEditor, range, *commonAncestor,
firstContentEntirelyInRange);
MOZ_ASSERT(startPoint.IsSet());
endPoint = GetShrunkenRangeEnd(aHTMLEditor, range, *commonAncestor,
lastContentEntirelyInRange);
MOZ_ASSERT(endPoint.IsSet());
// If shrunken range is swapped, it could like this case:
// `abc[</span><span>]def`, starts at very end of a node and ends at
// very start of immediately next node. In this case, we should use
// the original range instead.
if (MOZ_UNLIKELY(!startPoint.EqualsOrIsBefore(endPoint))) {
startPoint = range.StartRef().To<EditorRawDOMPoint>();
endPoint = range.EndRef().To<EditorRawDOMPoint>();
}
}
// Then, we may need to extend the range to wrap parent inline elements
// which specify same style since we need to remove same style elements to
// apply new value. E.g., abc
// <span style="background-color: red">
// <span style="background-color: blue">[def]</span>
// </span>
// ghi
// In this case, we need to wrap the other <span> element if setting
// background color. Then, the inner <span> element is removed and the
// other <span> element's style attribute will be updated rather than
// inserting new <span> element.
startPoint = GetExtendedRangeStartToWrapAncestorApplyingSameStyle(aHTMLEditor,
startPoint);
MOZ_ASSERT(startPoint.IsSet());
endPoint =
GetExtendedRangeEndToWrapAncestorApplyingSameStyle(aHTMLEditor, endPoint);
MOZ_ASSERT(endPoint.IsSet());
// Finally, we need to extend the range unless the range is in an element to
// reduce the number of creating new elements. E.g., if now selects
// `<span>[abc</span><span>def]</span>`, we should make it
// `<b><span>abc</span><span>def</span></b>` rather than
// `<span><b>abc</b></span><span><b>def</b></span>`.
EditorRawDOMRange finalRange =
GetExtendedRangeToMinimizeTheNumberOfNewElements(
aHTMLEditor, *commonAncestor, std::move(startPoint),
std::move(endPoint));
#if 0
fprintf(stderr,
"ExtendOrShrinkRangeToApplyTheStyle:\n"
" Result: {(\n %s\n ) - (\n %s\n )},\n"
" Input: {(\n %s\n ) - (\n %s\n )}\n",
ToString(finalRange.StartRef()).c_str(),
ToString(finalRange.EndRef()).c_str(),
ToString(aRange.StartRef()).c_str(),
ToString(aRange.EndRef()).c_str());
#endif
return finalRange;
}
Result<SplitRangeOffResult, nsresult>
HTMLEditor::SplitAncestorStyledInlineElementsAtRangeEdges(
const EditorDOMRange& aRange, const EditorInlineStyle& aStyle,
SplitAtEdges aSplitAtEdges) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!aRange.IsPositioned())) {
return Err(NS_ERROR_FAILURE);
}
EditorDOMRange range(aRange);
// split any matching style nodes above the start of range
auto resultAtStart =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<SplitNodeResult, nsresult> {
AutoTrackDOMRange tracker(RangeUpdaterRef(), &range);
Result<SplitNodeResult, nsresult> result =
SplitAncestorStyledInlineElementsAt(range.StartRef(), aStyle,
aSplitAtEdges);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::SplitAncestorStyledInlineElementsAt() failed");
return result;
}
tracker.FlushAndStopTracking();
if (result.inspect().Handled()) {
auto startOfRange = result.inspect().AtSplitPoint<EditorDOMPoint>();
if (!startOfRange.IsSet()) {
result.inspect().IgnoreCaretPointSuggestion();
NS_WARNING(
"HTMLEditor::SplitAncestorStyledInlineElementsAt() didn't return "
"split point");
return Err(NS_ERROR_FAILURE);
}
range.SetStart(std::move(startOfRange));
} else if (MOZ_UNLIKELY(!range.IsPositioned())) {
NS_WARNING(
"HTMLEditor::SplitAncestorStyledInlineElementsAt() caused unexpected "
"DOM tree");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return result;
}();
if (MOZ_UNLIKELY(resultAtStart.isErr())) {
return resultAtStart.propagateErr();
}
SplitNodeResult unwrappedResultAtStart = resultAtStart.unwrap();
// second verse, same as the first...
auto resultAtEnd =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<SplitNodeResult, nsresult> {
AutoTrackDOMRange tracker(RangeUpdaterRef(), &range);
Result<SplitNodeResult, nsresult> result =
SplitAncestorStyledInlineElementsAt(range.EndRef(), aStyle,
aSplitAtEdges);
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::SplitAncestorStyledInlineElementsAt() failed");
return result;
}
tracker.FlushAndStopTracking();
if (result.inspect().Handled()) {
auto endOfRange = result.inspect().AtSplitPoint<EditorDOMPoint>();
if (!endOfRange.IsSet()) {
result.inspect().IgnoreCaretPointSuggestion();
NS_WARNING(
"HTMLEditor::SplitAncestorStyledInlineElementsAt() didn't return "
"split point");
return Err(NS_ERROR_FAILURE);
}
range.SetEnd(std::move(endOfRange));
} else if (MOZ_UNLIKELY(!range.IsPositioned())) {
NS_WARNING(
"HTMLEditor::SplitAncestorStyledInlineElementsAt() caused unexpected "
"DOM tree");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
return result;
}();
if (MOZ_UNLIKELY(resultAtEnd.isErr())) {
unwrappedResultAtStart.IgnoreCaretPointSuggestion();
return resultAtEnd.propagateErr();
}
return SplitRangeOffResult(std::move(range),
std::move(unwrappedResultAtStart),
resultAtEnd.unwrap());
}
Result<SplitNodeResult, nsresult>
HTMLEditor::SplitAncestorStyledInlineElementsAt(
const EditorDOMPoint& aPointToSplit, const EditorInlineStyle& aStyle,
SplitAtEdges aSplitAtEdges) {
// If the point is in a non-content node, e.g., in the document node, we
// should split nothing.
if (MOZ_UNLIKELY(!aPointToSplit.IsInContentNode())) {
return SplitNodeResult::NotHandled(aPointToSplit);
}
// We assume that this method is called only when we're removing style(s).
// Even if we're in HTML mode and there is no presentation element in the
// block, we may need to overwrite the block's style with `<span>` element
// and CSS. For example, `<h1>` element has `font-weight: bold;` as its
// default style. If `Document.execCommand("bold")` is called for its
// text, we should make it unbold. Therefore, we shouldn't check
// IsCSSEnabled() in most cases. However, there is an exception.
// FontFaceStateCommand::SetState() calls RemoveInlinePropertyAsAction()
// with nsGkAtoms::tt before calling SetInlinePropertyAsAction() if we
// are handling a XUL command. Only in that case, we need to check
// IsCSSEnabled().
const bool handleCSS =
aStyle.mHTMLProperty != nsGkAtoms::tt || IsCSSEnabled();
AutoTArray<OwningNonNull<Element>, 24> arrayOfParents;
for (Element* element :
aPointToSplit.GetContainer()->InclusiveAncestorsOfType<Element>()) {
if (element->IsAnyOfHTMLElements(nsGkAtoms::body, nsGkAtoms::head,
nsGkAtoms::html) ||
HTMLEditUtils::IsBlockElement(
*element, BlockInlineCheck::UseComputedDisplayOutsideStyle) ||
!element->GetParent() ||
!EditorUtils::IsEditableContent(*element->GetParent(),
EditorType::HTML) ||
NS_WARN_IF(!HTMLEditUtils::IsSplittableNode(*element))) {
break;
}
arrayOfParents.AppendElement(*element);
}
// Split any matching style nodes above the point.
SplitNodeResult result = SplitNodeResult::NotHandled(aPointToSplit);
MOZ_ASSERT(!result.Handled());
EditorDOMPoint pointToPutCaret;
for (const OwningNonNull<Element>& element : arrayOfParents) {
auto isSetByCSSOrError = [&]() -> Result<bool, nsresult> {
if (!handleCSS) {
return false;
}
// The HTML style defined by aStyle has a CSS equivalence in this
// implementation for the node; let's check if it carries those CSS
// styles
if (aStyle.IsCSSRemovable(*element)) {
nsAutoString firstValue;
Result<bool, nsresult> isSpecifiedByCSSOrError =
CSSEditUtils::IsSpecifiedCSSEquivalentTo(*this, *element, aStyle,
firstValue);
if (MOZ_UNLIKELY(isSpecifiedByCSSOrError.isErr())) {
result.IgnoreCaretPointSuggestion();
NS_WARNING("CSSEditUtils::IsSpecifiedCSSEquivalentTo() failed");
return isSpecifiedByCSSOrError;
}
if (isSpecifiedByCSSOrError.unwrap()) {
return true;
}
}
// If this is <sub> or <sup>, we won't use vertical-align CSS property
// because <sub>/<sup> changes font size but neither `vertical-align:
// sub` nor `vertical-align: super` changes it (bug 394304 comment 2).
// Therefore, they are not equivalents. However, they're obviously
// conflict with vertical-align style. Thus, we need to remove ancestor
// elements having vertical-align style.
if (aStyle.IsStyleConflictingWithVerticalAlign()) {
nsAutoString value;
nsresult rv = CSSEditUtils::GetSpecifiedProperty(
*element, *nsGkAtoms::vertical_align, value);
if (NS_FAILED(rv)) {
NS_WARNING("CSSEditUtils::GetSpecifiedProperty() failed");
result.IgnoreCaretPointSuggestion();
return Err(rv);
}
if (!value.IsEmpty()) {
return true;
}
}
return false;
}();
if (MOZ_UNLIKELY(isSetByCSSOrError.isErr())) {
return isSetByCSSOrError.propagateErr();
}
if (!isSetByCSSOrError.inspect()) {
if (!aStyle.IsStyleToClearAllInlineStyles()) {
// If we're removing a link style and the element is an <a href>, we
// need to split it.
if (aStyle.mHTMLProperty == nsGkAtoms::href &&
HTMLEditUtils::IsHyperlinkElement(element)) {
}
// If we're removing HTML style, we should split only the element
// which represents the style.
else if (!element->IsHTMLElement(aStyle.mHTMLProperty) ||
(aStyle.mAttribute && !element->HasAttr(aStyle.mAttribute))) {
continue;
}
// If we're setting <font> related styles, it means that we're not
// toggling the style. In this case, we need to remove parent <font>
// elements and/or update parent <font> elements if there are some
// elements which have the attribute. However, we should not touch if
// the value is same as what the caller setting to keep the DOM tree
// as-is as far as possible.
if (aStyle.IsStyleOfFontElement() && aStyle.MaybeHasValue()) {
const nsAttrValue* const attrValue =
element->GetParsedAttr(aStyle.mAttribute);
if (attrValue) {
if (aStyle.mAttribute == nsGkAtoms::size) {
if (attrValue->Type() == nsAttrValue::eInteger &&
nsContentUtils::ParseLegacyFontSize(
aStyle.AsInlineStyleAndValue().mAttributeValue) ==
attrValue->GetIntegerValue()) {
continue;
}
} else if (aStyle.mAttribute == nsGkAtoms::color) {
nsAttrValue newValue;
nscolor oldColor, newColor;
if (attrValue->Type() == nsAttrValue::eColor &&
attrValue->GetColorValue(oldColor) &&
newValue.ParseColor(
aStyle.AsInlineStyleAndValue().mAttributeValue) &&
newValue.GetColorValue(newColor) && oldColor == newColor) {
continue;
}
} else if (attrValue->Equals(
aStyle.AsInlineStyleAndValue().mAttributeValue,
eIgnoreCase)) {
continue;
}
}
}
}
// If aProperty is nullptr, we need to split any style.
else if (!EditorUtils::IsEditableContent(element, EditorType::HTML) ||
!HTMLEditUtils::IsRemovableInlineStyleElement(*element)) {
continue;
}
}
// Found a style node we need to split.
// XXX If first content is a text node and CSS is enabled, we call this
// with text node but in such case, this does nothing, but returns
// as handled with setting only previous or next node. If its parent
// is a block, we do nothing but return as handled.
AutoTrackDOMPoint trackPointToPutCaret(RangeUpdaterRef(), &pointToPutCaret);
Result<SplitNodeResult, nsresult> splitNodeResult =
SplitNodeDeepWithTransaction(MOZ_KnownLive(element),
result.AtSplitPoint<EditorDOMPoint>(),
aSplitAtEdges);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitNodeResult;
}
SplitNodeResult unwrappedSplitNodeResult = splitNodeResult.unwrap();
trackPointToPutCaret.FlushAndStopTracking();
unwrappedSplitNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
// If it's not handled, it means that `content` is not a splittable node
// like a void element even if it has some children, and the split point
// is middle of it.
if (!unwrappedSplitNodeResult.Handled()) {
continue;
}
// Respect the last split result which actually did it.
if (!result.DidSplit() || unwrappedSplitNodeResult.DidSplit()) {
result = unwrappedSplitNodeResult.ToHandledResult();
}
MOZ_ASSERT(result.Handled());
}
return pointToPutCaret.IsSet()
? SplitNodeResult(std::move(result), std::move(pointToPutCaret))
: std::move(result);
}
Result<EditorDOMPoint, nsresult> HTMLEditor::ClearStyleAt(
const EditorDOMPoint& aPoint, const EditorInlineStyle& aStyleToRemove,
SpecifiedStyle aSpecifiedStyle, const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!aPoint.IsSet())) {
return Err(NS_ERROR_INVALID_ARG);
}
// TODO: We should rewrite this to stop unnecessary element creation and
// deleting it later because it causes the original element may be
// removed from the DOM tree even if same element is still in the
// DOM tree from point of view of users.
// First, split inline elements at the point.
// E.g., if aStyleToRemove.mHTMLProperty is nsGkAtoms::b and
// `<p><b><i>a[]bc</i></b></p>`, we want to make it as
// `<p><b><i>a</i></b><b><i>bc</i></b></p>`.
EditorDOMPoint pointToPutCaret(aPoint);
AutoTrackDOMPoint trackPointToPutCaret(RangeUpdaterRef(), &pointToPutCaret);
Result<SplitNodeResult, nsresult> splitNodeResult =
SplitAncestorStyledInlineElementsAt(
aPoint, aStyleToRemove, SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SplitAncestorStyledInlineElementsAt() failed");
return splitNodeResult.propagateErr();
}
trackPointToPutCaret.FlushAndStopTracking();
SplitNodeResult unwrappedSplitNodeResult = splitNodeResult.unwrap();
unwrappedSplitNodeResult.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
// If there is no styled inline elements of aStyleToRemove, we just return the
// given point.
// E.g., `<p><i>a[]bc</i></p>` for nsGkAtoms::b.
if (!unwrappedSplitNodeResult.Handled()) {
return pointToPutCaret;
}
// If it did split nodes, but topmost ancestor inline element is split
// at start of it, we don't need the empty inline element. Let's remove
// it now. Then, we'll get the following DOM tree if there is no "a" in the
// above case:
// <p><b><i>bc</i></b></p>
// ^^
if (unwrappedSplitNodeResult.GetPreviousContent() &&
HTMLEditUtils::IsEmptyNode(
*unwrappedSplitNodeResult.GetPreviousContent(),
{EmptyCheckOption::TreatSingleBRElementAsVisible,
EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible})) {
AutoTrackDOMPoint trackPointToPutCaret(RangeUpdaterRef(), &pointToPutCaret);
// Delete previous node if it's empty.
// MOZ_KnownLive(unwrappedSplitNodeResult.GetPreviousContent()):
// It's grabbed by unwrappedSplitNodeResult.
nsresult rv = DeleteNodeWithTransaction(
MOZ_KnownLive(*unwrappedSplitNodeResult.GetPreviousContent()));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
// If we reached block from end of a text node, we can do nothing here.
// E.g., `<p style="font-weight: bold;">a[]bc</p>` for nsGkAtoms::b and
// we're in CSS mode.
// XXX Chrome resets block style and creates `<span>` elements for each
// line in this case.
if (!unwrappedSplitNodeResult.GetNextContent()) {
return pointToPutCaret;
}
// Otherwise, the next node is topmost ancestor inline element which has
// the style. We want to put caret between the split nodes, but we need
// to keep other styles. Therefore, next, we need to split at start of
// the next node. The first example should become
// `<p><b><i>a</i></b><b><i></i></b><b><i>bc</i></b></p>`.
// ^^^^^^^^^^^^^^
nsIContent* firstLeafChildOfNextNode = HTMLEditUtils::GetFirstLeafContent(
*unwrappedSplitNodeResult.GetNextContent(), {LeafNodeType::OnlyLeafNode});
EditorDOMPoint atStartOfNextNode(
firstLeafChildOfNextNode ? firstLeafChildOfNextNode
: unwrappedSplitNodeResult.GetNextContent(),
0);
Maybe<EditorLineBreak> lineBreak;
// But don't try to split non-containers like `<br>`, `<hr>` and `<img>`
// element.
if (!atStartOfNextNode.IsInContentNode() ||
!HTMLEditUtils::IsContainerNode(
*atStartOfNextNode.ContainerAs<nsIContent>())) {
// If it's a `<br>` element, let's move it into new node later.
auto* const brElement =
HTMLBRElement::FromNode(atStartOfNextNode.GetContainer());
if (brElement) {
lineBreak.emplace(*brElement);
}
if (!atStartOfNextNode.GetContainerParentAs<nsIContent>()) {
NS_WARNING("atStartOfNextNode was in an orphan node");
return Err(NS_ERROR_FAILURE);
}
atStartOfNextNode.Set(atStartOfNextNode.GetContainerParent(), 0);
}
AutoTrackDOMPoint trackPointToPutCaret2(RangeUpdaterRef(), &pointToPutCaret);
Result<SplitNodeResult, nsresult> splitResultAtStartOfNextNode =
SplitAncestorStyledInlineElementsAt(
atStartOfNextNode, aStyleToRemove,
SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitResultAtStartOfNextNode.isErr())) {
NS_WARNING("HTMLEditor::SplitAncestorStyledInlineElementsAt() failed");
return splitResultAtStartOfNextNode.propagateErr();
}
trackPointToPutCaret2.FlushAndStopTracking();
SplitNodeResult unwrappedSplitResultAtStartOfNextNode =
splitResultAtStartOfNextNode.unwrap();
unwrappedSplitResultAtStartOfNextNode.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (unwrappedSplitResultAtStartOfNextNode.Handled() &&
unwrappedSplitResultAtStartOfNextNode.GetNextContent()) {
// If the right inline elements are empty, we should remove them. E.g.,
// if the split point is at end of a text node (or end of an inline
// element), e.g., <div><b><i>abc[]</i></b></div>, then now, it's been
// changed to:
// <div><b><i>abc</i></b><b><i>[]</i></b><b><i></i></b></div>
// ^^^^^^^^^^^^^^
// We will change it to:
// <div><b><i>abc</i></b><b><i>[]</i></b></div>
// ^^
// And if it has only padding <br> element, we should move it into the
// previous <i> which will have new content.
bool seenBR = false;
if (HTMLEditUtils::IsEmptyNode(
*unwrappedSplitResultAtStartOfNextNode.GetNextContent(),
{EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible},
&seenBR)) {
// MOZ_KnownLive because of grabbed by
// unwrappedSplitResultAtStartOfNextNode.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(
*unwrappedSplitResultAtStartOfNextNode.GetNextContent()));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
}
if (!unwrappedSplitResultAtStartOfNextNode.Handled()) {
return std::move(pointToPutCaret);
}
// If there is no content, we should return here.
// XXX Is this possible case without mutation event listener?
if (!unwrappedSplitResultAtStartOfNextNode.GetPreviousContent()) {
// XXX This is really odd, but we return this value...
const auto splitPoint =
unwrappedSplitNodeResult.AtSplitPoint<EditorRawDOMPoint>();
const auto splitPointAtStartOfNextNode =
unwrappedSplitResultAtStartOfNextNode.AtSplitPoint<EditorRawDOMPoint>();
return EditorDOMPoint(splitPoint.GetContainer(),
splitPointAtStartOfNextNode.Offset());
}
// Now, we want to put `<br>` element into the empty split node if
// it was in next node of the first split.
// E.g., `<p><b><i>a</i></b><b><i><br></i></b><b><i>bc</i></b></p>`
nsIContent* firstLeafChildOfPreviousNode = HTMLEditUtils::GetFirstLeafContent(
*unwrappedSplitResultAtStartOfNextNode.GetPreviousContent(),
{LeafNodeType::OnlyLeafNode});
pointToPutCaret.Set(
firstLeafChildOfPreviousNode
? firstLeafChildOfPreviousNode
: unwrappedSplitResultAtStartOfNextNode.GetPreviousContent(),
0);
// If the right node starts with a line break, suck it out of right node and
// into the left node left node. This is so we you don't revert back to the
// previous style if you happen to click at the end of a line.
if (lineBreak.isSome()) {
if (lineBreak->IsInComposedDoc()) {
Result<EditorDOMPoint, nsresult> lineBreakPointOrError =
DeleteLineBreakWithTransaction(lineBreak.ref(), nsIEditor::eStrip,
aEditingHost);
if (MOZ_UNLIKELY(lineBreakPointOrError.isErr())) {
NS_WARNING("HTMLEditor::DeleteLineBreakWithTransaction() failed");
return lineBreakPointOrError.propagateErr();
}
}
Result<CreateLineBreakResult, nsresult> insertBRElementResultOrError =
InsertLineBreak(WithTransaction::Yes, LineBreakType::BRElement,
pointToPutCaret);
if (MOZ_UNLIKELY(insertBRElementResultOrError.isErr())) {
NS_WARNING(
"HTMLEditor::InsertLineBreak(WithTransaction::Yes, "
"LineBreakType::BRElement) failed");
return insertBRElementResultOrError.propagateErr();
}
CreateLineBreakResult insertBRElementResult =
insertBRElementResultOrError.unwrap();
insertBRElementResult.MoveCaretPointTo(
pointToPutCaret, *this,
{SuggestCaret::OnlyIfHasSuggestion,
SuggestCaret::OnlyIfTransactionsAllowedToDoIt});
if (unwrappedSplitResultAtStartOfNextNode.GetNextContent() &&
unwrappedSplitResultAtStartOfNextNode.GetNextContent()
->IsInComposedDoc()) {
// If we split inline elements at immediately before <br> element which is
// the last visible content in the right element, we don't need the right
// element anymore. Otherwise, we'll create the following DOM tree:
// - <b>abc</b>{}<br><b></b>
// ^^^^^^^
// - <b><i>abc</i></b><i><br></i><b></b>
// ^^^^^^^
if (HTMLEditUtils::IsEmptyNode(
*unwrappedSplitResultAtStartOfNextNode.GetNextContent(),
{EmptyCheckOption::TreatSingleBRElementAsVisible,
EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible})) {
// MOZ_KnownLive because the result is grabbed by
// unwrappedSplitResultAtStartOfNextNode.
nsresult rv = DeleteNodeWithTransaction(MOZ_KnownLive(
*unwrappedSplitResultAtStartOfNextNode.GetNextContent()));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
// If the next content has only one <br> element, there may be empty
// inline elements around it. We don't need them anymore because user
// cannot put caret into them. E.g., <b><i>abc[]<br></i><br></b> has
// been changed to <b><i>abc</i></b><i>{}<br></i><b><i></i><br></b> now.
// ^^^^^^^^^^^^^^^^^^
// We don't need the empty <i>.
else if (HTMLEditUtils::IsEmptyNode(
*unwrappedSplitResultAtStartOfNextNode.GetNextContent(),
{EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible})) {
AutoTArray<OwningNonNull<nsIContent>, 4> emptyInlineContainerElements;
HTMLEditUtils::CollectEmptyInlineContainerDescendants(
*unwrappedSplitResultAtStartOfNextNode.GetNextContentAs<Element>(),
emptyInlineContainerElements,
{EmptyCheckOption::TreatSingleBRElementAsVisible,
EmptyCheckOption::TreatListItemAsVisible,
EmptyCheckOption::TreatTableCellAsVisible},
BlockInlineCheck::UseComputedDisplayOutsideStyle);
for (const OwningNonNull<nsIContent>& emptyInlineContainerElement :
emptyInlineContainerElements) {
// MOZ_KnownLive(emptyInlineContainerElement) due to bug 1622253.
nsresult rv = DeleteNodeWithTransaction(
MOZ_KnownLive(emptyInlineContainerElement));
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::DeleteNodeWithTransaction() failed");
return Err(rv);
}
}
}
}
// Update the child.
pointToPutCaret.Set(pointToPutCaret.GetContainer(), 0);
}
// Finally, remove the specified style in the previous node at the
// second split and tells good insertion point to the caller. I.e., we
// want to make the first example as:
// `<p><b><i>a</i></b><i>[]</i><b><i>bc</i></b></p>`
// ^^^^^^^^^
if (auto* const previousElementOfSplitPoint =
unwrappedSplitResultAtStartOfNextNode
.GetPreviousContentAs<Element>()) {
// Track the point at the new hierarchy. This is so we can know where
// to put the selection after we call RemoveStyleInside().
// RemoveStyleInside() could remove any and all of those nodes, so I
// have to use the range tracking system to find the right spot to put
// selection.
AutoTrackDOMPoint tracker(RangeUpdaterRef(), &pointToPutCaret);
// MOZ_KnownLive(previousElementOfSplitPoint):
// It's grabbed by unwrappedSplitResultAtStartOfNextNode.
Result<EditorDOMPoint, nsresult> removeStyleResult =
RemoveStyleInside(MOZ_KnownLive(*previousElementOfSplitPoint),
aStyleToRemove, aSpecifiedStyle);
if (MOZ_UNLIKELY(removeStyleResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveStyleInside() failed");
return removeStyleResult;
}
// We've already computed a suggested caret position at start of first leaf
// which is stored in pointToPutCaret, so we don't need to update it here.
}
return pointToPutCaret;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::RemoveStyleInside(
Element& aElement, const EditorInlineStyle& aStyleToRemove,
SpecifiedStyle aSpecifiedStyle) {
// First, handle all descendants.
AutoTArray<OwningNonNull<nsIContent>, 32> arrayOfChildContents;
HTMLEditUtils::CollectAllChildren(aElement, arrayOfChildContents);
EditorDOMPoint pointToPutCaret;
for (const OwningNonNull<nsIContent>& child : arrayOfChildContents) {
if (!child->IsElement()) {
continue;
}
Result<EditorDOMPoint, nsresult> removeStyleResult = RemoveStyleInside(
MOZ_KnownLive(*child->AsElement()), aStyleToRemove, aSpecifiedStyle);
if (MOZ_UNLIKELY(removeStyleResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveStyleInside() failed");
return removeStyleResult;
}
if (removeStyleResult.inspect().IsSet()) {
pointToPutCaret = removeStyleResult.unwrap();
}
}
// TODO: It seems that if aElement is not editable, we should insert new
// container to remove the style if possible.
if (!EditorUtils::IsEditableContent(aElement, EditorType::HTML)) {
return pointToPutCaret;
}
// Next, remove CSS style first. Then, `style` attribute will be removed if
// the corresponding CSS property is last one.
auto isStyleSpecifiedOrError = [&]() -> Result<bool, nsresult> {
if (!aStyleToRemove.IsCSSRemovable(aElement)) {
return false;
}
MOZ_ASSERT(!aStyleToRemove.IsStyleToClearAllInlineStyles());
Result<bool, nsresult> elementHasSpecifiedCSSEquivalentStylesOrError =
CSSEditUtils::HaveSpecifiedCSSEquivalentStyles(*this, aElement,
aStyleToRemove);
NS_WARNING_ASSERTION(
elementHasSpecifiedCSSEquivalentStylesOrError.isOk(),
"CSSEditUtils::HaveSpecifiedCSSEquivalentStyles() failed");
return elementHasSpecifiedCSSEquivalentStylesOrError;
}();
if (MOZ_UNLIKELY(isStyleSpecifiedOrError.isErr())) {
return isStyleSpecifiedOrError.propagateErr();
}
bool styleSpecified = isStyleSpecifiedOrError.unwrap();
if (nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement)) {
if (styleSpecified) {
// MOZ_KnownLive(*styledElement) because it's an alias of aElement.
nsresult rv = CSSEditUtils::RemoveCSSEquivalentToStyle(
WithTransaction::Yes, *this, MOZ_KnownLive(*styledElement),
aStyleToRemove, nullptr);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return Err(NS_ERROR_EDITOR_DESTROYED);
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"CSSEditUtils::RemoveCSSEquivalentToStyle() failed, but ignored");
}
// If the style is <sub> or <sup>, we won't use vertical-align CSS
// property because <sub>/<sup> changes font size but neither
// `vertical-align: sub` nor `vertical-align: super` changes it
// (bug 394304 comment 2). Therefore, they are not equivalents. However,
// they're obviously conflict with vertical-align style. Thus, we need to
// remove the vertical-align style from elements.
if (aStyleToRemove.IsStyleConflictingWithVerticalAlign()) {
nsAutoString value;
nsresult rv = CSSEditUtils::GetSpecifiedProperty(
aElement, *nsGkAtoms::vertical_align, value);
if (NS_FAILED(rv)) {
NS_WARNING("CSSEditUtils::GetSpecifiedProperty() failed");
return Err(rv);
}
if (!value.IsEmpty()) {
// MOZ_KnownLive(*styledElement) because it's an alias of aElement.
nsresult rv = CSSEditUtils::RemoveCSSPropertyWithTransaction(
*this, MOZ_KnownLive(*styledElement), *nsGkAtoms::vertical_align,
value);
if (NS_FAILED(rv)) {
NS_WARNING("CSSEditUtils::RemoveCSSPropertyWithTransaction() failed");
return Err(rv);
}
styleSpecified = true;
}
}
}
// Then, if we could and should remove or replace aElement, let's do it. Or
// just remove attribute.
const bool isStyleRepresentedByElement =
!aStyleToRemove.IsStyleToClearAllInlineStyles() &&
aStyleToRemove.IsRepresentedBy(aElement);
auto ShouldUpdateDOMTree = [&]() {
// If we're removing any inline styles and aElement is an inline style
// element, we can remove or replace it.
if (aStyleToRemove.IsStyleToClearAllInlineStyles() &&
HTMLEditUtils::IsRemovableInlineStyleElement(aElement)) {
return true;
}
// If we're a specific style and aElement represents it, we can remove or
// replace the element or remove the corresponding attribute.
if (isStyleRepresentedByElement) {
return true;
}
// If we've removed a CSS style from the `style` attribute of aElement, we
// could remove the element.
return aElement.IsHTMLElement(nsGkAtoms::span) && styleSpecified;
};
if (!ShouldUpdateDOMTree()) {
return pointToPutCaret;
}
const bool elementHasNecessaryAttributes = [&]() {
// If we're not removing nor replacing aElement itself, we don't need to
// take care of its `style` and `class` attributes even if aSpecifiedStyle
// is `Discard` because aSpecifiedStyle is not intended to be used in this
// case.
if (!isStyleRepresentedByElement) {
return HTMLEditUtils::ElementHasAttributeExcept(aElement,
*nsGkAtoms::_empty);
}
// If we're removing links, we don't need to keep <a> even if it has some
// specific attributes because it cannot be nested. However, if and only if
// it has `style` attribute and aSpecifiedStyle is not `Discard`, we need to
// replace it with new <span> to keep the style.
if (aStyleToRemove.IsStyleOfAnchorElement()) {
return aSpecifiedStyle == SpecifiedStyle::Preserve &&
(aElement.HasNonEmptyAttr(nsGkAtoms::style) ||
aElement.HasNonEmptyAttr(nsGkAtoms::_class));
}
nsAtom& attrKeepStaying = aStyleToRemove.mAttribute
? *aStyleToRemove.mAttribute
: *nsGkAtoms::_empty;
return aSpecifiedStyle == SpecifiedStyle::Preserve
// If we're try to remove the element but the caller wants to
// preserve the style, check whether aElement has attributes
// except the removing attribute since `style` and `class` should
// keep existing to preserve the style.
? HTMLEditUtils::ElementHasAttributeExcept(aElement,
attrKeepStaying)
// If we're try to remove the element and the caller wants to
// discard the style specified to the element, check whether
// aElement has attributes except the removing attribute, `style`
// and `class` since we don't want to keep these attributes.
: HTMLEditUtils::ElementHasAttributeExcept(
aElement, attrKeepStaying, *nsGkAtoms::style,
*nsGkAtoms::_class);
}();
// If the element is not a <span> and still has some attributes, we should
// replace it with new <span>.
auto ReplaceWithNewSpan = [&]() {
if (aStyleToRemove.IsStyleToClearAllInlineStyles()) {
return false; // Remove it even if it has attributes.
}
if (aElement.IsHTMLElement(nsGkAtoms::span)) {
return false; // Don't replace <span> with new <span>.
}
if (!isStyleRepresentedByElement) {
return false; // Keep non-related element as-is.
}
if (!elementHasNecessaryAttributes) {
return false; // Should remove it instead of replacing it.
}
if (aElement.IsHTMLElement(nsGkAtoms::font)) {
// Replace <font> if it won't have its specific attributes.
return (aStyleToRemove.mHTMLProperty == nsGkAtoms::color ||
!aElement.HasAttr(nsGkAtoms::color)) &&
(aStyleToRemove.mHTMLProperty == nsGkAtoms::face ||
!aElement.HasAttr(nsGkAtoms::face)) &&
(aStyleToRemove.mHTMLProperty == nsGkAtoms::size ||
!aElement.HasAttr(nsGkAtoms::size));
}
// The styled element has only global attributes, let's replace it with new
// <span> with cloning the attributes.
return true;
};
if (ReplaceWithNewSpan()) {
// Before cloning the attribute to new element, let's remove it.
if (aStyleToRemove.mAttribute) {
nsresult rv =
RemoveAttributeWithTransaction(aElement, *aStyleToRemove.mAttribute);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::RemoveAttributeWithTransaction() failed");
return Err(rv);
}
}
if (aSpecifiedStyle == SpecifiedStyle::Discard) {
nsresult rv = RemoveAttributeWithTransaction(aElement, *nsGkAtoms::style);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::RemoveAttributeWithTransaction(nsGkAtoms::style) "
"failed");
return Err(rv);
}
rv = RemoveAttributeWithTransaction(aElement, *nsGkAtoms::_class);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::RemoveAttributeWithTransaction(nsGkAtoms::_class) "
"failed");
return Err(rv);
}
}
// Move `style` attribute and `class` element to span element before
// removing aElement from the tree.
auto replaceWithSpanResult =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<CreateElementResult, nsresult> {
if (!aStyleToRemove.IsStyleOfAnchorElement()) {
return ReplaceContainerAndCloneAttributesWithTransaction(
aElement, *nsGkAtoms::span);
}
nsString styleValue; // Use nsString to avoid copying the buffer at
// setting the attribute.
aElement.GetAttr(nsGkAtoms::style, styleValue);
return ReplaceContainerWithTransaction(aElement, *nsGkAtoms::span,
*nsGkAtoms::style, styleValue);
}();
if (MOZ_UNLIKELY(replaceWithSpanResult.isErr())) {
NS_WARNING(
"HTMLEditor::ReplaceContainerWithTransaction(nsGkAtoms::span) "
"failed");
return replaceWithSpanResult.propagateErr();
}
CreateElementResult unwrappedReplaceWithSpanResult =
replaceWithSpanResult.unwrap();
if (AllowsTransactionsToChangeSelection()) {
unwrappedReplaceWithSpanResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
} else {
unwrappedReplaceWithSpanResult.IgnoreCaretPointSuggestion();
}
return pointToPutCaret;
}
auto RemoveElement = [&]() {
if (aStyleToRemove.IsStyleToClearAllInlineStyles()) {
MOZ_ASSERT(HTMLEditUtils::IsRemovableInlineStyleElement(aElement));
return true;
}
// If the element still has some attributes, we should not remove it to keep
// current presentation and/or semantics.
if (elementHasNecessaryAttributes) {
return false;
}
// If the style is represented by the element, let's remove it.
if (isStyleRepresentedByElement) {
return true;
}
// If we've removed a CSS style and that made the <span> element have no
// attributes, we can delete it.
if (styleSpecified && aElement.IsHTMLElement(nsGkAtoms::span)) {
return true;
}
return false;
};
if (RemoveElement()) {
Result<EditorDOMPoint, nsresult> unwrapElementResult =
RemoveContainerWithTransaction(aElement);
if (MOZ_UNLIKELY(unwrapElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveContainerWithTransaction() failed");
return unwrapElementResult.propagateErr();
}
if (AllowsTransactionsToChangeSelection() &&
unwrapElementResult.inspect().IsSet()) {
pointToPutCaret = unwrapElementResult.unwrap();
}
return pointToPutCaret;
}
// If the element needs to keep having some attributes, just remove the
// attribute. Note that we don't need to remove `style` attribute here when
// aSpecifiedStyle is `Discard` because we've already removed unnecessary
// CSS style above.
if (isStyleRepresentedByElement && aStyleToRemove.mAttribute) {
nsresult rv =
RemoveAttributeWithTransaction(aElement, *aStyleToRemove.mAttribute);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::RemoveAttributeWithTransaction() failed");
return Err(rv);
}
}
return pointToPutCaret;
}
EditorRawDOMRange HTMLEditor::GetExtendedRangeWrappingNamedAnchor(
const EditorRawDOMRange& aRange) const {
MOZ_ASSERT(aRange.StartRef().IsSet());
MOZ_ASSERT(aRange.EndRef().IsSet());
// FYI: We don't want to stop at ancestor block boundaries to extend the range
// because <a name> can have block elements with low level DOM API. We want
// to remove any <a name> ancestors to remove the style.
EditorRawDOMRange newRange(aRange);
for (Element* element :
aRange.StartRef().GetContainer()->InclusiveAncestorsOfType<Element>()) {
if (!HTMLEditUtils::IsNamedAnchorElement(*element)) {
continue;
}
newRange.SetStart(EditorRawDOMPoint(element));
}
for (Element* element :
aRange.EndRef().GetContainer()->InclusiveAncestorsOfType<Element>()) {
if (!HTMLEditUtils::IsNamedAnchorElement(*element)) {
continue;
}
newRange.SetEnd(EditorRawDOMPoint::After(*element));
}
return newRange;
}
EditorRawDOMRange HTMLEditor::GetExtendedRangeWrappingEntirelySelectedElements(
const EditorRawDOMRange& aRange) const {
MOZ_ASSERT(aRange.StartRef().IsSet());
MOZ_ASSERT(aRange.EndRef().IsSet());
// FYI: We don't want to stop at ancestor block boundaries to extend the range
// because the style may come from inline parents of block elements which may
// occur in invalid DOM tree. We want to split any (even invalid) ancestors
// at removing the styles.
EditorRawDOMRange newRange(aRange);
while (newRange.StartRef().IsInContentNode() &&
newRange.StartRef().IsStartOfContainer()) {
if (!EditorUtils::IsEditableContent(
*newRange.StartRef().ContainerAs<nsIContent>(), EditorType::HTML)) {
break;
}
newRange.SetStart(newRange.StartRef().ParentPoint());
}
while (newRange.EndRef().IsInContentNode() &&
newRange.EndRef().IsEndOfContainer()) {
if (!EditorUtils::IsEditableContent(
*newRange.EndRef().ContainerAs<nsIContent>(), EditorType::HTML)) {
break;
}
newRange.SetEnd(
EditorRawDOMPoint::After(*newRange.EndRef().ContainerAs<nsIContent>()));
}
return newRange;
}
nsresult HTMLEditor::GetInlinePropertyBase(const EditorInlineStyle& aStyle,
const nsAString* aValue,
bool* aFirst, bool* aAny, bool* aAll,
nsAString* outValue) const {
MOZ_ASSERT(!aStyle.IsStyleToClearAllInlineStyles());
MOZ_ASSERT(IsEditActionDataAvailable());
*aAny = false;
*aAll = true;
*aFirst = false;
bool first = true;
const bool isCollapsed = SelectionRef().IsCollapsed();
RefPtr<nsRange> range = SelectionRef().GetRangeAt(0);
// XXX: Should be a while loop, to get each separate range
// XXX: ERROR_HANDLING can currentItem be null?
if (range) {
// For each range, set a flag
bool firstNodeInRange = true;
if (isCollapsed) {
if (NS_WARN_IF(!range->GetStartContainer())) {
return NS_ERROR_FAILURE;
}
nsString tOutString;
const PendingStyleState styleState = [&]() {
if (aStyle.mAttribute) {
auto state = mPendingStylesToApplyToNewContent->GetStyleState(
*aStyle.mHTMLProperty, aStyle.mAttribute, &tOutString);
if (outValue) {
outValue->Assign(tOutString);
}
return state;
}
return mPendingStylesToApplyToNewContent->GetStyleState(
*aStyle.mHTMLProperty);
}();
if (styleState != PendingStyleState::NotUpdated) {
*aFirst = *aAny = *aAll =
(styleState == PendingStyleState::BeingPreserved);
return NS_OK;
}
nsIContent* const collapsedContent =
nsIContent::FromNode(range->GetStartContainer());
if (MOZ_LIKELY(collapsedContent &&
collapsedContent->GetAsElementOrParentElement()) &&
aStyle.IsCSSSettable(
*collapsedContent->GetAsElementOrParentElement())) {
if (aValue) {
tOutString.Assign(*aValue);
}
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(
*this, MOZ_KnownLive(*collapsedContent), aStyle, tOutString);
if (MOZ_UNLIKELY(isComputedCSSEquivalentToStyleOrError.isErr())) {
NS_WARNING("CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError.unwrapErr();
}
*aFirst = *aAny = *aAll =
isComputedCSSEquivalentToStyleOrError.unwrap();
if (outValue) {
outValue->Assign(tOutString);
}
return NS_OK;
}
*aFirst = *aAny = *aAll =
collapsedContent && HTMLEditUtils::IsInlineStyleSetByElement(
*collapsedContent, aStyle, aValue, outValue);
return NS_OK;
}
// Non-collapsed selection
nsAutoString firstValue, theValue;
nsCOMPtr<nsINode> endNode = range->GetEndContainer();
uint32_t endOffset = range->EndOffset();
PostContentIterator postOrderIter;
DebugOnly<nsresult> rvIgnored = postOrderIter.Init(range);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Failed to initialize post-order content iterator");
for (; !postOrderIter.IsDone(); postOrderIter.Next()) {
if (postOrderIter.GetCurrentNode()->IsHTMLElement(nsGkAtoms::body)) {
break;
}
RefPtr<Text> textNode = Text::FromNode(postOrderIter.GetCurrentNode());
if (!textNode) {
continue;
}
// just ignore any non-editable nodes
if (!EditorUtils::IsEditableContent(*textNode, EditorType::HTML) ||
!HTMLEditUtils::IsVisibleTextNode(*textNode)) {
continue;
}
if (!isCollapsed && first && firstNodeInRange) {
firstNodeInRange = false;
if (range->StartOffset() == textNode->TextDataLength()) {
continue;
}
} else if (textNode == endNode && !endOffset) {
continue;
}
const RefPtr<Element> element = textNode->GetParentElement();
bool isSet = false;
if (first) {
if (element) {
if (aStyle.IsCSSSettable(*element)) {
// The HTML styles defined by aHTMLProperty/aAttribute have a CSS
// equivalence in this implementation for node; let's check if it
// carries those CSS styles
if (aValue) {
firstValue.Assign(*aValue);
}
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(*this, *element, aStyle,
firstValue);
if (MOZ_UNLIKELY(isComputedCSSEquivalentToStyleOrError.isErr())) {
NS_WARNING("CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError.unwrapErr();
}
isSet = isComputedCSSEquivalentToStyleOrError.unwrap();
} else {
isSet = HTMLEditUtils::IsInlineStyleSetByElement(
*element, aStyle, aValue, &firstValue);
}
}
*aFirst = isSet;
first = false;
if (outValue) {
*outValue = firstValue;
}
} else {
if (element) {
if (aStyle.IsCSSSettable(*element)) {
// The HTML styles defined by aHTMLProperty/aAttribute have a CSS
// equivalence in this implementation for node; let's check if it
// carries those CSS styles
if (aValue) {
theValue.Assign(*aValue);
}
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(*this, *element, aStyle,
theValue);
if (MOZ_UNLIKELY(isComputedCSSEquivalentToStyleOrError.isErr())) {
NS_WARNING("CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError.unwrapErr();
}
isSet = isComputedCSSEquivalentToStyleOrError.unwrap();
} else {
isSet = HTMLEditUtils::IsInlineStyleSetByElement(*element, aStyle,
aValue, &theValue);
}
}
if (firstValue != theValue &&
// For text-decoration related HTML properties, i.e. <u> and
// <strike>, we have to also check |isSet| because text-decoration
// is a shorthand property, and it may contains other unrelated
// longhand components, e.g. text-decoration-color, so we have to do
// an extra check before setting |*aAll| to false.
// e.g.
// firstValue: "underline rgb(0, 0, 0)"
// theValue: "underline rgb(0, 0, 238)" // <a> uses blue color
// These two values should be the same if we are checking `<u>`.
// That's why we need to check |*aFirst| and |isSet|.
//
// This is a work-around for text-decoration.
// The spec issue: https://github.com/w3c/editing/issues/241.
// Once this spec issue is resolved, we could drop this work-around
// check.
(!aStyle.IsStyleOfTextDecoration(
EditorInlineStyle::IgnoreSElement::Yes) ||
*aFirst != isSet)) {
*aAll = false;
}
}
if (isSet) {
*aAny = true;
} else {
*aAll = false;
}
}
}
if (!*aAny) {
// make sure that if none of the selection is set, we don't report all is
// set
*aAll = false;
}
return NS_OK;
}
nsresult HTMLEditor::GetInlineProperty(nsStaticAtom& aHTMLProperty,
nsAtom* aAttribute,
const nsAString& aValue, bool* aFirst,
bool* aAny, bool* aAll) const {
if (NS_WARN_IF(!aFirst) || NS_WARN_IF(!aAny) || NS_WARN_IF(!aAll)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const nsAString* val = !aValue.IsEmpty() ? &aValue : nullptr;
nsresult rv =
GetInlinePropertyBase(EditorInlineStyle(aHTMLProperty, aAttribute), val,
aFirst, aAny, aAll, nullptr);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetInlinePropertyBase() failed");
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP HTMLEditor::GetInlinePropertyWithAttrValue(
const nsAString& aHTMLProperty, const nsAString& aAttribute,
const nsAString& aValue, bool* aFirst, bool* aAny, bool* aAll,
nsAString& outValue) {
nsStaticAtom* property = NS_GetStaticAtom(aHTMLProperty);
if (NS_WARN_IF(!property)) {
return NS_ERROR_INVALID_ARG;
}
nsStaticAtom* attribute = EditorUtils::GetAttributeAtom(aAttribute);
// MOZ_KnownLive because nsStaticAtom is available until shutting down.
nsresult rv = GetInlinePropertyWithAttrValue(MOZ_KnownLive(*property),
MOZ_KnownLive(attribute), aValue,
aFirst, aAny, aAll, outValue);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetInlinePropertyWithAttrValue() failed");
return rv;
}
nsresult HTMLEditor::GetInlinePropertyWithAttrValue(
nsStaticAtom& aHTMLProperty, nsAtom* aAttribute, const nsAString& aValue,
bool* aFirst, bool* aAny, bool* aAll, nsAString& outValue) {
if (NS_WARN_IF(!aFirst) || NS_WARN_IF(!aAny) || NS_WARN_IF(!aAll)) {
return NS_ERROR_INVALID_ARG;
}
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const nsAString* val = !aValue.IsEmpty() ? &aValue : nullptr;
nsresult rv =
GetInlinePropertyBase(EditorInlineStyle(aHTMLProperty, aAttribute), val,
aFirst, aAny, aAll, &outValue);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::GetInlinePropertyBase() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::RemoveAllInlinePropertiesAsAction(
nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(
*this, EditAction::eRemoveAllInlineStyleProperties, aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eRemoveAllTextProperties, nsIEditor::eNext,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return EditorBase::ToGenericNSResult(ignoredError.StealNSResult());
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
AutoTArray<EditorInlineStyle, 1> removeAllInlineStyles;
removeAllInlineStyles.AppendElement(EditorInlineStyle::RemoveAllStyles());
rv = RemoveInlinePropertiesAsSubAction(removeAllInlineStyles, *editingHost);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::RemoveInlinePropertiesAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::RemoveInlinePropertyAsAction(nsStaticAtom& aHTMLProperty,
nsStaticAtom* aAttribute,
nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(
*this,
HTMLEditUtils::GetEditActionForFormatText(aHTMLProperty, aAttribute,
false),
aPrincipal);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
switch (editActionData.GetEditAction()) {
case EditAction::eRemoveFontFamilyProperty:
MOZ_ASSERT(!u""_ns.IsVoid());
editActionData.SetData(u""_ns);
break;
case EditAction::eRemoveColorProperty:
case EditAction::eRemoveBackgroundColorPropertyInline:
editActionData.SetColorData(u""_ns);
break;
default:
break;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoTArray<EditorInlineStyle, 8> removeInlineStyleAndRelatedElements;
AppendInlineStyleAndRelatedStyle(EditorInlineStyle(aHTMLProperty, aAttribute),
removeInlineStyleAndRelatedElements);
rv = RemoveInlinePropertiesAsSubAction(removeInlineStyleAndRelatedElements,
*editingHost);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::RemoveInlinePropertiesAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
NS_IMETHODIMP HTMLEditor::RemoveInlineProperty(const nsAString& aProperty,
const nsAString& aAttribute) {
nsStaticAtom* property = NS_GetStaticAtom(aProperty);
nsStaticAtom* attribute = EditorUtils::GetAttributeAtom(aAttribute);
AutoEditActionDataSetter editActionData(
*this,
HTMLEditUtils::GetEditActionForFormatText(*property, attribute, false));
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
const RefPtr<Element> editingHost =
ComputeEditingHost(LimitInBodyElement::No);
if (!editingHost || editingHost->IsContentEditablePlainTextOnly()) {
return NS_SUCCESS_DOM_NO_OPERATION;
}
switch (editActionData.GetEditAction()) {
case EditAction::eRemoveFontFamilyProperty:
MOZ_ASSERT(!EmptyString().IsVoid());
editActionData.SetData(EmptyString());
break;
case EditAction::eRemoveColorProperty:
case EditAction::eRemoveBackgroundColorPropertyInline:
editActionData.SetColorData(EmptyString());
break;
default:
break;
}
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoTArray<EditorInlineStyle, 1> removeOneInlineStyle;
removeOneInlineStyle.AppendElement(EditorInlineStyle(*property, attribute));
rv = RemoveInlinePropertiesAsSubAction(removeOneInlineStyle, *editingHost);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::RemoveInlinePropertiesAsSubAction() failed");
return EditorBase::ToGenericNSResult(rv);
}
void HTMLEditor::AppendInlineStyleAndRelatedStyle(
const EditorInlineStyle& aStyleToRemove,
nsTArray<EditorInlineStyle>& aStylesToRemove) const {
if (nsStaticAtom* similarElementName =
aStyleToRemove.GetSimilarElementNameAtom()) {
EditorInlineStyle anotherStyle(*similarElementName);
if (!aStylesToRemove.Contains(anotherStyle)) {
aStylesToRemove.AppendElement(std::move(anotherStyle));
}
} else if (aStyleToRemove.mHTMLProperty == nsGkAtoms::font) {
if (aStyleToRemove.mAttribute == nsGkAtoms::size) {
EditorInlineStyle big(*nsGkAtoms::big), small(*nsGkAtoms::small);
if (!aStylesToRemove.Contains(big)) {
aStylesToRemove.AppendElement(std::move(big));
}
if (!aStylesToRemove.Contains(small)) {
aStylesToRemove.AppendElement(std::move(small));
}
}
// Handling <tt> element code was implemented for composer (bug 115922).
// This shouldn't work with Document.execCommand() for compatibility with
// the other browsers. Currently, edit action principal is set only when
// the root caller is Document::ExecCommand() so that we should handle <tt>
// element only when the principal is nullptr that must be only when XUL
// command is executed on composer.
else if (aStyleToRemove.mAttribute == nsGkAtoms::face &&
!GetEditActionPrincipal()) {
EditorInlineStyle tt(*nsGkAtoms::tt);
if (!aStylesToRemove.Contains(tt)) {
aStylesToRemove.AppendElement(std::move(tt));
}
}
}
if (!aStylesToRemove.Contains(aStyleToRemove)) {
aStylesToRemove.AppendElement(aStyleToRemove);
}
}
nsresult HTMLEditor::RemoveInlinePropertiesAsSubAction(
const nsTArray<EditorInlineStyle>& aStylesToRemove,
const Element& aEditingHost) {
MOZ_ASSERT(IsEditActionDataAvailable());
MOZ_ASSERT(!aStylesToRemove.IsEmpty());
DebugOnly<nsresult> rvIgnored = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
if (SelectionRef().IsCollapsed()) {
// Manipulating text attributes on a collapsed selection only sets state
// for the next text insertion
mPendingStylesToApplyToNewContent->ClearStyles(aStylesToRemove);
return NS_OK;
}
{
Result<EditActionResult, nsresult> result = CanHandleHTMLEditSubAction();
if (MOZ_UNLIKELY(result.isErr())) {
NS_WARNING("HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result.unwrapErr();
}
if (result.inspect().Canceled()) {
return NS_OK;
}
}
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eRemoveTextProperty, nsIEditor::eNext,
ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// TODO: We don't need AutoTransactionsConserveSelection here in the normal
// cases, but removing this may cause the behavior with the legacy
// mutation event listeners. We should try to delete this in a bug.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
AutoClonedSelectionRangeArray selectionRanges(SelectionRef());
for (const EditorInlineStyle& styleToRemove : aStylesToRemove) {
// The ranges may be updated by changing the DOM tree. In strictly
// speaking, we should save and restore the ranges at every range loop,
// but we've never done so and it may be expensive if there are a lot of
// ranges. Therefore, we should do it for every style handling for now.
// TODO: We should collect everything required for removing the style before
// touching the DOM tree. Then, we need to save and restore the
// ranges only once.
Maybe<AutoInlineStyleSetter> styleInverter;
if (styleToRemove.IsInvertibleWithCSS()) {
styleInverter.emplace(EditorInlineStyleAndValue::ToInvert(styleToRemove));
}
for (OwningNonNull<nsRange>& selectionRange : selectionRanges.Ranges()) {
AutoTrackDOMRange trackSelectionRange(RangeUpdaterRef(), &selectionRange);
// If we're removing <a name>, we don't want to split ancestors because
// the split fragment will keep working as named anchor. Therefore, we
// need to remove all <a name> elements which the selection range even
// partially contains.
const EditorDOMRange range(
styleToRemove.mHTMLProperty == nsGkAtoms::name
? GetExtendedRangeWrappingNamedAnchor(
EditorRawDOMRange(selectionRange))
: GetExtendedRangeWrappingEntirelySelectedElements(
EditorRawDOMRange(selectionRange)));
if (NS_WARN_IF(!range.IsPositioned())) {
continue;
}
// Remove this style from ancestors of our range endpoints, splitting
// them as appropriate
Result<SplitRangeOffResult, nsresult> splitRangeOffResult =
SplitAncestorStyledInlineElementsAtRangeEdges(
range, styleToRemove, SplitAtEdges::eAllowToCreateEmptyContainer);
if (MOZ_UNLIKELY(splitRangeOffResult.isErr())) {
NS_WARNING(
"HTMLEditor::SplitAncestorStyledInlineElementsAtRangeEdges() "
"failed");
return splitRangeOffResult.unwrapErr();
}
// There is AutoTransactionsConserveSelection, so we don't need to
// update selection here.
splitRangeOffResult.inspect().IgnoreCaretPointSuggestion();
// XXX Modifying `range` means that we may modify ranges in `Selection`.
// Is this intentional? Note that the range may be not in
// `Selection` too. It seems that at least one of them is not
// an unexpected case.
const EditorDOMRange& splitRange =
splitRangeOffResult.inspect().RangeRef();
if (NS_WARN_IF(!splitRange.IsPositioned())) {
continue;
}
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContentsToInvertStyle;
{
// Collect top level children in the range first.
// TODO: Perhaps, HTMLEditUtils::IsSplittableNode should be used here
// instead of EditorUtils::IsEditableContent.
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfContentsAroundRange;
if (splitRange.InSameContainer() &&
splitRange.StartRef().IsInTextNode()) {
if (!EditorUtils::IsEditableContent(
*splitRange.StartRef().ContainerAs<Text>(),
EditorType::HTML)) {
continue;
}
arrayOfContentsAroundRange.AppendElement(
*splitRange.StartRef().ContainerAs<Text>());
} else if (splitRange.IsInTextNodes() &&
splitRange.InAdjacentSiblings()) {
// Adjacent siblings are in a same element, so the editable state of
// both text nodes are always same.
if (!EditorUtils::IsEditableContent(
*splitRange.StartRef().ContainerAs<Text>(),
EditorType::HTML)) {
continue;
}
arrayOfContentsAroundRange.AppendElement(
*splitRange.StartRef().ContainerAs<Text>());
arrayOfContentsAroundRange.AppendElement(
*splitRange.EndRef().ContainerAs<Text>());
} else {
// Append first node if it's a text node but selected not entirely.
if (splitRange.StartRef().IsInTextNode() &&
!splitRange.StartRef().IsStartOfContainer() &&
EditorUtils::IsEditableContent(
*splitRange.StartRef().ContainerAs<Text>(),
EditorType::HTML)) {
arrayOfContentsAroundRange.AppendElement(
*splitRange.StartRef().ContainerAs<Text>());
}
// Append all entirely selected nodes.
ContentSubtreeIterator subtreeIter;
if (NS_SUCCEEDED(
subtreeIter.Init(splitRange.StartRef().ToRawRangeBoundary(),
splitRange.EndRef().ToRawRangeBoundary()))) {
for (; !subtreeIter.IsDone(); subtreeIter.Next()) {
nsCOMPtr<nsINode> node = subtreeIter.GetCurrentNode();
if (NS_WARN_IF(!node)) {
return NS_ERROR_FAILURE;
}
if (node->IsContent() &&
EditorUtils::IsEditableContent(*node->AsContent(),
EditorType::HTML)) {
arrayOfContentsAroundRange.AppendElement(*node->AsContent());
}
}
}
// Append last node if it's a text node but selected not entirely.
if (!splitRange.InSameContainer() &&
splitRange.EndRef().IsInTextNode() &&
!splitRange.EndRef().IsEndOfContainer() &&
EditorUtils::IsEditableContent(
*splitRange.EndRef().ContainerAs<Text>(), EditorType::HTML)) {
arrayOfContentsAroundRange.AppendElement(
*splitRange.EndRef().ContainerAs<Text>());
}
}
if (styleToRemove.IsInvertibleWithCSS()) {
arrayOfContentsToInvertStyle.SetCapacity(
arrayOfContentsAroundRange.Length());
}
for (OwningNonNull<nsIContent>& content : arrayOfContentsAroundRange) {
// We should remove style from the element and its descendants.
if (content->IsElement()) {
Result<EditorDOMPoint, nsresult> removeStyleResult =
RemoveStyleInside(MOZ_KnownLive(*content->AsElement()),
styleToRemove, SpecifiedStyle::Preserve);
if (MOZ_UNLIKELY(removeStyleResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveStyleInside() failed");
return removeStyleResult.unwrapErr();
}
// There is AutoTransactionsConserveSelection, so we don't need to
// update selection here.
// If the element was removed from the DOM tree by
// RemoveStyleInside, we need to do nothing for it anymore.
if (!content->GetParentNode()) {
continue;
}
}
if (styleToRemove.IsInvertibleWithCSS()) {
arrayOfContentsToInvertStyle.AppendElement(content);
}
} // for-loop for arrayOfContentsAroundRange
}
auto FlushAndStopTrackingAndShrinkSelectionRange =
[&]() MOZ_CAN_RUN_SCRIPT {
trackSelectionRange.FlushAndStopTracking();
if (NS_WARN_IF(!selectionRange->IsPositioned())) {
return;
}
EditorRawDOMRange range(selectionRange);
nsINode* const commonAncestor =
range.GetClosestCommonInclusiveAncestor();
// Shrink range for compatibility between browsers.
nsIContent* const maybeNextContent =
range.StartRef().IsInContentNode() &&
range.StartRef().IsEndOfContainer()
? AutoInlineStyleSetter::GetNextEditableInlineContent(
*range.StartRef().ContainerAs<nsIContent>(),
commonAncestor)
: nullptr;
nsIContent* const maybePreviousContent =
range.EndRef().IsInContentNode() &&
range.EndRef().IsStartOfContainer()
? AutoInlineStyleSetter::GetPreviousEditableInlineContent(
*range.EndRef().ContainerAs<nsIContent>(),
commonAncestor)
: nullptr;
if (!maybeNextContent && !maybePreviousContent) {
return;
}
const auto startPoint =
maybeNextContent &&
maybeNextContent != selectionRange->GetStartContainer()
? HTMLEditUtils::GetDeepestEditableStartPointOf<
EditorRawDOMPoint>(
*maybeNextContent,
{EditablePointOption::RecognizeInvisibleWhiteSpaces,
EditablePointOption::StopAtComment})
: range.StartRef();
const auto endPoint =
maybePreviousContent && maybePreviousContent !=
selectionRange->GetEndContainer()
? HTMLEditUtils::GetDeepestEditableEndPointOf<
EditorRawDOMPoint>(
*maybePreviousContent,
{EditablePointOption::RecognizeInvisibleWhiteSpaces,
EditablePointOption::StopAtComment})
: range.EndRef();
DebugOnly<nsresult> rvIgnored = selectionRange->SetStartAndEnd(
startPoint.ToRawRangeBoundary(), endPoint.ToRawRangeBoundary());
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsRange::SetStartAndEnd() failed, but ignored");
};
if (arrayOfContentsToInvertStyle.IsEmpty()) {
FlushAndStopTrackingAndShrinkSelectionRange();
continue;
}
MOZ_ASSERT(styleToRemove.IsInvertibleWithCSS());
// If the style is specified in parent block and we can remove the
// style with inserting new <span> element, we should do it.
for (OwningNonNull<nsIContent>& content : arrayOfContentsToInvertStyle) {
if (Element* element = Element::FromNode(content)) {
// XXX Do we need to call this even when data node or something? If
// so, for what?
// MOZ_KnownLive because 'arrayOfContents' is guaranteed to
// keep it alive.
nsresult rv = styleInverter->InvertStyleIfApplied(
*this, MOZ_KnownLive(*element));
if (NS_FAILED(rv)) {
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
NS_WARNING(
"AutoInlineStyleSetter::InvertStyleIfApplied() failed");
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING(
"AutoInlineStyleSetter::InvertStyleIfApplied() failed, but "
"ignored");
}
continue;
}
// Unfortunately, all browsers don't join text nodes when removing a
// style. Therefore, there may be multiple text nodes as adjacent
// siblings. That's the reason why we need to handle text nodes in this
// loop.
if (Text* textNode = Text::FromNode(content)) {
const uint32_t startOffset =
content == splitRange.StartRef().GetContainer()
? splitRange.StartRef().Offset()
: 0u;
const uint32_t endOffset =
content == splitRange.EndRef().GetContainer()
? splitRange.EndRef().Offset()
: textNode->TextDataLength();
Result<SplitRangeOffFromNodeResult, nsresult>
wrapTextInStyledElementResult =
styleInverter->InvertStyleIfApplied(
*this, MOZ_KnownLive(*textNode), startOffset, endOffset);
if (MOZ_UNLIKELY(wrapTextInStyledElementResult.isErr())) {
NS_WARNING("AutoInlineStyleSetter::InvertStyleIfApplied() failed");
return wrapTextInStyledElementResult.unwrapErr();
}
SplitRangeOffFromNodeResult unwrappedWrapTextInStyledElementResult =
wrapTextInStyledElementResult.unwrap();
// There is AutoTransactionsConserveSelection, so we don't need to
// update selection here.
unwrappedWrapTextInStyledElementResult.IgnoreCaretPointSuggestion();
// If we've split the content, let's swap content in
// arrayOfContentsToInvertStyle with the text node which is applied
// the style.
if (unwrappedWrapTextInStyledElementResult.DidSplit() &&
styleToRemove.IsInvertibleWithCSS()) {
MOZ_ASSERT(unwrappedWrapTextInStyledElementResult
.GetMiddleContentAs<Text>());
if (Text* styledTextNode = unwrappedWrapTextInStyledElementResult
.GetMiddleContentAs<Text>()) {
if (styledTextNode != content) {
arrayOfContentsToInvertStyle.ReplaceElementAt(
arrayOfContentsToInvertStyle.Length() - 1,
OwningNonNull<nsIContent>(*styledTextNode));
}
}
}
continue;
}
// If the node is not an element nor a text node, it's invisible.
// In this case, we don't need to make it wrapped in new element.
}
// Finally, we should remove the style from all leaf text nodes if
// they still have the style.
AutoTArray<OwningNonNull<Text>, 32> leafTextNodes;
for (const OwningNonNull<nsIContent>& content :
arrayOfContentsToInvertStyle) {
// XXX Should we ignore content which has already removed from the
// DOM tree by the previous for-loop?
if (content->IsElement()) {
CollectEditableLeafTextNodes(*content->AsElement(), leafTextNodes);
}
}
for (const OwningNonNull<Text>& textNode : leafTextNodes) {
Result<SplitRangeOffFromNodeResult, nsresult>
wrapTextInStyledElementResult = styleInverter->InvertStyleIfApplied(
*this, MOZ_KnownLive(*textNode), 0, textNode->TextLength());
if (MOZ_UNLIKELY(wrapTextInStyledElementResult.isErr())) {
NS_WARNING(
"AutoInlineStyleSetter::SplitTextNodeAndApplyStyleToMiddleNode() "
"failed");
return wrapTextInStyledElementResult.unwrapErr();
}
// There is AutoTransactionsConserveSelection, so we don't need to
// update selection here.
wrapTextInStyledElementResult.inspect().IgnoreCaretPointSuggestion();
} // for-loop of leafTextNodes
// styleInverter may have touched a part of the range. Therefore, we
// cannot adjust the range without comparing DOM node position and
// first/last touched positions, but it may be too expensive. I think
// that shrinking only the tracked range boundaries must be enough in most
// cases.
FlushAndStopTrackingAndShrinkSelectionRange();
} // for-loop of selectionRanges
} // for-loop of styles
MOZ_ASSERT(!selectionRanges.HasSavedRanges());
nsresult rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"AutoClonedSelectionRangeArray::ApplyTo() failed");
return rv;
}
nsresult HTMLEditor::AutoInlineStyleSetter::InvertStyleIfApplied(
HTMLEditor& aHTMLEditor, Element& aElement) {
MOZ_ASSERT(IsStyleToInvert());
Result<bool, nsresult> isRemovableParentStyleOrError =
aHTMLEditor.IsRemovableParentStyleWithNewSpanElement(aElement, *this);
if (MOZ_UNLIKELY(isRemovableParentStyleOrError.isErr())) {
NS_WARNING("HTMLEditor::IsRemovableParentStyleWithNewSpanElement() failed");
return isRemovableParentStyleOrError.unwrapErr();
}
if (!isRemovableParentStyleOrError.unwrap()) {
// E.g., text-decoration cannot be override visually in children.
// In such cases, we can do nothing.
return NS_OK;
}
// Wrap it into a new element, move it into direct child which has same style,
// or specify the style to its parent.
Result<CaretPoint, nsresult> pointToPutCaretOrError =
ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle(aHTMLEditor, aElement);
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
NS_WARNING(
"AutoInlineStyleSetter::"
"ApplyStyleToNodeOrChildrenAndRemoveNestedSameStyle() failed");
return pointToPutCaretOrError.unwrapErr();
}
// The caller must update `Selection` later so that we don't need this.
pointToPutCaretOrError.unwrap().IgnoreCaretPointSuggestion();
return NS_OK;
}
Result<SplitRangeOffFromNodeResult, nsresult>
HTMLEditor::AutoInlineStyleSetter::InvertStyleIfApplied(HTMLEditor& aHTMLEditor,
Text& aTextNode,
uint32_t aStartOffset,
uint32_t aEndOffset) {
MOZ_ASSERT(IsStyleToInvert());
Result<bool, nsresult> isRemovableParentStyleOrError =
aHTMLEditor.IsRemovableParentStyleWithNewSpanElement(aTextNode, *this);
if (MOZ_UNLIKELY(isRemovableParentStyleOrError.isErr())) {
NS_WARNING("HTMLEditor::IsRemovableParentStyleWithNewSpanElement() failed");
return isRemovableParentStyleOrError.propagateErr();
}
if (!isRemovableParentStyleOrError.unwrap()) {
// E.g., text-decoration cannot be override visually in children.
// In such cases, we can do nothing.
return SplitRangeOffFromNodeResult(nullptr, &aTextNode, nullptr);
}
// We need to use new `<span>` element or existing element if it's available
// to overwrite parent style.
Result<SplitRangeOffFromNodeResult, nsresult> wrapTextInStyledElementResult =
SplitTextNodeAndApplyStyleToMiddleNode(aHTMLEditor, aTextNode,
aStartOffset, aEndOffset);
NS_WARNING_ASSERTION(
wrapTextInStyledElementResult.isOk(),
"AutoInlineStyleSetter::SplitTextNodeAndApplyStyleToMiddleNode() failed");
return wrapTextInStyledElementResult;
}
Result<bool, nsresult> HTMLEditor::IsRemovableParentStyleWithNewSpanElement(
nsIContent& aContent, const EditorInlineStyle& aStyle) const {
// We don't support to remove all inline styles with this path.
if (aStyle.IsStyleToClearAllInlineStyles()) {
return false;
}
// First check whether the style is invertible since this is the fastest
// check.
if (!aStyle.IsInvertibleWithCSS()) {
return false;
}
// If aContent is not an element and it's not in an element, it means that
// aContent is disconnected non-element node. In this case, it's never
// applied any styles which are invertible.
const RefPtr<Element> element = aContent.GetAsElementOrParentElement();
if (MOZ_UNLIKELY(!element)) {
return false;
}
// If parent block has invertible style, we should remove the style with
// creating new `<span>` element even in HTML mode because Chrome does it.
if (!aStyle.IsCSSSettable(*element)) {
return false;
}
nsAutoString emptyString;
Result<bool, nsresult> isComputedCSSEquivalentToStyleOrError =
CSSEditUtils::IsComputedCSSEquivalentTo(*this, *element, aStyle,
emptyString);
NS_WARNING_ASSERTION(isComputedCSSEquivalentToStyleOrError.isOk(),
"CSSEditUtils::IsComputedCSSEquivalentTo() failed");
return isComputedCSSEquivalentToStyleOrError;
}
void HTMLEditor::CollectEditableLeafTextNodes(
Element& aElement, nsTArray<OwningNonNull<Text>>& aLeafTextNodes) const {
for (nsIContent* child = aElement.GetFirstChild(); child;
child = child->GetNextSibling()) {
if (child->IsElement()) {
CollectEditableLeafTextNodes(*child->AsElement(), aLeafTextNodes);
continue;
}
if (child->IsText()) {
aLeafTextNodes.AppendElement(*child->AsText());
}
}
}
nsresult HTMLEditor::IncreaseFontSizeAsAction(nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(*this, EditAction::eIncrementFontSize,
aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
rv = IncrementOrDecrementFontSizeAsSubAction(FontSize::incr);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::IncrementOrDecrementFontSizeAsSubAction("
"FontSize::incr) failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::DecreaseFontSizeAsAction(nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(*this, EditAction::eDecrementFontSize,
aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
rv = IncrementOrDecrementFontSizeAsSubAction(FontSize::decr);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::IncrementOrDecrementFontSizeAsSubAction("
"FontSize::decr) failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::IncrementOrDecrementFontSizeAsSubAction(
FontSize aIncrementOrDecrement) {
MOZ_ASSERT(IsEditActionDataAvailable());
// Committing composition and changing font size should be undone together.
AutoPlaceholderBatch treatAsOneTransaction(
*this, ScrollSelectionIntoView::Yes, __FUNCTION__);
DebugOnly<nsresult> rvIgnored = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
// If selection is collapsed, set typing state
if (SelectionRef().IsCollapsed()) {
nsStaticAtom& bigOrSmallTagName = aIncrementOrDecrement == FontSize::incr
? *nsGkAtoms::big
: *nsGkAtoms::small;
// Let's see in what kind of element the selection is
if (!SelectionRef().RangeCount()) {
return NS_OK;
}
const auto firstRangeStartPoint =
EditorBase::GetFirstSelectionStartPoint<EditorRawDOMPoint>();
if (NS_WARN_IF(!firstRangeStartPoint.IsSet())) {
return NS_OK;
}
Element* element =
firstRangeStartPoint.GetContainerOrContainerParentElement();
if (NS_WARN_IF(!element)) {
return NS_OK;
}
if (!HTMLEditUtils::CanNodeContain(*element, bigOrSmallTagName)) {
return NS_OK;
}
// Manipulating text attributes on a collapsed selection only sets state
// for the next text insertion
mPendingStylesToApplyToNewContent->PreserveStyle(bigOrSmallTagName, nullptr,
u""_ns);
return NS_OK;
}
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eSetTextProperty, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
// TODO: We don't need AutoTransactionsConserveSelection here in the normal
// cases, but removing this may cause the behavior with the legacy
// mutation event listeners. We should try to delete this in a bug.
AutoTransactionsConserveSelection dontChangeMySelection(*this);
AutoClonedSelectionRangeArray selectionRanges(SelectionRef());
MOZ_ALWAYS_TRUE(selectionRanges.SaveAndTrackRanges(*this));
for (const OwningNonNull<nsRange>& domRange : selectionRanges.Ranges()) {
// TODO: We should stop extending the range outside ancestor blocks because
// we don't need to do it for setting inline styles. However, here is
// chrome only handling path. Therefore, we don't need to fix here
// soon.
const EditorDOMRange range(GetExtendedRangeWrappingEntirelySelectedElements(
EditorRawDOMRange(domRange)));
if (NS_WARN_IF(!range.IsPositioned())) {
continue;
}
if (range.InSameContainer() && range.StartRef().IsInTextNode()) {
Result<CreateElementResult, nsresult> wrapInBigOrSmallElementResult =
SetFontSizeOnTextNode(
MOZ_KnownLive(*range.StartRef().ContainerAs<Text>()),
range.StartRef().Offset(), range.EndRef().Offset(),
aIncrementOrDecrement);
if (MOZ_UNLIKELY(wrapInBigOrSmallElementResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeOnTextNode() failed");
return wrapInBigOrSmallElementResult.unwrapErr();
}
// There is an AutoTransactionsConserveSelection instance so that we don't
// need to update selection for this change.
wrapInBigOrSmallElementResult.inspect().IgnoreCaretPointSuggestion();
continue;
}
// Not the easy case. Range not contained in single text node. There
// are up to three phases here. There are all the nodes reported by the
// subtree iterator to be processed. And there are potentially a
// starting textnode and an ending textnode which are only partially
// contained by the range.
// Let's handle the nodes reported by the iterator. These nodes are
// entirely contained in the selection range. We build up a list of them
// (since doing operations on the document during iteration would perturb
// the iterator).
// Iterate range and build up array
ContentSubtreeIterator subtreeIter;
if (NS_SUCCEEDED(subtreeIter.Init(range.StartRef().ToRawRangeBoundary(),
range.EndRef().ToRawRangeBoundary()))) {
nsTArray<OwningNonNull<nsIContent>> arrayOfContents;
for (; !subtreeIter.IsDone(); subtreeIter.Next()) {
if (NS_WARN_IF(!subtreeIter.GetCurrentNode()->IsContent())) {
return NS_ERROR_FAILURE;
}
OwningNonNull<nsIContent> content =
*subtreeIter.GetCurrentNode()->AsContent();
if (EditorUtils::IsEditableContent(content, EditorType::HTML)) {
arrayOfContents.AppendElement(content);
}
}
// Now that we have the list, do the font size change on each node
for (OwningNonNull<nsIContent>& content : arrayOfContents) {
// MOZ_KnownLive because of bug 1622253
Result<EditorDOMPoint, nsresult> fontChangeOnNodeResult =
SetFontSizeWithBigOrSmallElement(MOZ_KnownLive(content),
aIncrementOrDecrement);
if (MOZ_UNLIKELY(fontChangeOnNodeResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeWithBigOrSmallElement() failed");
return fontChangeOnNodeResult.unwrapErr();
}
// There is an AutoTransactionsConserveSelection, so we don't need to
// update selection here.
}
}
// Now check the start and end parents of the range to see if they need
// to be separately handled (they do if they are text nodes, due to how
// the subtree iterator works - it will not have reported them).
if (range.StartRef().IsInTextNode() &&
!range.StartRef().IsEndOfContainer() &&
EditorUtils::IsEditableContent(*range.StartRef().ContainerAs<Text>(),
EditorType::HTML)) {
Result<CreateElementResult, nsresult> wrapInBigOrSmallElementResult =
SetFontSizeOnTextNode(
MOZ_KnownLive(*range.StartRef().ContainerAs<Text>()),
range.StartRef().Offset(),
range.StartRef().ContainerAs<Text>()->TextDataLength(),
aIncrementOrDecrement);
if (MOZ_UNLIKELY(wrapInBigOrSmallElementResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeOnTextNode() failed");
return wrapInBigOrSmallElementResult.unwrapErr();
}
// There is an AutoTransactionsConserveSelection instance so that we
// don't need to update selection for this change.
wrapInBigOrSmallElementResult.inspect().IgnoreCaretPointSuggestion();
}
if (range.EndRef().IsInTextNode() && !range.EndRef().IsStartOfContainer() &&
EditorUtils::IsEditableContent(*range.EndRef().ContainerAs<Text>(),
EditorType::HTML)) {
Result<CreateElementResult, nsresult> wrapInBigOrSmallElementResult =
SetFontSizeOnTextNode(
MOZ_KnownLive(*range.EndRef().ContainerAs<Text>()), 0u,
range.EndRef().Offset(), aIncrementOrDecrement);
if (MOZ_UNLIKELY(wrapInBigOrSmallElementResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeOnTextNode() failed");
return wrapInBigOrSmallElementResult.unwrapErr();
}
// There is an AutoTransactionsConserveSelection instance so that we
// don't need to update selection for this change.
wrapInBigOrSmallElementResult.inspect().IgnoreCaretPointSuggestion();
}
}
MOZ_ASSERT(selectionRanges.HasSavedRanges());
selectionRanges.RestoreFromSavedRanges();
nsresult rv = selectionRanges.ApplyTo(SelectionRef());
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"AutoClonedSelectionRangeArray::ApplyTo() failed");
return rv;
}
Result<CreateElementResult, nsresult> HTMLEditor::SetFontSizeOnTextNode(
Text& aTextNode, uint32_t aStartOffset, uint32_t aEndOffset,
FontSize aIncrementOrDecrement) {
// Don't need to do anything if no characters actually selected
if (aStartOffset == aEndOffset) {
return CreateElementResult::NotHandled();
}
if (!aTextNode.GetParentNode() ||
!HTMLEditUtils::CanNodeContain(*aTextNode.GetParentNode(),
*nsGkAtoms::big)) {
return CreateElementResult::NotHandled();
}
aEndOffset = std::min(aTextNode.Length(), aEndOffset);
// Make the range an independent node.
RefPtr<Text> textNodeForTheRange = &aTextNode;
EditorDOMPoint pointToPutCaret;
{
auto pointToPutCaretOrError =
[&]() MOZ_CAN_RUN_SCRIPT -> Result<EditorDOMPoint, nsresult> {
EditorDOMPoint pointToPutCaret;
// Split at the end of the range.
EditorDOMPoint atEnd(textNodeForTheRange, aEndOffset);
if (!atEnd.IsEndOfContainer()) {
// We need to split off back of text node
Result<SplitNodeResult, nsresult> splitAtEndResult =
SplitNodeWithTransaction(atEnd);
if (MOZ_UNLIKELY(splitAtEndResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitAtEndResult.propagateErr();
}
SplitNodeResult unwrappedSplitAtEndResult = splitAtEndResult.unwrap();
if (MOZ_UNLIKELY(
!unwrappedSplitAtEndResult.HasCaretPointSuggestion())) {
NS_WARNING(
"HTMLEditor::SplitNodeWithTransaction() didn't suggest caret "
"point");
return Err(NS_ERROR_FAILURE);
}
unwrappedSplitAtEndResult.MoveCaretPointTo(pointToPutCaret, *this, {});
MOZ_ASSERT_IF(AllowsTransactionsToChangeSelection(),
pointToPutCaret.IsSet());
textNodeForTheRange =
unwrappedSplitAtEndResult.GetPreviousContentAs<Text>();
MOZ_DIAGNOSTIC_ASSERT(textNodeForTheRange);
}
// Split at the start of the range.
EditorDOMPoint atStart(textNodeForTheRange, aStartOffset);
if (!atStart.IsStartOfContainer()) {
// We need to split off front of text node
Result<SplitNodeResult, nsresult> splitAtStartResult =
SplitNodeWithTransaction(atStart);
if (MOZ_UNLIKELY(splitAtStartResult.isErr())) {
NS_WARNING("HTMLEditor::SplitNodeWithTransaction() failed");
return splitAtStartResult.propagateErr();
}
SplitNodeResult unwrappedSplitAtStartResult =
splitAtStartResult.unwrap();
if (MOZ_UNLIKELY(
!unwrappedSplitAtStartResult.HasCaretPointSuggestion())) {
NS_WARNING(
"HTMLEditor::SplitNodeWithTransaction() didn't suggest caret "
"point");
return Err(NS_ERROR_FAILURE);
}
unwrappedSplitAtStartResult.MoveCaretPointTo(pointToPutCaret, *this,
{});
MOZ_ASSERT_IF(AllowsTransactionsToChangeSelection(),
pointToPutCaret.IsSet());
textNodeForTheRange =
unwrappedSplitAtStartResult.GetNextContentAs<Text>();
MOZ_DIAGNOSTIC_ASSERT(textNodeForTheRange);
}
return pointToPutCaret;
}();
if (MOZ_UNLIKELY(pointToPutCaretOrError.isErr())) {
// Don't warn here since it should be done in the lambda.
return pointToPutCaretOrError.propagateErr();
}
pointToPutCaret = pointToPutCaretOrError.unwrap();
}
// Look for siblings that are correct type of node
nsStaticAtom* const bigOrSmallTagName =
aIncrementOrDecrement == FontSize::incr ? nsGkAtoms::big
: nsGkAtoms::small;
nsCOMPtr<nsIContent> sibling = HTMLEditUtils::GetPreviousSibling(
*textNodeForTheRange, {WalkTreeOption::IgnoreNonEditableNode});
if (sibling && sibling->IsHTMLElement(bigOrSmallTagName)) {
// Previous sib is already right kind of inline node; slide this over
Result<MoveNodeResult, nsresult> moveTextNodeResult =
MoveNodeToEndWithTransaction(*textNodeForTheRange, *sibling);
if (MOZ_UNLIKELY(moveTextNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveTextNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveTextNodeResult = moveTextNodeResult.unwrap();
unwrappedMoveTextNodeResult.MoveCaretPointTo(
pointToPutCaret, *this, {SuggestCaret::OnlyIfHasSuggestion});
// XXX Should we return the new container?
return CreateElementResult::NotHandled(std::move(pointToPutCaret));
}
sibling = HTMLEditUtils::GetNextSibling(
*textNodeForTheRange, {WalkTreeOption::IgnoreNonEditableNode});
if (sibling && sibling->IsHTMLElement(bigOrSmallTagName)) {
// Following sib is already right kind of inline node; slide this over
Result<MoveNodeResult, nsresult> moveTextNodeResult =
MoveNodeWithTransaction(*textNodeForTheRange,
EditorDOMPoint(sibling, 0u));
if (MOZ_UNLIKELY(moveTextNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveTextNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveTextNodeResult = moveTextNodeResult.unwrap();
unwrappedMoveTextNodeResult.MoveCaretPointTo(
pointToPutCaret, *this, {SuggestCaret::OnlyIfHasSuggestion});
// XXX Should we return the new container?
return CreateElementResult::NotHandled(std::move(pointToPutCaret));
}
// Else wrap the node inside font node with appropriate relative size
Result<CreateElementResult, nsresult> wrapTextInBigOrSmallElementResult =
InsertContainerWithTransaction(*textNodeForTheRange,
MOZ_KnownLive(*bigOrSmallTagName));
if (wrapTextInBigOrSmallElementResult.isErr()) {
NS_WARNING("HTMLEditor::InsertContainerWithTransaction() failed");
return wrapTextInBigOrSmallElementResult;
}
CreateElementResult unwrappedWrapTextInBigOrSmallElementResult =
wrapTextInBigOrSmallElementResult.unwrap();
unwrappedWrapTextInBigOrSmallElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
return CreateElementResult(
unwrappedWrapTextInBigOrSmallElementResult.UnwrapNewNode(),
std::move(pointToPutCaret));
}
Result<EditorDOMPoint, nsresult> HTMLEditor::SetFontSizeOfFontElementChildren(
nsIContent& aContent, FontSize aIncrementOrDecrement) {
// This routine looks for all the font nodes in the tree rooted by aNode,
// including aNode itself, looking for font nodes that have the size attr
// set. Any such nodes need to have big or small put inside them, since
// they override any big/small that are above them.
// If this is a font node with size, put big/small inside it.
if (aContent.IsHTMLElement(nsGkAtoms::font) &&
aContent.AsElement()->HasAttr(nsGkAtoms::size)) {
EditorDOMPoint pointToPutCaret;
// Cycle through children and adjust relative font size.
AutoTArray<OwningNonNull<nsIContent>, 32> arrayOfContents;
HTMLEditUtils::CollectAllChildren(aContent, arrayOfContents);
for (const auto& child : arrayOfContents) {
// MOZ_KnownLive because of bug 1622253
Result<EditorDOMPoint, nsresult> setFontSizeOfChildResult =
SetFontSizeWithBigOrSmallElement(MOZ_KnownLive(child),
aIncrementOrDecrement);
if (MOZ_UNLIKELY(setFontSizeOfChildResult.isErr())) {
NS_WARNING("HTMLEditor::WrapContentInBigOrSmallElement() failed");
return setFontSizeOfChildResult;
}
if (setFontSizeOfChildResult.inspect().IsSet()) {
pointToPutCaret = setFontSizeOfChildResult.unwrap();
}
}
// WrapContentInBigOrSmallElement already calls us recursively,
// so we don't need to check our children again.
return pointToPutCaret;
}
// Otherwise cycle through the children.
EditorDOMPoint pointToPutCaret;
AutoTArray<OwningNonNull<nsIContent>, 32> arrayOfContents;
HTMLEditUtils::CollectAllChildren(aContent, arrayOfContents);
for (const auto& child : arrayOfContents) {
// MOZ_KnownLive because of bug 1622253
Result<EditorDOMPoint, nsresult> fontSizeChangeResult =
SetFontSizeOfFontElementChildren(MOZ_KnownLive(child),
aIncrementOrDecrement);
if (MOZ_UNLIKELY(fontSizeChangeResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeOfFontElementChildren() failed");
return fontSizeChangeResult;
}
if (fontSizeChangeResult.inspect().IsSet()) {
pointToPutCaret = fontSizeChangeResult.unwrap();
}
}
return pointToPutCaret;
}
Result<EditorDOMPoint, nsresult> HTMLEditor::SetFontSizeWithBigOrSmallElement(
nsIContent& aContent, FontSize aIncrementOrDecrement) {
nsStaticAtom* const bigOrSmallTagName =
aIncrementOrDecrement == FontSize::incr ? nsGkAtoms::big
: nsGkAtoms::small;
// Is aContent the opposite of what we want?
if ((aIncrementOrDecrement == FontSize::incr &&
aContent.IsHTMLElement(nsGkAtoms::small)) ||
(aIncrementOrDecrement == FontSize::decr &&
aContent.IsHTMLElement(nsGkAtoms::big))) {
// First, populate any nested font elements that have the size attr set
Result<EditorDOMPoint, nsresult> fontSizeChangeOfDescendantsResult =
SetFontSizeOfFontElementChildren(aContent, aIncrementOrDecrement);
if (MOZ_UNLIKELY(fontSizeChangeOfDescendantsResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeOfFontElementChildren() failed");
return fontSizeChangeOfDescendantsResult;
}
EditorDOMPoint pointToPutCaret = fontSizeChangeOfDescendantsResult.unwrap();
// In that case, just unwrap the <big> or <small> element.
Result<EditorDOMPoint, nsresult> unwrapBigOrSmallElementResult =
RemoveContainerWithTransaction(MOZ_KnownLive(*aContent.AsElement()));
if (MOZ_UNLIKELY(unwrapBigOrSmallElementResult.isErr())) {
NS_WARNING("HTMLEditor::RemoveContainerWithTransaction() failed");
return unwrapBigOrSmallElementResult;
}
if (unwrapBigOrSmallElementResult.inspect().IsSet()) {
pointToPutCaret = unwrapBigOrSmallElementResult.unwrap();
}
return pointToPutCaret;
}
if (HTMLEditUtils::CanNodeContain(*bigOrSmallTagName, aContent)) {
// First, populate any nested font tags that have the size attr set
Result<EditorDOMPoint, nsresult> fontSizeChangeOfDescendantsResult =
SetFontSizeOfFontElementChildren(aContent, aIncrementOrDecrement);
if (MOZ_UNLIKELY(fontSizeChangeOfDescendantsResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeOfFontElementChildren() failed");
return fontSizeChangeOfDescendantsResult;
}
EditorDOMPoint pointToPutCaret = fontSizeChangeOfDescendantsResult.unwrap();
// Next, if next or previous is <big> or <small>, move aContent into it.
nsCOMPtr<nsIContent> sibling = HTMLEditUtils::GetPreviousSibling(
aContent, {WalkTreeOption::IgnoreNonEditableNode});
if (sibling && sibling->IsHTMLElement(bigOrSmallTagName)) {
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeToEndWithTransaction(aContent, *sibling);
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeToEndWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
unwrappedMoveNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
return pointToPutCaret;
}
sibling = HTMLEditUtils::GetNextSibling(
aContent, {WalkTreeOption::IgnoreNonEditableNode});
if (sibling && sibling->IsHTMLElement(bigOrSmallTagName)) {
Result<MoveNodeResult, nsresult> moveNodeResult =
MoveNodeWithTransaction(aContent, EditorDOMPoint(sibling, 0u));
if (MOZ_UNLIKELY(moveNodeResult.isErr())) {
NS_WARNING("HTMLEditor::MoveNodeWithTransaction() failed");
return moveNodeResult.propagateErr();
}
MoveNodeResult unwrappedMoveNodeResult = moveNodeResult.unwrap();
unwrappedMoveNodeResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
return pointToPutCaret;
}
// Otherwise, wrap aContent in new <big> or <small>
Result<CreateElementResult, nsresult> wrapInBigOrSmallElementResult =
InsertContainerWithTransaction(aContent,
MOZ_KnownLive(*bigOrSmallTagName));
if (MOZ_UNLIKELY(wrapInBigOrSmallElementResult.isErr())) {
NS_WARNING("HTMLEditor::InsertContainerWithTransaction() failed");
return Err(wrapInBigOrSmallElementResult.unwrapErr());
}
CreateElementResult unwrappedWrapInBigOrSmallElementResult =
wrapInBigOrSmallElementResult.unwrap();
MOZ_ASSERT(unwrappedWrapInBigOrSmallElementResult.GetNewNode());
unwrappedWrapInBigOrSmallElementResult.MoveCaretPointTo(
pointToPutCaret, {SuggestCaret::OnlyIfHasSuggestion});
return pointToPutCaret;
}
// none of the above? then cycle through the children.
// MOOSE: we should group the children together if possible
// into a single "big" or "small". For the moment they are
// each getting their own.
EditorDOMPoint pointToPutCaret;
AutoTArray<OwningNonNull<nsIContent>, 32> arrayOfContents;
HTMLEditUtils::CollectAllChildren(aContent, arrayOfContents);
for (const auto& child : arrayOfContents) {
// MOZ_KnownLive because of bug 1622253
Result<EditorDOMPoint, nsresult> setFontSizeOfChildResult =
SetFontSizeWithBigOrSmallElement(MOZ_KnownLive(child),
aIncrementOrDecrement);
if (MOZ_UNLIKELY(setFontSizeOfChildResult.isErr())) {
NS_WARNING("HTMLEditor::SetFontSizeWithBigOrSmallElement() failed");
return setFontSizeOfChildResult;
}
if (setFontSizeOfChildResult.inspect().IsSet()) {
pointToPutCaret = setFontSizeOfChildResult.unwrap();
}
}
return pointToPutCaret;
}
NS_IMETHODIMP HTMLEditor::GetFontFaceState(bool* aMixed, nsAString& outFace) {
if (NS_WARN_IF(!aMixed)) {
return NS_ERROR_INVALID_ARG;
}
*aMixed = true;
outFace.Truncate();
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
bool first, any, all;
nsresult rv = GetInlinePropertyBase(
EditorInlineStyle(*nsGkAtoms::font, nsGkAtoms::face), nullptr, &first,
&any, &all, &outFace);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::GetInlinePropertyBase(nsGkAtoms::font, nsGkAtoms::face) "
"failed");
return EditorBase::ToGenericNSResult(rv);
}
if (any && !all) {
return NS_OK; // mixed
}
if (all) {
*aMixed = false;
return NS_OK;
}
// if there is no font face, check for tt
rv = GetInlinePropertyBase(EditorInlineStyle(*nsGkAtoms::tt), nullptr, &first,
&any, &all, nullptr);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::GetInlinePropertyBase(nsGkAtoms::tt) failed");
return EditorBase::ToGenericNSResult(rv);
}
if (any && !all) {
return NS_OK; // mixed
}
if (all) {
*aMixed = false;
outFace.AssignLiteral("tt");
}
if (!any) {
// there was no font face attrs of any kind. We are in normal font.
outFace.Truncate();
*aMixed = false;
}
return NS_OK;
}
nsresult HTMLEditor::GetFontColorState(bool* aMixed, nsAString& aOutColor) {
if (NS_WARN_IF(!aMixed)) {
return NS_ERROR_INVALID_ARG;
}
*aMixed = true;
aOutColor.Truncate();
AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return NS_ERROR_NOT_INITIALIZED;
}
bool first, any, all;
nsresult rv = GetInlinePropertyBase(
EditorInlineStyle(*nsGkAtoms::font, nsGkAtoms::color), nullptr, &first,
&any, &all, &aOutColor);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::GetInlinePropertyBase(nsGkAtoms::font, nsGkAtoms::color) "
"failed");
return EditorBase::ToGenericNSResult(rv);
}
if (any && !all) {
return NS_OK; // mixed
}
if (all) {
*aMixed = false;
return NS_OK;
}
if (!any) {
// there was no font color attrs of any kind..
aOutColor.Truncate();
*aMixed = false;
}
return NS_OK;
}
// The return value is true only if the instance of the HTML editor we created
// can handle CSS styles and if the CSS preference is checked.
NS_IMETHODIMP HTMLEditor::GetIsCSSEnabled(bool* aIsCSSEnabled) {
*aIsCSSEnabled = IsCSSEnabled();
return NS_OK;
}
bool HTMLEditor::HasStyleOrIdOrClassAttribute(Element& aElement) {
return aElement.HasNonEmptyAttr(nsGkAtoms::style) ||
aElement.HasNonEmptyAttr(nsGkAtoms::_class) ||
aElement.HasNonEmptyAttr(nsGkAtoms::id);
}
} // namespace mozilla
|