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
|
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/testing/internals.h"
#include <atomic>
#include <memory>
#include <optional>
#include <utility>
#include "base/functional/function_ref.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/process_handle.h"
#include "base/task/single_thread_task_runner.h"
#include "cc/layers/picture_layer.h"
#include "cc/trees/layer_tree_host.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "third_party/blink/public/common/widget/device_emulation_params.h"
#include "third_party/blink/public/mojom/devtools/inspector_issue.mojom-blink.h"
#include "third_party/blink/public/mojom/favicon/favicon_url.mojom-blink.h"
#include "third_party/blink/public/mojom/input/focus_type.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h"
#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser.h"
#include "third_party/blink/renderer/core/css/properties/css_unresolved_property.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/dom_string_list.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/dom/range.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/static_node_list.h"
#include "third_party/blink/renderer/core/dom/tree_scope.h"
#include "third_party/blink/renderer/core/editing/drag_caret.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/iterators/text_iterator.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker_controller.h"
#include "third_party/blink/renderer/core/editing/markers/spell_check_marker.h"
#include "third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.h"
#include "third_party/blink/renderer/core/editing/markers/text_match_marker.h"
#include "third_party/blink/renderer/core/editing/plain_text_range.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.h"
#include "third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h"
#include "third_party/blink/renderer/core/editing/spellcheck/spell_checker.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
#include "third_party/blink/renderer/core/frame/event_handler_registry.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/performance_monitor.h"
#include "third_party/blink/renderer/core/frame/remote_dom_window.h"
#include "third_party/blink/renderer/core/frame/report.h"
#include "third_party/blink/renderer/core/frame/reporting_context.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/test_report_body.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/geometry/dom_point.h"
#include "third_party/blink/renderer/core/geometry/dom_rect.h"
#include "third_party/blink/renderer/core/geometry/dom_rect_list.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_font_cache.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/custom/custom_element.h"
#include "third_party/blink/renderer/core/html/forms/form_controller.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
#include "third_party/blink/renderer/core/html/forms/text_control_inner_elements.h"
#include "third_party/blink/renderer/core/html/html_iframe_element.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/html/media/remote_playback_controller.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/input/keyboard_event_manager.h"
#include "third_party/blink/renderer/core/inspector/inspector_audits_issue.h"
#include "third_party/blink/renderer/core/inspector/inspector_issue.h"
#include "third_party/blink/renderer/core/inspector/inspector_issue_conversion.h"
#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_tree_as_text.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/lcp_critical_path_predictor/element_locator.h"
#include "third_party/blink/renderer/core/lcp_critical_path_predictor/lcp_critical_path_predictor.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/history_item.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/print_context.h"
#include "third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h"
#include "third_party/blink/renderer/core/page/spatial_navigation_controller.h"
#include "third_party/blink/renderer/core/page/touch_adjustment.h"
#include "third_party/blink/renderer/core/page/validation_message_client.h"
#include "third_party/blink/renderer/core/page/viewport_description.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/script/import_map.h"
#include "third_party/blink/renderer/core/script/modulator.h"
#include "third_party/blink/renderer/core/scroll/mac_scrollbar_animator.h"
#include "third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h"
#include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/core/streams/readable_stream_default_controller_with_script_scope.h"
#include "third_party/blink/renderer/core/streams/readable_stream_transferring_optimizer.h"
#include "third_party/blink/renderer/core/streams/underlying_sink_base.h"
#include "third_party/blink/renderer/core/streams/underlying_source_base.h"
#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/streams/writable_stream_transferring_optimizer.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/core/svg/svg_image_element.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/core/testing/callback_function_test.h"
#include "third_party/blink/renderer/core/testing/dictionary_test.h"
#include "third_party/blink/renderer/core/testing/gc_observation.h"
#include "third_party/blink/renderer/core/testing/hit_test_layer_rect.h"
#include "third_party/blink/renderer/core/testing/hit_test_layer_rect_list.h"
#include "third_party/blink/renderer/core/testing/internal_runtime_flags.h"
#include "third_party/blink/renderer/core/testing/internal_settings.h"
#include "third_party/blink/renderer/core/testing/internals_ukm_recorder.h"
#include "third_party/blink/renderer/core/testing/mock_hyphenation.h"
#include "third_party/blink/renderer/core/testing/nadc_attribute_test.h"
#include "third_party/blink/renderer/core/testing/origin_trials_test.h"
#include "third_party/blink/renderer/core/testing/record_test.h"
#include "third_party/blink/renderer/core/testing/scoped_mock_overlay_scrollbars.h"
#include "third_party/blink/renderer/core/testing/sequence_test.h"
#include "third_party/blink/renderer/core/testing/static_selection.h"
#include "third_party/blink/renderer/core/testing/type_conversions.h"
#include "third_party/blink/renderer/core/testing/union_types_test.h"
#include "third_party/blink/renderer/core/timezone/timezone_controller.h"
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
#include "third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.h"
#include "third_party/blink/renderer/platform/heap/cross_thread_handle.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/language.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
#include "third_party/blink/renderer/platform/text/layout_locale.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_base.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_std.h"
#include "third_party/blink/renderer/platform/wtf/dtoa.h"
#include "third_party/blink/renderer/platform/wtf/text/string_buffer.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding_registry.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-blink.h"
#include "ui/base/ui_base_features.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/canvas_image_source.h"
#include "v8/include/v8.h"
namespace blink {
using ui::mojom::ImeTextSpanThickness;
using ui::mojom::ImeTextSpanUnderlineStyle;
namespace {
ScopedMockOverlayScrollbars* g_mock_overlay_scrollbars = nullptr;
void ResetMockOverlayScrollbars() {
if (g_mock_overlay_scrollbars)
delete g_mock_overlay_scrollbars;
g_mock_overlay_scrollbars = nullptr;
}
class UseCounterImplObserverImpl final : public UseCounterImpl::Observer {
public:
UseCounterImplObserverImpl(ScriptPromiseResolver<IDLUndefined>* resolver,
WebFeature feature)
: resolver_(resolver), feature_(feature) {}
UseCounterImplObserverImpl(const UseCounterImplObserverImpl&) = delete;
UseCounterImplObserverImpl& operator=(const UseCounterImplObserverImpl&) =
delete;
bool OnCountFeature(WebFeature feature) final {
if (feature_ != feature)
return false;
resolver_->Resolve();
return true;
}
void Trace(Visitor* visitor) const override {
UseCounterImpl::Observer::Trace(visitor);
visitor->Trace(resolver_);
}
private:
Member<ScriptPromiseResolver<IDLUndefined>> resolver_;
WebFeature feature_;
};
class TestReadableStreamSource : public UnderlyingSourceBase {
public:
class Generator;
using Reply = CrossThreadOnceFunction<void(std::unique_ptr<Generator>)>;
using OptimizerCallback =
CrossThreadOnceFunction<void(scoped_refptr<base::SingleThreadTaskRunner>,
Reply)>;
enum class Type {
kWithNullOptimizer,
kWithPerformNullOptimizer,
kWithObservableOptimizer,
kWithPerfectOptimizer,
};
class Generator final {
USING_FAST_MALLOC(Generator);
public:
explicit Generator(int max_count) : max_count_(max_count) {}
std::optional<int> Generate() {
if (count_ >= max_count_) {
return std::nullopt;
}
++count_;
return current_++;
}
void Add(int n) { current_ += n; }
private:
friend class Optimizer;
int current_ = 0;
int count_ = 0;
const int max_count_;
};
class Optimizer final : public ReadableStreamTransferringOptimizer {
USING_FAST_MALLOC(Optimizer);
public:
Optimizer(scoped_refptr<base::SingleThreadTaskRunner> task_runner,
OptimizerCallback callback,
Type type)
: task_runner_(std::move(task_runner)),
callback_(std::move(callback)),
type_(type) {}
UnderlyingSourceBase* PerformInProcessOptimization(
ScriptState* script_state) override;
private:
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
OptimizerCallback callback_;
const Type type_;
};
TestReadableStreamSource(ScriptState* script_state, Type type)
: UnderlyingSourceBase(script_state), type_(type) {}
ScriptPromise<IDLUndefined> Start(ScriptState* script_state) override {
if (generator_) {
return ToResolvedUndefinedPromise(script_state);
}
resolver_ =
MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(script_state);
return resolver_->Promise();
}
ScriptPromise<IDLUndefined> Pull(ScriptState* script_state,
ExceptionState&) override {
if (!generator_) {
return ToResolvedUndefinedPromise(script_state);
}
const auto result = generator_->Generate();
if (!result) {
Controller()->Close();
return ToResolvedUndefinedPromise(script_state);
}
Controller()->Enqueue(
v8::Integer::New(script_state->GetIsolate(), *result));
return ToResolvedUndefinedPromise(script_state);
}
std::unique_ptr<ReadableStreamTransferringOptimizer>
CreateTransferringOptimizer(ScriptState* script_state) {
switch (type_) {
case Type::kWithNullOptimizer:
return nullptr;
case Type::kWithPerformNullOptimizer:
return std::make_unique<ReadableStreamTransferringOptimizer>();
case Type::kWithObservableOptimizer:
case Type::kWithPerfectOptimizer:
ExecutionContext* context = ExecutionContext::From(script_state);
return std::make_unique<Optimizer>(
context->GetTaskRunner(TaskType::kInternalDefault),
CrossThreadBindOnce(&TestReadableStreamSource::Detach,
MakeUnwrappingCrossThreadWeakHandle(this)),
type_);
}
}
void Attach(std::unique_ptr<Generator> generator) {
if (type_ == Type::kWithObservableOptimizer) {
generator->Add(100);
}
generator_ = std::move(generator);
if (resolver_) {
resolver_->Resolve();
}
}
void Detach(scoped_refptr<base::SingleThreadTaskRunner> task_runner,
Reply reply) {
Controller()->Close();
PostCrossThreadTask(
*task_runner, FROM_HERE,
CrossThreadBindOnce(std::move(reply), std::move(generator_)));
}
void Trace(Visitor* visitor) const override {
visitor->Trace(resolver_);
UnderlyingSourceBase::Trace(visitor);
}
private:
const Type type_;
std::unique_ptr<Generator> generator_;
Member<ScriptPromiseResolver<IDLUndefined>> resolver_;
};
UnderlyingSourceBase*
TestReadableStreamSource::Optimizer::PerformInProcessOptimization(
ScriptState* script_state) {
TestReadableStreamSource* source =
MakeGarbageCollected<TestReadableStreamSource>(script_state, type_);
ExecutionContext* context = ExecutionContext::From(script_state);
Reply reply = CrossThreadBindOnce(&TestReadableStreamSource::Attach,
MakeUnwrappingCrossThreadHandle(source));
PostCrossThreadTask(
*task_runner_, FROM_HERE,
CrossThreadBindOnce(std::move(callback_),
context->GetTaskRunner(TaskType::kInternalDefault),
std::move(reply)));
return source;
}
class TestWritableStreamSink final : public UnderlyingSinkBase {
public:
class InternalSink;
using Reply = CrossThreadOnceFunction<void(std::unique_ptr<InternalSink>)>;
using OptimizerCallback =
CrossThreadOnceFunction<void(scoped_refptr<base::SingleThreadTaskRunner>,
Reply)>;
enum class Type {
kWithNullOptimizer,
kWithPerformNullOptimizer,
kWithObservableOptimizer,
kWithPerfectOptimizer,
};
class InternalSink final {
USING_FAST_MALLOC(InternalSink);
public:
InternalSink(scoped_refptr<base::SingleThreadTaskRunner> task_runner,
CrossThreadOnceFunction<void(std::string)> success_callback,
CrossThreadOnceFunction<void()> error_callback)
: task_runner_(std::move(task_runner)),
success_callback_(std::move(success_callback)),
error_callback_(std::move(error_callback)) {}
void Append(const std::string& s) { result_.append(s); }
void Close() {
PostCrossThreadTask(
*task_runner_, FROM_HERE,
CrossThreadBindOnce(std::move(success_callback_), result_));
}
void Abort() {
PostCrossThreadTask(*task_runner_, FROM_HERE, std::move(error_callback_));
}
// We don't use WTF::String because this object can be accessed from
// multiple threads.
std::string result_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
CrossThreadOnceFunction<void(std::string)> success_callback_;
CrossThreadOnceFunction<void()> error_callback_;
};
class Optimizer final : public WritableStreamTransferringOptimizer {
USING_FAST_MALLOC(Optimizer);
public:
Optimizer(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
OptimizerCallback callback,
scoped_refptr<base::RefCountedData<std::atomic_bool>> optimizer_flag,
Type type)
: task_runner_(std::move(task_runner)),
callback_(std::move(callback)),
optimizer_flag_(std::move(optimizer_flag)),
type_(type) {}
UnderlyingSinkBase* PerformInProcessOptimization(
ScriptState* script_state) override;
private:
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
OptimizerCallback callback_;
scoped_refptr<base::RefCountedData<std::atomic_bool>> optimizer_flag_;
const Type type_;
};
explicit TestWritableStreamSink(ScriptState* script_state, Type type)
: type_(type),
optimizer_flag_(
base::MakeRefCounted<base::RefCountedData<std::atomic_bool>>(
std::in_place,
false)) {}
ScriptPromise<IDLUndefined> start(ScriptState* script_state,
WritableStreamDefaultController*,
ExceptionState&) override {
if (internal_sink_) {
return ToResolvedUndefinedPromise(script_state);
}
start_resolver_ =
MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(script_state);
return start_resolver_->Promise();
}
ScriptPromise<IDLUndefined> write(ScriptState* script_state,
ScriptValue chunk,
WritableStreamDefaultController*,
ExceptionState&) override {
DCHECK(internal_sink_);
internal_sink_->Append(
ToCoreString(script_state->GetIsolate(),
chunk.V8Value()
->ToString(script_state->GetContext())
.ToLocalChecked())
.Utf8());
return ToResolvedUndefinedPromise(script_state);
}
ScriptPromise<IDLUndefined> close(ScriptState* script_state,
ExceptionState&) override {
DCHECK(internal_sink_);
closed_ = true;
if (!optimizer_flag_->data.load()) {
// The normal closure case.
internal_sink_->Close();
return ToResolvedUndefinedPromise(script_state);
}
// When the optimizer is active, we need to detach `internal_sink_` and
// pass it to the optimizer (i.e., the sink in the destination realm).
if (detached_) {
PostCrossThreadTask(
*reply_task_runner_, FROM_HERE,
CrossThreadBindOnce(std::move(reply_), std::move(internal_sink_)));
}
return ToResolvedUndefinedPromise(script_state);
}
ScriptPromise<IDLUndefined> abort(ScriptState* script_state,
ScriptValue reason,
ExceptionState&) override {
return ToResolvedUndefinedPromise(script_state);
}
void Attach(std::unique_ptr<InternalSink> internal_sink) {
DCHECK(!internal_sink_);
if (type_ == Type::kWithObservableOptimizer) {
internal_sink->Append("A");
}
internal_sink_ = std::move(internal_sink);
if (start_resolver_) {
start_resolver_->Resolve();
}
}
void Detach(scoped_refptr<base::SingleThreadTaskRunner> task_runner,
Reply reply) {
detached_ = true;
// We need to wait for the close signal before actually detaching
// `internal_sink_`.
if (closed_) {
PostCrossThreadTask(
*task_runner, FROM_HERE,
CrossThreadBindOnce(std::move(reply), std::move(internal_sink_)));
} else {
reply_ = std::move(reply);
reply_task_runner_ = std::move(task_runner);
}
}
std::unique_ptr<WritableStreamTransferringOptimizer>
CreateTransferringOptimizer(ScriptState* script_state) {
DCHECK(internal_sink_);
if (type_ == Type::kWithNullOptimizer) {
return nullptr;
}
ExecutionContext* context = ExecutionContext::From(script_state);
return std::make_unique<Optimizer>(
context->GetTaskRunner(TaskType::kInternalDefault),
CrossThreadBindOnce(&TestWritableStreamSink::Detach,
MakeUnwrappingCrossThreadWeakHandle(this)),
optimizer_flag_, type_);
}
void Trace(Visitor* visitor) const override {
visitor->Trace(start_resolver_);
UnderlyingSinkBase::Trace(visitor);
}
static void Resolve(ScriptPromiseResolver<IDLString>* resolver,
std::string result) {
resolver->Resolve(String::FromUTF8(result));
}
static void Reject(ScriptPromiseResolverBase* resolver) {
ScriptState* script_state = resolver->GetScriptState();
ScriptState::Scope scope(script_state);
resolver->Reject(
V8ThrowException::CreateTypeError(script_state->GetIsolate(), "error"));
}
private:
const Type type_;
// `optimizer_flag_` is always non_null. The flag referenced is false
// initially, and set atomically when the associated optimizer is activated.
scoped_refptr<base::RefCountedData<std::atomic_bool>> optimizer_flag_;
std::unique_ptr<InternalSink> internal_sink_;
Member<ScriptPromiseResolver<IDLUndefined>> start_resolver_;
bool closed_ = false;
bool detached_ = false;
Reply reply_;
scoped_refptr<base::SingleThreadTaskRunner> reply_task_runner_;
};
UnderlyingSinkBase*
TestWritableStreamSink::Optimizer::PerformInProcessOptimization(
ScriptState* script_state) {
if (type_ == Type::kWithPerformNullOptimizer) {
return nullptr;
}
TestWritableStreamSink* sink =
MakeGarbageCollected<TestWritableStreamSink>(script_state, type_);
// Set the flag atomically, to notify that this optimizer is active.
optimizer_flag_->data.store(true);
ExecutionContext* context = ExecutionContext::From(script_state);
Reply reply = CrossThreadBindOnce(&TestWritableStreamSink::Attach,
MakeUnwrappingCrossThreadHandle(sink));
PostCrossThreadTask(
*task_runner_, FROM_HERE,
CrossThreadBindOnce(std::move(callback_),
context->GetTaskRunner(TaskType::kInternalDefault),
std::move(reply)));
return sink;
}
void OnLCPPredicted(ScriptPromiseResolver<IDLString>* resolver,
const Element* lcp_element) {
const ElementLocator locator =
lcp_element ? element_locator::OfElement(*lcp_element) : ElementLocator();
resolver->Resolve(element_locator::ToStringForTesting(locator));
}
} // namespace
static std::optional<DocumentMarker::MarkerType> MarkerTypeFrom(
const String& marker_type) {
if (EqualIgnoringASCIICase(marker_type, "Spelling"))
return DocumentMarker::kSpelling;
if (EqualIgnoringASCIICase(marker_type, "Grammar"))
return DocumentMarker::kGrammar;
if (EqualIgnoringASCIICase(marker_type, "TextMatch"))
return DocumentMarker::kTextMatch;
if (EqualIgnoringASCIICase(marker_type, "Composition"))
return DocumentMarker::kComposition;
if (EqualIgnoringASCIICase(marker_type, "ActiveSuggestion"))
return DocumentMarker::kActiveSuggestion;
if (EqualIgnoringASCIICase(marker_type, "Suggestion"))
return DocumentMarker::kSuggestion;
return std::nullopt;
}
static std::optional<DocumentMarker::MarkerTypes> MarkerTypesFrom(
const String& marker_type) {
if (marker_type.empty() || EqualIgnoringASCIICase(marker_type, "all"))
return DocumentMarker::MarkerTypes::All();
std::optional<DocumentMarker::MarkerType> type = MarkerTypeFrom(marker_type);
if (!type)
return std::nullopt;
return DocumentMarker::MarkerTypes(type.value());
}
static SpellCheckRequester* GetSpellCheckRequester(Document* document) {
if (!document || !document->GetFrame())
return nullptr;
return &document->GetFrame()->GetSpellChecker().GetSpellCheckRequester();
}
static ScrollableArea* ScrollableAreaForNode(Node* node) {
if (!node)
return nullptr;
if (auto* box = DynamicTo<LayoutBox>(node->GetLayoutObject()))
return box->GetScrollableArea();
return nullptr;
}
void Internals::ResetToConsistentState(Page* page) {
DCHECK(page);
page->SetIsCursorVisible(true);
// Ensure the PageScaleFactor always stays within limits, if the test changed
// the limits.
page->SetDefaultPageScaleLimits(1, 4);
page->SetPageScaleFactor(1);
page->GetChromeClient().GetWebView()->DisableDeviceEmulation();
// Ensure timers are reset so timers such as EventHandler's |hover_timer_| do
// not cause additional lifecycle updates.
for (Frame* frame = page->MainFrame(); frame;
frame = frame->Tree().TraverseNext()) {
if (auto* local_frame = DynamicTo<LocalFrame>(frame))
local_frame->GetEventHandler().Clear();
}
LocalFrame* frame = page->DeprecatedLocalMainFrame();
frame->View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(), mojom::blink::ScrollType::kProgrammatic);
OverrideUserPreferredLanguagesForTesting(Vector<AtomicString>());
KeyboardEventManager::SetCurrentCapsLockState(
OverrideCapsLockState::kDefault);
IntersectionObserver::SetThrottleDelayEnabledForTesting(true);
ResetMockOverlayScrollbars();
Page::SetMaxNumberOfFramesToTenForTesting(false);
}
Internals::Internals(ExecutionContext* context)
: runtime_flags_(InternalRuntimeFlags::create()),
document_(To<LocalDOMWindow>(context)->document()) {
document_->Fetcher()->EnableIsPreloadedForTest();
}
LocalFrame* Internals::GetFrame() const {
if (!document_)
return nullptr;
return document_->GetFrame();
}
InternalSettings* Internals::settings() const {
if (!document_)
return nullptr;
Page* page = document_->GetPage();
if (!page)
return nullptr;
return InternalSettings::From(*page);
}
InternalRuntimeFlags* Internals::runtimeFlags() const {
return runtime_flags_.Get();
}
unsigned Internals::workerThreadCount() const {
return WorkerThread::WorkerThreadCount();
}
GCObservation* Internals::observeGC(ScriptValue script_value,
ExceptionState& exception_state) {
v8::Local<v8::Value> observed_value = script_value.V8Value();
DCHECK(!observed_value.IsEmpty());
if (observed_value->IsNull() || observed_value->IsUndefined()) {
exception_state.ThrowTypeError("value to observe is null or undefined");
return nullptr;
}
return MakeGarbageCollected<GCObservation>(script_value.GetIsolate(),
observed_value);
}
unsigned Internals::updateStyleAndReturnAffectedElementCount(
ExceptionState& exception_state) const {
if (!document_) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No context document is available.");
return 0;
}
unsigned before_count = document_->GetStyleEngine().StyleForElementCount();
document_->UpdateStyleAndLayoutTree();
return document_->GetStyleEngine().StyleForElementCount() - before_count;
}
unsigned Internals::styleForElementCount(
ExceptionState& exception_state) const {
if (!document_) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No context document is available.");
return 0;
}
return document_->GetStyleEngine().StyleForElementCount();
}
unsigned Internals::needsLayoutCount(ExceptionState& exception_state) const {
LocalFrame* context_frame = GetFrame();
if (!context_frame) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No context frame is available.");
return 0;
}
bool is_partial;
unsigned needs_layout_objects;
unsigned total_objects;
context_frame->View()->CountObjectsNeedingLayout(needs_layout_objects,
total_objects, is_partial);
return needs_layout_objects;
}
unsigned Internals::layoutCountForTesting(
ExceptionState& exception_state) const {
LocalFrame* context_frame = GetFrame();
if (!context_frame) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No context frame is available.");
return 0;
}
return context_frame->View()->LayoutCountForTesting();
}
bool Internals::nodeNeedsStyleRecalc(Node* node,
ExceptionState& exception_state) const {
if (!node) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidNodeTypeError,
"Not a node");
return false;
}
return node->NeedsStyleRecalc();
}
unsigned Internals::hitTestCount(Document* doc,
ExceptionState& exception_state) const {
if (!doc) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"Must supply document to check");
return 0;
}
if (!doc->GetLayoutView())
return 0;
return doc->GetLayoutView()->HitTestCount();
}
unsigned Internals::hitTestCacheHits(Document* doc,
ExceptionState& exception_state) const {
if (!doc) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"Must supply document to check");
return 0;
}
if (!doc->GetLayoutView())
return 0;
return doc->GetLayoutView()->HitTestCacheHits();
}
Element* Internals::elementFromPoint(Document* doc,
double x,
double y,
bool ignore_clipping,
bool allow_child_frame_content,
ExceptionState& exception_state) const {
if (!doc) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"Must supply document to check");
return nullptr;
}
if (!doc->GetLayoutView())
return nullptr;
HitTestRequest::HitTestRequestType hit_type =
HitTestRequest::kReadOnly | HitTestRequest::kActive;
if (ignore_clipping)
hit_type |= HitTestRequest::kIgnoreClipping;
if (allow_child_frame_content)
hit_type |= HitTestRequest::kAllowChildFrameContent;
HitTestRequest request(hit_type);
return doc->HitTestPoint(x, y, request);
}
void Internals::clearHitTestCache(Document* doc,
ExceptionState& exception_state) const {
if (!doc) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"Must supply document to check");
return;
}
if (!doc->GetLayoutView())
return;
doc->GetLayoutView()->ClearHitTestCache();
}
Element* Internals::innerEditorElement(Element* container,
ExceptionState& exception_state) const {
if (auto* control = ToTextControlOrNull(container))
return control->InnerEditorElement();
exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
"Not a text control element.");
return nullptr;
}
bool Internals::isPreloaded(const String& url) {
return isPreloadedBy(url, document_.Get());
}
bool Internals::isPreloadedBy(const String& url, Document* document) {
if (!document)
return false;
return document->Fetcher()->IsPreloadedForTest(document->CompleteURL(url));
}
bool Internals::isLoading(const String& url) {
if (!document_)
return false;
const KURL full_url = document_->CompleteURL(url);
const String cache_identifier = document_->Fetcher()->GetCacheIdentifier(
full_url, /*skip_service_worker=*/false);
Resource* resource =
MemoryCache::Get()->ResourceForURL(full_url, cache_identifier);
// We check loader() here instead of isLoading(), because a multipart
// ImageResource lies isLoading() == false after the first part is loaded.
return resource && resource->Loader();
}
bool Internals::isLoadingFromMemoryCache(const String& url) {
if (!document_)
return false;
const KURL full_url = document_->CompleteURL(url);
const String cache_identifier = document_->Fetcher()->GetCacheIdentifier(
full_url, /*skip_service_worker=*/false);
Resource* resource =
MemoryCache::Get()->ResourceForURL(full_url, cache_identifier);
return resource && resource->GetStatus() == ResourceStatus::kCached;
}
ScriptPromise<IDLLong> Internals::getInitialResourcePriority(
ScriptState* script_state,
const String& url,
Document* document,
bool new_load_only) {
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLLong>>(script_state);
auto promise = resolver->Promise();
KURL resource_url = url_test_helpers::ToKURL(url.Utf8());
auto callback = WTF::BindOnce(&Internals::ResolveResourcePriority,
WrapPersistent(this), WrapPersistent(resolver));
document->Fetcher()->AddPriorityObserverForTesting(
resource_url, std::move(callback), new_load_only);
return promise;
}
ScriptPromise<IDLLong> Internals::getInitialResourcePriorityOfNewLoad(
ScriptState* script_state,
const String& url,
Document* document) {
return getInitialResourcePriority(script_state, url, document, true);
}
bool Internals::doesWindowHaveUrlFragment(DOMWindow* window) {
if (IsA<RemoteDOMWindow>(window))
return false;
return To<LocalFrame>(window->GetFrame())
->GetDocument()
->Url()
.HasFragmentIdentifier();
}
String Internals::getResourceHeader(const String& url,
const String& header,
Document* document) {
if (!document)
return String();
Resource* resource = document->Fetcher()->AllResources().at(
url_test_helpers::ToKURL(url.Utf8()));
if (!resource)
return String();
return resource->GetResourceRequest().HttpHeaderField(AtomicString(header));
}
Node* Internals::treeScopeRootNode(Node* node) {
DCHECK(node);
return &node->GetTreeScope().RootNode();
}
Node* Internals::parentTreeScope(Node* node) {
DCHECK(node);
const TreeScope* parent_tree_scope = node->GetTreeScope().ParentTreeScope();
return parent_tree_scope ? &parent_tree_scope->RootNode() : nullptr;
}
uint16_t Internals::compareTreeScopePosition(
const Node* node1,
const Node* node2,
ExceptionState& exception_state) const {
DCHECK(node1 && node2);
const TreeScope* tree_scope1 =
IsA<Document>(node1) ? static_cast<const TreeScope*>(To<Document>(node1))
: IsA<ShadowRoot>(node1)
? static_cast<const TreeScope*>(To<ShadowRoot>(node1))
: nullptr;
const TreeScope* tree_scope2 =
IsA<Document>(node2) ? static_cast<const TreeScope*>(To<Document>(node2))
: IsA<ShadowRoot>(node2)
? static_cast<const TreeScope*>(To<ShadowRoot>(node2))
: nullptr;
if (!tree_scope1 || !tree_scope2) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
String::Format(
"The %s node is neither a document node, nor a shadow root.",
tree_scope1 ? "second" : "first"));
return 0;
}
return tree_scope1->ComparePosition(*tree_scope2);
}
void Internals::pauseAnimations(double pause_time,
ExceptionState& exception_state) {
if (pause_time < 0) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
ExceptionMessages::IndexExceedsMinimumBound("pauseTime", pause_time,
0.0));
return;
}
if (!GetFrame())
return;
GetFrame()->View()->UpdateAllLifecyclePhasesForTest();
GetFrame()->GetDocument()->Timeline().PauseAnimationsForTesting(
ANIMATION_TIME_DELTA_FROM_SECONDS(pause_time));
}
bool Internals::isCompositedAnimation(Animation* animation) {
return animation->HasActiveAnimationsOnCompositor();
}
void Internals::disableCompositedAnimation(Animation* animation) {
animation->DisableCompositedAnimationForTesting();
}
void Internals::advanceImageAnimation(Element* image,
ExceptionState& exception_state) {
DCHECK(image);
ImageResourceContent* content = nullptr;
if (auto* html_image = DynamicTo<HTMLImageElement>(*image)) {
content = html_image->CachedImage();
} else if (auto* svg_image = DynamicTo<SVGImageElement>(*image)) {
content = svg_image->CachedImage();
} else {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The element provided is not a image element.");
return;
}
if (!content || !content->HasImage()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The image resource is not available.");
return;
}
Image* image_data = content->GetImage();
image_data->AdvanceAnimationForTesting();
}
uint32_t Internals::countElementShadow(const Node* root,
ExceptionState& exception_state) const {
DCHECK(root);
if (!IsA<ShadowRoot>(root)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The node argument is not a shadow root.");
return 0;
}
return To<ShadowRoot>(root)->ChildShadowRootCount();
}
namespace {
bool CheckForFlatTreeExceptions(Node* node, ExceptionState& exception_state) {
if (node && !node->IsShadowRoot())
return false;
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The node argument doesn't participate in the flat tree.");
return true;
}
} // namespace
Node* Internals::nextSiblingInFlatTree(Node* node,
ExceptionState& exception_state) {
if (CheckForFlatTreeExceptions(node, exception_state))
return nullptr;
return FlatTreeTraversal::NextSibling(*node);
}
Node* Internals::firstChildInFlatTree(Node* node,
ExceptionState& exception_state) {
if (CheckForFlatTreeExceptions(node, exception_state))
return nullptr;
return FlatTreeTraversal::FirstChild(*node);
}
Node* Internals::lastChildInFlatTree(Node* node,
ExceptionState& exception_state) {
if (CheckForFlatTreeExceptions(node, exception_state))
return nullptr;
return FlatTreeTraversal::LastChild(*node);
}
Node* Internals::nextInFlatTree(Node* node, ExceptionState& exception_state) {
if (CheckForFlatTreeExceptions(node, exception_state))
return nullptr;
return FlatTreeTraversal::Next(*node);
}
Node* Internals::previousInFlatTree(Node* node,
ExceptionState& exception_state) {
if (CheckForFlatTreeExceptions(node, exception_state))
return nullptr;
return FlatTreeTraversal::Previous(*node);
}
String Internals::elementLayoutTreeAsText(Element* element,
ExceptionState& exception_state) {
DCHECK(element);
element->GetDocument().View()->UpdateAllLifecyclePhasesForTest();
String representation = ExternalRepresentation(element);
if (representation.empty()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The element provided has no external representation.");
return String();
}
return representation;
}
CSSStyleDeclaration* Internals::computedStyleIncludingVisitedInfo(
Element* element) const {
DCHECK(element);
bool allow_visited_style = true;
return MakeGarbageCollected<CSSComputedStyleDeclaration>(element,
allow_visited_style);
}
ShadowRoot* Internals::createUserAgentShadowRoot(Element* host) {
DCHECK(host);
return &host->EnsureUserAgentShadowRoot();
}
void Internals::setBrowserControlsState(float top_height,
float bottom_height,
bool shrinks_layout) {
document_->GetPage()->GetChromeClient().SetBrowserControlsState(
top_height, bottom_height, shrinks_layout);
}
void Internals::setBrowserControlsShownRatio(float top_ratio,
float bottom_ratio) {
document_->GetPage()->GetChromeClient().SetBrowserControlsShownRatio(
top_ratio, bottom_ratio);
}
Node* Internals::effectiveRootScroller(Document* document) {
if (!document)
document = document_;
return &document->GetRootScrollerController().EffectiveRootScroller();
}
ShadowRoot* Internals::shadowRoot(Element* host) {
DCHECK(host);
if (auto* input = DynamicTo<HTMLInputElement>(*host)) {
input->EnsureShadowSubtree();
}
return host->GetShadowRoot();
}
String Internals::ShadowRootMode(const Node* root,
ExceptionState& exception_state) const {
DCHECK(root);
auto* shadow_root = DynamicTo<ShadowRoot>(root);
if (!shadow_root) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The node provided is not a shadow root.");
return String();
}
switch (shadow_root->GetMode()) {
case ShadowRootMode::kUserAgent:
return String("UserAgentShadowRoot");
case ShadowRootMode::kOpen:
return String("OpenShadowRoot");
case ShadowRootMode::kClosed:
return String("ClosedShadowRoot");
default:
NOTREACHED();
}
}
const AtomicString& Internals::shadowPseudoId(Element* element) {
DCHECK(element);
return element->ShadowPseudoId();
}
bool Internals::isValidationMessageVisible(Element* element) {
DCHECK(element);
if (auto* page = element->GetDocument().GetPage()) {
return page->GetValidationMessageClient().IsValidationMessageVisible(
*element);
}
return false;
}
void Internals::selectColorInColorChooser(Element* element,
const String& color_value) {
DCHECK(element);
Color color;
if (!color.SetFromString(color_value))
return;
if (auto* input = DynamicTo<HTMLInputElement>(*element))
input->SelectColorInColorChooser(color);
}
void Internals::endColorChooser(Element* element) {
DCHECK(element);
if (auto* input = DynamicTo<HTMLInputElement>(*element))
input->EndColorChooserForTesting();
}
bool Internals::hasAutofocusRequest(Document* document) {
if (!document)
document = document_;
return document->HasAutofocusCandidates();
}
bool Internals::hasAutofocusRequest() {
return hasAutofocusRequest(nullptr);
}
Vector<String> Internals::formControlStateOfHistoryItem(
ExceptionState& exception_state) {
HistoryItem* main_item = nullptr;
if (GetFrame())
main_item = GetFrame()->Loader().GetDocumentLoader()->GetHistoryItem();
if (!main_item) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No history item is available.");
return Vector<String>();
}
return main_item->GetDocumentState();
}
void Internals::setFormControlStateOfHistoryItem(
const Vector<String>& state,
ExceptionState& exception_state) {
HistoryItem* main_item = nullptr;
if (GetFrame())
main_item = GetFrame()->Loader().GetDocumentLoader()->GetHistoryItem();
if (!main_item) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No history item is available.");
return;
}
main_item->ClearDocumentState();
main_item->SetDocumentState(state);
}
DOMWindow* Internals::pagePopupWindow() const {
if (!document_)
return nullptr;
if (Page* page = document_->GetPage()) {
return To<LocalDOMWindow>(
page->GetChromeClient().PagePopupWindowForTesting());
}
return nullptr;
}
DOMRectReadOnly* Internals::absoluteCaretBounds(
ExceptionState& exception_state) {
if (!GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The document's frame cannot be retrieved.");
return nullptr;
}
document_->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return DOMRectReadOnly::FromRect(
GetFrame()->Selection().AbsoluteCaretBounds());
}
String Internals::textAffinity() {
if (GetFrame() && GetFrame()
->GetPage()
->GetFocusController()
.FocusedFrame()
->Selection()
.GetSelectionInDOMTree()
.Affinity() == TextAffinity::kUpstream) {
return "Upstream";
}
return "Downstream";
}
DOMRectReadOnly* Internals::boundingBox(Element* element) {
DCHECK(element);
element->GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);
LayoutObject* layout_object = element->GetLayoutObject();
if (!layout_object)
return DOMRectReadOnly::Create(0, 0, 0, 0);
return DOMRectReadOnly::FromRect(layout_object->AbsoluteBoundingBoxRect());
}
void Internals::setMarker(Document* document,
const Range* range,
const String& marker_type,
ExceptionState& exception_state) {
if (!document) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No context document is available.");
return;
}
std::optional<DocumentMarker::MarkerType> type = MarkerTypeFrom(marker_type);
if (!type) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The marker type provided ('" + marker_type + "') is invalid.");
return;
}
if (type != DocumentMarker::kSpelling && type != DocumentMarker::kGrammar) {
exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
"internals.setMarker() currently only "
"supports spelling and grammar markers; "
"attempted to add marker of type '" +
marker_type + "'.");
return;
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
if (type == DocumentMarker::kSpelling)
document->Markers().AddSpellingMarker(EphemeralRange(range));
else
document->Markers().AddGrammarMarker(EphemeralRange(range));
}
void Internals::removeMarker(Document* document,
const Range* range,
const String& marker_type,
ExceptionState& exception_state) {
if (!document) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No context document is available.");
return;
}
std::optional<DocumentMarker::MarkerType> type = MarkerTypeFrom(marker_type);
if (!type) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The marker type provided ('" + marker_type + "') is invalid.");
return;
}
if (type != DocumentMarker::kSpelling && type != DocumentMarker::kGrammar) {
exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
"internals.setMarker() currently only "
"supports spelling and grammar markers; "
"attempted to add marker of type '" +
marker_type + "'.");
return;
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
if (type == DocumentMarker::kSpelling) {
document->Markers().RemoveMarkersInRange(
EphemeralRange(range), DocumentMarker::MarkerTypes::Spelling());
} else {
document->Markers().RemoveMarkersInRange(
EphemeralRange(range), DocumentMarker::MarkerTypes::Grammar());
}
}
unsigned Internals::markerCountForNode(Text* text,
const String& marker_type,
ExceptionState& exception_state) {
DCHECK(text);
std::optional<DocumentMarker::MarkerTypes> marker_types =
MarkerTypesFrom(marker_type);
if (!marker_types) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The marker type provided ('" + marker_type + "') is invalid.");
return 0;
}
return text->GetDocument()
.Markers()
.MarkersFor(*text, marker_types.value())
.size();
}
unsigned Internals::activeMarkerCountForNode(Text* text) {
DCHECK(text);
// Only TextMatch markers can be active.
DocumentMarkerVector markers = text->GetDocument().Markers().MarkersFor(
*text, DocumentMarker::MarkerTypes::TextMatch());
unsigned active_marker_count = 0;
for (const auto& marker : markers) {
if (To<TextMatchMarker>(marker.Get())->IsActiveMatch())
active_marker_count++;
}
return active_marker_count;
}
DocumentMarker* Internals::MarkerAt(Text* text,
const String& marker_type,
unsigned index,
ExceptionState& exception_state) {
DCHECK(text);
std::optional<DocumentMarker::MarkerTypes> marker_types =
MarkerTypesFrom(marker_type);
if (!marker_types) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The marker type provided ('" + marker_type + "') is invalid.");
return nullptr;
}
DocumentMarkerVector markers =
text->GetDocument().Markers().MarkersFor(*text, marker_types.value());
if (markers.size() <= index)
return nullptr;
return markers[index].Get();
}
Range* Internals::markerRangeForNode(Text* text,
const String& marker_type,
unsigned index,
ExceptionState& exception_state) {
DCHECK(text);
DocumentMarker* marker = MarkerAt(text, marker_type, index, exception_state);
if (!marker)
return nullptr;
return MakeGarbageCollected<Range>(text->GetDocument(), text,
marker->StartOffset(), text,
marker->EndOffset());
}
String Internals::markerDescriptionForNode(Text* text,
const String& marker_type,
unsigned index,
ExceptionState& exception_state) {
DocumentMarker* marker = MarkerAt(text, marker_type, index, exception_state);
if (!marker || !IsSpellCheckMarker(*marker))
return String();
return To<SpellCheckMarker>(marker)->Description();
}
unsigned Internals::markerBackgroundColorForNode(
Text* text,
const String& marker_type,
unsigned index,
ExceptionState& exception_state) {
DocumentMarker* marker = MarkerAt(text, marker_type, index, exception_state);
auto* style_marker = DynamicTo<StyleableMarker>(marker);
if (!style_marker)
return 0;
return style_marker->BackgroundColor().Rgb();
}
unsigned Internals::markerUnderlineColorForNode(
Text* text,
const String& marker_type,
unsigned index,
ExceptionState& exception_state) {
DocumentMarker* marker = MarkerAt(text, marker_type, index, exception_state);
auto* style_marker = DynamicTo<StyleableMarker>(marker);
if (!style_marker)
return 0;
return style_marker->UnderlineColor().Rgb();
}
static std::optional<TextMatchMarker::MatchStatus> MatchStatusFrom(
const String& match_status) {
if (EqualIgnoringASCIICase(match_status, "kActive"))
return TextMatchMarker::MatchStatus::kActive;
if (EqualIgnoringASCIICase(match_status, "kInactive"))
return TextMatchMarker::MatchStatus::kInactive;
return std::nullopt;
}
void Internals::addTextMatchMarker(const Range* range,
const String& match_status,
ExceptionState& exception_state) {
DCHECK(range);
if (!range->OwnerDocument().View())
return;
std::optional<TextMatchMarker::MatchStatus> match_status_enum =
MatchStatusFrom(match_status);
if (!match_status_enum) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The match status provided ('" + match_status + "') is invalid.");
return;
}
range->OwnerDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);
range->OwnerDocument().Markers().AddTextMatchMarker(
EphemeralRange(range), match_status_enum.value());
// This simulates what the production code does after
// DocumentMarkerController::addTextMatchMarker().
range->OwnerDocument().GetLayoutView()->InvalidatePaintForTickmarks();
}
static bool ParseColor(const String& value,
Color& color,
ExceptionState& exception_state,
String error_message) {
if (!color.SetFromString(value)) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
error_message);
return false;
}
return true;
}
static std::optional<ImeTextSpanThickness> ThicknessFrom(
const String& thickness) {
if (EqualIgnoringASCIICase(thickness, "none"))
return ImeTextSpanThickness::kNone;
if (EqualIgnoringASCIICase(thickness, "thin"))
return ImeTextSpanThickness::kThin;
if (EqualIgnoringASCIICase(thickness, "thick"))
return ImeTextSpanThickness::kThick;
return std::nullopt;
}
static std::optional<ImeTextSpanUnderlineStyle> UnderlineStyleFrom(
const String& underline_style) {
if (EqualIgnoringASCIICase(underline_style, "none"))
return ImeTextSpanUnderlineStyle::kNone;
if (EqualIgnoringASCIICase(underline_style, "solid"))
return ImeTextSpanUnderlineStyle::kSolid;
if (EqualIgnoringASCIICase(underline_style, "dot"))
return ImeTextSpanUnderlineStyle::kDot;
if (EqualIgnoringASCIICase(underline_style, "dash"))
return ImeTextSpanUnderlineStyle::kDash;
if (EqualIgnoringASCIICase(underline_style, "squiggle"))
return ImeTextSpanUnderlineStyle::kSquiggle;
return std::nullopt;
}
namespace {
void AddStyleableMarkerHelper(const Range* range,
const String& underline_color_value,
const String& thickness_value,
const String& underline_style_value,
const String& text_color_value,
const String& background_color_value,
ExceptionState& exception_state,
base::FunctionRef<void(const EphemeralRange&,
Color,
ImeTextSpanThickness,
ImeTextSpanUnderlineStyle,
Color,
Color)> create_marker) {
DCHECK(range);
range->OwnerDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);
std::optional<ImeTextSpanThickness> thickness =
ThicknessFrom(thickness_value);
if (!thickness) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The thickness provided ('" + thickness_value + "') is invalid.");
return;
}
std::optional<ImeTextSpanUnderlineStyle> underline_style =
UnderlineStyleFrom(underline_style_value);
if (!underline_style_value) {
exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
"The underline style provided ('" +
underline_style_value +
"') is invalid.");
return;
}
Color underline_color;
Color background_color;
Color text_color;
if (ParseColor(underline_color_value, underline_color, exception_state,
"Invalid underline color.") &&
ParseColor(text_color_value, text_color, exception_state,
"Invalid text color.") &&
ParseColor(background_color_value, background_color, exception_state,
"Invalid background color.")) {
create_marker(EphemeralRange(range), underline_color, thickness.value(),
underline_style.value(), text_color, background_color);
}
}
} // namespace
void Internals::addCompositionMarker(const Range* range,
const String& underline_color_value,
const String& thickness_value,
const String& underline_style_value,
const String& text_color_value,
const String& background_color_value,
ExceptionState& exception_state) {
DocumentMarkerController& document_marker_controller =
range->OwnerDocument().Markers();
AddStyleableMarkerHelper(
range, underline_color_value, thickness_value, underline_style_value,
text_color_value, background_color_value, exception_state,
[&document_marker_controller](const EphemeralRange& range,
Color underline_color,
ImeTextSpanThickness thickness,
ImeTextSpanUnderlineStyle underline_style,
Color text_color, Color background_color) {
document_marker_controller.AddCompositionMarker(
range, underline_color, thickness, underline_style, text_color,
background_color);
});
}
void Internals::addActiveSuggestionMarker(const Range* range,
const String& underline_color_value,
const String& thickness_value,
const String& background_color_value,
ExceptionState& exception_state) {
// Underline style and text color aren't really supported for suggestions so
// providing default values for now.
String underline_style_value = "solid";
String text_color_value = "transparent";
DocumentMarkerController& document_marker_controller =
range->OwnerDocument().Markers();
AddStyleableMarkerHelper(
range, underline_color_value, thickness_value, underline_style_value,
text_color_value, background_color_value, exception_state,
[&document_marker_controller](const EphemeralRange& range,
Color underline_color,
ImeTextSpanThickness thickness,
ImeTextSpanUnderlineStyle underline_style,
Color text_color, Color background_color) {
document_marker_controller.AddActiveSuggestionMarker(
range, underline_color, thickness, underline_style, text_color,
background_color);
});
}
void Internals::addSuggestionMarker(
const Range* range,
const Vector<String>& suggestions,
const String& suggestion_highlight_color_value,
const String& underline_color_value,
const String& thickness_value,
const String& background_color_value,
ExceptionState& exception_state) {
// Underline style and text color aren't really supported for suggestions so
// providing default values for now.
String underline_style_value = "solid";
String text_color_value = "transparent";
Color suggestion_highlight_color;
if (!ParseColor(suggestion_highlight_color_value, suggestion_highlight_color,
exception_state, "Invalid suggestion highlight color."))
return;
DocumentMarkerController& document_marker_controller =
range->OwnerDocument().Markers();
AddStyleableMarkerHelper(
range, underline_color_value, thickness_value, underline_style_value,
text_color_value, background_color_value, exception_state,
[&document_marker_controller, &suggestions, &suggestion_highlight_color](
const EphemeralRange& range, Color underline_color,
ImeTextSpanThickness thickness,
ImeTextSpanUnderlineStyle underline_style, Color text_color,
Color background_color) {
document_marker_controller.AddSuggestionMarker(
range,
SuggestionMarkerProperties::Builder()
.SetType(SuggestionMarker::SuggestionType::kNotMisspelling)
.SetSuggestions(suggestions)
.SetHighlightColor(suggestion_highlight_color)
.SetUnderlineColor(underline_color)
.SetThickness(thickness)
.SetUnderlineStyle(underline_style)
.SetTextColor(text_color)
.SetBackgroundColor(background_color)
.Build());
});
}
void Internals::setTextMatchMarkersActive(Node* node,
unsigned start_offset,
unsigned end_offset,
bool active) {
DCHECK(node);
node->GetDocument().Markers().SetTextMatchMarkersActive(
To<Text>(*node), start_offset, end_offset, active);
}
String Internals::viewportAsText(Document* document,
float,
int available_width,
int available_height,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetPage()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return String();
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
Page* page = document->GetPage();
// Update initial viewport size.
gfx::Size initial_viewport_size(available_width, available_height);
document->GetPage()->DeprecatedLocalMainFrame()->View()->SetFrameRect(
gfx::Rect(gfx::Point(), initial_viewport_size));
ViewportDescription description = page->GetViewportDescription();
PageScaleConstraints constraints =
description.Resolve(gfx::SizeF(initial_viewport_size), Length());
constraints.FitToContentsWidth(constraints.layout_size.width(),
available_width);
constraints.ResolveAutoInitialScale();
StringBuilder builder;
builder.Append("viewport size ");
builder.Append(String::Number(constraints.layout_size.width()));
builder.Append('x');
builder.Append(String::Number(constraints.layout_size.height()));
builder.Append(" scale ");
builder.Append(String::Number(constraints.initial_scale));
builder.Append(" with limits [");
builder.Append(String::Number(constraints.minimum_scale));
builder.Append(", ");
builder.Append(String::Number(constraints.maximum_scale));
builder.Append("] and userScalable ");
builder.Append(String::Boolean(description.user_zoom));
return builder.ToString();
}
bool Internals::elementShouldAutoComplete(Element* element,
ExceptionState& exception_state) {
DCHECK(element);
if (auto* input = DynamicTo<HTMLInputElement>(*element))
return input->ShouldAutocomplete();
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not an INPUT.");
return false;
}
String Internals::suggestedValue(Element* element,
ExceptionState& exception_state) {
DCHECK(element);
if (!element->IsFormControlElement()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not a form control element.");
return String();
}
String suggested_value;
if (auto* input = DynamicTo<HTMLInputElement>(*element))
return input->SuggestedValue();
if (auto* textarea = DynamicTo<HTMLTextAreaElement>(*element))
return textarea->SuggestedValue();
if (auto* select = DynamicTo<HTMLSelectElement>(*element))
return select->SuggestedValue();
return suggested_value;
}
void Internals::setSuggestedValue(Element* element,
const String& value,
ExceptionState& exception_state) {
DCHECK(element);
if (!element->IsFormControlElement()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not a form control element.");
return;
}
if (auto* input = DynamicTo<HTMLInputElement>(*element))
input->SetSuggestedValue(value);
if (auto* textarea = DynamicTo<HTMLTextAreaElement>(*element))
textarea->SetSuggestedValue(value);
if (auto* select = DynamicTo<HTMLSelectElement>(*element)) {
// A Null string resets the suggested value.
select->SetSuggestedValue(value.empty() ? String() : value);
}
To<HTMLFormControlElement>(element)->SetAutofillState(
value.empty() ? WebAutofillState::kNotFilled
: WebAutofillState::kPreviewed);
}
void Internals::setAutofilledValue(Element* element,
const String& value,
ExceptionState& exception_state) {
DCHECK(element);
if (!element->IsFormControlElement()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not a form control element.");
return;
}
if (auto* input = DynamicTo<HTMLInputElement>(*element)) {
input->DispatchScopedEvent(
*Event::CreateBubble(event_type_names::kKeydown));
input->SetAutofillValue(value);
input->DispatchScopedEvent(*Event::CreateBubble(event_type_names::kKeyup));
}
if (auto* textarea = DynamicTo<HTMLTextAreaElement>(*element)) {
textarea->DispatchScopedEvent(
*Event::CreateBubble(event_type_names::kKeydown));
textarea->SetAutofillValue(value);
textarea->DispatchScopedEvent(
*Event::CreateBubble(event_type_names::kKeyup));
}
if (auto* select = DynamicTo<HTMLSelectElement>(*element)) {
select->SetAutofillValue(
value.empty() ? String() // Null string resets the autofill state.
: value,
value.empty() ? WebAutofillState::kNotFilled
: WebAutofillState::kAutofilled);
}
}
void Internals::setAutofilled(Element* element,
bool enabled,
ExceptionState& exception_state) {
DCHECK(element);
auto* form_control_element = DynamicTo<HTMLFormControlElement>(element);
if (!form_control_element) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not a form control element.");
return;
}
form_control_element->SetAutofillState(
enabled ? WebAutofillState::kAutofilled : WebAutofillState::kNotFilled);
}
void Internals::setSelectionRangeForNumberType(
Element* input_element,
uint32_t start,
uint32_t end,
ExceptionState& exception_state) {
DCHECK(input_element);
auto* html_input_element = DynamicTo<HTMLInputElement>(input_element);
if (!html_input_element) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not an input element.");
return;
}
html_input_element->SetSelectionRangeForTesting(start, end, exception_state);
}
Range* Internals::rangeFromLocationAndLength(Element* scope,
int range_location,
int range_length) {
DCHECK(scope);
// TextIterator depends on Layout information, make sure layout it up to date.
scope->GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return CreateRange(
PlainTextRange(range_location, range_location + range_length)
.CreateRange(*scope));
}
unsigned Internals::locationFromRange(Element* scope, const Range* range) {
DCHECK(scope && range);
// PlainTextRange depends on Layout information, make sure layout it up to
// date.
scope->GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return PlainTextRange::Create(*scope, *range).Start();
}
unsigned Internals::lengthFromRange(Element* scope, const Range* range) {
DCHECK(scope && range);
// PlainTextRange depends on Layout information, make sure layout it up to
// date.
scope->GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return PlainTextRange::Create(*scope, *range).length();
}
String Internals::rangeAsText(const Range* range) {
DCHECK(range);
// Clean layout is required by plain text extraction.
range->OwnerDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return range->GetText();
}
void Internals::HitTestRect(HitTestLocation& location,
HitTestResult& result,
int x,
int y,
int width,
int height,
Document* document) {
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
EventHandler& event_handler = document->GetFrame()->GetEventHandler();
PhysicalRect rect{LayoutUnit(x), LayoutUnit(y), LayoutUnit(width),
LayoutUnit(height)};
rect.offset = document->GetFrame()->View()->ConvertFromRootFrame(rect.offset);
location = HitTestLocation(rect);
result = event_handler.HitTestResultAtLocation(
location, HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kListBased);
}
// TODO(mustaq): The next 5 functions are very similar, can we combine them?
DOMPoint* Internals::touchPositionAdjustedToBestClickableNode(
int x,
int y,
int width,
int height,
Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return nullptr;
}
HitTestLocation location;
HitTestResult result;
HitTestRect(location, result, x, y, width, height, document);
Node* target_node = nullptr;
gfx::Point adjusted_point;
EventHandler& event_handler = document->GetFrame()->GetEventHandler();
bool found_node = event_handler.BestNodeForHitTestResult(
TouchAdjustmentCandidateType::kClickable, location, result,
adjusted_point, target_node);
if (found_node)
return DOMPoint::Create(adjusted_point.x(), adjusted_point.y());
return nullptr;
}
Node* Internals::touchNodeAdjustedToBestClickableNode(
int x,
int y,
int width,
int height,
Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return nullptr;
}
HitTestLocation location;
HitTestResult result;
HitTestRect(location, result, x, y, width, height, document);
Node* target_node = nullptr;
gfx::Point adjusted_point;
document->GetFrame()->GetEventHandler().BestNodeForHitTestResult(
TouchAdjustmentCandidateType::kClickable, location, result,
adjusted_point, target_node);
return target_node;
}
DOMPoint* Internals::touchPositionAdjustedToBestContextMenuNode(
int x,
int y,
int width,
int height,
Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return nullptr;
}
HitTestLocation location;
HitTestResult result;
HitTestRect(location, result, x, y, width, height, document);
Node* target_node = nullptr;
gfx::Point adjusted_point;
EventHandler& event_handler = document->GetFrame()->GetEventHandler();
bool found_node = event_handler.BestNodeForHitTestResult(
TouchAdjustmentCandidateType::kContextMenu, location, result,
adjusted_point, target_node);
if (found_node)
return DOMPoint::Create(adjusted_point.x(), adjusted_point.y());
return DOMPoint::Create(x, y);
}
Node* Internals::touchNodeAdjustedToBestContextMenuNode(
int x,
int y,
int width,
int height,
Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return nullptr;
}
HitTestLocation location;
HitTestResult result;
HitTestRect(location, result, x, y, width, height, document);
Node* target_node = nullptr;
gfx::Point adjusted_point;
document->GetFrame()->GetEventHandler().BestNodeForHitTestResult(
TouchAdjustmentCandidateType::kContextMenu, location, result,
adjusted_point, target_node);
return target_node;
}
Node* Internals::touchNodeAdjustedToBestStylusWritableNode(
int x,
int y,
int width,
int height,
Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return nullptr;
}
HitTestLocation location;
HitTestResult result;
HitTestRect(location, result, x, y, width, height, document);
Node* target_node = nullptr;
gfx::Point adjusted_point;
document->GetFrame()->GetEventHandler().BestNodeForHitTestResult(
TouchAdjustmentCandidateType::kStylusWritable, location, result,
adjusted_point, target_node);
return target_node;
}
int Internals::lastSpellCheckRequestSequence(Document* document,
ExceptionState& exception_state) {
SpellCheckRequester* requester = GetSpellCheckRequester(document);
if (!requester) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No spell check requestor can be obtained for the provided document.");
return -1;
}
return requester->LastRequestSequence();
}
int Internals::lastSpellCheckProcessedSequence(
Document* document,
ExceptionState& exception_state) {
SpellCheckRequester* requester = GetSpellCheckRequester(document);
if (!requester) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No spell check requestor can be obtained for the provided document.");
return -1;
}
return requester->LastProcessedSequence();
}
int Internals::spellCheckedTextLength(Document* document,
ExceptionState& exception_state) {
SpellCheckRequester* requester = GetSpellCheckRequester(document);
if (!requester) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No spell check requestor can be obtained for the provided document.");
return -1;
}
return requester->SpellCheckedTextLength();
}
void Internals::cancelCurrentSpellCheckRequest(
Document* document,
ExceptionState& exception_state) {
SpellCheckRequester* requester = GetSpellCheckRequester(document);
if (!requester) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No spell check requestor can be obtained for the provided document.");
return;
}
requester->CancelCheck();
}
String Internals::idleTimeSpellCheckerState(Document* document,
ExceptionState& exception_state) {
if (!document || !document->GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No frame can be obtained from the provided document.");
return String();
}
return document->GetFrame()
->GetSpellChecker()
.GetIdleSpellCheckController()
.GetStateAsString();
}
void Internals::runIdleTimeSpellChecker(Document* document,
ExceptionState& exception_state) {
if (!document || !document->GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No frame can be obtained from the provided document.");
return;
}
document->GetFrame()
->GetSpellChecker()
.GetIdleSpellCheckController()
.ForceInvocationForTesting();
}
bool Internals::hasLastEditCommand(Document* document,
ExceptionState& exception_state) {
if (!document || !document->GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No frame can be obtained from the provided document.");
return false;
}
return document->GetFrame()->GetEditor().LastEditCommand();
}
Vector<AtomicString> Internals::userPreferredLanguages() const {
return blink::UserPreferredLanguages();
}
// Optimally, the bindings generator would pass a Vector<AtomicString> here but
// this is not supported yet.
void Internals::setUserPreferredLanguages(const Vector<String>& languages) {
Vector<AtomicString> atomic_languages;
for (const String& language : languages)
atomic_languages.push_back(AtomicString(language));
OverrideUserPreferredLanguagesForTesting(atomic_languages);
}
void Internals::setSystemTimeZone(const String& timezone) {
blink::TimeZoneController::ChangeTimeZoneForTesting(timezone);
}
unsigned Internals::mediaKeysCount() {
return InstanceCounters::CounterValue(InstanceCounters::kMediaKeysCounter);
}
unsigned Internals::mediaKeySessionCount() {
return InstanceCounters::CounterValue(
InstanceCounters::kMediaKeySessionCounter);
}
static unsigned EventHandlerCount(
Document& document,
EventHandlerRegistry::EventHandlerClass handler_class) {
if (!document.GetPage())
return 0;
EventHandlerRegistry* registry =
&document.GetFrame()->GetEventHandlerRegistry();
unsigned count = 0;
const EventTargetSet* targets = registry->EventHandlerTargets(handler_class);
if (targets) {
for (const auto& target : *targets)
count += target.value;
}
return count;
}
unsigned Internals::wheelEventHandlerCount(Document* document) const {
DCHECK(document);
return EventHandlerCount(*document,
EventHandlerRegistry::kWheelEventBlocking) +
EventHandlerCount(*document, EventHandlerRegistry::kWheelEventPassive);
}
unsigned Internals::scrollEventHandlerCount(Document* document) const {
DCHECK(document);
return EventHandlerCount(*document, EventHandlerRegistry::kScrollEvent);
}
unsigned Internals::touchStartOrMoveEventHandlerCount(
Document* document) const {
DCHECK(document);
return EventHandlerCount(*document, EventHandlerRegistry::kTouchAction) +
EventHandlerCount(
*document, EventHandlerRegistry::kTouchStartOrMoveEventBlocking) +
EventHandlerCount(
*document,
EventHandlerRegistry::kTouchStartOrMoveEventBlockingLowLatency) +
EventHandlerCount(*document,
EventHandlerRegistry::kTouchStartOrMoveEventPassive);
}
unsigned Internals::touchEndOrCancelEventHandlerCount(
Document* document) const {
DCHECK(document);
return EventHandlerCount(
*document, EventHandlerRegistry::kTouchEndOrCancelEventBlocking) +
EventHandlerCount(*document,
EventHandlerRegistry::kTouchEndOrCancelEventPassive);
}
unsigned Internals::pointerEventHandlerCount(Document* document) const {
DCHECK(document);
return EventHandlerCount(*document, EventHandlerRegistry::kPointerEvent) +
EventHandlerCount(*document,
EventHandlerRegistry::kPointerRawUpdateEvent);
}
// Given a vector of rects, merge those that are adjacent, leaving empty rects
// in the place of no longer used slots. This is intended to simplify the list
// of rects returned by an SkRegion (which have been split apart for sorting
// purposes). No attempt is made to do this efficiently (eg. by relying on the
// sort criteria of SkRegion).
static void MergeRects(Vector<gfx::Rect>& rects) {
for (wtf_size_t i = 0; i < rects.size(); ++i) {
if (rects[i].IsEmpty())
continue;
bool updated;
do {
updated = false;
for (wtf_size_t j = i + 1; j < rects.size(); ++j) {
if (rects[j].IsEmpty())
continue;
// Try to merge rects[j] into rects[i] along the 4 possible edges.
if (rects[i].y() == rects[j].y() &&
rects[i].height() == rects[j].height()) {
if (rects[i].x() + rects[i].width() == rects[j].x()) {
rects[i].set_width(rects[i].width() + rects[j].width());
rects[j] = gfx::Rect();
updated = true;
} else if (rects[i].x() == rects[j].x() + rects[j].width()) {
rects[i].set_x(rects[j].x());
rects[i].set_width(rects[i].width() + rects[j].width());
rects[j] = gfx::Rect();
updated = true;
}
} else if (rects[i].x() == rects[j].x() &&
rects[i].width() == rects[j].width()) {
if (rects[i].y() + rects[i].height() == rects[j].y()) {
rects[i].set_height(rects[i].height() + rects[j].height());
rects[j] = gfx::Rect();
updated = true;
} else if (rects[i].y() == rects[j].y() + rects[j].height()) {
rects[i].set_y(rects[j].y());
rects[i].set_height(rects[i].height() + rects[j].height());
rects[j] = gfx::Rect();
updated = true;
}
}
}
} while (updated);
}
}
HitTestLayerRectList* Internals::touchEventTargetLayerRects(
Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->View() || !document->GetPage() || document != document_) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return nullptr;
}
document->View()->UpdateAllLifecyclePhasesForTest();
auto* hit_test_rects = MakeGarbageCollected<HitTestLayerRectList>();
if (!document->View()->RootCcLayer()) {
return hit_test_rects;
}
for (const auto& layer : document->View()->RootCcLayer()->children()) {
const cc::TouchActionRegion& touch_action_region =
layer->touch_action_region();
if (!touch_action_region.GetAllRegions().IsEmpty()) {
const auto& offset = layer->offset_to_transform_parent();
gfx::Rect layer_rect(
gfx::ToRoundedPoint(gfx::PointAtOffsetFromOrigin(offset)),
layer->bounds());
Vector<gfx::Rect> layer_hit_test_rects;
for (auto hit_test_rect : touch_action_region.GetAllRegions())
layer_hit_test_rects.push_back(hit_test_rect);
MergeRects(layer_hit_test_rects);
for (const gfx::Rect& hit_test_rect : layer_hit_test_rects) {
if (!hit_test_rect.IsEmpty()) {
hit_test_rects->Append(DOMRectReadOnly::FromRect(layer_rect),
DOMRectReadOnly::FromRect(hit_test_rect));
}
}
}
}
return hit_test_rects;
}
bool Internals::executeCommand(Document* document,
const String& name,
const String& value,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return false;
}
LocalFrame* frame = document->GetFrame();
return frame->GetEditor().ExecuteCommand(name, value);
}
void Internals::triggerTestInspectorIssue(Document* document) {
DCHECK(document);
auto info = mojom::blink::InspectorIssueInfo::New(
mojom::InspectorIssueCode::kCookieIssue,
mojom::blink::InspectorIssueDetails::New());
document->GetFrame()->AddInspectorIssue(
AuditsIssue(ConvertInspectorIssueToProtocolFormat(
InspectorIssue::Create(std::move(info)))));
}
AtomicString Internals::htmlNamespace() {
return html_names::xhtmlNamespaceURI;
}
Vector<AtomicString> Internals::htmlTags() {
base::HeapArray<const QualifiedName*> qualified_names = html_names::GetTags();
Vector<AtomicString> tags(qualified_names.size());
for (size_t i = 0; i < qualified_names.size(); ++i) {
tags[i] = qualified_names[i]->LocalName();
}
return tags;
}
AtomicString Internals::svgNamespace() {
return svg_names::kNamespaceURI;
}
Vector<AtomicString> Internals::svgTags() {
base::HeapArray<const QualifiedName*> qualified_names = svg_names::GetTags();
Vector<AtomicString> tags(qualified_names.size());
for (size_t i = 0; i < qualified_names.size(); ++i) {
tags[i] = qualified_names[i]->LocalName();
}
return tags;
}
StaticNodeList* Internals::nodesFromRect(
ScriptState* script_state,
Document* document,
int x,
int y,
int width,
int height,
bool ignore_clipping,
bool allow_child_frame_content,
ExceptionState& exception_state) const {
DCHECK(document);
if (!document->GetFrame() || !document->GetFrame()->View()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No view can be obtained from the provided document.");
return nullptr;
}
HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kReadOnly |
HitTestRequest::kActive |
HitTestRequest::kListBased;
LocalFrame* frame = document->GetFrame();
PhysicalRect rect{LayoutUnit(x), LayoutUnit(y), LayoutUnit(width),
LayoutUnit(height)};
if (ignore_clipping) {
hit_type |= HitTestRequest::kIgnoreClipping;
} else if (!gfx::Rect(gfx::Point(), frame->View()->Size())
.Intersects(ToEnclosingRect(rect))) {
return nullptr;
}
if (allow_child_frame_content)
hit_type |= HitTestRequest::kAllowChildFrameContent;
HitTestRequest request(hit_type);
HitTestLocation location(rect);
HitTestResult result(request, location);
frame->ContentLayoutObject()->HitTest(location, result);
HeapVector<Member<Node>> matches(result.ListBasedTestResult());
// Ensure WindowProxy instances for child frames. crbug.com/1407555.
for (auto& node : matches) {
if (node->IsDocumentNode() && node.Get() != document) {
node->GetDocument().GetFrame()->GetWindowProxy(script_state->World());
}
}
return StaticNodeList::Adopt(matches);
}
bool Internals::hasSpellingMarker(Document* document,
int from,
int length,
ExceptionState& exception_state) {
if (!document || !document->GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No frame can be obtained from the provided document.");
return false;
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return document->GetFrame()->GetSpellChecker().SelectionStartHasMarkerFor(
DocumentMarker::kSpelling, from, length);
}
void Internals::replaceMisspelled(Document* document,
const String& replacement,
ExceptionState& exception_state) {
if (!document || !document->GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No frame can be obtained from the provided document.");
return;
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
document->GetFrame()->GetSpellChecker().ReplaceMisspelledRange(replacement);
}
bool Internals::canHyphenate(const AtomicString& locale) {
return LayoutLocale::ValueOrDefault(LayoutLocale::Get(locale))
.GetHyphenation();
}
void Internals::setMockHyphenation(const AtomicString& locale) {
LayoutLocale::SetHyphenationForTesting(locale, MockHyphenation::Create());
}
unsigned Internals::numberOfLiveNodes() const {
return InstanceCounters::CounterValue(InstanceCounters::kNodeCounter);
}
unsigned Internals::numberOfLiveDocuments() const {
return InstanceCounters::CounterValue(InstanceCounters::kDocumentCounter);
}
bool Internals::hasGrammarMarker(Document* document,
int from,
int length,
ExceptionState& exception_state) {
if (!document || !document->GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"No frame can be obtained from the provided document.");
return false;
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return document->GetFrame()->GetSpellChecker().SelectionStartHasMarkerFor(
DocumentMarker::kGrammar, from, length);
}
unsigned Internals::numberOfScrollableAreas(Document* document) {
DCHECK(document);
if (!document->GetFrame())
return 0;
unsigned count = 0;
LocalFrame* frame = document->GetFrame();
for (const auto& scrollable_area :
frame->View()->ScrollableAreas().Values()) {
if (scrollable_area->ScrollsOverflow()) {
count++;
}
}
for (Frame* child = frame->Tree().FirstChild(); child;
child = child->Tree().NextSibling()) {
auto* child_local_frame = DynamicTo<LocalFrame>(child);
if (child_local_frame && child_local_frame->View()) {
for (const auto& scrollable_area :
child_local_frame->View()->ScrollableAreas().Values()) {
if (scrollable_area->ScrollsOverflow())
count++;
}
}
}
return count;
}
String Internals::layerTreeAsText(Document* document,
ExceptionState& exception_state) const {
return layerTreeAsText(document, 0, exception_state);
}
String Internals::layerTreeAsText(Document* document,
unsigned flags,
ExceptionState& exception_state) const {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return String();
}
document->View()->UpdateAllLifecyclePhasesForTest();
return document->GetFrame()->GetLayerTreeAsTextForTesting(flags);
}
String Internals::mainThreadScrollingReasons(
Document* document,
ExceptionState& exception_state) const {
DCHECK(document);
if (!document->GetFrame()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return String();
}
document->GetFrame()->View()->UpdateAllLifecyclePhasesForTest();
return document->GetFrame()->View()->MainThreadScrollingReasonsAsText();
}
void Internals::evictAllResources() const {
MemoryCache::Get()->EvictResources();
}
String Internals::counterValue(Element* element) {
if (!element)
return String();
return CounterValueForElement(element);
}
int Internals::pageNumber(Element* element,
float page_width,
float page_height,
ExceptionState& exception_state) {
if (!element)
return 0;
if (page_width <= 0 || page_height <= 0) {
exception_state.ThrowTypeError(
"Page width and height must be larger than 0.");
return 0;
}
return PrintContext::PageNumberForElement(
element, gfx::SizeF(page_width, page_height));
}
Vector<String> Internals::IconURLs(Document* document,
int icon_types_mask) const {
Vector<IconURL> icon_urls = document->IconURLs(icon_types_mask);
Vector<String> array;
for (auto& icon_url : icon_urls)
array.push_back(icon_url.icon_url_.GetString());
return array;
}
Vector<String> Internals::shortcutIconURLs(Document* document) const {
int icon_types_mask =
1 << static_cast<int>(mojom::blink::FaviconIconType::kFavicon);
return IconURLs(document, icon_types_mask);
}
Vector<String> Internals::allIconURLs(Document* document) const {
int icon_types_mask =
1 << static_cast<int>(mojom::blink::FaviconIconType::kFavicon) |
1 << static_cast<int>(mojom::blink::FaviconIconType::kTouchIcon) |
1 << static_cast<int>(
mojom::blink::FaviconIconType::kTouchPrecomposedIcon);
return IconURLs(document, icon_types_mask);
}
int Internals::numberOfPages(float page_width,
float page_height,
ExceptionState& exception_state) {
if (!GetFrame())
return -1;
if (page_width <= 0 || page_height <= 0) {
exception_state.ThrowTypeError(
"Page width and height must be larger than 0.");
return -1;
}
return PrintContext::NumberOfPages(GetFrame(),
gfx::SizeF(page_width, page_height));
}
float Internals::pageScaleFactor(ExceptionState& exception_state) {
if (!document_->GetPage()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The document's page cannot be retrieved.");
return 0;
}
Page* page = document_->GetPage();
return page->GetVisualViewport().Scale();
}
void Internals::setPageScaleFactor(float scale_factor,
ExceptionState& exception_state) {
if (scale_factor <= 0)
return;
if (!document_->GetPage()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The document's page cannot be retrieved.");
return;
}
Page* page = document_->GetPage();
page->GetVisualViewport().SetScale(scale_factor);
}
void Internals::setPageScaleFactorLimits(float min_scale_factor,
float max_scale_factor,
ExceptionState& exception_state) {
if (!document_->GetPage()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The document's page cannot be retrieved.");
return;
}
Page* page = document_->GetPage();
page->SetDefaultPageScaleLimits(min_scale_factor, max_scale_factor);
}
float Internals::layoutZoomFactor(ExceptionState& exception_state) {
if (!document_->GetPage()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The document's page cannot be retrieved.");
return 0;
}
// Layout zoom without Device Scale Factor.
return document_->GetPage()->GetChromeClient().UserZoomFactor(
document_->GetFrame());
}
void Internals::setIsCursorVisible(Document* document,
bool is_visible,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetPage()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"No context document can be obtained.");
return;
}
document->GetPage()->SetIsCursorVisible(is_visible);
}
void Internals::setMaxNumberOfFramesToTen(bool enabled) {
// This gets reset by Internals::ResetToConsistentState
Page::SetMaxNumberOfFramesToTenForTesting(enabled);
}
String Internals::effectivePreload(HTMLMediaElement* media_element) {
DCHECK(media_element);
return media_element->EffectivePreload();
}
void Internals::mediaPlayerRemoteRouteAvailabilityChanged(
HTMLMediaElement* media_element,
bool available) {
DCHECK(media_element);
RemotePlaybackController::From(*media_element)
->AvailabilityChangedForTesting(available);
}
void Internals::mediaPlayerPlayingRemotelyChanged(
HTMLMediaElement* media_element,
bool remote) {
DCHECK(media_element);
RemotePlaybackController::From(*media_element)
->StateChangedForTesting(remote);
}
void Internals::setPersistent(HTMLVideoElement* video_element,
bool persistent) {
DCHECK(video_element);
video_element->SetPersistentState(persistent);
}
void Internals::forceStaleStateForMediaElement(HTMLMediaElement* media_element,
int target_state) {
DCHECK(media_element);
// Even though this is an internals method, the checks are necessary to
// prevent fuzzers from taking this path and generating useless noise.
if (target_state < static_cast<int>(WebMediaPlayer::kReadyStateHaveNothing) ||
target_state >
static_cast<int>(WebMediaPlayer::kReadyStateHaveEnoughData)) {
return;
}
if (auto* wmp = media_element->GetWebMediaPlayer()) {
wmp->ForceStaleStateForTesting(
static_cast<WebMediaPlayer::ReadyState>(target_state));
}
}
bool Internals::isMediaElementSuspended(HTMLMediaElement* media_element) {
DCHECK(media_element);
if (auto* wmp = media_element->GetWebMediaPlayer())
return wmp->IsSuspendedForTesting();
return false;
}
void Internals::setMediaControlsTestMode(HTMLMediaElement* media_element,
bool enable) {
DCHECK(media_element);
MediaControls* media_controls = media_element->GetMediaControls();
DCHECK(media_controls);
media_controls->SetTestMode(enable);
}
void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(
const String& scheme) {
#if DCHECK_IS_ON()
WTF::SetIsBeforeThreadCreatedForTest(); // Required for next operation:
#endif
SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(scheme);
}
void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(
const String& scheme,
const Vector<String>& policy_areas) {
uint32_t policy_areas_enum = SchemeRegistry::kPolicyAreaNone;
for (const auto& policy_area : policy_areas) {
if (policy_area == "img")
policy_areas_enum |= SchemeRegistry::kPolicyAreaImage;
else if (policy_area == "style")
policy_areas_enum |= SchemeRegistry::kPolicyAreaStyle;
}
#if DCHECK_IS_ON()
WTF::SetIsBeforeThreadCreatedForTest(); // Required for next operation:
#endif
SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
scheme, static_cast<SchemeRegistry::PolicyAreas>(policy_areas_enum));
}
void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(
const String& scheme) {
#if DCHECK_IS_ON()
WTF::SetIsBeforeThreadCreatedForTest(); // Required for next operation:
#endif
SchemeRegistry::RemoveURLSchemeRegisteredAsBypassingContentSecurityPolicy(
scheme);
}
TypeConversions* Internals::typeConversions() const {
return MakeGarbageCollected<TypeConversions>();
}
DictionaryTest* Internals::dictionaryTest() const {
return MakeGarbageCollected<DictionaryTest>();
}
RecordTest* Internals::recordTest() const {
return MakeGarbageCollected<RecordTest>();
}
SequenceTest* Internals::sequenceTest() const {
return MakeGarbageCollected<SequenceTest>();
}
UnionTypesTest* Internals::unionTypesTest() const {
return MakeGarbageCollected<UnionTypesTest>();
}
InternalsUkmRecorder* Internals::initializeUKMRecorder() {
return MakeGarbageCollected<InternalsUkmRecorder>(document_);
}
OriginTrialsTest* Internals::originTrialsTest() const {
return MakeGarbageCollected<OriginTrialsTest>();
}
CallbackFunctionTest* Internals::callbackFunctionTest() const {
return MakeGarbageCollected<CallbackFunctionTest>();
}
NADCAttributeTest* Internals::nadcAttributeTest() const {
return MakeGarbageCollected<NADCAttributeTest>();
}
Vector<String> Internals::getReferencedFilePaths() const {
if (!GetFrame())
return Vector<String>();
return GetFrame()
->Loader()
.GetDocumentLoader()
->GetHistoryItem()
->GetReferencedFilePaths();
}
void Internals::disableReferencedFilePathsVerification() const {
if (!GetFrame())
return;
GetFrame()
->GetDocument()
->GetFormController()
.SetDropReferencedFilePathsForTesting();
}
void Internals::startTrackingRepaints(Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->View()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return;
}
LocalFrameView* frame_view = document->View();
frame_view->UpdateAllLifecyclePhasesForTest();
frame_view->SetTracksRasterInvalidations(true);
}
void Internals::stopTrackingRepaints(Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->View()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return;
}
LocalFrameView* frame_view = document->View();
frame_view->UpdateAllLifecyclePhasesForTest();
frame_view->SetTracksRasterInvalidations(false);
}
void Internals::updateLayoutAndRunPostLayoutTasks(
Node* node,
ExceptionState& exception_state) {
Document* document = nullptr;
if (!node) {
document = document_;
} else if (auto* node_document = DynamicTo<Document>(node)) {
document = node_document;
} else if (auto* iframe = DynamicTo<HTMLIFrameElement>(*node)) {
document = iframe->contentDocument();
}
if (!document) {
exception_state.ThrowTypeError(
"The node provided is neither a document nor an IFrame.");
return;
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
if (auto* view = document->View())
view->FlushAnyPendingPostLayoutTasks();
}
void Internals::forceFullRepaint(Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->View()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return;
}
if (auto* layout_view = document->GetLayoutView())
layout_view->InvalidatePaintForViewAndDescendants();
}
DOMRectList* Internals::draggableRegions(Document* document,
ExceptionState& exception_state) {
return DraggableRegions(document, true, exception_state);
}
DOMRectList* Internals::nonDraggableRegions(Document* document,
ExceptionState& exception_state) {
return DraggableRegions(document, false, exception_state);
}
void Internals::SetSupportsDraggableRegions(bool supports_draggable_regions) {
document_->GetPage()
->GetChromeClient()
.GetWebView()
->SetSupportsDraggableRegions(supports_draggable_regions);
}
DOMRectList* Internals::DraggableRegions(Document* document,
bool draggable,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->View()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return MakeGarbageCollected<DOMRectList>();
}
document->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
document->View()->UpdateDocumentDraggableRegions();
Vector<DraggableRegionValue> regions = document->DraggableRegions();
Vector<gfx::QuadF> quads;
for (const DraggableRegionValue& region : regions) {
if (region.draggable == draggable)
quads.push_back(gfx::QuadF(gfx::RectF(region.bounds)));
}
return MakeGarbageCollected<DOMRectList>(quads);
}
static const char* CursorTypeToString(
ui::mojom::blink::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::blink::CursorType::kPointer:
return "Pointer";
case ui::mojom::blink::CursorType::kCross:
return "Cross";
case ui::mojom::blink::CursorType::kHand:
return "Hand";
case ui::mojom::blink::CursorType::kIBeam:
return "IBeam";
case ui::mojom::blink::CursorType::kWait:
return "Wait";
case ui::mojom::blink::CursorType::kHelp:
return "Help";
case ui::mojom::blink::CursorType::kEastResize:
return "EastResize";
case ui::mojom::blink::CursorType::kNorthResize:
return "NorthResize";
case ui::mojom::blink::CursorType::kNorthEastResize:
return "NorthEastResize";
case ui::mojom::blink::CursorType::kNorthWestResize:
return "NorthWestResize";
case ui::mojom::blink::CursorType::kSouthResize:
return "SouthResize";
case ui::mojom::blink::CursorType::kSouthEastResize:
return "SouthEastResize";
case ui::mojom::blink::CursorType::kSouthWestResize:
return "SouthWestResize";
case ui::mojom::blink::CursorType::kWestResize:
return "WestResize";
case ui::mojom::blink::CursorType::kNorthSouthResize:
return "NorthSouthResize";
case ui::mojom::blink::CursorType::kEastWestResize:
return "EastWestResize";
case ui::mojom::blink::CursorType::kNorthEastSouthWestResize:
return "NorthEastSouthWestResize";
case ui::mojom::blink::CursorType::kNorthWestSouthEastResize:
return "NorthWestSouthEastResize";
case ui::mojom::blink::CursorType::kColumnResize:
return "ColumnResize";
case ui::mojom::blink::CursorType::kRowResize:
return "RowResize";
case ui::mojom::blink::CursorType::kMiddlePanning:
return "MiddlePanning";
case ui::mojom::blink::CursorType::kMiddlePanningVertical:
return "MiddlePanningVertical";
case ui::mojom::blink::CursorType::kMiddlePanningHorizontal:
return "MiddlePanningHorizontal";
case ui::mojom::blink::CursorType::kEastPanning:
return "EastPanning";
case ui::mojom::blink::CursorType::kNorthPanning:
return "NorthPanning";
case ui::mojom::blink::CursorType::kNorthEastPanning:
return "NorthEastPanning";
case ui::mojom::blink::CursorType::kNorthWestPanning:
return "NorthWestPanning";
case ui::mojom::blink::CursorType::kSouthPanning:
return "SouthPanning";
case ui::mojom::blink::CursorType::kSouthEastPanning:
return "SouthEastPanning";
case ui::mojom::blink::CursorType::kSouthWestPanning:
return "SouthWestPanning";
case ui::mojom::blink::CursorType::kWestPanning:
return "WestPanning";
case ui::mojom::blink::CursorType::kMove:
return "Move";
case ui::mojom::blink::CursorType::kVerticalText:
return "VerticalText";
case ui::mojom::blink::CursorType::kCell:
return "Cell";
case ui::mojom::blink::CursorType::kContextMenu:
return "ContextMenu";
case ui::mojom::blink::CursorType::kAlias:
return "Alias";
case ui::mojom::blink::CursorType::kProgress:
return "Progress";
case ui::mojom::blink::CursorType::kNoDrop:
return "NoDrop";
case ui::mojom::blink::CursorType::kCopy:
return "Copy";
case ui::mojom::blink::CursorType::kNone:
return "None";
case ui::mojom::blink::CursorType::kNotAllowed:
return "NotAllowed";
case ui::mojom::blink::CursorType::kZoomIn:
return "ZoomIn";
case ui::mojom::blink::CursorType::kZoomOut:
return "ZoomOut";
case ui::mojom::blink::CursorType::kGrab:
return "Grab";
case ui::mojom::blink::CursorType::kGrabbing:
return "Grabbing";
case ui::mojom::blink::CursorType::kCustom:
return "Custom";
case ui::mojom::blink::CursorType::kNull:
return "Null";
case ui::mojom::blink::CursorType::kDndNone:
return "DragAndDropNone";
case ui::mojom::blink::CursorType::kDndMove:
return "DragAndDropMove";
case ui::mojom::blink::CursorType::kDndCopy:
return "DragAndDropCopy";
case ui::mojom::blink::CursorType::kDndLink:
return "DragAndDropLink";
case ui::mojom::blink::CursorType::kNorthSouthNoResize:
return "NorthSouthNoResize";
case ui::mojom::blink::CursorType::kEastWestNoResize:
return "EastWestNoResize";
case ui::mojom::blink::CursorType::kNorthEastSouthWestNoResize:
return "NorthEastSouthWestNoResize";
case ui::mojom::blink::CursorType::kNorthWestSouthEastNoResize:
return "NorthWestSouthEastNoResize";
}
NOTREACHED();
}
String Internals::getCurrentCursorInfo() {
if (!GetFrame())
return String();
ui::Cursor cursor =
GetFrame()->GetPage()->GetChromeClient().LastSetCursorForTesting();
StringBuilder result;
result.Append("type=");
result.Append(CursorTypeToString(cursor.type()));
if (cursor.type() == ui::mojom::blink::CursorType::kCustom) {
result.Append(" hotSpot=");
result.AppendNumber(cursor.custom_hotspot().x());
result.Append(',');
result.AppendNumber(cursor.custom_hotspot().y());
SkBitmap bitmap = cursor.custom_bitmap();
DCHECK(!bitmap.isNull());
result.Append(" image=");
result.AppendNumber(bitmap.width());
result.Append('x');
result.AppendNumber(bitmap.height());
if (cursor.image_scale_factor() != 1.0f) {
result.Append(" scale=");
result.AppendNumber(cursor.image_scale_factor(), 8);
}
}
return result.ToString();
}
bool Internals::cursorUpdatePending() const {
if (!GetFrame())
return false;
return GetFrame()->GetEventHandler().CursorUpdatePending();
}
DOMArrayBuffer* Internals::serializeObject(
v8::Isolate* isolate,
const ScriptValue& value,
ExceptionState& exception_state) const {
scoped_refptr<SerializedScriptValue> serialized_value =
SerializedScriptValue::Serialize(
isolate, value.V8Value(),
SerializedScriptValue::SerializeOptions(
SerializedScriptValue::kNotForStorage),
exception_state);
if (exception_state.HadException())
return nullptr;
base::span<const uint8_t> span = serialized_value->GetWireData();
DOMArrayBuffer* buffer = DOMArrayBuffer::CreateUninitializedOrNull(
base::checked_cast<uint32_t>(span.size()), sizeof(uint8_t));
if (buffer)
buffer->ByteSpan().copy_from(span);
return buffer;
}
ScriptValue Internals::deserializeBuffer(v8::Isolate* isolate,
DOMArrayBuffer* buffer) const {
scoped_refptr<SerializedScriptValue> serialized_value =
SerializedScriptValue::Create(buffer->ByteSpan());
return ScriptValue(isolate, serialized_value->Deserialize(isolate));
}
void Internals::forceReload(bool bypass_cache) {
if (!GetFrame())
return;
GetFrame()->Reload(bypass_cache ? WebFrameLoadType::kReloadBypassingCache
: WebFrameLoadType::kReload);
}
StaticSelection* Internals::getDragCaret() {
SelectionInDOMTree::Builder builder;
if (GetFrame()) {
const DragCaret& caret = GetFrame()->GetPage()->GetDragCaret();
const PositionWithAffinity& position = caret.CaretPosition();
if (position.GetDocument() == GetFrame()->GetDocument())
builder.Collapse(caret.CaretPosition());
}
return StaticSelection::FromSelectionInDOMTree(builder.Build());
}
StaticSelection* Internals::getSelectionInFlatTree(
DOMWindow* window,
ExceptionState& exception_state) {
Frame* const frame = window->GetFrame();
auto* local_frame = DynamicTo<LocalFrame>(frame);
if (!local_frame) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"Must supply local window");
return nullptr;
}
return StaticSelection::FromSelectionInFlatTree(ConvertToSelectionInFlatTree(
local_frame->Selection().GetSelectionInDOMTree()));
}
Node* Internals::visibleSelectionAnchorNode() {
if (!GetFrame())
return nullptr;
GetFrame()->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
Position position =
GetFrame()->Selection().ComputeVisibleSelectionInDOMTree().Anchor();
return position.IsNull() ? nullptr : position.ComputeContainerNode();
}
unsigned Internals::visibleSelectionAnchorOffset() {
if (!GetFrame())
return 0;
GetFrame()->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
Position position =
GetFrame()->Selection().ComputeVisibleSelectionInDOMTree().Anchor();
return position.IsNull() ? 0 : position.ComputeOffsetInContainerNode();
}
Node* Internals::visibleSelectionFocusNode() {
if (!GetFrame())
return nullptr;
GetFrame()->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
Position position =
GetFrame()->Selection().ComputeVisibleSelectionInDOMTree().Focus();
return position.IsNull() ? nullptr : position.ComputeContainerNode();
}
unsigned Internals::visibleSelectionFocusOffset() {
if (!GetFrame())
return 0;
GetFrame()->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
Position position =
GetFrame()->Selection().ComputeVisibleSelectionInDOMTree().Focus();
return position.IsNull() ? 0 : position.ComputeOffsetInContainerNode();
}
DOMRect* Internals::selectionBounds(ExceptionState& exception_state) {
if (!GetFrame()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The document's frame cannot be retrieved.");
return nullptr;
}
GetFrame()->View()->UpdateLifecycleToLayoutClean(
DocumentUpdateReason::kSelection);
return DOMRect::FromRectF(
gfx::RectF(GetFrame()->Selection().AbsoluteUnclippedBounds()));
}
String Internals::markerTextForListItem(Element* element) {
DCHECK(element);
return blink::MarkerTextForListItem(element);
}
String Internals::getImageSourceURL(Element* element) {
DCHECK(element);
return element->ImageSourceURL();
}
void Internals::forceImageReload(Element* element,
ExceptionState& exception_state) {
auto* html_image_element = DynamicTo<HTMLImageElement>(element);
if (!html_image_element) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The element should be HTMLImageElement.");
}
html_image_element->ForceReload();
}
String Internals::selectMenuListText(HTMLSelectElement* select) {
DCHECK(select);
if (!select->UsesMenuList())
return String();
return select->InnerElement().innerText();
}
bool Internals::isSelectPopupVisible(Node* node) {
DCHECK(node);
if (auto* select = DynamicTo<HTMLSelectElement>(*node))
return select->PopupIsVisible();
return false;
}
bool Internals::selectPopupItemStyleIsRtl(Node* node, int item_index) {
auto* select = DynamicTo<HTMLSelectElement>(node);
if (!select)
return false;
if (item_index < 0 ||
static_cast<wtf_size_t>(item_index) >= select->GetListItems().size())
return false;
const ComputedStyle* item_style =
select->ItemComputedStyle(*select->GetListItems()[item_index]);
return item_style && item_style->Direction() == TextDirection::kRtl;
}
int Internals::selectPopupItemStyleFontHeight(Node* node, int item_index) {
auto* select = DynamicTo<HTMLSelectElement>(node);
if (!select)
return false;
if (item_index < 0 ||
static_cast<wtf_size_t>(item_index) >= select->GetListItems().size())
return false;
const ComputedStyle* item_style =
select->ItemComputedStyle(*select->GetListItems()[item_index]);
if (item_style) {
const SimpleFontData* font_data = item_style->GetFont()->PrimaryFont();
DCHECK(font_data);
return font_data ? font_data->GetFontMetrics().Height() : 0;
}
return 0;
}
void Internals::resetTypeAheadSession(HTMLSelectElement* select) {
DCHECK(select);
select->ResetTypeAheadSessionForTesting();
}
void Internals::forceCompositingUpdate(Document* document,
ExceptionState& exception_state) {
DCHECK(document);
if (!document->GetLayoutView()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
"The document provided is invalid.");
return;
}
document->GetFrame()->View()->UpdateAllLifecyclePhasesForTest();
}
void Internals::setForcedColorsAndDarkPreferredColorScheme(Document* document) {
DCHECK(document);
color_scheme_helper_.emplace(*document);
color_scheme_helper_->SetPreferredColorScheme(
mojom::blink::PreferredColorScheme::kDark);
color_scheme_helper_->SetInForcedColors(*document, /*in_forced_colors=*/true);
color_scheme_helper_->SetEmulatedForcedColors(*document,
/*is_dark_theme=*/false);
}
void Internals::setDarkPreferredColorScheme(Document* document) {
DCHECK(document);
Settings* settings = document->GetSettings();
settings->SetPreferredColorScheme(mojom::blink::PreferredColorScheme::kDark);
}
void Internals::setDarkPreferredRootScrollbarColorScheme(Document* document) {
DCHECK(document);
color_scheme_helper_.emplace(*document);
color_scheme_helper_->SetPreferredRootScrollbarColorScheme(
mojom::blink::PreferredColorScheme::kDark);
}
void Internals::setShouldRevealPassword(Element* element,
bool reveal,
ExceptionState& exception_state) {
DCHECK(element);
auto* html_input_element = DynamicTo<HTMLInputElement>(element);
if (!html_input_element) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not an INPUT.");
return;
}
return html_input_element->SetShouldRevealPassword(reveal);
}
namespace {
class AddOneFunction : public ThenCallable<IDLLong, AddOneFunction, IDLLong> {
public:
int32_t React(ScriptState*, int32_t value) { return value + 1; }
};
class AddOneTypeMismatch
: public ThenCallable<IDLAny, AddOneTypeMismatch, IDLAny> {
public:
ScriptValue React(ScriptState*, ScriptValue value) { return value; }
};
} // namespace
ScriptPromise<IDLAny> Internals::createResolvedPromise(
ScriptState* script_state,
ScriptValue value) {
return ToResolvedPromise<IDLAny>(script_state, value);
}
ScriptPromise<IDLAny> Internals::createRejectedPromise(
ScriptState* script_state,
ScriptValue value) {
return ScriptPromise<IDLAny>::Reject(script_state, value);
}
ScriptPromise<IDLLong> Internals::addOneToPromise(
ScriptState* script_state,
ScriptPromise<IDLLong> promise) {
return promise.Then(script_state, MakeGarbageCollected<AddOneFunction>(),
MakeGarbageCollected<AddOneTypeMismatch>());
}
ScriptPromise<IDLAny> Internals::promiseCheck(ScriptState* script_state,
int32_t arg1,
bool arg2,
const ScriptValue& arg3,
const String& arg4,
const Vector<String>& arg5,
ExceptionState& exception_state) {
if (arg2) {
return ToResolvedPromise<IDLAny>(
script_state, V8String(script_state->GetIsolate(), "done"));
}
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Thrown from the native implementation.");
return EmptyPromise();
}
ScriptPromise<IDLAny> Internals::promiseCheckWithoutExceptionState(
ScriptState* script_state,
const ScriptValue& arg1,
const String& arg2,
const Vector<String>& arg3) {
return ToResolvedPromise<IDLAny>(
script_state, V8String(script_state->GetIsolate(), "done"));
}
ScriptPromise<IDLAny> Internals::promiseCheckRange(ScriptState* script_state,
int32_t arg1) {
return ToResolvedPromise<IDLAny>(
script_state, V8String(script_state->GetIsolate(), "done"));
}
ScriptPromise<IDLAny> Internals::promiseCheckOverload(ScriptState* script_state,
Location*) {
return ToResolvedPromise<IDLAny>(
script_state, V8String(script_state->GetIsolate(), "done"));
}
ScriptPromise<IDLAny> Internals::promiseCheckOverload(ScriptState* script_state,
Document*) {
return ToResolvedPromise<IDLAny>(
script_state, V8String(script_state->GetIsolate(), "done"));
}
ScriptPromise<IDLAny> Internals::promiseCheckOverload(ScriptState* script_state,
Location*,
int32_t,
int32_t) {
return ToResolvedPromise<IDLAny>(
script_state, V8String(script_state->GetIsolate(), "done"));
}
void Internals::Trace(Visitor* visitor) const {
visitor->Trace(runtime_flags_);
visitor->Trace(document_);
ScriptWrappable::Trace(visitor);
}
void Internals::setValueForUser(HTMLInputElement* element,
const String& value) {
element->SetValueForUser(value);
}
void Internals::setFocused(bool focused) {
if (!GetFrame())
return;
GetFrame()->GetPage()->GetFocusController().SetFocused(focused);
}
void Internals::setInitialFocus(bool reverse) {
if (!GetFrame())
return;
GetFrame()->GetDocument()->ClearFocusedElement();
GetFrame()->GetPage()->GetFocusController().SetInitialFocus(
reverse ? mojom::blink::FocusType::kBackward
: mojom::blink::FocusType::kForward);
}
bool Internals::isActivated() {
if (!GetFrame())
return false;
return GetFrame()->GetPage()->GetFocusController().IsActive();
}
bool Internals::isInCanvasFontCache(Document* document,
const String& font_string) {
return document->GetCanvasFontCache()->IsInCache(font_string);
}
unsigned Internals::canvasFontCacheMaxFonts() {
return CanvasFontCache::MaxFonts();
}
void Internals::forceLoseCanvasContext(CanvasRenderingContext* context) {
context->LoseContext(CanvasRenderingContext::kSyntheticLostContext);
}
void Internals::disableCanvasAcceleration(HTMLCanvasElement* canvas) {
canvas->DisableAcceleration();
}
bool Internals::isCanvasImageSourceAccelerated(
const CanvasImageSource* image_source) const {
return image_source->IsAccelerated();
}
String Internals::selectedHTMLForClipboard() {
if (!GetFrame())
return String();
// Selection normalization and markup generation require clean layout.
GetFrame()->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return GetFrame()->Selection().SelectedHTMLForClipboard();
}
String Internals::selectedTextForClipboard() {
if (!GetFrame() || !GetFrame()->GetDocument())
return String();
// Clean layout is required for extracting plain text from selection.
GetFrame()->GetDocument()->UpdateStyleAndLayout(DocumentUpdateReason::kTest);
return GetFrame()->Selection().SelectedTextForClipboard();
}
void Internals::setVisualViewportOffset(int css_x, int css_y) {
if (!GetFrame())
return;
float zoom = GetFrame()->LayoutZoomFactor();
gfx::PointF offset(css_x * zoom, css_y * zoom);
GetFrame()->GetPage()->GetVisualViewport().SetLocation(offset);
}
bool Internals::isUseCounted(Document* document, uint32_t feature) {
if (feature > static_cast<int32_t>(WebFeature::kMaxValue)) {
return false;
}
return document->IsUseCounted(static_cast<WebFeature>(feature));
}
bool Internals::isWebDXFeatureUseCounted(Document* document, uint32_t feature) {
if (feature > static_cast<int32_t>(WebDXFeature::kMaxValue)) {
return false;
}
return document->IsWebDXFeatureCounted(static_cast<WebDXFeature>(feature));
}
bool Internals::isCSSPropertyUseCounted(Document* document,
const String& property_name) {
return document->IsPropertyCounted(
UnresolvedCSSPropertyID(document->GetExecutionContext(), property_name));
}
bool Internals::isAnimatedCSSPropertyUseCounted(Document* document,
const String& property_name) {
return document->IsAnimatedPropertyCounted(
UnresolvedCSSPropertyID(document->GetExecutionContext(), property_name));
}
void Internals::clearUseCounter(Document* document, uint32_t feature) {
if (feature > static_cast<int32_t>(WebFeature::kMaxValue)) {
return;
}
document->ClearUseCounterForTesting(static_cast<WebFeature>(feature));
}
Vector<String> Internals::getCSSPropertyLonghands() const {
Vector<String> result;
for (CSSPropertyID property : CSSPropertyIDList()) {
const CSSProperty& property_class = CSSProperty::Get(property);
if (property_class.IsWebExposed(document_->GetExecutionContext()) &&
property_class.IsLonghand()) {
result.push_back(property_class.GetPropertyNameString());
}
}
return result;
}
Vector<String> Internals::getCSSPropertyShorthands() const {
Vector<String> result;
for (CSSPropertyID property : CSSPropertyIDList()) {
const CSSProperty& property_class = CSSProperty::Get(property);
if (property_class.IsWebExposed(document_->GetExecutionContext()) &&
property_class.IsShorthand()) {
result.push_back(property_class.GetPropertyNameString());
}
}
return result;
}
Vector<String> Internals::getCSSPropertyAliases() const {
Vector<String> result;
for (CSSPropertyID alias : kCSSPropertyAliasList) {
DCHECK(IsPropertyAlias(alias));
const CSSUnresolvedProperty& property_class = *GetPropertyInternal(alias);
if (property_class.IsWebExposed(document_->GetExecutionContext())) {
result.push_back(property_class.GetPropertyNameString());
}
}
return result;
}
ScriptPromise<IDLUndefined> Internals::observeUseCounter(
ScriptState* script_state,
Document* document,
uint32_t feature) {
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(script_state);
auto promise = resolver->Promise();
if (feature > static_cast<int32_t>(WebFeature::kMaxValue)) {
resolver->Reject();
return promise;
}
WebFeature use_counter_feature = static_cast<WebFeature>(feature);
if (document->IsUseCounted(use_counter_feature)) {
resolver->Resolve();
return promise;
}
DocumentLoader* loader = document->Loader();
if (!loader) {
resolver->Reject();
return promise;
}
loader->GetUseCounter().AddObserver(
MakeGarbageCollected<UseCounterImplObserverImpl>(
resolver, static_cast<WebFeature>(use_counter_feature)));
return promise;
}
String Internals::unscopableAttribute() {
return "unscopableAttribute";
}
String Internals::unscopableMethod() {
return "unscopableMethod";
}
void Internals::setCapsLockState(bool enabled) {
KeyboardEventManager::SetCurrentCapsLockState(
enabled ? OverrideCapsLockState::kOn : OverrideCapsLockState::kOff);
}
void Internals::setPseudoClassState(Element* element,
const String& pseudo,
bool matches,
ExceptionState& exception_state) {
if (!element->GetDocument().SetPseudoStateForTesting(*element, pseudo,
matches)) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
pseudo + " is not supported");
}
}
bool Internals::setScrollbarVisibilityInScrollableArea(Node* node,
bool visible) {
if (ScrollableArea* scrollable_area = ScrollableAreaForNode(node)) {
scrollable_area->SetScrollbarsHiddenForTesting(!visible);
return scrollable_area->GetPageScrollbarTheme().UsesOverlayScrollbars();
}
return false;
}
double Internals::monotonicTimeToZeroBasedDocumentTime(
double platform_time,
ExceptionState& exception_state) {
return document_->Loader()
->GetTiming()
.MonotonicTimeToZeroBasedDocumentTime(base::TimeTicks() +
base::Seconds(platform_time))
.InSecondsF();
}
int64_t Internals::zeroBasedDocumentTimeToMonotonicTime(double dom_event_time) {
return document_->Loader()->GetTiming().ZeroBasedDocumentTimeToMonotonicTime(
dom_event_time);
}
int64_t Internals::currentTimeTicks() {
return base::TimeTicks::Now().since_origin().InMicroseconds();
}
String Internals::getScrollAnimationState(Node* node) const {
if (ScrollableArea* scrollable_area = ScrollableAreaForNode(node))
return scrollable_area->GetScrollAnimator().RunStateAsText();
return String();
}
String Internals::getProgrammaticScrollAnimationState(Node* node) const {
if (ScrollableArea* scrollable_area = ScrollableAreaForNode(node))
return scrollable_area->GetProgrammaticScrollAnimator().RunStateAsText();
return String();
}
void Internals::crash() {
NOTREACHED() << "Intentional crash";
}
String Internals::evaluateInInspectorOverlay(const String& script) {
LocalFrame* frame = GetFrame();
if (frame && frame->Client())
return frame->Client()->evaluateInInspectorOverlayForTesting(script);
return g_empty_string;
}
void Internals::setIsLowEndDevice(bool is_low_end_device) {
MemoryPressureListenerRegistry::SetIsLowEndDeviceForTesting(
is_low_end_device);
}
bool Internals::isLowEndDevice() const {
return MemoryPressureListenerRegistry::IsLowEndDevice();
}
Vector<String> Internals::supportedTextEncodingLabels() const {
return WTF::TextEncodingAliasesForTesting();
}
void Internals::simulateRasterUnderInvalidations(bool enable) {
RasterInvalidationTracking::SimulateRasterUnderInvalidations(enable);
}
void Internals::DisableIntersectionObserverThrottleDelay() const {
// This gets reset by Internals::ResetToConsistentState
IntersectionObserver::SetThrottleDelayEnabledForTesting(false);
}
bool Internals::isSiteIsolated(HTMLIFrameElement* iframe) const {
return iframe->ContentFrame() && iframe->ContentFrame()->IsRemoteFrame();
}
bool Internals::isTrackingOcclusionForIFrame(HTMLIFrameElement* iframe) const {
if (!iframe->ContentFrame() || !iframe->ContentFrame()->IsRemoteFrame())
return false;
RemoteFrame* remote_frame = To<RemoteFrame>(iframe->ContentFrame());
return remote_frame->View()->NeedsOcclusionTracking();
}
void Internals::addEmbedderCustomElementName(const AtomicString& name,
ExceptionState& exception_state) {
CustomElement::AddEmbedderCustomElementNameForTesting(name, exception_state);
}
String Internals::getParsedImportMap(Document* document,
ExceptionState& exception_state) {
Modulator* modulator =
Modulator::From(ToScriptStateForMainWorld(document->GetFrame()));
if (!modulator) {
exception_state.ThrowTypeError("No modulator");
return String();
}
const ImportMap* import_map = modulator->GetImportMapForTest();
if (!import_map)
return "{}";
return import_map->ToStringForTesting();
}
void Internals::setDeviceEmulationScale(float scale,
ExceptionState& exception_state) {
if (scale <= 0)
return;
auto* page = document_->GetPage();
if (!page) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The document's page cannot be retrieved.");
return;
}
DeviceEmulationParams params;
params.scale = scale;
page->GetChromeClient().GetWebView()->EnableDeviceEmulation(params);
}
void Internals::ResolveResourcePriority(
ScriptPromiseResolver<IDLLong>* resolver,
int resource_load_priority) {
resolver->Resolve(resource_load_priority);
}
String Internals::getAgentId(DOMWindow* window) {
if (!window->IsLocalDOMWindow())
return String();
// Create a unique id from the process id and the address of the agent.
const base::ProcessId process_id = base::GetCurrentProcId();
uintptr_t agent_address =
reinterpret_cast<uintptr_t>(To<LocalDOMWindow>(window)->GetAgent());
// This serializes a pointer as a decimal number, which is a bit ugly, but
// it works. Is there any utility to dump a number in a hexadecimal form?
// I couldn't find one in WTF.
return String::Number(process_id) + ":" + String::Number(agent_address);
}
void Internals::useMockOverlayScrollbars() {
// Note: it's important to reset `g_mock_overlay_scrollbars` before the
// assignment, since if `g_mock_overlay_scrollbars` is non-null, its
// destructor will end up running after the constructor for the new
// ScopedMockOverlayScrollbars runs, meaning the global state the new pointer
// stores will in fact be the state from the previous pointer, which may not
// be what was intended. E.g. if a test calls this function twice, then
// whatever the original global state was in Blink's ScrollbarThemeSettings
// will be lost, and the state after the second call may be wrong.
ResetMockOverlayScrollbars();
g_mock_overlay_scrollbars = new ScopedMockOverlayScrollbars(true);
}
bool Internals::overlayScrollbarsEnabled() const {
return ScrollbarThemeSettings::OverlayScrollbarsEnabled();
}
void Internals::generateTestReport(const String& message) {
// Construct the test report.
TestReportBody* body = MakeGarbageCollected<TestReportBody>(message);
Report* report =
MakeGarbageCollected<Report>("test", document_->Url().GetString(), body);
// Send the test report to any ReportingObservers.
ReportingContext::From(document_->domWindow())->QueueReport(report);
}
void Internals::setIsAdFrame(Document* target_doc,
ExceptionState& exception_state) {
LocalFrame* frame = target_doc->GetFrame();
if (frame->IsMainFrame() && !frame->IsInFencedFrameTree()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Frame must be an iframe or a fenced frame.");
return;
}
blink::FrameAdEvidence ad_evidence(/*parent_is_ad=*/frame->Parent() &&
frame->Parent()->IsAdFrame());
ad_evidence.set_created_by_ad_script(
mojom::FrameCreationStackEvidence::kCreatedByAdScript);
ad_evidence.set_is_complete();
frame->SetAdEvidence(ad_evidence);
}
ReadableStream* Internals::createReadableStream(
ScriptState* script_state,
int32_t queue_size,
const String& optimizer,
ExceptionState& exception_state) {
TestReadableStreamSource::Type type;
if (optimizer.empty()) {
type = TestReadableStreamSource::Type::kWithNullOptimizer;
} else if (optimizer == "perform-null") {
type = TestReadableStreamSource::Type::kWithPerformNullOptimizer;
} else if (optimizer == "observable") {
type = TestReadableStreamSource::Type::kWithObservableOptimizer;
} else if (optimizer == "perfect") {
type = TestReadableStreamSource::Type::kWithPerformNullOptimizer;
} else {
exception_state.ThrowRangeError(
"The \"optimizer\" parameter is not correctly set.");
return nullptr;
}
auto* source =
MakeGarbageCollected<TestReadableStreamSource>(script_state, type);
source->Attach(std::make_unique<TestReadableStreamSource::Generator>(10));
return ReadableStream::CreateWithCountQueueingStrategy(
script_state, source, queue_size, AllowPerChunkTransferring(false),
source->CreateTransferringOptimizer(script_state));
}
ScriptValue Internals::createWritableStreamAndSink(
ScriptState* script_state,
int32_t queue_size,
const String& optimizer,
ExceptionState& exception_state) {
TestWritableStreamSink::Type type;
if (optimizer.empty()) {
type = TestWritableStreamSink::Type::kWithNullOptimizer;
} else if (optimizer == "perform-null") {
type = TestWritableStreamSink::Type::kWithPerformNullOptimizer;
} else if (optimizer == "observable") {
type = TestWritableStreamSink::Type::kWithObservableOptimizer;
} else if (optimizer == "perfect") {
type = TestWritableStreamSink::Type::kWithPerfectOptimizer;
} else {
exception_state.ThrowRangeError(
"The \"optimizer\" parameter is not correctly set.");
return ScriptValue();
}
ExecutionContext* context = ExecutionContext::From(script_state);
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLString>>(script_state);
auto internal_sink = std::make_unique<TestWritableStreamSink::InternalSink>(
context->GetTaskRunner(TaskType::kInternalDefault),
CrossThreadBindOnce(&TestWritableStreamSink::Resolve,
MakeUnwrappingCrossThreadHandle(resolver)),
CrossThreadBindOnce(&TestWritableStreamSink::Reject,
MakeUnwrappingCrossThreadHandle(resolver)));
auto* sink = MakeGarbageCollected<TestWritableStreamSink>(script_state, type);
sink->Attach(std::move(internal_sink));
auto* stream = WritableStream::CreateWithCountQueueingStrategy(
script_state, sink, queue_size,
sink->CreateTransferringOptimizer(script_state));
v8::Local<v8::Object> object = v8::Object::New(script_state->GetIsolate());
object
->Set(script_state->GetContext(),
V8String(script_state->GetIsolate(), "stream"),
ToV8Traits<WritableStream>::ToV8(script_state, stream))
.Check();
object
->Set(script_state->GetContext(),
V8String(script_state->GetIsolate(), "sink"),
ToV8Traits<IDLPromise<IDLString>>::ToV8(script_state,
resolver->Promise()))
.Check();
return ScriptValue(script_state->GetIsolate(), object);
}
void Internals::setAllowPerChunkTransferring(ReadableStream* stream) {
if (!stream) {
return;
}
stream->SetAllowPerChunkTransferringForTesting(
AllowPerChunkTransferring(true));
}
void Internals::setBackForwardCacheRestorationBufferSize(unsigned int maxSize) {
WindowPerformance& perf =
*DOMWindowPerformance::performance(*document_->domWindow());
perf.setBackForwardCacheRestorationBufferSizeForTest(maxSize);
}
void Internals::setEventTimingBufferSize(unsigned int maxSize) {
WindowPerformance& perf =
*DOMWindowPerformance::performance(*document_->domWindow());
perf.setEventTimingBufferSizeForTest(maxSize);
}
void Internals::stopResponsivenessMetricsUkmSampling() {
WindowPerformance& perf =
*DOMWindowPerformance::performance(*document_->domWindow());
perf.GetResponsivenessMetrics().StopUkmSamplingForTesting();
}
Vector<String> Internals::getCreatorScripts(HTMLImageElement* img) {
DCHECK(img);
return Vector<String>(img->creator_scripts());
}
String Internals::lastCompiledScriptFileName(Document* document) {
return ToScriptStateForMainWorld(document->GetFrame())
->last_compiled_script_file_name();
}
bool Internals::lastCompiledScriptUsedCodeCache(Document* document) {
return ToScriptStateForMainWorld(document->GetFrame())
->last_compiled_script_used_code_cache();
}
ScriptPromise<IDLString> Internals::LCPPrediction(ScriptState* script_state,
Document* document) {
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLString>>(script_state);
auto promise = resolver->Promise();
LCPCriticalPathPredictor* lcpp = document->GetFrame()->GetLCPP();
CHECK(lcpp);
lcpp->AddLCPPredictedCallback(
WTF::BindOnce(&OnLCPPredicted, WrapPersistent(resolver)));
return promise;
}
void ExemptUrlFromNetworkRevocationComplete(
ScriptPromiseResolver<IDLUndefined>* resolver) {
resolver->Resolve();
}
ScriptPromise<IDLUndefined> Internals::exemptUrlFromNetworkRevocation(
ScriptState* script_state,
const String& url) {
if (!blink::features::IsFencedFramesEnabled()) {
return EmptyPromise();
}
if (!base::FeatureList::IsEnabled(
blink::features::kFencedFramesLocalUnpartitionedDataAccess)) {
return EmptyPromise();
}
if (!base::FeatureList::IsEnabled(
blink::features::kExemptUrlFromNetworkRevocationForTesting)) {
return EmptyPromise();
}
if (!GetFrame()) {
return EmptyPromise();
}
LocalFrame* frame = GetFrame();
DCHECK(frame->GetDocument());
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(script_state);
auto promise = resolver->Promise();
frame->GetLocalFrameHostRemote().ExemptUrlFromNetworkRevocationForTesting(
url_test_helpers::ToKURL(url.Utf8()),
WTF::BindOnce(&ExemptUrlFromNetworkRevocationComplete,
WrapPersistent(resolver)));
return promise;
}
} // namespace blink
|