1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
|
/* eslint-disable no-nested-ternary */
/**
* EventUtils provides some utility methods for creating and sending DOM events.
*
* When adding methods to this file, please add a performance test for it.
*/
// Certain functions assume this is loaded into browser window scope.
// This is modifiable because certain chrome tests create their own gBrowser.
/* global gBrowser:true */
// This file is used both in privileged and unprivileged contexts, so we have to
// be careful about our access to Components.interfaces. We also want to avoid
// naming collisions with anything that might be defined in the scope that imports
// this script.
//
// Even if the real |Components| doesn't exist, we might shim in a simple JS
// placebo for compat. An easy way to differentiate this from the real thing
// is whether the property is read-only or not. The real |Components| property
// is read-only.
/* global _EU_Ci, _EU_Cc, _EU_Cu, _EU_ChromeUtils, _EU_OS */
window.__defineGetter__("_EU_Ci", function () {
var c = Object.getOwnPropertyDescriptor(window, "Components");
return c && c.value && !c.writable ? Ci : SpecialPowers.Ci;
});
window.__defineGetter__("_EU_Cc", function () {
var c = Object.getOwnPropertyDescriptor(window, "Components");
return c && c.value && !c.writable ? Cc : SpecialPowers.Cc;
});
window.__defineGetter__("_EU_Cu", function () {
var c = Object.getOwnPropertyDescriptor(window, "Components");
return c && c.value && !c.writable ? Cu : SpecialPowers.Cu;
});
window.__defineGetter__("_EU_ChromeUtils", function () {
var c = Object.getOwnPropertyDescriptor(window, "ChromeUtils");
return c && c.value && !c.writable ? ChromeUtils : SpecialPowers.ChromeUtils;
});
window.__defineGetter__("_EU_OS", function () {
delete this._EU_OS;
try {
this._EU_OS = _EU_ChromeUtils.importESModule(
"resource://gre/modules/AppConstants.sys.mjs"
).platform;
} catch (ex) {
this._EU_OS = null;
}
return this._EU_OS;
});
function _EU_isMac(aWindow = window) {
if (window._EU_OS) {
return window._EU_OS == "macosx";
}
if (aWindow) {
try {
return aWindow.navigator.platform.indexOf("Mac") > -1;
} catch (ex) {}
}
return navigator.platform.indexOf("Mac") > -1;
}
function _EU_isWin(aWindow = window) {
if (window._EU_OS) {
return window._EU_OS == "win";
}
if (aWindow) {
try {
return aWindow.navigator.platform.indexOf("Win") > -1;
} catch (ex) {}
}
return navigator.platform.indexOf("Win") > -1;
}
function _EU_isLinux(aWindow = window) {
if (window._EU_OS) {
return window._EU_OS == "linux";
}
if (aWindow) {
try {
return aWindow.navigator.platform.startsWith("Linux");
} catch (ex) {}
}
return navigator.platform.startsWith("Linux");
}
function _EU_isAndroid(aWindow = window) {
if (window._EU_OS) {
return window._EU_OS == "android";
}
if (aWindow) {
try {
return aWindow.navigator.userAgent.includes("Android");
} catch (ex) {}
}
return navigator.userAgent.includes("Android");
}
function _EU_maybeWrap(o) {
// We're used in some contexts where there is no SpecialPowers and also in
// some where it exists but has no wrap() method. And this is somewhat
// independent of whether window.Components is a thing...
var haveWrap = false;
try {
haveWrap = SpecialPowers.wrap != undefined;
} catch (e) {
// Just leave it false.
}
if (!haveWrap) {
// Not much we can do here.
return o;
}
var c = Object.getOwnPropertyDescriptor(window, "Components");
return c && c.value && !c.writable ? o : SpecialPowers.wrap(o);
}
function _EU_maybeUnwrap(o) {
var haveWrap = false;
try {
haveWrap = SpecialPowers.unwrap != undefined;
} catch (e) {
// Just leave it false.
}
if (!haveWrap) {
// Not much we can do here.
return o;
}
var c = Object.getOwnPropertyDescriptor(window, "Components");
return c && c.value && !c.writable ? o : SpecialPowers.unwrap(o);
}
function _EU_getPlatform() {
if (_EU_isWin()) {
return "windows";
}
if (_EU_isMac()) {
return "mac";
}
if (_EU_isAndroid()) {
return "android";
}
if (_EU_isLinux()) {
return "linux";
}
return "unknown";
}
function _EU_roundDevicePixels(aMaybeFractionalPixels) {
return Math.floor(aMaybeFractionalPixels + 0.5);
}
/**
* promiseElementReadyForUserInput() dispatches mousemove events to aElement
* and waits one of them for a while. Then, returns "resolved" state when it's
* successfully received. Otherwise, if it couldn't receive mousemove event on
* it, this throws an exception. So, aElement must be an element which is
* assumed non-collapsed visible element in the window.
*
* This is useful if you need to synthesize mouse events via the main process
* but your test cannot check whether the element is now in APZ to deliver
* a user input event.
*/
async function promiseElementReadyForUserInput(
aElement,
aWindow = window,
aLogFunc = null
) {
if (typeof aElement == "string") {
aElement = aWindow.document.getElementById(aElement);
}
function waitForMouseMoveForHittest() {
return new Promise(resolve => {
let timeout;
const onHit = () => {
if (aLogFunc) {
aLogFunc("mousemove received");
}
aWindow.clearInterval(timeout);
resolve(true);
};
aElement.addEventListener("mousemove", onHit, {
capture: true,
once: true,
});
timeout = aWindow.setInterval(() => {
if (aLogFunc) {
aLogFunc("mousemove not received in this 300ms");
}
aElement.removeEventListener("mousemove", onHit, {
capture: true,
});
resolve(false);
}, 300);
synthesizeMouseAtCenter(aElement, { type: "mousemove" }, aWindow);
});
}
for (let i = 0; i < 20; i++) {
if (await waitForMouseMoveForHittest()) {
return Promise.resolve();
}
}
throw new Error("The element or the window did not become interactive");
}
function getElement(id) {
return typeof id == "string" ? document.getElementById(id) : id;
}
this.$ = this.getElement;
function computeButton(aEvent) {
if (typeof aEvent.button != "undefined") {
return aEvent.button;
}
return aEvent.type == "contextmenu" ? 2 : 0;
}
/**
* Send a mouse event to the node aTarget (aTarget can be an id, or an
* actual node) . The "event" passed in to aEvent is just a JavaScript
* object with the properties set that the real mouse event object should
* have. This includes the type of the mouse event. Pretty much all those
* properties are optional.
* E.g. to send an click event to the node with id 'node' you might do this:
*
* ``sendMouseEvent({type:'click'}, 'node');``
*/
function sendMouseEvent(aEvent, aTarget, aWindow) {
if (
![
"click",
"contextmenu",
"dblclick",
"mousedown",
"mouseup",
"mouseover",
"mouseout",
].includes(aEvent.type)
) {
throw new Error(
"sendMouseEvent doesn't know about event type '" + aEvent.type + "'"
);
}
if (!aWindow) {
aWindow = window;
}
if (typeof aTarget == "string") {
aTarget = aWindow.document.getElementById(aTarget);
}
let dict = {
bubbles: true,
cancelable: true,
view: aWindow,
detail:
aEvent.detail ||
// eslint-disable-next-line no-nested-ternary
(aEvent.type == "click" ||
aEvent.type == "mousedown" ||
aEvent.type == "mouseup"
? 1
: aEvent.type == "dblclick"
? 2
: 0),
screenX: aEvent.screenX || 0,
screenY: aEvent.screenY || 0,
clientX: aEvent.clientX || 0,
clientY: aEvent.clientY || 0,
ctrlKey: aEvent.ctrlKey || false,
altKey: aEvent.altKey || false,
shiftKey: aEvent.shiftKey || false,
metaKey: aEvent.metaKey || false,
button: computeButton(aEvent),
// FIXME: Set buttons
relatedTarget: aEvent.relatedTarget || null,
};
let event =
aEvent.type == "click" || aEvent.type == "contextmenu"
? new aWindow.PointerEvent(aEvent.type, dict)
: new aWindow.MouseEvent(aEvent.type, dict);
// If documentURIObject exists or `window` is a stub object, we're in
// a chrome scope, so don't bother trying to go through SpecialPowers.
if (!window.document || window.document.documentURIObject) {
return aTarget.dispatchEvent(event);
}
return SpecialPowers.dispatchEvent(aWindow, aTarget, event);
}
function isHidden(aElement) {
var box = aElement.getBoundingClientRect();
return box.width == 0 && box.height == 0;
}
/**
* Send a drag event to the node aTarget (aTarget can be an id, or an
* actual node) . The "event" passed in to aEvent is just a JavaScript
* object with the properties set that the real drag event object should
* have. This includes the type of the drag event.
*
* @returns {boolean}
*/
function sendDragEvent(aEvent, aTarget, aWindow = window) {
if (
![
"drag",
"dragstart",
"dragend",
"dragover",
"dragenter",
"dragleave",
"drop",
].includes(aEvent.type)
) {
throw new Error(
"sendDragEvent doesn't know about event type '" + aEvent.type + "'"
);
}
if (typeof aTarget == "string") {
aTarget = aWindow.document.getElementById(aTarget);
}
/*
* Drag event cannot be performed if the element is hidden, except 'dragend'
* event where the element can becomes hidden after start dragging.
*/
if (aEvent.type != "dragend" && isHidden(aTarget)) {
var targetName = aTarget.nodeName;
if ("id" in aTarget && aTarget.id) {
targetName += "#" + aTarget.id;
}
throw new Error(`${aEvent.type} event target ${targetName} is hidden`);
}
var event = aWindow.document.createEvent("DragEvent");
var typeArg = aEvent.type;
var canBubbleArg = true;
var cancelableArg = true;
var viewArg = aWindow;
var detailArg = aEvent.detail || 0;
var screenXArg = aEvent.screenX || 0;
var screenYArg = aEvent.screenY || 0;
var clientXArg = aEvent.clientX || 0;
var clientYArg = aEvent.clientY || 0;
var ctrlKeyArg = aEvent.ctrlKey || false;
var altKeyArg = aEvent.altKey || false;
var shiftKeyArg = aEvent.shiftKey || false;
var metaKeyArg = aEvent.metaKey || false;
var buttonArg = computeButton(aEvent);
var relatedTargetArg = aEvent.relatedTarget || null;
var dataTransfer = aEvent.dataTransfer || null;
event.initDragEvent(
typeArg,
canBubbleArg,
cancelableArg,
viewArg,
detailArg,
Math.round(screenXArg),
Math.round(screenYArg),
Math.round(clientXArg),
Math.round(clientYArg),
ctrlKeyArg,
altKeyArg,
shiftKeyArg,
metaKeyArg,
buttonArg,
relatedTargetArg,
dataTransfer
);
if (aEvent._domDispatchOnly) {
return aTarget.dispatchEvent(event);
}
var utils = _getDOMWindowUtils(aWindow);
return utils.dispatchDOMEventViaPresShellForTesting(aTarget, event);
}
/**
* Send the char aChar to the focused element. This method handles casing of
* chars (sends the right charcode, and sends a shift key for uppercase chars).
* No other modifiers are handled at this point.
*
* For now this method only works for ASCII characters and emulates the shift
* key state on US keyboard layout.
*/
function sendChar(aChar, aWindow) {
var hasShift;
// Emulate US keyboard layout for the shiftKey state.
switch (aChar) {
case "!":
case "@":
case "#":
case "$":
case "%":
case "^":
case "&":
case "*":
case "(":
case ")":
case "_":
case "+":
case "{":
case "}":
case ":":
case '"':
case "|":
case "<":
case ">":
case "?":
hasShift = true;
break;
default:
hasShift =
aChar.toLowerCase() != aChar.toUpperCase() &&
aChar == aChar.toUpperCase();
break;
}
synthesizeKey(aChar, { shiftKey: hasShift }, aWindow);
}
/**
* Send the string aStr to the focused element.
*
* For now this method only works for ASCII characters and emulates the shift
* key state on US keyboard layout.
*/
function sendString(aStr, aWindow) {
for (let i = 0; i < aStr.length; ++i) {
// Do not split a surrogate pair to call synthesizeKey. Dispatching two
// sets of keydown and keyup caused by two calls of synthesizeKey is not
// good behavior. It could happen due to a bug, but a surrogate pair should
// be introduced with one key press operation. Therefore, calling it with
// a surrogate pair is the right thing.
// Note that TextEventDispatcher will consider whether a surrogate pair
// should cause one or two keypress events automatically. Therefore, we
// don't need to check the related prefs here.
if (
(aStr.charCodeAt(i) & 0xfc00) == 0xd800 &&
i + 1 < aStr.length &&
(aStr.charCodeAt(i + 1) & 0xfc00) == 0xdc00
) {
sendChar(aStr.substring(i, i + 2), aWindow);
i++;
} else {
sendChar(aStr.charAt(i), aWindow);
}
}
}
/**
* Send the non-character key aKey to the focused node.
* The name of the key should be the part that comes after ``DOM_VK_`` in the
* KeyEvent constant name for this key.
* No modifiers are handled at this point.
*/
function sendKey(aKey, aWindow) {
var keyName = "VK_" + aKey.toUpperCase();
synthesizeKey(keyName, { shiftKey: false }, aWindow);
}
/**
* Parse the key modifier flags from aEvent. Used to share code between
* synthesizeMouse and synthesizeKey.
*/
function _parseModifiers(aEvent, aWindow = window) {
var nsIDOMWindowUtils = _EU_Ci.nsIDOMWindowUtils;
var mval = 0;
if (aEvent.shiftKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SHIFT;
}
if (aEvent.ctrlKey) {
mval |= nsIDOMWindowUtils.MODIFIER_CONTROL;
}
if (aEvent.altKey) {
mval |= nsIDOMWindowUtils.MODIFIER_ALT;
}
if (aEvent.metaKey) {
mval |= nsIDOMWindowUtils.MODIFIER_META;
}
if (aEvent.accelKey) {
mval |= _EU_isMac(aWindow)
? nsIDOMWindowUtils.MODIFIER_META
: nsIDOMWindowUtils.MODIFIER_CONTROL;
}
if (aEvent.altGrKey) {
mval |= nsIDOMWindowUtils.MODIFIER_ALTGRAPH;
}
if (aEvent.capsLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_CAPSLOCK;
}
if (aEvent.fnKey) {
mval |= nsIDOMWindowUtils.MODIFIER_FN;
}
if (aEvent.fnLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_FNLOCK;
}
if (aEvent.numLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_NUMLOCK;
}
if (aEvent.scrollLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SCROLLLOCK;
}
if (aEvent.symbolKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SYMBOL;
}
if (aEvent.symbolLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SYMBOLLOCK;
}
return mval;
}
/**
* Return the drag service. Note that if we're in the headless mode, this
* may return null because the service may be never instantiated (e.g., on
* Linux).
*/
function getDragService() {
try {
return _EU_Cc["@mozilla.org/widget/dragservice;1"].getService(
_EU_Ci.nsIDragService
);
} catch (e) {
// If we're in the headless mode, the drag service may be never
// instantiated. In this case, an exception is thrown. Let's ignore
// any exceptions since without the drag service, nobody can create a
// drag session.
return null;
}
}
/**
* End drag session if there is.
*
* TODO: This should synthesize "drop" if necessary.
*
* @param left X offset in the viewport
* @param top Y offset in the viewport
* @param aEvent The event data, the modifiers are applied to the
* "dragend" event.
* @param aWindow The window.
* @return true if handled. In this case, the caller should not
* synthesize DOM events basically.
*/
function _maybeEndDragSession(left, top, aEvent, aWindow) {
let utils = _getDOMWindowUtils(aWindow);
const dragSession = utils.dragSession;
if (!dragSession) {
return false;
}
// FIXME: If dragSession.dragAction is not
// nsIDragService.DRAGDROP_ACTION_NONE nor aEvent.type is not `keydown`, we
// need to synthesize a "drop" event or call setDragEndPointForTests here to
// set proper left/top to `dragend` event.
try {
dragSession.endDragSession(false, _parseModifiers(aEvent, aWindow));
} catch (e) {}
return true;
}
function _maybeSynthesizeDragOver(left, top, aEvent, aWindow) {
let utils = _getDOMWindowUtils(aWindow);
const dragSession = utils.dragSession;
if (!dragSession) {
return false;
}
const target = aWindow.document.elementFromPoint(left, top);
if (target) {
sendDragEvent(
createDragEventObject(
"dragover",
target,
aWindow,
dragSession.dataTransfer,
{
accelKey: aEvent.accelKey,
altKey: aEvent.altKey,
altGrKey: aEvent.altGrKey,
ctrlKey: aEvent.ctrlKey,
metaKey: aEvent.metaKey,
shiftKey: aEvent.shiftKey,
capsLockKey: aEvent.capsLockKey,
fnKey: aEvent.fnKey,
fnLockKey: aEvent.fnLockKey,
numLockKey: aEvent.numLockKey,
scrollLockKey: aEvent.scrollLockKey,
symbolKey: aEvent.symbolKey,
symbolLockKey: aEvent.symbolLockKey,
}
),
target,
aWindow
);
}
return true;
}
/**
* @typedef {object} MouseEventData
*
* @property {string} [accessKey] - The character or key associated with
* the access key event. Typically a single character used to activate a UI
* element via keyboard shortcuts (e.g., Alt + accessKey).
* @property {boolean} [altKey] - If set to `true`, the Alt key will be
* considered pressed.
* @property {boolean} [asyncEnabled] - If `true`, the event is
* dispatched to the parent process through APZ, without being injected
* into the OS event queue.
* @property {number} [button=0] - Button to synthesize.
* @property {number} [buttons] - Indicates which mouse buttons are pressed
* when a mouse event is triggered.
* @property {number} [clickCount=1] - Number of clicks that have to be performed.
* @property {boolean} [ctrlKey] - If set to `true`, the Ctrl key will
* be considered pressed.
* @property {number} [id] - A unique identifier for the pointer causing the event.
* @property {number} [inputSource] - Input source, see MouseEvent for values.
* Defaults to MouseEvent.MOZ_SOURCE_MOUSE.
* @property {boolean} [isSynthesized] - Controls Event.isSynthesized value that
* helps identifying test related events
* @property {boolean} [isWidgetEventSynthesized] - Controls WidgetMouseEvent.mReason value.
* @property {boolean} [metaKey] - If set to `true`, the Meta key will
* be considered pressed.
* @property {number} [pressure=0] - Touch input pressure (0.0 -> 1.0).
* @property {boolean} [shiftKey] - If set to `true`, the Shift key will
* be considered pressed.
* @property {string} [type] - Event type to synthesize. If not specified
* a `mousedown` followed by a `mouseup` are performed.
*
* @see nsIDOMWindowUtils.sendMouseEvent
*/
/**
* Synthesize a mouse event on a target.
*
* The actual client point is determined by taking the aTarget's client box
* and offsetting it by aOffsetX and aOffsetY.
*
* Note that additional events may be fired as a result of this call. For
* instance, typically a click event will be fired as a result of a
* mousedown and mouseup in sequence.
*
* @param {Element} aTarget - DOM element to dispatch the event on.
* @param {number} aOffsetX - X offset in CSS pixels from the element’s left edge.
* @param {number} aOffsetY - Y offset in CSS pixels from the element’s top edge.
* @param {MouseEventData} aEvent - Details of the mouse event to dispatch.
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
* @param {Function} [aCallback] - A callback function that is invoked when the
* mouse event is dispatched.
*
* @returns {boolean} Whether the event had preventDefault() called on it.
*/
function synthesizeMouse(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aWindow,
aCallback
) {
var rect = aTarget.getBoundingClientRect();
return synthesizeMouseAtPoint(
rect.left + aOffsetX,
rect.top + aOffsetY,
aEvent,
aWindow,
aCallback
);
}
/**
* Synthesize a mouse event in `aWindow` at a point.
*
* `nsIDOMWindowUtils.sendMouseEvent` takes floats for the coordinates.
* Therefore, don't round or truncate the values.
*
* Note that additional events may be fired as a result of this call. For
* instance, typically a click event will be fired as a result of a
* mousedown and mouseup in sequence.
*
* @param {number} aLeft - Floating-point value for the X offset in CSS pixels.
* @param {number} aTop - Floating-point value for the Y offset in CSS pixels.
* @param {MouseEventData} aEvent - Details of the mouse event to dispatch.
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
* @param {Function} [aCallback] - A callback function that is invoked when the
* mouse event is dispatched.
*
* @returns {boolean} Whether the event had preventDefault() called on it.
*/
function synthesizeMouseAtPoint(
aLeft,
aTop,
aEvent,
aWindow = window,
aCallback
) {
if (aEvent.allowToHandleDragDrop) {
if (aEvent.type == "mouseup" || !aEvent.type) {
if (_maybeEndDragSession(aLeft, aTop, aEvent, aWindow)) {
return false;
}
} else if (aEvent.type == "mousemove") {
if (_maybeSynthesizeDragOver(aLeft, aTop, aEvent, aWindow)) {
return false;
}
}
}
var utils = _getDOMWindowUtils(aWindow);
var defaultPrevented = false;
if (utils) {
var button = computeButton(aEvent);
var clickCount = aEvent.clickCount || 1;
var modifiers = _parseModifiers(aEvent, aWindow);
var pressure = "pressure" in aEvent ? aEvent.pressure : 0;
// aWindow might be cross-origin from us.
var MouseEvent = _EU_maybeWrap(aWindow).MouseEvent;
// Default source to mouse.
var inputSource =
"inputSource" in aEvent
? aEvent.inputSource
: MouseEvent.MOZ_SOURCE_MOUSE;
// Compute a pointerId if needed.
var id;
if ("id" in aEvent) {
id = aEvent.id;
} else {
var isFromPen = inputSource === MouseEvent.MOZ_SOURCE_PEN;
id = isFromPen
? utils.DEFAULT_PEN_POINTER_ID
: utils.DEFAULT_MOUSE_POINTER_ID;
}
// FYI: Window.synthesizeMouseEvent takes floats for the coordinates.
// Therefore, don't round/truncate the fractional values.
const isDOMEventSynthesized =
"isSynthesized" in aEvent ? aEvent.isSynthesized : true;
const isWidgetEventSynthesized =
"isWidgetEventSynthesized" in aEvent
? aEvent.isWidgetEventSynthesized
: false;
const isAsyncEnabled =
"asyncEnabled" in aEvent ? aEvent.asyncEnabled : false;
if ("type" in aEvent && aEvent.type) {
defaultPrevented = _EU_maybeWrap(aWindow).synthesizeMouseEvent(
aEvent.type,
aLeft,
aTop,
{
identifier: id,
button,
buttons: aEvent.buttons,
clickCount,
modifiers,
pressure,
inputSource,
},
{
isDOMEventSynthesized,
isWidgetEventSynthesized,
isAsyncEnabled,
},
aCallback
);
} else {
_EU_maybeWrap(aWindow).synthesizeMouseEvent(
"mousedown",
aLeft,
aTop,
{
identifier: id,
button,
buttons: aEvent.buttons,
clickCount,
modifiers,
pressure,
inputSource,
},
{
isDOMEventSynthesized,
isWidgetEventSynthesized,
isAsyncEnabled,
},
aCallback
);
_EU_maybeWrap(aWindow).synthesizeMouseEvent(
"mouseup",
aLeft,
aTop,
{
identifier: id,
button,
buttons: aEvent.buttons,
clickCount,
modifiers,
pressure,
inputSource,
},
{
isDOMEventSynthesized,
isWidgetEventSynthesized,
isAsyncEnabled,
},
aCallback
);
}
}
return defaultPrevented;
}
/**
* Synthesize a mouse event at the center of `aTarget`.
*
* Note that additional events may be fired as a result of this call. For
* instance, typically a click event will be fired as a result of a
* mousedown and mouseup in sequence.
*
* @param {Element} aTarget - DOM element to dispatch the event on.
* @param {MouseEventData} aEvent - Details of the mouse event to dispatch.
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
* @param {Function} [aCallback] - A callback function that is invoked when the
* mouse event is dispatched.
*
* @returns {boolean} Whether the event had preventDefault() called on it.
*/
function synthesizeMouseAtCenter(aTarget, aEvent, aWindow, aCallback) {
var rect = aTarget.getBoundingClientRect();
return synthesizeMouse(
aTarget,
rect.width / 2,
rect.height / 2,
aEvent,
aWindow,
aCallback
);
}
/**
* @typedef {object} TouchEventData
* @property {boolean} [aEvent.asyncEnabled] - If `true`, the event is
* dispatched to the parent process through APZ, without being injected
* into the OS event queue.
* @property {string} [aEvent.type] - The touch event type. If undefined,
* "touchstart" and "touchend" will be synthesized at same point.
* @property {number | number[]} [aEvent.id] - The touch id. If you don't specify this,
* default touch id will be used for first touch and further touch ids
* are the values incremented from the first id.
* @property {number | number[]} [aEvent.ry] - The X radius in CSS pixels of the touch
* @property {number | number[]} [aEvent.ry] - The Y radius in CSS pixels of the touch
* @property {number | number[]} [aEvent.angle] - The angle in degrees
* @property {number | number[]} [aEvent.force] - The force of the touch
* @property {number | number[]} [aEvent.tiltX] - The X tilt of the touch
* @property {number | number[]} [aEvent.tiltY] - The Y tilt of the touch
* @property {number | number[]} [aEvent.twist] - The twist of the touch
*/
/**
* Synthesize one or more touches on aTarget. aTarget can be either Element
* or Array of Elements. aOffsetX, aOffsetY, aEvent.id, aEvent.rx, aEvent.ry,
* aEvent.angle, aEvent.force, aEvent.tiltX, aEvent.tiltY and aEvent.twist can
* be either number or array of numbers (can be mixed). If you specify array
* to synthesize a multi-touch, you need to specify same length arrays. If
* you don't specify array to them, same values (or computed default values for
* aEvent.id) are used for all touches.
*
* @param {Element | Element[]} aTarget - The target element which you specify
* relative offset from its top-left.
* @param {number | number[]} aOffsetX - The relative offset from left of aTarget.
* @param {number | number[]} aOffsetY - The relative offset from top of aTarget.
* @param {TouchEventData} aEvent - Details of the touch event to dispatch
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
*
* @returns true if and only if aEvent.type is specified and default of the
* event is prevented.
*/
function synthesizeTouch(
aTarget,
aOffsetX,
aOffsetY,
aEvent = {},
aWindow = window
) {
let rectX, rectY;
if (Array.isArray(aTarget)) {
let lastTarget, lastTargetRect;
aTarget.forEach(target => {
const rect =
target == lastTarget ? lastTargetRect : target.getBoundingClientRect();
rectX.push(rect.left);
rectY.push(rect.top);
lastTarget = target;
lastTargetRect = rect;
});
} else {
const rect = aTarget.getBoundingClientRect();
rectX = [rect.left];
rectY = [rect.top];
}
const offsetX = (() => {
if (Array.isArray(aOffsetX)) {
let ret = [];
aOffsetX.forEach((value, index) => {
ret.push(value + rectX[Math.min(index, rectX.length - 1)]);
});
return ret;
}
return aOffsetX + rectX[0];
})();
const offsetY = (() => {
if (Array.isArray(aOffsetY)) {
let ret = [];
aOffsetY.forEach((value, index) => {
ret.push(value + rectY[Math.min(index, rectY.length - 1)]);
});
return ret;
}
return aOffsetY + rectY[0];
})();
return synthesizeTouchAtPoint(offsetX, offsetY, aEvent, aWindow);
}
/**
* Synthesize one or more touches at the points. aLeft, aTop, aEvent.id,
* aEvent.rx, aEvent.ry, aEvent.angle, aEvent.force, aEvent.tiltX, aEvent.tiltY
* and aEvent.twist can be either number or array of numbers (can be mixed).
* If you specify array to synthesize a multi-touch, you need to specify same
* length arrays. If you don't specify array to them, same values are used for
* all touches.
*
* @param {number | number[]} aLeft - The relative offset from left of aTarget.
* @param {number | number[]} aTop - The relative offset from top of aTarget.
* @param {TouchEventData} aEvent - Details of the touch event to dispatch
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
*
* @returns true if and only if aEvent.type is specified and default of the
* event is prevented.
*/
function synthesizeTouchAtPoint(aLeft, aTop, aEvent = {}, aWindow = window) {
let utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return false;
}
if (
Array.isArray(aLeft) &&
Array.isArray(aTop) &&
aLeft.length != aTop.length
) {
throw new Error(`aLeft and aTop should be same length array`);
}
const arrayLength = Array.isArray(aLeft)
? aLeft.length
: Array.isArray(aTop)
? aTop.length
: 1;
function throwExceptionIfDifferentLengthArray(aArray, aName) {
if (Array.isArray(aArray) && arrayLength !== aArray.length) {
throw new Error(`${aName} is different length array`);
}
}
const leftArray = (() => {
if (Array.isArray(aLeft)) {
for (let i = 0; i < aLeft.length; i++) {
aLeft[i] = _EU_roundDevicePixels(aLeft[i]);
}
return aLeft;
}
return new Array(arrayLength).fill(_EU_roundDevicePixels(aLeft));
})();
const topArray = (() => {
if (Array.isArray(aTop)) {
throwExceptionIfDifferentLengthArray(aTop, "aTop");
for (let i = 0; i < aTop.length; i++) {
aTop[i] = _EU_roundDevicePixels(aTop[i]);
}
return aTop;
}
return new Array(arrayLength).fill(_EU_roundDevicePixels(aTop));
})();
const idArray = (() => {
if ("id" in aEvent && Array.isArray(aEvent.id)) {
throwExceptionIfDifferentLengthArray(aEvent.id, "aEvent.id");
return aEvent.id;
}
let id = aEvent.id || utils.DEFAULT_TOUCH_POINTER_ID;
let ret = [];
for (let i = 0; i < arrayLength; i++) {
ret.push(id++);
}
return ret;
})();
function getSameLengthArrayOfEventProperty(aProperty, aDefaultValue) {
if (aProperty in aEvent && Array.isArray(aEvent[aProperty])) {
throwExceptionIfDifferentLengthArray(
aEvent.rx,
arrayLength,
`aEvent.${aProperty}`
);
return aEvent[aProperty];
}
return new Array(arrayLength).fill(aEvent[aProperty] || aDefaultValue);
}
const rxArray = getSameLengthArrayOfEventProperty("rx", 1);
const ryArray = getSameLengthArrayOfEventProperty("ry", 1);
const angleArray = getSameLengthArrayOfEventProperty("angle", 0);
const forceArray = getSameLengthArrayOfEventProperty(
"force",
aEvent.type === "touchend" ? 0 : 1
);
const tiltXArray = getSameLengthArrayOfEventProperty("tiltX", 0);
const tiltYArray = getSameLengthArrayOfEventProperty("tiltY", 0);
const twistArray = getSameLengthArrayOfEventProperty("twist", 0);
const modifiers = _parseModifiers(aEvent, aWindow);
const asyncOption = aEvent.asyncEnabled
? utils.ASYNC_ENABLED
: utils.ASYNC_DISABLED;
const args = [
idArray,
leftArray,
topArray,
rxArray,
ryArray,
angleArray,
forceArray,
tiltXArray,
tiltYArray,
twistArray,
modifiers,
asyncOption,
];
const sender =
aEvent.mozInputSource === "pen" ? "sendTouchEventAsPen" : "sendTouchEvent";
if ("type" in aEvent && aEvent.type) {
return utils[sender](aEvent.type, ...args);
}
utils[sender]("touchstart", ...args);
utils[sender]("touchend", ...args);
return false;
}
/**
* Synthesize one or more touches at the center of your target
*
* @param {Element | Element[]} aTarget - The target element
* @param {TouchEventData} aEvent - Details of the touch event to dispatch
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
*/
function synthesizeTouchAtCenter(aTarget, aEvent = {}, aWindow = window) {
var rect = aTarget.getBoundingClientRect();
synthesizeTouchAtPoint(
rect.left + rect.width / 2,
rect.top + rect.height / 2,
aEvent,
aWindow
);
}
/**
* @typedef {object} WheelEventData
* @property {string} [aEvent.accessKey] - The character or key associated with
* the access key event. Typically a single character used to activate a UI
* element via keyboard shortcuts (e.g., Alt + accessKey).
* @property {boolean} [aEvent.altKey] - If set to `true`, the Alt key will be
* considered pressed.
* @property {boolean} [aEvent.asyncEnabled] - If `true`, the event is
* dispatched to the parent process through APZ, without being injected
* into the OS event queue.
* @property {boolean} [aEvent.ctrlKey] - If set to `true`, the Ctrl key will
* be considered pressed.
* @property {number} [aEvent.deltaMode=WheelEvent.DOM_DELTA_PIXEL] - Delta Mode
* for scrolling (pixel, line, or page), which must be one of the
* `WheelEvent.DOM_DELTA_*` constants.
* @property {number} [aEvent.deltaX=0] - Floating-point value in CSS pixels to
* scroll in the x direction.
* @property {number} [aEvent.deltaY=0] - Floating-point value in CSS pixels to
* scroll in the y direction.
* @property {number} [aEvent.deltaZ=0] - Floating-point value in CSS pixels to
* scroll in the z direction.
* @property {number} [aEvent.expectedOverflowDeltaX] - Decimal value
* indicating horizontal scroll overflow. Only the sign is checked: `0`,
* positive, or negative.
* @property {number} [aEvent.expectedOverflowDeltaY] - Decimal value
* indicating vertical scroll overflow. Only the sign is checked: `0`,
* positive, or negative.
* @property {boolean} [aEvent.isCustomizedByPrefs] - If set to `true` the
* delta values are computed from preferences.
* @property {boolean} [aEvent.isMomentum] - If set to `true` the event will be
* caused by momentum.
* @property {boolean} [aEvent.isNoLineOrPageDelta] - If `true`, the creator
* does not set `lineOrPageDeltaX/Y`. When a widget wheel event is
* generated from this object, those fields will be automatically
* calculated during dispatch by the `EventStateManager`.
* @property {number} [aEvent.lineOrPageDeltaX] - If set to a non-zero value
* for a `DOM_DELTA_PIXEL` event, the EventStateManager will dispatch a
* `NS_MOUSE_SCROLL` event for a horizontal scroll.
* @property {number} [aEvent.lineOrPageDeltaY] - If set to a non-zero value
* for a `DOM_DELTA_PIXEL` event, the EventStateManager will dispatch a
* `NS_MOUSE_SCROLL` event for a vertical scroll.
* @property {boolean} [aEvent.metaKey] - If set to `true`, the Meta key will
* be considered pressed.
* @property {boolean} [aEvent.shiftKey] - If set to `true`, the Shift key will
* be considered pressed.
*/
/**
* Synthesize a wheel event in `aWindow` at a point, without flushing layout.
*
* `nsIDOMWindowUtils.sendWheelEvent` takes floats for the coordinates.
* Therefore, don't round or truncate the values.
*
* @param {number} aLeft - Floating-point value for the X offset in CSS pixels.
* @param {number} aTop - Floating-point value for the Y offset in CSS pixels.
* @param {WheelEventData} aEvent - Details of the wheel event to dispatch.
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
* @param {Function} [aCallback=null] - A callback function that is invoked when
* the wheel event is dispatched.
*/
function synthesizeWheelAtPoint(
aLeft,
aTop,
aEvent,
aWindow = window,
aCallback = null
) {
var utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return;
}
var modifiers = _parseModifiers(aEvent, aWindow);
var options = 0;
if (aEvent.isNoLineOrPageDelta) {
options |= utils.WHEEL_EVENT_CAUSED_BY_NO_LINE_OR_PAGE_DELTA_DEVICE;
}
if (aEvent.isMomentum) {
options |= utils.WHEEL_EVENT_CAUSED_BY_MOMENTUM;
}
if (aEvent.isCustomizedByPrefs) {
options |= utils.WHEEL_EVENT_CUSTOMIZED_BY_USER_PREFS;
}
if (typeof aEvent.expectedOverflowDeltaX !== "undefined") {
if (aEvent.expectedOverflowDeltaX === 0) {
options |= utils.WHEEL_EVENT_EXPECTED_OVERFLOW_DELTA_X_ZERO;
} else if (aEvent.expectedOverflowDeltaX > 0) {
options |= utils.WHEEL_EVENT_EXPECTED_OVERFLOW_DELTA_X_POSITIVE;
} else {
options |= utils.WHEEL_EVENT_EXPECTED_OVERFLOW_DELTA_X_NEGATIVE;
}
}
if (typeof aEvent.expectedOverflowDeltaY !== "undefined") {
if (aEvent.expectedOverflowDeltaY === 0) {
options |= utils.WHEEL_EVENT_EXPECTED_OVERFLOW_DELTA_Y_ZERO;
} else if (aEvent.expectedOverflowDeltaY > 0) {
options |= utils.WHEEL_EVENT_EXPECTED_OVERFLOW_DELTA_Y_POSITIVE;
} else {
options |= utils.WHEEL_EVENT_EXPECTED_OVERFLOW_DELTA_Y_NEGATIVE;
}
}
if (aEvent.asyncEnabled) {
options |= utils.WHEEL_EVENT_ASYNC_ENABLED;
}
// Avoid the JS warnings "reference to undefined property"
if (!aEvent.deltaMode) {
aEvent.deltaMode = WheelEvent.DOM_DELTA_PIXEL;
}
if (!aEvent.deltaX) {
aEvent.deltaX = 0;
}
if (!aEvent.deltaY) {
aEvent.deltaY = 0;
}
if (!aEvent.deltaZ) {
aEvent.deltaZ = 0;
}
var lineOrPageDeltaX =
// eslint-disable-next-line no-nested-ternary
aEvent.lineOrPageDeltaX != null
? aEvent.lineOrPageDeltaX
: aEvent.deltaX > 0
? Math.floor(aEvent.deltaX)
: Math.ceil(aEvent.deltaX);
var lineOrPageDeltaY =
// eslint-disable-next-line no-nested-ternary
aEvent.lineOrPageDeltaY != null
? aEvent.lineOrPageDeltaY
: aEvent.deltaY > 0
? Math.floor(aEvent.deltaY)
: Math.ceil(aEvent.deltaY);
utils.sendWheelEvent(
aLeft,
aTop,
aEvent.deltaX,
aEvent.deltaY,
aEvent.deltaZ,
aEvent.deltaMode,
modifiers,
lineOrPageDeltaX,
lineOrPageDeltaY,
options,
aCallback
);
}
/**
* Synthesize a wheel event on a target.
*
* The actual client point is determined by taking the aTarget's client box
* and offsetting it by aOffsetX and aOffsetY.
*
* @param {Element} aTarget - DOM element to dispatch the event on.
* @param {number} aOffsetX - X offset in CSS pixels from the element’s left edge.
* @param {number} aOffsetY - Y offset in CSS pixels from the element’s top edge.
* @param {WheelEventData} aEvent - Details of the wheel event to dispatch.
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
* @param {Function} [aCallback=null] - A callback function that is invoked when
* the wheel event is dispatched.
*/
function synthesizeWheel(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aWindow = window,
aCallback = null
) {
var rect = aTarget.getBoundingClientRect();
synthesizeWheelAtPoint(
rect.left + aOffsetX,
rect.top + aOffsetY,
aEvent,
aWindow,
aCallback
);
}
const _FlushModes = {
FLUSH: 0,
NOFLUSH: 1,
};
function _sendWheelAndPaint(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
aFlushMode = _FlushModes.FLUSH,
aWindow = window
) {
var utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return;
}
if (utils.isMozAfterPaintPending) {
// If a paint is pending, then APZ may be waiting for a scroll acknowledgement
// from the content thread. If we send a wheel event now, it could be ignored
// by APZ (or its scroll offset could be overridden). To avoid problems we
// just wait for the paint to complete.
aWindow.waitForAllPaintsFlushed(function () {
_sendWheelAndPaint(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
aFlushMode,
aWindow
);
});
return;
}
var onwheel = function () {
SpecialPowers.wrap(window).removeEventListener("wheel", onwheel, {
mozSystemGroup: true,
});
// Wait one frame since the wheel event has not caused a refresh observer
// to be added yet.
setTimeout(function () {
utils.advanceTimeAndRefresh(1000);
if (!aCallback) {
utils.advanceTimeAndRefresh(0);
return;
}
var waitForPaints = function () {
SpecialPowers.Services.obs.removeObserver(
waitForPaints,
"apz-repaints-flushed"
);
aWindow.waitForAllPaintsFlushed(function () {
utils.restoreNormalRefresh();
aCallback();
});
};
SpecialPowers.Services.obs.addObserver(
waitForPaints,
"apz-repaints-flushed"
);
if (!utils.flushApzRepaints()) {
waitForPaints();
}
}, 0);
};
// Listen for the system wheel event, because it happens after all of
// the other wheel events, including legacy events.
SpecialPowers.wrap(aWindow).addEventListener("wheel", onwheel, {
mozSystemGroup: true,
});
if (aFlushMode === _FlushModes.FLUSH) {
synthesizeWheel(aTarget, aOffsetX, aOffsetY, aEvent, aWindow);
} else {
synthesizeWheelAtPoint(aOffsetX, aOffsetY, aEvent, aWindow);
}
}
/**
* Wrapper around synthesizeWheel that waits for the wheel event to be
* dispatched and for any resulting layout and paint operations to flush.
*
* Requires including `paint_listener.js`. Tests using this function must call
* `DOMWindowUtils.restoreNormalRefresh()` before finishing.
*
* @param {Element} aTarget - DOM element to dispatch the event on.
* @param {number} aOffsetX - X offset in CSS pixels from the element’s left edge.
* @param {number} aOffsetY - Y offset in CSS pixels from the element’s top edge.
* @param {WheelEventData} aEvent - Details of the wheel event to dispatch.
* @param {Function} [aCallback] - Called after paint flush, if provided. If not,
* the caller is expected to handle scroll completion manually. In this case,
* the refresh driver will not be restored automatically.
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
*/
function sendWheelAndPaint(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
aWindow = window
) {
_sendWheelAndPaint(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
_FlushModes.FLUSH,
aWindow
);
}
/**
* Similar to `sendWheelAndPaint()`, but skips layout flush when resolving
* `aTarget`'s position in `aWindow` before dispatching the wheel event.
*
* @param {Element} aTarget - DOM element to dispatch the event on.
* @param {number} aOffsetX - X offset in CSS pixels from the `aWindow`’s left edge.
* @param {number} aOffsetY - Y offset in CSS pixels from the `aWindow`’s top edge.
* @param {WheelEventData} aEvent - Details of the wheel event to dispatch.
* @param {Function} [aCallback] - Called after paint, if provided. If not,
* the caller is expected to handle scroll completion manually. In this case,
* the refresh driver will not be restored automatically.
* @param {DOMWindow} [aWindow=window] - DOM window used to dispatch the event.
*/
function sendWheelAndPaintNoFlush(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
aWindow = window
) {
_sendWheelAndPaint(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
_FlushModes.NOFLUSH,
aWindow
);
}
function synthesizeNativeTapAtCenter(
aTarget,
aLongTap = false,
aCallback = null,
aWindow = window
) {
let rect = aTarget.getBoundingClientRect();
return synthesizeNativeTap(
aTarget,
rect.width / 2,
rect.height / 2,
aLongTap,
aCallback,
aWindow
);
}
function synthesizeNativeTap(
aTarget,
aOffsetX,
aOffsetY,
aLongTap = false,
aCallback = null,
aWindow = window
) {
let utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return;
}
let scale = aWindow.devicePixelRatio;
let rect = aTarget.getBoundingClientRect();
let x = _EU_roundDevicePixels(
(aWindow.mozInnerScreenX + rect.left + aOffsetX) * scale
);
let y = _EU_roundDevicePixels(
(aWindow.mozInnerScreenY + rect.top + aOffsetY) * scale
);
utils.sendNativeTouchTap(x, y, aLongTap, aCallback);
}
/**
* Similar to synthesizeMouse but generates a native widget level event
* (so will actually move the "real" mouse cursor etc. Be careful because
* this can impact later code as well! (e.g. with hover states etc.)
*
* @description There are 3 mutually exclusive ways of indicating the location of the
* mouse event: set ``atCenter``, or pass ``offsetX`` and ``offsetY``,
* or pass ``screenX`` and ``screenY``. Do not attempt to mix these.
*
* @param {object} aParams
* @param {string} aParams.type "click", "mousedown", "mouseup" or "mousemove"
* @param {Element} aParams.target Origin of offsetX and offsetY, must be an element
* @param {boolean} [aParams.atCenter]
* Instead of offsetX/Y, synthesize the event at center of `target`.
* @param {number} [aParams.offsetX]
* X offset in `target` (in CSS pixels if `scale` is "screenPixelsPerCSSPixel")
* @param {number} [aParams.offsetY]
* Y offset in `target` (in CSS pixels if `scale` is "screenPixelsPerCSSPixel")
* @param {number} [aParams.screenX]
* X offset in screen (in CSS pixels if `scale` is "screenPixelsPerCSSPixel"),
* Neither offsetX/Y nor atCenter must be set if this is set.
* @param {number} [aParams.screenY]
* Y offset in screen (in CSS pixels if `scale` is "screenPixelsPerCSSPixel"),
* Neither offsetX/Y nor atCenter must be set if this is set.
* @param {string} [aParams.scale="screenPixelsPerCSSPixel"]
* If scale is "screenPixelsPerCSSPixel", devicePixelRatio will be used.
* If scale is "inScreenPixels", clientX/Y nor scaleX/Y are not adjusted with screenPixelsPerCSSPixel.
* @param {number} [aParams.button=0]
* Defaults to 0, if "click", "mousedown", "mouseup", set same value as DOM MouseEvent.button
* @param {object} [aParams.modifiers={}]
* Active modifiers, see `_parseNativeModifiers`
* @param {DOMWindow} [aParams.win=window]
* The window to use its utils. Defaults to the window in which EventUtils.js is running.
* @param {Element} [aParams.elementOnWidget=target]
* Defaults to target. If element under the point is in another widget from target's widget,
* e.g., when it's in a XUL <panel>, specify this.
*/
function synthesizeNativeMouseEvent(aParams, aCallback = null) {
const {
type,
target,
offsetX,
offsetY,
atCenter,
screenX,
screenY,
scale = "screenPixelsPerCSSPixel",
button = 0,
modifiers = {},
win = window,
elementOnWidget = target,
} = aParams;
if (atCenter) {
if (offsetX != undefined || offsetY != undefined) {
throw Error(
`atCenter is specified, but offsetX (${offsetX}) and/or offsetY (${offsetY}) are also specified`
);
}
if (screenX != undefined || screenY != undefined) {
throw Error(
`atCenter is specified, but screenX (${screenX}) and/or screenY (${screenY}) are also specified`
);
}
if (!target) {
throw Error("atCenter is specified, but target is not specified");
}
} else if (offsetX != undefined && offsetY != undefined) {
if (screenX != undefined || screenY != undefined) {
throw Error(
`offsetX/Y are specified, but screenX (${screenX}) and/or screenY (${screenY}) are also specified`
);
}
if (!target) {
throw Error(
"offsetX and offsetY are specified, but target is not specified"
);
}
} else if (screenX != undefined && screenY != undefined) {
if (offsetX != undefined || offsetY != undefined) {
throw Error(
`screenX/Y are specified, but offsetX (${offsetX}) and/or offsetY (${offsetY}) are also specified`
);
}
}
const utils = _getDOMWindowUtils(win);
if (!utils) {
return;
}
const rect = target?.getBoundingClientRect();
const resolution = _getTopWindowResolution(win);
const scaleValue = (() => {
if (scale === "inScreenPixels") {
return 1.0;
}
if (scale === "screenPixelsPerCSSPixel") {
return win.devicePixelRatio;
}
throw Error(`invalid scale value (${scale}) is specified`);
})();
// XXX mozInnerScreen might be invalid value on mobile viewport (Bug 1701546),
// so use window.top's mozInnerScreen. But this won't work fission+xorigin
// with mobile viewport until mozInnerScreen returns valid value with
// scale.
const x = _EU_roundDevicePixels(
(() => {
if (screenX != undefined) {
return screenX * scaleValue;
}
const winInnerOffsetX = _getScreenXInUnscaledCSSPixels(win);
return (
(((atCenter ? rect.width / 2 : offsetX) + rect.left) * resolution +
winInnerOffsetX) *
scaleValue
);
})()
);
const y = _EU_roundDevicePixels(
(() => {
if (screenY != undefined) {
return screenY * scaleValue;
}
const winInnerOffsetY = _getScreenYInUnscaledCSSPixels(win);
return (
(((atCenter ? rect.height / 2 : offsetY) + rect.top) * resolution +
winInnerOffsetY) *
scaleValue
);
})()
);
const modifierFlags = _parseNativeModifiers(modifiers);
if (type === "click") {
utils.sendNativeMouseEvent(
x,
y,
utils.NATIVE_MOUSE_MESSAGE_BUTTON_DOWN,
button,
modifierFlags,
elementOnWidget,
function () {
utils.sendNativeMouseEvent(
x,
y,
utils.NATIVE_MOUSE_MESSAGE_BUTTON_UP,
button,
modifierFlags,
elementOnWidget,
aCallback
);
}
);
return;
}
utils.sendNativeMouseEvent(
x,
y,
(() => {
switch (type) {
case "mousedown":
return utils.NATIVE_MOUSE_MESSAGE_BUTTON_DOWN;
case "mouseup":
return utils.NATIVE_MOUSE_MESSAGE_BUTTON_UP;
case "mousemove":
return utils.NATIVE_MOUSE_MESSAGE_MOVE;
default:
throw Error(`Invalid type is specified: ${type}`);
}
})(),
button,
modifierFlags,
elementOnWidget,
aCallback
);
}
function promiseNativeMouseEvent(aParams) {
return new Promise(resolve => synthesizeNativeMouseEvent(aParams, resolve));
}
function synthesizeNativeMouseEventAndWaitForEvent(aParams, aCallback) {
const listener = aParams.eventTargetToListen || aParams.target;
const eventType = aParams.eventTypeToWait || aParams.type;
listener.addEventListener(eventType, aCallback, {
capture: true,
once: true,
});
synthesizeNativeMouseEvent(aParams);
}
function promiseNativeMouseEventAndWaitForEvent(aParams) {
return new Promise(resolve =>
synthesizeNativeMouseEventAndWaitForEvent(aParams, resolve)
);
}
/**
* This is a wrapper around synthesizeNativeMouseEvent that waits for the mouse
* event to be dispatched to the target content.
*
* This API is supposed to be used in those test cases that synthesize some
* input events to chrome process and have some checks in content.
*/
function synthesizeAndWaitNativeMouseMove(
aTarget,
aOffsetX,
aOffsetY,
aCallback,
aWindow = window
) {
let browser = gBrowser.selectedTab.linkedBrowser;
let mm = browser.messageManager;
let { ContentTask } = _EU_ChromeUtils.importESModule(
"resource://testing-common/ContentTask.sys.mjs"
);
let eventRegisteredPromise = new Promise(resolve => {
mm.addMessageListener("Test:MouseMoveRegistered", function processed() {
mm.removeMessageListener("Test:MouseMoveRegistered", processed);
resolve();
});
});
let eventReceivedPromise = ContentTask.spawn(
browser,
[aOffsetX, aOffsetY],
([clientX, clientY]) => {
return new Promise(resolve => {
addEventListener("mousemove", function onMouseMoveEvent(e) {
if (e.clientX == clientX && e.clientY == clientY) {
removeEventListener("mousemove", onMouseMoveEvent);
resolve();
}
});
sendAsyncMessage("Test:MouseMoveRegistered");
});
}
);
eventRegisteredPromise.then(() => {
synthesizeNativeMouseEvent({
type: "mousemove",
target: aTarget,
offsetX: aOffsetX,
offsetY: aOffsetY,
win: aWindow,
});
});
return eventReceivedPromise;
}
/**
* Synthesize a key event. It is targeted at whatever would be targeted by an
* actual keypress by the user, typically the focused element.
*
* @param {string} aKey
* Should be either:
*
* - key value (recommended). If you specify a non-printable key name,
* prepend the ``KEY_`` prefix. Otherwise, specifying a printable key, the
* key value should be specified.
*
* - keyCode name starting with ``VK_`` (e.g., ``VK_RETURN``). This is available
* only for compatibility with legacy API. Don't use this with new tests.
*
* @param {object} [aEvent]
* Optional event object with more specifics about the key event to
* synthesize.
* @param {string} [aEvent.code]
* If you don't specify this explicitly, it'll be guessed from aKey
* of US keyboard layout. Note that this value may be different
* between browsers. For example, "Insert" is never set only on
* macOS since actual key operation won't cause this code value.
* In such case, the value becomes empty string.
* If you need to emulate non-US keyboard layout or virtual keyboard
* which doesn't emulate hardware key input, you should set this value
* to empty string explicitly.
* @param {number} [aEvent.repeat]
* If you emulate auto-repeat, you should set the count of repeat.
* This method will automatically synthesize keydown (and keypress).
* @param {*} aEvent.location
* If you want to specify this, you can specify this explicitly.
* However, if you don't specify this value, it will be computed
* from code value.
* @param {string} aEvent.type
* Basically, you shouldn't specify this. Then, this function will
* synthesize keydown (, keypress) and keyup.
* If keydown is specified, this only fires keydown (and keypress if
* it should be fired).
* If keyup is specified, this only fires keyup.
* @param {number} aEvent.keyCode
* Must be 0 - 255 (0xFF). If this is specified explicitly,
* .keyCode value is initialized with this value.
* @param {DOMWindow} [aWindow=window]
* DOM window used to dispatch the event.
* @param {Function} aCallback
* Is optional and can be used to receive notifications from TIP.
*
* @description
* ``accelKey``, ``altKey``, ``altGraphKey``, ``ctrlKey``, ``capsLockKey``,
* ``fnKey``, ``fnLockKey``, ``numLockKey``, ``metaKey``, ``scrollLockKey``,
* ``shiftKey``, ``symbolKey``, ``symbolLockKey``
* Basically, you shouldn't use these attributes. nsITextInputProcessor
* manages modifier key state when you synthesize modifier key events.
* However, if some of these attributes are true, this function activates
* the modifiers only during dispatching the key events.
* Note that if some of these values are false, they are ignored (i.e.,
* not inactivated with this function).
*/
function synthesizeKey(aKey, aEvent = undefined, aWindow = window, aCallback) {
const event = aEvent === undefined || aEvent === null ? {} : aEvent;
let dispatchKeydown =
!("type" in event) || event.type === "keydown" || !event.type;
const dispatchKeyup =
!("type" in event) || event.type === "keyup" || !event.type;
if (dispatchKeydown && aKey == "KEY_Escape") {
let eventForKeydown = Object.assign({}, JSON.parse(JSON.stringify(event)));
eventForKeydown.type = "keydown";
if (
_maybeEndDragSession(
// TODO: We should set the last dragover point instead
0,
0,
eventForKeydown,
aWindow
)
) {
if (!dispatchKeyup) {
return;
}
// We don't need to dispatch only keydown event because it's consumed by
// the drag session.
dispatchKeydown = false;
}
}
var TIP = _getTIP(aWindow, aCallback);
if (!TIP) {
return;
}
var KeyboardEvent = _getKeyboardEvent(aWindow);
var modifiers = _emulateToActivateModifiers(TIP, event, aWindow);
var keyEventDict = _createKeyboardEventDictionary(aKey, event, TIP, aWindow);
var keyEvent = new KeyboardEvent("", keyEventDict.dictionary);
try {
if (dispatchKeydown) {
TIP.keydown(keyEvent, keyEventDict.flags);
if ("repeat" in event && event.repeat > 1) {
keyEventDict.dictionary.repeat = true;
var repeatedKeyEvent = new KeyboardEvent("", keyEventDict.dictionary);
for (var i = 1; i < event.repeat; i++) {
TIP.keydown(repeatedKeyEvent, keyEventDict.flags);
}
}
}
if (dispatchKeyup) {
TIP.keyup(keyEvent, keyEventDict.flags);
}
} finally {
_emulateToInactivateModifiers(TIP, modifiers, aWindow);
}
}
/**
* This is a wrapper around synthesizeKey that waits for the key event to be
* dispatched to the target content. It returns a promise which is resolved
* when the content receives the key event.
*
* This API is supposed to be used in those test cases that synthesize some
* input events to chrome process and have some checks in content.
*/
function synthesizeAndWaitKey(
aKey,
aEvent,
aWindow = window,
checkBeforeSynthesize,
checkAfterSynthesize
) {
let browser = gBrowser.selectedTab.linkedBrowser;
let mm = browser.messageManager;
let keyCode = _createKeyboardEventDictionary(aKey, aEvent, null, aWindow)
.dictionary.keyCode;
let { ContentTask } = _EU_ChromeUtils.importESModule(
"resource://testing-common/ContentTask.sys.mjs"
);
let keyRegisteredPromise = new Promise(resolve => {
mm.addMessageListener("Test:KeyRegistered", function processed() {
mm.removeMessageListener("Test:KeyRegistered", processed);
resolve();
});
});
// eslint-disable-next-line no-shadow
let keyReceivedPromise = ContentTask.spawn(browser, keyCode, keyCode => {
return new Promise(resolve => {
addEventListener("keyup", function onKeyEvent(e) {
if (e.keyCode == keyCode) {
removeEventListener("keyup", onKeyEvent);
resolve();
}
});
sendAsyncMessage("Test:KeyRegistered");
});
});
keyRegisteredPromise.then(() => {
if (checkBeforeSynthesize) {
checkBeforeSynthesize();
}
synthesizeKey(aKey, aEvent, aWindow);
if (checkAfterSynthesize) {
checkAfterSynthesize();
}
});
return keyReceivedPromise;
}
function _parseNativeModifiers(aModifiers, aWindow = window) {
let modifiers = 0;
if (aModifiers.capsLockKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CAPS_LOCK;
}
if (aModifiers.numLockKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_NUM_LOCK;
}
if (aModifiers.shiftKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_SHIFT_LEFT;
}
if (aModifiers.shiftRightKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_SHIFT_RIGHT;
}
if (aModifiers.ctrlKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CONTROL_LEFT;
}
if (aModifiers.ctrlRightKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CONTROL_RIGHT;
}
if (aModifiers.altKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_ALT_LEFT;
}
if (aModifiers.altRightKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_ALT_RIGHT;
}
if (aModifiers.metaKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_COMMAND_LEFT;
}
if (aModifiers.metaRightKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_COMMAND_RIGHT;
}
if (aModifiers.helpKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_HELP;
}
if (aModifiers.fnKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_FUNCTION;
}
if (aModifiers.numericKeyPadKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_NUMERIC_KEY_PAD;
}
if (aModifiers.accelKey) {
modifiers |= _EU_isMac(aWindow)
? SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_COMMAND_LEFT
: SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CONTROL_LEFT;
}
if (aModifiers.accelRightKey) {
modifiers |= _EU_isMac(aWindow)
? SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_COMMAND_RIGHT
: SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CONTROL_RIGHT;
}
if (aModifiers.altGrKey) {
modifiers |= _EU_isMac(aWindow)
? SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_ALT_LEFT
: SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_ALT_GRAPH;
}
return modifiers;
}
// Mac: Any unused number is okay for adding new keyboard layout.
// When you add new keyboard layout here, you need to modify
// TISInputSourceWrapper::InitByLayoutID().
// Win: These constants can be found by inspecting registry keys under
// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Keyboard Layouts
const KEYBOARD_LAYOUT_ARABIC = {
name: "Arabic",
Mac: 6,
Win: 0x00000401,
hasAltGrOnWin: false,
};
_defineConstant("KEYBOARD_LAYOUT_ARABIC", KEYBOARD_LAYOUT_ARABIC);
const KEYBOARD_LAYOUT_ARABIC_PC = {
name: "Arabic - PC",
Mac: 7,
Win: null,
hasAltGrOnWin: false,
};
_defineConstant("KEYBOARD_LAYOUT_ARABIC_PC", KEYBOARD_LAYOUT_ARABIC_PC);
const KEYBOARD_LAYOUT_BRAZILIAN_ABNT = {
name: "Brazilian ABNT",
Mac: null,
Win: 0x00000416,
hasAltGrOnWin: true,
};
_defineConstant(
"KEYBOARD_LAYOUT_BRAZILIAN_ABNT",
KEYBOARD_LAYOUT_BRAZILIAN_ABNT
);
const KEYBOARD_LAYOUT_DVORAK_QWERTY = {
name: "Dvorak-QWERTY",
Mac: 4,
Win: null,
hasAltGrOnWin: false,
};
_defineConstant("KEYBOARD_LAYOUT_DVORAK_QWERTY", KEYBOARD_LAYOUT_DVORAK_QWERTY);
const KEYBOARD_LAYOUT_EN_US = {
name: "US",
Mac: 0,
Win: 0x00000409,
hasAltGrOnWin: false,
};
_defineConstant("KEYBOARD_LAYOUT_EN_US", KEYBOARD_LAYOUT_EN_US);
const KEYBOARD_LAYOUT_FRENCH = {
name: "French",
Mac: 8, // Some keys mapped different from PC, e.g., Digit6, Digit8, Equal, Slash and Backslash
Win: 0x0000040c,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_FRENCH", KEYBOARD_LAYOUT_FRENCH);
const KEYBOARD_LAYOUT_FRENCH_PC = {
name: "French-PC",
Mac: 13, // Compatible with Windows
Win: 0x0000040c,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_FRENCH_PC", KEYBOARD_LAYOUT_FRENCH_PC);
const KEYBOARD_LAYOUT_GREEK = {
name: "Greek",
Mac: 1,
Win: 0x00000408,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_GREEK", KEYBOARD_LAYOUT_GREEK);
const KEYBOARD_LAYOUT_GERMAN = {
name: "German",
Mac: 2,
Win: 0x00000407,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_GERMAN", KEYBOARD_LAYOUT_GERMAN);
const KEYBOARD_LAYOUT_HEBREW = {
name: "Hebrew",
Mac: 9,
Win: 0x0000040d,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_HEBREW", KEYBOARD_LAYOUT_HEBREW);
const KEYBOARD_LAYOUT_JAPANESE = {
name: "Japanese",
Mac: null,
Win: 0x00000411,
hasAltGrOnWin: false,
};
_defineConstant("KEYBOARD_LAYOUT_JAPANESE", KEYBOARD_LAYOUT_JAPANESE);
const KEYBOARD_LAYOUT_KHMER = {
name: "Khmer",
Mac: null,
Win: 0x00000453,
hasAltGrOnWin: true,
}; // available on Win7 or later.
_defineConstant("KEYBOARD_LAYOUT_KHMER", KEYBOARD_LAYOUT_KHMER);
const KEYBOARD_LAYOUT_LITHUANIAN = {
name: "Lithuanian",
Mac: 10,
Win: 0x00010427,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_LITHUANIAN", KEYBOARD_LAYOUT_LITHUANIAN);
const KEYBOARD_LAYOUT_NORWEGIAN = {
name: "Norwegian",
Mac: 11,
Win: 0x00000414,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_NORWEGIAN", KEYBOARD_LAYOUT_NORWEGIAN);
const KEYBOARD_LAYOUT_RUSSIAN = {
name: "Russian",
Mac: null,
Win: 0x00000419,
hasAltGrOnWin: true, // No AltGr, but Ctrl + Alt + Digit8 introduces a char
};
_defineConstant("KEYBOARD_LAYOUT_RUSSIAN", KEYBOARD_LAYOUT_RUSSIAN);
const KEYBOARD_LAYOUT_RUSSIAN_MNEMONIC = {
name: "Russian - Mnemonic",
Mac: null,
Win: 0x00020419,
hasAltGrOnWin: true,
}; // available on Win8 or later.
_defineConstant(
"KEYBOARD_LAYOUT_RUSSIAN_MNEMONIC",
KEYBOARD_LAYOUT_RUSSIAN_MNEMONIC
);
const KEYBOARD_LAYOUT_SPANISH = {
name: "Spanish",
Mac: 12,
Win: 0x0000040a,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_SPANISH", KEYBOARD_LAYOUT_SPANISH);
const KEYBOARD_LAYOUT_SWEDISH = {
name: "Swedish",
Mac: 3,
Win: 0x0000041d,
hasAltGrOnWin: true,
};
_defineConstant("KEYBOARD_LAYOUT_SWEDISH", KEYBOARD_LAYOUT_SWEDISH);
const KEYBOARD_LAYOUT_THAI = {
name: "Thai",
Mac: 5,
Win: 0x0002041e,
hasAltGrOnWin: false,
};
_defineConstant("KEYBOARD_LAYOUT_THAI", KEYBOARD_LAYOUT_THAI);
/**
* synthesizeNativeKey() dispatches native key event on active window.
* This is implemented only on Windows and Mac. Note that this function
* dispatches the key event asynchronously and returns immediately. If a
* callback function is provided, the callback will be called upon
* completion of the key dispatch.
*
* @param aKeyboardLayout One of KEYBOARD_LAYOUT_* defined above.
* @param aNativeKeyCode A native keycode value defined in
* NativeKeyCodes.js.
* @param aModifiers Modifier keys. If no modifire key is pressed,
* this must be {}. Otherwise, one or more items
* referred in _parseNativeModifiers() must be
* true.
* @param aChars Specify characters which should be generated
* by the key event.
* @param aUnmodifiedChars Specify characters of unmodified (except Shift)
* aChar value.
* @param aCallback If provided, this callback will be invoked
* once the native keys have been processed
* by Gecko. Will never be called if this
* function returns false.
* @return True if this function succeed dispatching
* native key event. Otherwise, false.
*/
function synthesizeNativeKey(
aKeyboardLayout,
aNativeKeyCode,
aModifiers,
aChars,
aUnmodifiedChars,
aCallback,
aWindow = window
) {
var utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return false;
}
var nativeKeyboardLayout = null;
if (_EU_isMac(aWindow)) {
nativeKeyboardLayout = aKeyboardLayout.Mac;
} else if (_EU_isWin(aWindow)) {
nativeKeyboardLayout = aKeyboardLayout.Win;
}
if (nativeKeyboardLayout === null) {
return false;
}
utils.sendNativeKeyEvent(
nativeKeyboardLayout,
aNativeKeyCode,
_parseNativeModifiers(aModifiers, aWindow),
aChars,
aUnmodifiedChars,
aCallback
);
return true;
}
var _gSeenEvent = false;
/**
* Indicate that an event with an original target of aExpectedTarget and
* a type of aExpectedEvent is expected to be fired, or not expected to
* be fired.
*/
function _expectEvent(aExpectedTarget, aExpectedEvent, aTestName) {
if (!aExpectedTarget || !aExpectedEvent) {
return null;
}
_gSeenEvent = false;
var type =
aExpectedEvent.charAt(0) == "!"
? aExpectedEvent.substring(1)
: aExpectedEvent;
var eventHandler = function (event) {
var epassed =
!_gSeenEvent &&
event.originalTarget == aExpectedTarget &&
event.type == type;
is(
epassed,
true,
aTestName + " " + type + " event target " + (_gSeenEvent ? "twice" : "")
);
_gSeenEvent = true;
};
aExpectedTarget.addEventListener(type, eventHandler);
return eventHandler;
}
/**
* Check if the event was fired or not. The event handler aEventHandler
* will be removed.
*/
function _checkExpectedEvent(
aExpectedTarget,
aExpectedEvent,
aEventHandler,
aTestName
) {
if (aEventHandler) {
var expectEvent = aExpectedEvent.charAt(0) != "!";
var type = expectEvent ? aExpectedEvent : aExpectedEvent.substring(1);
aExpectedTarget.removeEventListener(type, aEventHandler);
var desc = type + " event";
if (!expectEvent) {
desc += " not";
}
is(_gSeenEvent, expectEvent, aTestName + " " + desc + " fired");
}
_gSeenEvent = false;
}
/**
* Similar to synthesizeMouse except that a test is performed to see if an
* event is fired at the right target as a result.
*
* aExpectedTarget - the expected originalTarget of the event.
* aExpectedEvent - the expected type of the event, such as 'select'.
* aTestName - the test name when outputing results
*
* To test that an event is not fired, use an expected type preceded by an
* exclamation mark, such as '!select'. This might be used to test that a
* click on a disabled element doesn't fire certain events for instance.
*
* aWindow is optional, and defaults to the current window object.
*/
function synthesizeMouseExpectEvent(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aExpectedTarget,
aExpectedEvent,
aTestName,
aWindow
) {
var eventHandler = _expectEvent(aExpectedTarget, aExpectedEvent, aTestName);
synthesizeMouse(aTarget, aOffsetX, aOffsetY, aEvent, aWindow);
_checkExpectedEvent(aExpectedTarget, aExpectedEvent, eventHandler, aTestName);
}
/**
* Similar to synthesizeKey except that a test is performed to see if an
* event is fired at the right target as a result.
*
* aExpectedTarget - the expected originalTarget of the event.
* aExpectedEvent - the expected type of the event, such as 'select'.
* aTestName - the test name when outputing results
*
* To test that an event is not fired, use an expected type preceded by an
* exclamation mark, such as '!select'.
*
* aWindow is optional, and defaults to the current window object.
*/
function synthesizeKeyExpectEvent(
key,
aEvent,
aExpectedTarget,
aExpectedEvent,
aTestName,
aWindow
) {
var eventHandler = _expectEvent(aExpectedTarget, aExpectedEvent, aTestName);
synthesizeKey(key, aEvent, aWindow);
_checkExpectedEvent(aExpectedTarget, aExpectedEvent, eventHandler, aTestName);
}
function disableNonTestMouseEvents(aDisable) {
var domutils = _getDOMWindowUtils();
domutils.disableNonTestMouseEvents(aDisable);
}
function _getDOMWindowUtils(aWindow = window) {
// Leave this here as something, somewhere, passes a falsy argument
// to this, causing the |window| default argument not to get picked up.
if (!aWindow) {
aWindow = window;
}
// If documentURIObject exists or `window` is a stub object, we're in
// a chrome scope, so don't bother trying to go through SpecialPowers.
if (!aWindow.document || aWindow.document.documentURIObject) {
return aWindow.windowUtils;
}
// we need parent.SpecialPowers for:
// layout/base/tests/test_reftests_with_caret.html
// chrome: toolkit/content/tests/chrome/test_findbar.xul
// chrome: toolkit/content/tests/chrome/test_popup_anchor.xul
if ("SpecialPowers" in aWindow && aWindow.SpecialPowers != undefined) {
return aWindow.SpecialPowers.getDOMWindowUtils(aWindow);
}
if (
"SpecialPowers" in aWindow.parent &&
aWindow.parent.SpecialPowers != undefined
) {
return aWindow.parent.SpecialPowers.getDOMWindowUtils(aWindow);
}
// TODO: this is assuming we are in chrome space
return aWindow.windowUtils;
}
/**
* @param {DOMWindow} [aWindow] - DOM window
* @returns The scaling value applied to the top window.
*/
function _getTopWindowResolution(aWindow) {
let resolution = 1.0;
try {
resolution = _getDOMWindowUtils(aWindow.top).getResolution();
} catch (e) {
// XXX How to get mobile viewport scale on Fission+xorigin since
// window.top access isn't allowed due to cross-origin?
}
return resolution;
}
/**
* @param {DOMWindow} [aWindow] - The DOM window which you want
* to get its x-offset in the screen.
* @returns The screenX of aWindow in the unscaled CSS pixels.
*/
function _getScreenXInUnscaledCSSPixels(aWindow) {
// XXX mozInnerScreen might be invalid value on mobile viewport (Bug 1701546),
// so use window.top's mozInnerScreen. But this won't work fission+xorigin
// with mobile viewport until mozInnerScreen returns valid value with
// scale.
let winInnerOffsetX = aWindow.mozInnerScreenX;
try {
winInnerOffsetX =
aWindow.top.mozInnerScreenX +
(aWindow.mozInnerScreenX - aWindow.top.mozInnerScreenX) *
_getTopWindowResolution(aWindow);
} catch (e) {
// XXX fission+xorigin test throws permission denied since win.top is
// cross-origin.
}
return winInnerOffsetX;
}
/**
* @param {DOMWindow} [aWindow] - The DOM window which you want
* to get its y-offset in the screen.
* @returns The screenY of aWindow in the unscaled CSS pixels.
*/
function _getScreenYInUnscaledCSSPixels(aWindow) {
// XXX mozInnerScreen might be invalid value on mobile viewport (Bug 1701546),
// so use window.top's mozInnerScreen. But this won't work fission+xorigin
// with mobile viewport until mozInnerScreen returns valid value with
// scale.
let winInnerOffsetY = aWindow.mozInnerScreenY;
try {
winInnerOffsetY =
aWindow.top.mozInnerScreenY +
(aWindow.mozInnerScreenY - aWindow.top.mozInnerScreenY) *
_getTopWindowResolution(aWindow);
} catch (e) {
// XXX fission+xorigin test throws permission denied since win.top is
// cross-origin.
}
return winInnerOffsetY;
}
function _defineConstant(name, value) {
Object.defineProperty(this, name, {
value,
enumerable: true,
writable: false,
});
}
const COMPOSITION_ATTR_RAW_CLAUSE =
_EU_Ci.nsITextInputProcessor.ATTR_RAW_CLAUSE;
_defineConstant("COMPOSITION_ATTR_RAW_CLAUSE", COMPOSITION_ATTR_RAW_CLAUSE);
const COMPOSITION_ATTR_SELECTED_RAW_CLAUSE =
_EU_Ci.nsITextInputProcessor.ATTR_SELECTED_RAW_CLAUSE;
_defineConstant(
"COMPOSITION_ATTR_SELECTED_RAW_CLAUSE",
COMPOSITION_ATTR_SELECTED_RAW_CLAUSE
);
const COMPOSITION_ATTR_CONVERTED_CLAUSE =
_EU_Ci.nsITextInputProcessor.ATTR_CONVERTED_CLAUSE;
_defineConstant(
"COMPOSITION_ATTR_CONVERTED_CLAUSE",
COMPOSITION_ATTR_CONVERTED_CLAUSE
);
const COMPOSITION_ATTR_SELECTED_CLAUSE =
_EU_Ci.nsITextInputProcessor.ATTR_SELECTED_CLAUSE;
_defineConstant(
"COMPOSITION_ATTR_SELECTED_CLAUSE",
COMPOSITION_ATTR_SELECTED_CLAUSE
);
var TIPMap = new WeakMap();
function _getTIP(aWindow, aCallback) {
if (!aWindow) {
aWindow = window;
}
var tip;
if (TIPMap.has(aWindow)) {
tip = TIPMap.get(aWindow);
} else {
tip = _EU_Cc["@mozilla.org/text-input-processor;1"].createInstance(
_EU_Ci.nsITextInputProcessor
);
TIPMap.set(aWindow, tip);
}
if (!tip.beginInputTransactionForTests(aWindow, aCallback)) {
tip = null;
TIPMap.delete(aWindow);
}
return tip;
}
function _getKeyboardEvent(aWindow = window) {
if (typeof KeyboardEvent != "undefined") {
try {
// See if the object can be instantiated; sometimes this yields
// 'TypeError: can't access dead object' or 'KeyboardEvent is not a constructor'.
new KeyboardEvent("", {});
return KeyboardEvent;
} catch (ex) {}
}
if (typeof content != "undefined" && "KeyboardEvent" in content) {
return content.KeyboardEvent;
}
return aWindow.KeyboardEvent;
}
// eslint-disable-next-line complexity
function _guessKeyNameFromKeyCode(aKeyCode, aWindow = window) {
var KeyboardEvent = _getKeyboardEvent(aWindow);
switch (aKeyCode) {
case KeyboardEvent.DOM_VK_CANCEL:
return "Cancel";
case KeyboardEvent.DOM_VK_HELP:
return "Help";
case KeyboardEvent.DOM_VK_BACK_SPACE:
return "Backspace";
case KeyboardEvent.DOM_VK_TAB:
return "Tab";
case KeyboardEvent.DOM_VK_CLEAR:
return "Clear";
case KeyboardEvent.DOM_VK_RETURN:
return "Enter";
case KeyboardEvent.DOM_VK_SHIFT:
return "Shift";
case KeyboardEvent.DOM_VK_CONTROL:
return "Control";
case KeyboardEvent.DOM_VK_ALT:
return "Alt";
case KeyboardEvent.DOM_VK_PAUSE:
return "Pause";
case KeyboardEvent.DOM_VK_EISU:
return "Eisu";
case KeyboardEvent.DOM_VK_ESCAPE:
return "Escape";
case KeyboardEvent.DOM_VK_CONVERT:
return "Convert";
case KeyboardEvent.DOM_VK_NONCONVERT:
return "NonConvert";
case KeyboardEvent.DOM_VK_ACCEPT:
return "Accept";
case KeyboardEvent.DOM_VK_MODECHANGE:
return "ModeChange";
case KeyboardEvent.DOM_VK_PAGE_UP:
return "PageUp";
case KeyboardEvent.DOM_VK_PAGE_DOWN:
return "PageDown";
case KeyboardEvent.DOM_VK_END:
return "End";
case KeyboardEvent.DOM_VK_HOME:
return "Home";
case KeyboardEvent.DOM_VK_LEFT:
return "ArrowLeft";
case KeyboardEvent.DOM_VK_UP:
return "ArrowUp";
case KeyboardEvent.DOM_VK_RIGHT:
return "ArrowRight";
case KeyboardEvent.DOM_VK_DOWN:
return "ArrowDown";
case KeyboardEvent.DOM_VK_SELECT:
return "Select";
case KeyboardEvent.DOM_VK_PRINT:
return "Print";
case KeyboardEvent.DOM_VK_EXECUTE:
return "Execute";
case KeyboardEvent.DOM_VK_PRINTSCREEN:
return "PrintScreen";
case KeyboardEvent.DOM_VK_INSERT:
return "Insert";
case KeyboardEvent.DOM_VK_DELETE:
return "Delete";
case KeyboardEvent.DOM_VK_WIN:
return "OS";
case KeyboardEvent.DOM_VK_CONTEXT_MENU:
return "ContextMenu";
case KeyboardEvent.DOM_VK_SLEEP:
return "Standby";
case KeyboardEvent.DOM_VK_F1:
return "F1";
case KeyboardEvent.DOM_VK_F2:
return "F2";
case KeyboardEvent.DOM_VK_F3:
return "F3";
case KeyboardEvent.DOM_VK_F4:
return "F4";
case KeyboardEvent.DOM_VK_F5:
return "F5";
case KeyboardEvent.DOM_VK_F6:
return "F6";
case KeyboardEvent.DOM_VK_F7:
return "F7";
case KeyboardEvent.DOM_VK_F8:
return "F8";
case KeyboardEvent.DOM_VK_F9:
return "F9";
case KeyboardEvent.DOM_VK_F10:
return "F10";
case KeyboardEvent.DOM_VK_F11:
return "F11";
case KeyboardEvent.DOM_VK_F12:
return "F12";
case KeyboardEvent.DOM_VK_F13:
return "F13";
case KeyboardEvent.DOM_VK_F14:
return "F14";
case KeyboardEvent.DOM_VK_F15:
return "F15";
case KeyboardEvent.DOM_VK_F16:
return "F16";
case KeyboardEvent.DOM_VK_F17:
return "F17";
case KeyboardEvent.DOM_VK_F18:
return "F18";
case KeyboardEvent.DOM_VK_F19:
return "F19";
case KeyboardEvent.DOM_VK_F20:
return "F20";
case KeyboardEvent.DOM_VK_F21:
return "F21";
case KeyboardEvent.DOM_VK_F22:
return "F22";
case KeyboardEvent.DOM_VK_F23:
return "F23";
case KeyboardEvent.DOM_VK_F24:
return "F24";
case KeyboardEvent.DOM_VK_NUM_LOCK:
return "NumLock";
case KeyboardEvent.DOM_VK_SCROLL_LOCK:
return "ScrollLock";
case KeyboardEvent.DOM_VK_VOLUME_MUTE:
return "AudioVolumeMute";
case KeyboardEvent.DOM_VK_VOLUME_DOWN:
return "AudioVolumeDown";
case KeyboardEvent.DOM_VK_VOLUME_UP:
return "AudioVolumeUp";
case KeyboardEvent.DOM_VK_META:
return "Meta";
case KeyboardEvent.DOM_VK_ALTGR:
return "AltGraph";
case KeyboardEvent.DOM_VK_PROCESSKEY:
return "Process";
case KeyboardEvent.DOM_VK_ATTN:
return "Attn";
case KeyboardEvent.DOM_VK_CRSEL:
return "CrSel";
case KeyboardEvent.DOM_VK_EXSEL:
return "ExSel";
case KeyboardEvent.DOM_VK_EREOF:
return "EraseEof";
case KeyboardEvent.DOM_VK_PLAY:
return "Play";
default:
return "Unidentified";
}
}
function _createKeyboardEventDictionary(
aKey,
aKeyEvent,
aTIP = null,
aWindow = window
) {
var result = { dictionary: null, flags: 0 };
var keyCodeIsDefined = "keyCode" in aKeyEvent;
var keyCode =
keyCodeIsDefined && aKeyEvent.keyCode >= 0 && aKeyEvent.keyCode <= 255
? aKeyEvent.keyCode
: 0;
var keyName = "Unidentified";
var code = aKeyEvent.code;
if (!aTIP) {
aTIP = _getTIP(aWindow);
}
if (aKey.indexOf("KEY_") == 0) {
keyName = aKey.substr("KEY_".length);
result.flags |= _EU_Ci.nsITextInputProcessor.KEY_NON_PRINTABLE_KEY;
if (code === undefined) {
code = aTIP.computeCodeValueOfNonPrintableKey(
keyName,
aKeyEvent.location
);
}
} else if (aKey.indexOf("VK_") == 0) {
keyCode = _getKeyboardEvent(aWindow)["DOM_" + aKey];
if (!keyCode) {
throw new Error("Unknown key: " + aKey);
}
keyName = _guessKeyNameFromKeyCode(keyCode, aWindow);
result.flags |= _EU_Ci.nsITextInputProcessor.KEY_NON_PRINTABLE_KEY;
if (code === undefined) {
code = aTIP.computeCodeValueOfNonPrintableKey(
keyName,
aKeyEvent.location
);
}
} else if (aKey != "") {
keyName = aKey;
if (!keyCodeIsDefined) {
keyCode = aTIP.guessKeyCodeValueOfPrintableKeyInUSEnglishKeyboardLayout(
aKey,
aKeyEvent.location
);
}
if (!keyCode) {
result.flags |= _EU_Ci.nsITextInputProcessor.KEY_KEEP_KEYCODE_ZERO;
}
result.flags |= _EU_Ci.nsITextInputProcessor.KEY_FORCE_PRINTABLE_KEY;
if (code === undefined) {
code = aTIP.guessCodeValueOfPrintableKeyInUSEnglishKeyboardLayout(
keyName,
aKeyEvent.location
);
}
}
var locationIsDefined = "location" in aKeyEvent;
if (locationIsDefined && aKeyEvent.location === 0) {
result.flags |= _EU_Ci.nsITextInputProcessor.KEY_KEEP_KEY_LOCATION_STANDARD;
}
if (aKeyEvent.doNotMarkKeydownAsProcessed) {
result.flags |=
_EU_Ci.nsITextInputProcessor.KEY_DONT_MARK_KEYDOWN_AS_PROCESSED;
}
if (aKeyEvent.markKeyupAsProcessed) {
result.flags |= _EU_Ci.nsITextInputProcessor.KEY_MARK_KEYUP_AS_PROCESSED;
}
result.dictionary = {
key: keyName,
code,
location: locationIsDefined ? aKeyEvent.location : 0,
repeat: "repeat" in aKeyEvent ? aKeyEvent.repeat === true : false,
keyCode,
};
return result;
}
function _emulateToActivateModifiers(aTIP, aKeyEvent, aWindow = window) {
if (!aKeyEvent) {
return null;
}
var KeyboardEvent = _getKeyboardEvent(aWindow);
var modifiers = {
normal: [
{ key: "Alt", attr: "altKey" },
{ key: "AltGraph", attr: "altGraphKey" },
{ key: "Control", attr: "ctrlKey" },
{ key: "Fn", attr: "fnKey" },
{ key: "Meta", attr: "metaKey" },
{ key: "Shift", attr: "shiftKey" },
{ key: "Symbol", attr: "symbolKey" },
{ key: _EU_isMac(aWindow) ? "Meta" : "Control", attr: "accelKey" },
],
lockable: [
{ key: "CapsLock", attr: "capsLockKey" },
{ key: "FnLock", attr: "fnLockKey" },
{ key: "NumLock", attr: "numLockKey" },
{ key: "ScrollLock", attr: "scrollLockKey" },
{ key: "SymbolLock", attr: "symbolLockKey" },
],
};
for (let i = 0; i < modifiers.normal.length; i++) {
if (!aKeyEvent[modifiers.normal[i].attr]) {
continue;
}
if (aTIP.getModifierState(modifiers.normal[i].key)) {
continue; // already activated.
}
let event = new KeyboardEvent("", { key: modifiers.normal[i].key });
aTIP.keydown(
event,
aTIP.KEY_NON_PRINTABLE_KEY | aTIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT
);
modifiers.normal[i].activated = true;
}
for (let i = 0; i < modifiers.lockable.length; i++) {
if (!aKeyEvent[modifiers.lockable[i].attr]) {
continue;
}
if (aTIP.getModifierState(modifiers.lockable[i].key)) {
continue; // already activated.
}
let event = new KeyboardEvent("", { key: modifiers.lockable[i].key });
aTIP.keydown(
event,
aTIP.KEY_NON_PRINTABLE_KEY | aTIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT
);
aTIP.keyup(
event,
aTIP.KEY_NON_PRINTABLE_KEY | aTIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT
);
modifiers.lockable[i].activated = true;
}
return modifiers;
}
function _emulateToInactivateModifiers(aTIP, aModifiers, aWindow = window) {
if (!aModifiers) {
return;
}
var KeyboardEvent = _getKeyboardEvent(aWindow);
for (let i = 0; i < aModifiers.normal.length; i++) {
if (!aModifiers.normal[i].activated) {
continue;
}
let event = new KeyboardEvent("", { key: aModifiers.normal[i].key });
aTIP.keyup(
event,
aTIP.KEY_NON_PRINTABLE_KEY | aTIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT
);
}
for (let i = 0; i < aModifiers.lockable.length; i++) {
if (!aModifiers.lockable[i].activated) {
continue;
}
if (!aTIP.getModifierState(aModifiers.lockable[i].key)) {
continue; // who already inactivated this?
}
let event = new KeyboardEvent("", { key: aModifiers.lockable[i].key });
aTIP.keydown(
event,
aTIP.KEY_NON_PRINTABLE_KEY | aTIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT
);
aTIP.keyup(
event,
aTIP.KEY_NON_PRINTABLE_KEY | aTIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT
);
}
}
/**
* Synthesize a composition event and keydown event and keyup events unless
* you prevent to dispatch them explicitly (see aEvent.key's explanation).
*
* Note that you shouldn't call this with "compositionstart" unless you need to
* test compositionstart event which is NOT followed by compositionupdate
* event immediately. Typically, native IME starts composition with
* a pair of keydown and keyup event and dispatch compositionstart and
* compositionupdate (and non-standard text event) between them. So, in most
* cases, you should call synthesizeCompositionChange() directly.
* If you call this with compositionstart, keyup event will be fired
* immediately after compositionstart. In other words, you should use
* "compositionstart" only when you need to emulate IME which just starts
* composition with compositionstart event but does not send composing text to
* us until committing the composition. This is behavior of some Chinese IMEs.
*
* @param aEvent The composition event information. This must
* have |type| member. The value must be
* "compositionstart", "compositionend",
* "compositioncommitasis" or "compositioncommit".
*
* And also this may have |data| and |locale| which
* would be used for the value of each property of
* the composition event. Note that the |data| is
* ignored if the event type is "compositionstart"
* or "compositioncommitasis".
*
* If |key| is undefined, "keydown" and "keyup"
* events which are marked as "processed by IME"
* are dispatched. If |key| is not null, "keydown"
* and/or "keyup" events are dispatched (if the
* |key.type| is specified as "keydown", only
* "keydown" event is dispatched). Otherwise,
* i.e., if |key| is null, neither "keydown" nor
* "keyup" event is dispatched.
*
* If |key.doNotMarkKeydownAsProcessed| is not true,
* key value and keyCode value of "keydown" event
* will be set to "Process" and DOM_VK_PROCESSKEY.
* If |key.markKeyupAsProcessed| is true,
* key value and keyCode value of "keyup" event
* will be set to "Process" and DOM_VK_PROCESSKEY.
* @param aWindow Optional (If null, current |window| will be used)
* @param aCallback Optional (If non-null, use the callback for
* receiving notifications to IME)
*/
function synthesizeComposition(aEvent, aWindow = window, aCallback) {
var TIP = _getTIP(aWindow, aCallback);
if (!TIP) {
return;
}
var KeyboardEvent = _getKeyboardEvent(aWindow);
var modifiers = _emulateToActivateModifiers(TIP, aEvent.key, aWindow);
var keyEventDict = { dictionary: null, flags: 0 };
var keyEvent = null;
if (aEvent.key && typeof aEvent.key.key === "string") {
keyEventDict = _createKeyboardEventDictionary(
aEvent.key.key,
aEvent.key,
TIP,
aWindow
);
keyEvent = new KeyboardEvent(
// eslint-disable-next-line no-nested-ternary
aEvent.key.type === "keydown"
? "keydown"
: aEvent.key.type === "keyup"
? "keyup"
: "",
keyEventDict.dictionary
);
} else if (aEvent.key === undefined) {
keyEventDict = _createKeyboardEventDictionary(
"KEY_Process",
{},
TIP,
aWindow
);
keyEvent = new KeyboardEvent("", keyEventDict.dictionary);
}
try {
switch (aEvent.type) {
case "compositionstart":
TIP.startComposition(keyEvent, keyEventDict.flags);
break;
case "compositioncommitasis":
TIP.commitComposition(keyEvent, keyEventDict.flags);
break;
case "compositioncommit":
TIP.commitCompositionWith(aEvent.data, keyEvent, keyEventDict.flags);
break;
}
} finally {
_emulateToInactivateModifiers(TIP, modifiers, aWindow);
}
}
/**
* Synthesize eCompositionChange event which causes a DOM text event, may
* cause compositionupdate event, and causes keydown event and keyup event
* unless you prevent to dispatch them explicitly (see aEvent.key's
* explanation).
*
* Note that if you call this when there is no composition, compositionstart
* event will be fired automatically. This is better than you use
* synthesizeComposition("compositionstart") in most cases. See the
* explanation of synthesizeComposition().
*
* @param aEvent The compositionchange event's information, this has
* |composition| and |caret| members. |composition| has
* |string| and |clauses| members. |clauses| must be array
* object. Each object has |length| and |attr|. And |caret|
* has |start| and |length|. See the following tree image.
*
* aEvent
* +-- composition
* | +-- string
* | +-- clauses[]
* | +-- length
* | +-- attr
* +-- caret
* | +-- start
* | +-- length
* +-- key
*
* Set the composition string to |composition.string|. Set its
* clauses information to the |clauses| array.
*
* When it's composing, set the each clauses' length to the
* |composition.clauses[n].length|. The sum of the all length
* values must be same as the length of |composition.string|.
* Set nsICompositionStringSynthesizer.ATTR_* to the
* |composition.clauses[n].attr|.
*
* When it's not composing, set 0 to the
* |composition.clauses[0].length| and
* |composition.clauses[0].attr|.
*
* Set caret position to the |caret.start|. It's offset from
* the start of the composition string. Set caret length to
* |caret.length|. If it's larger than 0, it should be wide
* caret. However, current nsEditor doesn't support wide
* caret, therefore, you should always set 0 now.
*
* If |key| is undefined, "keydown" and "keyup" events which
* are marked as "processed by IME" are dispatched. If |key|
* is not null, "keydown" and/or "keyup" events are dispatched
* (if the |key.type| is specified as "keydown", only "keydown"
* event is dispatched). Otherwise, i.e., if |key| is null,
* neither "keydown" nor "keyup" event is dispatched.
* If |key.doNotMarkKeydownAsProcessed| is not true, key value
* and keyCode value of "keydown" event will be set to
* "Process" and DOM_VK_PROCESSKEY.
* If |key.markKeyupAsProcessed| is true key value and keyCode
* value of "keyup" event will be set to "Process" and
* DOM_VK_PROCESSKEY.
*
* @param aWindow Optional (If null, current |window| will be used)
* @param aCallback Optional (If non-null, use the callback for receiving
* notifications to IME)
*/
function synthesizeCompositionChange(aEvent, aWindow = window, aCallback) {
var TIP = _getTIP(aWindow, aCallback);
if (!TIP) {
return;
}
var KeyboardEvent = _getKeyboardEvent(aWindow);
if (
!aEvent.composition ||
!aEvent.composition.clauses ||
!aEvent.composition.clauses[0]
) {
return;
}
TIP.setPendingCompositionString(aEvent.composition.string);
if (aEvent.composition.clauses[0].length) {
for (var i = 0; i < aEvent.composition.clauses.length; i++) {
switch (aEvent.composition.clauses[i].attr) {
case TIP.ATTR_RAW_CLAUSE:
case TIP.ATTR_SELECTED_RAW_CLAUSE:
case TIP.ATTR_CONVERTED_CLAUSE:
case TIP.ATTR_SELECTED_CLAUSE:
TIP.appendClauseToPendingComposition(
aEvent.composition.clauses[i].length,
aEvent.composition.clauses[i].attr
);
break;
case 0:
// Ignore dummy clause for the argument.
break;
default:
throw new Error("invalid clause attribute specified");
}
}
}
if (aEvent.caret) {
TIP.setCaretInPendingComposition(aEvent.caret.start);
}
var modifiers = _emulateToActivateModifiers(TIP, aEvent.key, aWindow);
try {
var keyEventDict = { dictionary: null, flags: 0 };
var keyEvent = null;
if (aEvent.key && typeof aEvent.key.key === "string") {
keyEventDict = _createKeyboardEventDictionary(
aEvent.key.key,
aEvent.key,
TIP,
aWindow
);
keyEvent = new KeyboardEvent(
// eslint-disable-next-line no-nested-ternary
aEvent.key.type === "keydown"
? "keydown"
: aEvent.key.type === "keyup"
? "keyup"
: "",
keyEventDict.dictionary
);
} else if (aEvent.key === undefined) {
keyEventDict = _createKeyboardEventDictionary(
"KEY_Process",
{},
TIP,
aWindow
);
keyEvent = new KeyboardEvent("", keyEventDict.dictionary);
}
TIP.flushPendingComposition(keyEvent, keyEventDict.flags);
} finally {
_emulateToInactivateModifiers(TIP, modifiers, aWindow);
}
}
// Must be synchronized with nsIDOMWindowUtils.
const QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK = 0x0000;
const QUERY_CONTENT_FLAG_USE_XP_LINE_BREAK = 0x0001;
const QUERY_CONTENT_FLAG_SELECTION_NORMAL = 0x0000;
const QUERY_CONTENT_FLAG_SELECTION_SPELLCHECK = 0x0002;
const QUERY_CONTENT_FLAG_SELECTION_IME_RAWINPUT = 0x0004;
const QUERY_CONTENT_FLAG_SELECTION_IME_SELECTEDRAWTEXT = 0x0008;
const QUERY_CONTENT_FLAG_SELECTION_IME_CONVERTEDTEXT = 0x0010;
const QUERY_CONTENT_FLAG_SELECTION_IME_SELECTEDCONVERTEDTEXT = 0x0020;
const QUERY_CONTENT_FLAG_SELECTION_ACCESSIBILITY = 0x0040;
const QUERY_CONTENT_FLAG_SELECTION_FIND = 0x0080;
const QUERY_CONTENT_FLAG_SELECTION_URLSECONDARY = 0x0100;
const QUERY_CONTENT_FLAG_SELECTION_URLSTRIKEOUT = 0x0200;
const QUERY_CONTENT_FLAG_OFFSET_RELATIVE_TO_INSERTION_POINT = 0x0400;
const SELECTION_SET_FLAG_USE_NATIVE_LINE_BREAK = 0x0000;
const SELECTION_SET_FLAG_USE_XP_LINE_BREAK = 0x0001;
const SELECTION_SET_FLAG_REVERSE = 0x0002;
/**
* Synthesize a query text content event.
*
* @param aOffset The character offset. 0 means the first character in the
* selection root.
* @param aLength The length of getting text. If the length is too long,
* the extra length is ignored.
* @param aIsRelative Optional (If true, aOffset is relative to start of
* composition if there is, or start of selection.)
* @param aWindow Optional (If null, current |window| will be used)
* @return An nsIQueryContentEventResult object. If this failed,
* the result might be null.
*/
function synthesizeQueryTextContent(aOffset, aLength, aIsRelative, aWindow) {
var utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return null;
}
var flags = QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK;
if (aIsRelative === true) {
flags |= QUERY_CONTENT_FLAG_OFFSET_RELATIVE_TO_INSERTION_POINT;
}
return utils.sendQueryContentEvent(
utils.QUERY_TEXT_CONTENT,
aOffset,
aLength,
0,
0,
flags
);
}
/**
* Synthesize a query selected text event.
*
* @param aSelectionType Optional, one of QUERY_CONTENT_FLAG_SELECTION_*.
* If null, QUERY_CONTENT_FLAG_SELECTION_NORMAL will
* be used.
* @param aWindow Optional (If null, current |window| will be used)
* @return An nsIQueryContentEventResult object. If this failed,
* the result might be null.
*/
function synthesizeQuerySelectedText(aSelectionType, aWindow) {
var utils = _getDOMWindowUtils(aWindow);
var flags = QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK;
if (aSelectionType) {
flags |= aSelectionType;
}
return utils.sendQueryContentEvent(
utils.QUERY_SELECTED_TEXT,
0,
0,
0,
0,
flags
);
}
/**
* Synthesize a query caret rect event.
*
* @param aOffset The caret offset. 0 means left side of the first character
* in the selection root.
* @param aWindow Optional (If null, current |window| will be used)
* @return An nsIQueryContentEventResult object. If this failed,
* the result might be null.
*/
function synthesizeQueryCaretRect(aOffset, aWindow) {
var utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return null;
}
return utils.sendQueryContentEvent(
utils.QUERY_CARET_RECT,
aOffset,
0,
0,
0,
QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK
);
}
/**
* Synthesize a selection set event.
*
* @param aOffset The character offset. 0 means the first character in the
* selection root.
* @param aLength The length of the text. If the length is too long,
* the extra length is ignored.
* @param aReverse If true, the selection is from |aOffset + aLength| to
* |aOffset|. Otherwise, from |aOffset| to |aOffset + aLength|.
* @param aWindow Optional (If null, current |window| will be used)
* @return True, if succeeded. Otherwise false.
*/
async function synthesizeSelectionSet(
aOffset,
aLength,
aReverse,
aWindow = window
) {
const utils = _getDOMWindowUtils(aWindow);
if (!utils) {
return false;
}
// eSetSelection event will be compared with selection cache in
// IMEContentObserver, but it may have not been updated yet. Therefore, we
// need to flush pending things of IMEContentObserver.
await new Promise(resolve =>
aWindow.requestAnimationFrame(() => aWindow.requestAnimationFrame(resolve))
);
const flags = aReverse ? SELECTION_SET_FLAG_REVERSE : 0;
return utils.sendSelectionSetEvent(aOffset, aLength, flags);
}
/**
* Synthesize a query text rect event.
*
* @param aOffset The character offset. 0 means the first character in the
* selection root.
* @param aLength The length of the text. If the length is too long,
* the extra length is ignored.
* @param aIsRelative Optional (If true, aOffset is relative to start of
* composition if there is, or start of selection.)
* @param aWindow Optional (If null, current |window| will be used)
* @return An nsIQueryContentEventResult object. If this failed,
* the result might be null.
*/
function synthesizeQueryTextRect(aOffset, aLength, aIsRelative, aWindow) {
if (aIsRelative !== undefined && typeof aIsRelative !== "boolean") {
throw new Error(
"Maybe, you set Window object to the 3rd argument, but it should be a boolean value"
);
}
var utils = _getDOMWindowUtils(aWindow);
let flags = QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK;
if (aIsRelative === true) {
flags |= QUERY_CONTENT_FLAG_OFFSET_RELATIVE_TO_INSERTION_POINT;
}
return utils.sendQueryContentEvent(
utils.QUERY_TEXT_RECT,
aOffset,
aLength,
0,
0,
flags
);
}
/**
* Synthesize a query text rect array event.
*
* @param aOffset The character offset. 0 means the first character in the
* selection root.
* @param aLength The length of the text. If the length is too long,
* the extra length is ignored.
* @param aWindow Optional (If null, current |window| will be used)
* @return An nsIQueryContentEventResult object. If this failed,
* the result might be null.
*/
function synthesizeQueryTextRectArray(aOffset, aLength, aWindow) {
var utils = _getDOMWindowUtils(aWindow);
return utils.sendQueryContentEvent(
utils.QUERY_TEXT_RECT_ARRAY,
aOffset,
aLength,
0,
0,
QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK
);
}
/**
* Synthesize a query editor rect event.
*
* @param aWindow Optional (If null, current |window| will be used)
* @return An nsIQueryContentEventResult object. If this failed,
* the result might be null.
*/
function synthesizeQueryEditorRect(aWindow) {
var utils = _getDOMWindowUtils(aWindow);
return utils.sendQueryContentEvent(
utils.QUERY_EDITOR_RECT,
0,
0,
0,
0,
QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK
);
}
/**
* Synthesize a character at point event.
*
* @param aX, aY The offset in the client area of the DOM window.
* @param aWindow Optional (If null, current |window| will be used)
* @return An nsIQueryContentEventResult object. If this failed,
* the result might be null.
*/
function synthesizeCharAtPoint(aX, aY, aWindow) {
var utils = _getDOMWindowUtils(aWindow);
return utils.sendQueryContentEvent(
utils.QUERY_CHARACTER_AT_POINT,
0,
0,
aX,
aY,
QUERY_CONTENT_FLAG_USE_NATIVE_LINE_BREAK
);
}
/**
* INTERNAL USE ONLY
* Create an event object to pass to sendDragEvent.
*
* @param aType The string represents drag event type.
* @param aDestElement The element to fire the drag event, used to calculate
* screenX/Y and clientX/Y.
* @param aDestWindow Optional; Defaults to the current window object.
* @param aDataTransfer dataTransfer for current drag session.
* @param aDragEvent The object contains properties to override the event
* object
* @return An object to pass to sendDragEvent.
*/
function createDragEventObject(
aType,
aDestElement,
aDestWindow,
aDataTransfer,
aDragEvent
) {
const resolution = _getTopWindowResolution(aDestWindow.top);
const destRect = aDestElement.getBoundingClientRect();
// If clientX and/or clientY are specified, we should use them. Otherwise,
// use the center of the dest element.
const destClientXInCSSPixels =
"clientX" in aDragEvent && !("screenX" in aDragEvent)
? aDragEvent.clientX
: destRect.left + destRect.width / 2;
const destClientYInCSSPixels =
"clientY" in aDragEvent && !("screenY" in aDragEvent)
? aDragEvent.clientY
: destRect.top + destRect.height / 2;
const devicePixelRatio = aDestWindow.devicePixelRatio;
const destScreenXInDevicePixels =
(_getScreenXInUnscaledCSSPixels(aDestWindow) +
destClientXInCSSPixels * resolution) *
devicePixelRatio;
const destScreenYInDevicePixels =
(_getScreenYInUnscaledCSSPixels(aDestWindow) +
destClientYInCSSPixels * resolution) *
devicePixelRatio;
// Wrap only in plain mochitests
let dataTransfer;
if (aDataTransfer) {
dataTransfer = _EU_maybeUnwrap(
_EU_maybeWrap(aDataTransfer).mozCloneForEvent(aType)
);
// Copy over the drop effect. This isn't copied over by Clone, as it uses
// more complex logic in the actual implementation (see
// nsContentUtils::SetDataTransferInEvent for actual impl).
dataTransfer.dropEffect = aDataTransfer.dropEffect;
}
return Object.assign(
{
type: aType,
screenX: _EU_roundDevicePixels(destScreenXInDevicePixels),
screenY: _EU_roundDevicePixels(destScreenYInDevicePixels),
clientX: _EU_roundDevicePixels(destClientXInCSSPixels),
clientY: _EU_roundDevicePixels(destClientYInCSSPixels),
dataTransfer,
_domDispatchOnly: aDragEvent._domDispatchOnly,
},
aDragEvent
);
}
/**
* Emulate a event sequence of dragstart, dragenter, and dragover.
*
* @param {Element} aSrcElement
* The element to use to start the drag.
* @param {Element} aDestElement
* The element to fire the dragover, dragenter events
* @param {Array} aDragData
* The data to supply for the data transfer.
* This data is in the format:
*
* [
* [
* {"type": value, "data": value },
* ...,
* ],
* ...
* ]
*
* Pass null to avoid modifying dataTransfer.
* @param {string} [aDropEffect="move"]
* The drop effect to set during the dragstart event, or 'move' if omitted.
* @param {DOMWindow} [aWindow=window]
* The DOM window in which the drag happens. Defaults to the window in which
* EventUtils.js is loaded.
* @param {DOMWindow} [aDestWindow=aWindow]
* Used when aDestElement is in a different DOM window than aSrcElement.
* Default is to match ``aWindow``.
* @param {object} [aDragEvent={}]
* Defaults to empty object. Overwrites an object passed to sendDragEvent.
* @return {[boolean, DataTransfer]}
* A two element array, where the first element is the value returned
* from sendDragEvent for dragover event, and the second element is the
* dataTransfer for the current drag session.
*/
function synthesizeDragOver(
aSrcElement,
aDestElement,
aDragData,
aDropEffect,
aWindow,
aDestWindow,
aDragEvent = {}
) {
if (!aWindow) {
aWindow = window;
}
if (!aDestWindow) {
aDestWindow = aWindow;
}
// eslint-disable-next-line mozilla/use-services
const obs = _EU_Cc["@mozilla.org/observer-service;1"].getService(
_EU_Ci.nsIObserverService
);
let utils = _getDOMWindowUtils(aWindow);
var sess = utils.dragSession;
// This method runs before other callbacks, and acts as a way to inject the
// initial drag data into the DataTransfer.
function fillDrag(event) {
if (aDragData) {
for (var i = 0; i < aDragData.length; i++) {
var item = aDragData[i];
for (var j = 0; j < item.length; j++) {
_EU_maybeWrap(event.dataTransfer).mozSetDataAt(
item[j].type,
item[j].data,
i
);
}
}
}
event.dataTransfer.dropEffect = aDropEffect || "move";
event.preventDefault();
}
function trapDrag(subject, topic) {
if (topic == "on-datatransfer-available") {
sess.dataTransfer = _EU_maybeUnwrap(
_EU_maybeWrap(subject).mozCloneForEvent("drop")
);
sess.dataTransfer.dropEffect = subject.dropEffect;
}
}
// need to use real mouse action
aWindow.addEventListener("dragstart", fillDrag, true);
obs.addObserver(trapDrag, "on-datatransfer-available");
synthesizeMouseAtCenter(aSrcElement, { type: "mousedown" }, aWindow);
var rect = aSrcElement.getBoundingClientRect();
var x = rect.width / 2;
var y = rect.height / 2;
synthesizeMouse(aSrcElement, x, y, { type: "mousemove" }, aWindow);
synthesizeMouse(aSrcElement, x + 10, y + 10, { type: "mousemove" }, aWindow);
aWindow.removeEventListener("dragstart", fillDrag, true);
obs.removeObserver(trapDrag, "on-datatransfer-available");
var dataTransfer = sess.dataTransfer;
if (!dataTransfer) {
throw new Error("No data transfer object after synthesizing the mouse!");
}
// The EventStateManager will fire our dragenter event if it needs to.
var event = createDragEventObject(
"dragover",
aDestElement,
aDestWindow,
dataTransfer,
aDragEvent
);
var result = sendDragEvent(event, aDestElement, aDestWindow);
return [result, dataTransfer];
}
/**
* Emulate the drop event and mouseup event.
* This should be called after synthesizeDragOver.
*
* @param {*} aResult
* The first element of the array returned from ``synthesizeDragOver``.
* @param {DataTransfer} aDataTransfer
* The second element of the array returned from ``synthesizeDragOver``.
* @param {Element} aDestElement
* The element on which to fire the drop event.
* @param {DOMWindow} [aDestWindow=window]
* The DOM window in which the drop happens. Defaults to the window in which
* EventUtils.js is loaded.
* @param {object} [aDragEvent={}]
* Defaults to empty object. Overwrites an object passed to sendDragEvent.
* @return {string}
* "none" if aResult is true, ``aDataTransfer.dropEffect`` otherwise.
*/
function synthesizeDropAfterDragOver(
aResult,
aDataTransfer,
aDestElement,
aDestWindow,
aDragEvent = {}
) {
if (!aDestWindow) {
aDestWindow = window;
}
var effect = aDataTransfer.dropEffect;
var event;
if (aResult) {
effect = "none";
} else if (effect != "none") {
event = createDragEventObject(
"drop",
aDestElement,
aDestWindow,
aDataTransfer,
aDragEvent
);
sendDragEvent(event, aDestElement, aDestWindow);
}
// Don't run accessibility checks for this click, since we're not actually
// clicking. It's just generated as part of the drop.
// this.AccessibilityUtils might not be set if this isn't a browser test or
// if a browser test has loaded its own copy of EventUtils for some reason.
// In the latter case, the test probably shouldn't do that.
this.AccessibilityUtils?.suppressClickHandling(true);
synthesizeMouse(aDestElement, 2, 2, { type: "mouseup" }, aDestWindow);
this.AccessibilityUtils?.suppressClickHandling(false);
return effect;
}
/**
* Calls `nsIDragService.startDragSessionForTests`, which is required before
* any other code can use `nsIDOMWindowUtils.dragSession`. Most notably,
* a drag session is required before populating a drag-drop event's
* `dataTransfer` property.
*
* @param {Window} aWindow
* @param {typeof DataTransfer.prototype.dropEffect} aDropEffect
*/
function startDragSession(aWindow, aDropEffect) {
const ds = _EU_Cc["@mozilla.org/widget/dragservice;1"].getService(
_EU_Ci.nsIDragService
);
let dropAction;
switch (aDropEffect) {
case null:
case undefined:
case "move":
dropAction = _EU_Ci.nsIDragService.DRAGDROP_ACTION_MOVE;
break;
case "copy":
dropAction = _EU_Ci.nsIDragService.DRAGDROP_ACTION_COPY;
break;
case "link":
dropAction = _EU_Ci.nsIDragService.DRAGDROP_ACTION_LINK;
break;
default:
throw new Error(`${aDropEffect} is an invalid drop effect value`);
}
ds.startDragSessionForTests(aWindow, dropAction);
}
/**
* Emulate a drag and drop by emulating a dragstart and firing events dragenter,
* dragover, and drop.
*
* @param {Element} aSrcElement
* The element to use to start the drag.
* @param {Element} aDestElement
* The element to fire the dragover, dragenter events
* @param {Array} aDragData
* The data to supply for the data transfer.
* This data is in the format:
*
* [
* [
* {"type": value, "data": value },
* ...,
* ],
* ...
* ]
*
* Pass null to avoid modifying dataTransfer.
* @param {string} [aDropEffect="move"]
* The drop effect to set during the dragstart event, or 'move' if omitted..
* @param {DOMWindow} [aWindow=window]
* The DOM window in which the drag happens. Defaults to the window in which
* EventUtils.js is loaded.
* @param {DOMWindow} [aDestWindow=aWindow]
* Used when aDestElement is in a different DOM window than aSrcElement.
* Default is to match ``aWindow``.
* @param {object} [aDragEvent={}]
* Defaults to empty object. Overwrites an object passed to sendDragEvent.
* @return {string}
* The drop effect that was desired.
*/
function synthesizeDrop(
aSrcElement,
aDestElement,
aDragData,
aDropEffect,
aWindow,
aDestWindow,
aDragEvent = {}
) {
if (!aWindow) {
aWindow = window;
}
if (!aDestWindow) {
aDestWindow = aWindow;
}
startDragSession(aWindow, aDropEffect);
try {
var [result, dataTransfer] = synthesizeDragOver(
aSrcElement,
aDestElement,
aDragData,
aDropEffect,
aWindow,
aDestWindow,
aDragEvent
);
return synthesizeDropAfterDragOver(
result,
dataTransfer,
aDestElement,
aDestWindow,
aDragEvent
);
} finally {
let srcWindowUtils = _getDOMWindowUtils(aWindow);
const srcDragSession = srcWindowUtils.dragSession;
srcDragSession.endDragSession(true, _parseModifiers(aDragEvent));
}
}
function _getFlattenedTreeParentNode(aNode) {
return _EU_maybeUnwrap(_EU_maybeWrap(aNode).flattenedTreeParentNode);
}
function _getInclusiveFlattenedTreeParentElement(aNode) {
for (
let inclusiveAncestor = aNode;
inclusiveAncestor;
inclusiveAncestor = _getFlattenedTreeParentNode(inclusiveAncestor)
) {
if (inclusiveAncestor.nodeType == Node.ELEMENT_NODE) {
return inclusiveAncestor;
}
}
return null;
}
function _nodeIsFlattenedTreeDescendantOf(
aPossibleDescendant,
aPossibleAncestor
) {
do {
if (aPossibleDescendant == aPossibleAncestor) {
return true;
}
aPossibleDescendant = _getFlattenedTreeParentNode(aPossibleDescendant);
} while (aPossibleDescendant);
return false;
}
function _computeSrcElementFromSrcSelection(aSrcSelection) {
let srcElement = _EU_maybeUnwrap(
_EU_maybeWrap(aSrcSelection).mayCrossShadowBoundaryFocusNode
);
while (_EU_maybeWrap(srcElement).isNativeAnonymous) {
srcElement = _getFlattenedTreeParentNode(srcElement);
}
if (srcElement.nodeType !== Node.ELEMENT_NODE) {
srcElement = _getInclusiveFlattenedTreeParentElement(srcElement);
}
return srcElement;
}
/**
* Emulate a drag and drop by emulating a dragstart by mousedown and mousemove,
* and firing events dragenter, dragover, drop, and dragend.
* This does not modify dataTransfer and tries to emulate the plain drag and
* drop as much as possible, compared to synthesizeDrop.
* Note that if synthesized dragstart is canceled, this throws an exception
* because in such case, Gecko does not start drag session.
*
* @param {object} aParams
* @param {Event} aParams.dragEvent
* The DnD events will be generated with modifiers specified with this.
* @param {Element} aParams.srcElement
* The element to start dragging. If srcSelection is
* set, this is computed for element at focus node.
* @param {Selection|null} aParams.srcSelection
* The selection to start to drag, set null if srcElement is set.
* @param {Element|null} aParams.destElement
* The element to drop on. Pass null to emulate a drop on an invalid target.
* @param {number} aParams.srcX
* The initial x coordinate inside srcElement or ignored if srcSelection is set.
* @param {number} aParams.srcY
* The initial y coordinate inside srcElement or ignored if srcSelection is set.
* @param {number} aParams.stepX
* The x-axis step for mousemove inside srcElement
* @param {number} aParams.stepY
* The y-axis step for mousemove inside srcElement
* @param {number} aParams.finalX
* The final x coordinate inside srcElement
* @param {number} aParams.finalY
* The final x coordinate inside srcElement
* @param {Any} aParams.id
* The pointer event id
* @param {DOMWindow} aParams.srcWindow
* The DOM window for dispatching event on srcElement, defaults to the current window object.
* @param {DOMWindow} aParams.destWindow
* The DOM window for dispatching event on destElement, defaults to the current window object.
* @param {boolean} aParams.expectCancelDragStart
* Set to true if the test cancels "dragstart"
* @param {boolean} aParams.expectSrcElementDisconnected
* Set to true if srcElement will be disconnected and
* "dragend" event won't be fired.
* @param {Function} aParams.logFunc
* Set function which takes one argument if you need to log rect of target. E.g., `console.log`.
*/
// eslint-disable-next-line complexity
async function synthesizePlainDragAndDrop(aParams) {
let {
dragEvent = {},
srcElement,
srcSelection,
destElement,
srcX = 2,
srcY = 2,
stepX = 9,
stepY = 9,
finalX = srcX + stepX * 2,
finalY = srcY + stepY * 2,
id = _getDOMWindowUtils(window).DEFAULT_MOUSE_POINTER_ID,
srcWindow = window,
destWindow = window,
expectCancelDragStart = false,
expectSrcElementDisconnected = false,
logFunc,
} = aParams;
// Don't modify given dragEvent object because we modify dragEvent below and
// callers may use the object multiple times so that callers must not assume
// that it'll be modified.
if (aParams.dragEvent !== undefined) {
dragEvent = Object.assign({}, aParams.dragEvent);
}
function rectToString(aRect) {
return `left: ${aRect.left}, top: ${aRect.top}, right: ${aRect.right}, bottom: ${aRect.bottom}`;
}
let srcWindowUtils = _getDOMWindowUtils(srcWindow);
let destWindowUtils = _getDOMWindowUtils(destWindow);
if (logFunc) {
logFunc("synthesizePlainDragAndDrop() -- START");
}
if (srcSelection) {
srcElement = _computeSrcElementFromSrcSelection(srcSelection);
let srcElementRect = srcElement.getBoundingClientRect();
if (logFunc) {
logFunc(
`srcElement.getBoundingClientRect(): ${rectToString(srcElementRect)}`
);
}
// Use last selection client rect because nsIDragSession.sourceNode is
// initialized from focus node which is usually in last rect.
let selectionRectList = SpecialPowers.wrap(
srcSelection.getRangeAt(0)
).getAllowCrossShadowBoundaryClientRects();
let lastSelectionRect = selectionRectList[selectionRectList.length - 1];
if (logFunc) {
logFunc(
`srcSelection.getRangeAt(0).getClientRects()[${
selectionRectList.length - 1
}]: ${rectToString(lastSelectionRect)}`
);
}
// Click at center of last selection rect.
srcX = Math.floor(lastSelectionRect.left + lastSelectionRect.width / 2);
srcY = Math.floor(lastSelectionRect.top + lastSelectionRect.height / 2);
// Then, adjust srcX and srcY for making them offset relative to
// srcElementRect because they will be used when we call synthesizeMouse()
// with srcElement.
srcX = Math.floor(srcX - srcElementRect.left);
srcY = Math.floor(srcY - srcElementRect.top);
// Finally, recalculate finalX and finalY with new srcX and srcY if they
// are not specified by the caller.
if (aParams.finalX === undefined) {
finalX = srcX + stepX * 2;
}
if (aParams.finalY === undefined) {
finalY = srcY + stepY * 2;
}
} else if (logFunc) {
logFunc(
`srcElement.getBoundingClientRect(): ${rectToString(
srcElement.getBoundingClientRect()
)}`
);
}
const editingHost = (() => {
if (!srcElement.matches(":read-write")) {
return null;
}
let lastEditableElement = srcElement;
for (
let inclusiveAncestor =
_getInclusiveFlattenedTreeParentElement(srcElement);
inclusiveAncestor;
inclusiveAncestor = _getInclusiveFlattenedTreeParentElement(
_getFlattenedTreeParentNode(inclusiveAncestor)
)
) {
if (inclusiveAncestor.matches(":read-write")) {
lastEditableElement = inclusiveAncestor;
if (lastEditableElement == srcElement.ownerDocument.body) {
break;
}
}
}
return lastEditableElement;
})();
try {
srcWindowUtils.disableNonTestMouseEvents(true);
await new Promise(r => setTimeout(r, 0));
let mouseDownEvent;
function onMouseDown(aEvent) {
mouseDownEvent = aEvent;
if (logFunc) {
logFunc(
`"${aEvent.type}" event is fired on ${
aEvent.target
} (composedTarget: ${_EU_maybeUnwrap(
_EU_maybeWrap(aEvent).composedTarget
)}`
);
}
if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
srcElement
)
) {
// If srcX and srcY does not point in one of rects in srcElement,
// "mousedown" target is not in srcElement. Such case must not
// be expected by this API users so that we should throw an exception
// for making debugging easier.
throw new Error(
'event target of "mousedown" is not srcElement nor its descendant'
);
}
}
try {
srcWindow.addEventListener("mousedown", onMouseDown, { capture: true });
synthesizeMouse(
srcElement,
srcX,
srcY,
{ type: "mousedown", id },
srcWindow
);
if (logFunc) {
logFunc(`mousedown at ${srcX}, ${srcY}`);
}
if (!mouseDownEvent) {
throw new Error('"mousedown" event is not fired');
}
} finally {
srcWindow.removeEventListener("mousedown", onMouseDown, {
capture: true,
});
}
let dragStartEvent;
function onDragStart(aEvent) {
dragStartEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
srcElement
)
) {
// If srcX and srcY does not point in one of rects in srcElement,
// "dragstart" target is not in srcElement. Such case must not
// be expected by this API users so that we should throw an exception
// for making debugging easier.
throw new Error(
'event target of "dragstart" is not srcElement nor its descendant'
);
}
}
let dragEnterEvent;
function onDragEnterGenerated(aEvent) {
dragEnterEvent = aEvent;
}
srcWindow.addEventListener("dragstart", onDragStart, { capture: true });
srcWindow.addEventListener("dragenter", onDragEnterGenerated, {
capture: true,
});
try {
// Wait for the next event tick after each event dispatch, so that UI
// elements (e.g. menu) work like the real user input.
await new Promise(r => setTimeout(r, 0));
srcX += stepX;
srcY += stepY;
synthesizeMouse(
srcElement,
srcX,
srcY,
{ type: "mousemove", id },
srcWindow
);
if (logFunc) {
logFunc(`first mousemove at ${srcX}, ${srcY}`);
}
await new Promise(r => setTimeout(r, 0));
srcX += stepX;
srcY += stepY;
synthesizeMouse(
srcElement,
srcX,
srcY,
{ type: "mousemove", id },
srcWindow
);
if (logFunc) {
logFunc(`second mousemove at ${srcX}, ${srcY}`);
}
await new Promise(r => setTimeout(r, 0));
if (!dragStartEvent) {
throw new Error('"dragstart" event is not fired');
}
} finally {
srcWindow.removeEventListener("dragstart", onDragStart, {
capture: true,
});
srcWindow.removeEventListener("dragenter", onDragEnterGenerated, {
capture: true,
});
}
let srcSession = srcWindowUtils.dragSession;
if (!srcSession) {
if (expectCancelDragStart) {
synthesizeMouse(
srcElement,
finalX,
finalY,
{ type: "mouseup", id },
srcWindow
);
return;
}
throw new Error("drag hasn't been started by the operation");
} else if (expectCancelDragStart) {
throw new Error("drag has been started by the operation");
}
if (destElement) {
if (
(srcElement != destElement && !dragEnterEvent) ||
destElement != dragEnterEvent.target
) {
if (logFunc) {
logFunc(
`destElement.getBoundingClientRect(): ${rectToString(
destElement.getBoundingClientRect()
)}`
);
}
function onDragEnter(aEvent) {
dragEnterEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (aEvent.target != destElement) {
throw new Error('event target of "dragenter" is not destElement');
}
}
destWindow.addEventListener("dragenter", onDragEnter, {
capture: true,
});
try {
let event = createDragEventObject(
"dragenter",
destElement,
destWindow,
null,
dragEvent
);
sendDragEvent(event, destElement, destWindow);
if (!dragEnterEvent && !destElement.disabled) {
throw new Error('"dragenter" event is not fired');
}
if (dragEnterEvent && destElement.disabled) {
throw new Error(
'"dragenter" event should not be fired on disable element'
);
}
} finally {
destWindow.removeEventListener("dragenter", onDragEnter, {
capture: true,
});
}
}
let dragOverEvent;
function onDragOver(aEvent) {
dragOverEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (aEvent.target != destElement) {
throw new Error('event target of "dragover" is not destElement');
}
}
destWindow.addEventListener("dragover", onDragOver, { capture: true });
try {
// dragover and drop are only fired to a valid drop target. If the
// destElement parameter is null, this function is being used to
// simulate a drag'n'drop over an invalid drop target.
let event = createDragEventObject(
"dragover",
destElement,
destWindow,
null,
dragEvent
);
sendDragEvent(event, destElement, destWindow);
if (!dragOverEvent && !destElement.disabled) {
throw new Error('"dragover" event is not fired');
}
if (dragEnterEvent && destElement.disabled) {
throw new Error(
'"dragover" event should not be fired on disable element'
);
}
} finally {
destWindow.removeEventListener("dragover", onDragOver, {
capture: true,
});
}
await new Promise(r => setTimeout(r, 0));
// If there is not accept to drop the data, "drop" event shouldn't be
// fired.
// XXX nsIDragSession.canDrop is different only on Linux. It must be
// a bug of gtk/nsDragService since it manages `mCanDrop` by itself.
// Thus, we should use nsIDragSession.dragAction instead.
let destSession = destWindowUtils.dragSession;
if (
destSession.dragAction != _EU_Ci.nsIDragService.DRAGDROP_ACTION_NONE
) {
let dropEvent;
function onDrop(aEvent) {
dropEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
destElement
)
) {
throw new Error(
'event target of "drop" is not destElement nor its descendant'
);
}
}
destWindow.addEventListener("drop", onDrop, { capture: true });
try {
let event = createDragEventObject(
"drop",
destElement,
destWindow,
null,
dragEvent
);
sendDragEvent(event, destElement, destWindow);
if (!dropEvent && destSession.canDrop) {
throw new Error('"drop" event is not fired');
}
} finally {
destWindow.removeEventListener("drop", onDrop, { capture: true });
}
return;
}
}
// Since we don't synthesize drop event, we need to set drag end point
// explicitly for "dragEnd" event which will be fired by
// endDragSession().
dragEvent.clientX = srcElement.getBoundingClientRect().x + finalX;
dragEvent.clientY = srcElement.getBoundingClientRect().y + finalY;
let event = createDragEventObject(
"dragend",
srcElement,
srcWindow,
null,
dragEvent
);
srcSession.setDragEndPointForTests(event.screenX, event.screenY);
if (logFunc) {
logFunc(
`dragend event client (X,Y) = (${event.clientX}, ${event.clientY})`
);
logFunc(
`dragend event screen (X,Y) = (${event.screenX}, ${event.screenY})`
);
}
} finally {
await new Promise(r => setTimeout(r, 0));
if (srcWindowUtils.dragSession) {
const sourceNode = srcWindowUtils.dragSession.sourceNode;
let dragEndEvent;
function onDragEnd(aEvent) {
dragEndEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
srcElement
) &&
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget) != editingHost
) {
throw new Error(
'event target of "dragend" is not srcElement nor its descendant'
);
}
if (expectSrcElementDisconnected) {
throw new Error(
`"dragend" event shouldn't be fired when the source node is disconnected (the source node is ${
sourceNode?.isConnected ? "connected" : "null or disconnected"
})`
);
}
}
srcWindow.addEventListener("dragend", onDragEnd, { capture: true });
try {
srcWindowUtils.dragSession.endDragSession(
true,
_parseModifiers(dragEvent)
);
if (!expectSrcElementDisconnected && !dragEndEvent) {
// eslint-disable-next-line no-unsafe-finally
throw new Error(
`"dragend" event is not fired by nsIDragSession.endDragSession()${
srcWindowUtils.dragSession.sourceNode &&
!srcWindowUtils.dragSession.sourceNode.isConnected
? "(sourceNode was disconnected)"
: ""
}`
);
}
} finally {
srcWindow.removeEventListener("dragend", onDragEnd, { capture: true });
}
}
srcWindowUtils.disableNonTestMouseEvents(false);
if (logFunc) {
logFunc("synthesizePlainDragAndDrop() -- END");
}
}
}
function _checkDataTransferItems(aDataTransfer, aExpectedDragData) {
try {
// We must wrap only in plain mochitests, not chrome
let dataTransfer = _EU_maybeWrap(aDataTransfer);
if (!dataTransfer) {
return null;
}
if (
aExpectedDragData == null ||
dataTransfer.mozItemCount != aExpectedDragData.length
) {
return dataTransfer;
}
for (let i = 0; i < dataTransfer.mozItemCount; i++) {
let dtTypes = dataTransfer.mozTypesAt(i);
if (dtTypes.length != aExpectedDragData[i].length) {
return dataTransfer;
}
for (let j = 0; j < dtTypes.length; j++) {
if (dtTypes[j] != aExpectedDragData[i][j].type) {
return dataTransfer;
}
let dtData = dataTransfer.mozGetDataAt(dtTypes[j], i);
if (aExpectedDragData[i][j].eqTest) {
if (
!aExpectedDragData[i][j].eqTest(
dtData,
aExpectedDragData[i][j].data
)
) {
return dataTransfer;
}
} else if (aExpectedDragData[i][j].data != dtData) {
return dataTransfer;
}
}
}
} catch (ex) {
return ex;
}
return true;
}
/**
* This callback type is used with ``synthesizePlainDragAndCancel()``.
* It should compare ``actualData`` and ``expectedData`` and return
* true if the two should be considered equal, false otherwise.
*
* @callback eqTest
* @param {*} actualData
* @param {*} expectedData
* @return {boolean}
*/
/**
* synthesizePlainDragAndCancel() synthesizes drag start with
* synthesizePlainDragAndDrop(), but always cancel it with preventing default
* of "dragstart". Additionally, this checks whether the dataTransfer of
* "dragstart" event has only expected items.
*
* @param {object} aParams
* The params which is set to the argument of ``synthesizePlainDragAndDrop()``.
* @param {Array} aExpectedDataTransferItems
* All expected dataTransfer items.
* This data is in the format:
*
* [
* [
* {"type": value, "data": value, eqTest: function}
* ...,
* ],
* ...
* ]
*
* This can also be null.
* You can optionally provide ``eqTest`` {@type eqTest} if the
* comparison to the expected data transfer items can't be done
* with x == y;
* @return {boolean}
* true if aExpectedDataTransferItems matches with
* DragEvent.dataTransfer of "dragstart" event.
* Otherwise, the dataTransfer object (may be null) or
* thrown exception, NOT false. Therefore, you shouldn't
* use.
*/
async function synthesizePlainDragAndCancel(
aParams,
aExpectedDataTransferItems
) {
let srcElement = aParams.srcSelection
? _computeSrcElementFromSrcSelection(aParams.srcSelection)
: aParams.srcElement;
let result;
function onDragStart(aEvent) {
aEvent.preventDefault();
result = _checkDataTransferItems(
aEvent.dataTransfer,
aExpectedDataTransferItems
);
}
SpecialPowers.wrap(srcElement.ownerDocument).addEventListener(
"dragstart",
onDragStart,
{ capture: true, mozSystemGroup: true }
);
try {
aParams.expectCancelDragStart = true;
await synthesizePlainDragAndDrop(aParams);
} finally {
SpecialPowers.wrap(srcElement.ownerDocument).removeEventListener(
"dragstart",
onDragStart,
{ capture: true, mozSystemGroup: true }
);
}
return result;
}
async function _synthesizeMockDndFromChild(aParams) {
// Since we know that this is the (only) content process that will be involved
// in the drag, we can set this for the caller.
const ds = SpecialPowers.Cc["@mozilla.org/widget/dragservice;1"].getService(
SpecialPowers.Ci.nsIDragService
);
ds.neverAllowSessionIsSynthesizedForTests = true;
let sourceElt = document.getElementById(aParams.srcElement);
let targetElt = document.getElementById(aParams.targetElement);
// The spawnChrome call below may return before the DND is complete since
// the parent process will not synchronize with the child for child-initiated
// drags. So we need to wait for the dragend here. If the drag motion is
// expected to not result in a drag session then we wait for the mouseup
// instead.
let resolveEndPromise;
let endPromise = new Promise(res => {
resolveEndPromise = res;
});
let endEvent = aParams.expectNoDragEvents ? "mouseup" : "dragend";
sourceElt.addEventListener(
endEvent,
() => {
resolveEndPromise();
},
{ once: true }
);
// The parent call will not get the element positions, so set 'sourceOffset' to
// the screen coordinates for the drag start and 'targetOffset' for the screen
// position to drag to.
const scale = window.devicePixelRatio;
let sourceOffset = [
(window.mozInnerScreenX + sourceElt.offsetLeft) * scale +
aParams.sourceOffset[0],
(window.mozInnerScreenY + sourceElt.offsetTop) * scale +
aParams.sourceOffset[1],
];
let targetOffset = [
(window.mozInnerScreenX + targetElt.offsetLeft) * scale +
aParams.targetOffset[0],
(window.mozInnerScreenY + targetElt.offsetTop) * scale +
aParams.targetOffset[1],
];
let params = {
srcElement: aParams.srcElement,
targetElement: aParams.targetElement,
sourceOffset,
targetOffset,
step: aParams.step,
expectCancelDragStart: aParams.expectCancelDragStart,
cancel: aParams.cancel,
expectSrcElementDisconnected: aParams.expectSrcElementDisconnected,
expectDragLeave: aParams.expectDragLeave,
expectNoDragEvents: aParams.expectNoDragEvents,
expectNoDragTargetEvents: aParams.expectNoDragTargetEvents,
contextLabel: aParams.contextLabel,
throwOnExtraMessage: aParams.throwOnExtraMessage,
};
let record =
aParams.record ||
((cond, msg, _, stack) => {
if (cond) {
console.error(msg + "\n" + stack);
}
});
let info = aParams.info || console.log;
try {
await SpecialPowers.spawnChrome([params], async _params => {
let params = {
sourceBrowsingCxt: browsingContext,
targetBrowsingCxt: browsingContext,
record: () => {},
info: () => {},
..._params,
};
await EventUtils.synthesizeMockDragAndDrop(params);
});
await endPromise;
} catch (ex) {
// Display any exceptions since EventUtils does not propagate them.
record(
true,
`Parent synthesizeMockDragAndDrop threw exception: ${ex}`,
null,
ex.stack
);
} finally {
info("Remote synthesizeMockDragAndDrop has completed.");
}
}
/**
* Emulate a drag and drop by generating a dragstart from mousedown and mousemove,
* then firing events dragover and drop (or dragleave if expectDragLeave is set).
* This does not modify dataTransfer and tries to emulate the plain drag and
* drop as much as possible, compared to synthesizeDrop and
* synthesizePlainDragAndDrop. MockDragService is used in place of the native
* nsIDragService implementation. All coordinates are in client space.
*
* This method can be called from the parent process, in which case it will
* perform checks of DND internals (if 'record' is set). It can also be
* called from content processes, in which case the drag is over the window
* that is in context, and no checks of DND internals will occur.
*
* @param {object} aParams
* @param {Window} aParams.sourceBrowsingCxt
* The BrowsingContext (possibly remote) that contains
* srcElement. Only set in parent process.
* @param {Window} aParams.targetBrowsingCxt
* The BrowsingContext (possibly remote) that contains
* targetElement. Only set in parent process.
* Default is sourceBrowsingCxt.
* @param {Element} aParams.srcElement
* ID of the element to drag.
* @param {Element|null} aParams.targetElement
* ID of the element to drop on.
* @param {number} aParams.sourceOffset
* The 2D offset from the source element at which the drag
* starts. Default is [0,0].
* @param {number} aParams.targetOffset
* The 2D offset from the target element at which the drag ends.
* Default is [0,0].
* @param {number} aParams.step
* The 2D step for intermediate dragging mousemoves.
* Default is [5,5].
* @param {boolean} aParams.expectCancelDragStart
* Set to true if srcElement is set up to cancel "dragstart"
* @param {number} aParams.cancel
* The 2D coord the mouse is moved to as the last step if
* expectCancelDragStart is set
* @param {boolean} aParams.expectSrcElementDisconnected
* Set to true if srcElement will be disconnected and
* "dragend" event won't be fired.
* @param {boolean} aParams.expectDragLeave
* Set to true if the drop event will be converted to a
* dragleave before it is sent (e.g. it was rejected by a
* content analysis check).
* @param {boolean} aParams.expectNoDragEvents
* Set to true if no mouse or drag events should be received
* on the source or target.
* @param {boolean} aParams.expectNoDragTargetEvents
* Set to true if the drag should be blocked from sending
* events to the target.
* @param {boolean} aParams.dropPromise
* A promise that the caller will resolve before we check
* that the drop has happened. Default is a pre-resolved
* promise.
* @param {string} aParms.contextLabel
* Label that will appear in each output message. Useful to
* distinguish between concurrent calls. Default is none.
* @param {boolean} aParams.throwOnExtraMessage
* Throw an exception in child process when an unexpected
* event is received. Used for debugging. Default is false.
* @param {Function} aParams.record
* Four-parameter function that logs the results of a remote
* assertion. The parameters are (condition, message, ignored,
* stack). This is the type of the mochitest report function.
* Pass the empty function, or call this from content, to skip
* testing of DND internals.
* This parameter is required in the parent process and is
* optional in content processes.
* @param {Function} aParams.info
* One-parameter info logging function. This is the type of
* the mochitest info function. Pass the empty function, or
* call this from content, to skip testing of DND internals.
* This parameter is required in the parent process and is
* optional in content processes.
* @param {object} aParams.dragController
* MockDragController that the function should use. This
* function will automatically generate one if none is given.
* This can only be set in the parent process.
*/
// eslint-disable-next-line complexity
async function synthesizeMockDragAndDrop(aParams) {
// eslint-disable-next-line mozilla/use-services
let appinfo = _EU_Cc["@mozilla.org/xre/app-info;1"].getService(
_EU_Ci.nsIXULRuntime
);
if (appinfo.processType !== appinfo.PROCESS_TYPE_DEFAULT) {
await _synthesizeMockDndFromChild(aParams);
return;
}
const {
srcElement,
targetElement,
sourceOffset = [0, 0],
targetOffset = [0, 0],
step = [5, 5],
cancel = [0, 0],
sourceBrowsingCxt,
targetBrowsingCxt = sourceBrowsingCxt,
expectCancelDragStart = false,
expectSrcElementDisconnected = false,
expectDragLeave = false,
expectNoDragEvents = false,
dropPromise = Promise.resolve(undefined),
contextLabel = "",
throwOnExtraMessage = false,
} = aParams;
let { dragController = null, expectNoDragTargetEvents = false } = aParams;
// Configure test reporting functions
const prefix = contextLabel ? `[${contextLabel}]| ` : "";
const info = msg => {
aParams.info(`${prefix}${msg}`);
};
const record = (cond, msg, _, stack) => {
aParams.record(cond, `${prefix}${msg}`, null, stack);
};
const ok = (cond, msg) => {
record(cond, msg, null, Components.stack.caller);
};
info("synthesizeMockDragAndDrop() -- START");
// Validate parameters
ok(sourceBrowsingCxt, "sourceBrowsingCxt was given");
ok(
sourceBrowsingCxt != targetBrowsingCxt || srcElement != targetElement,
"sourceBrowsingCxt+Element cannot be the same as targetBrowsingCxt+Element"
);
// no drag implies no drag target
expectNoDragTargetEvents |= expectNoDragEvents;
// Returns true if one browsing context is an ancestor of the other.
let browsingContextsAreRelated = function (cxt1, cxt2) {
return cxt1.top == cxt2.top;
};
// The rules for accessing the dataTransfer from internal drags in Gecko
// during drag event handlers are as follows:
//
// dragstart:
// Always grants read-write access
// dragenter/dragover/dragleave:
// If dom.events.dataTransfer.protected.enabled is set:
// Read-only permission is granted if any of these holds:
// * The drag target's browsing context is the same as the drag
// source's (e.g. dragging inside of one frame on a web page).
// * The drag source and target are the same domain/principal and
// one has a browsing context that is an ancestor of the other
// (e.g. one is an iframe nested inside of the other).
// * The principal of the drag target element is privileged (not
// a content principal).
// Otherwise:
// Permission is never granted
// drop:
// Always grants read-only permission
// dragend:
// Read-only permission is granted if
// dom.events.dataTransfer.protected.enabled is set.
//
// dragstart and dragend are special because they target the drag-source,
// not the drag-target.
// eslint-disable-next-line mozilla/use-services
let prefs = _EU_Cc["@mozilla.org/preferences-service;1"].getService(
Ci.nsIPrefBranch
);
let expectProtectedDataTransferAccessSource = !prefs.getBoolPref(
"dom.events.dataTransfer.protected.enabled"
);
let expectProtectedDataTransferAccessTarget =
expectProtectedDataTransferAccessSource &&
browsingContextsAreRelated(targetBrowsingCxt, sourceBrowsingCxt);
info(
`expectProtectedDataTransferAccessSource: ${expectProtectedDataTransferAccessSource}`
);
info(
`expectProtectedDataTransferAccessTarget: ${expectProtectedDataTransferAccessTarget}`
);
// Essentially the entire function is in a try block so that we can make sure
// that the mock drag service is removed and non-test mouse events are
// restored.
const { MockRegistrar } = ChromeUtils.importESModule(
"resource://testing-common/MockRegistrar.sys.mjs"
);
let dragServiceCid;
let sourceCxt;
let targetCxt;
let srcWindowUtils = _getDOMWindowUtils(sourceBrowsingCxt.ownerGlobal);
let targetWindowUtils = _getDOMWindowUtils(targetBrowsingCxt.ownerGlobal);
try {
// Disable native mouse events to avoid external interference while the test
// runs. One call disables for all windows.
if (srcWindowUtils) {
srcWindowUtils.disableNonTestMouseEvents(true);
}
if (targetWindowUtils) {
targetWindowUtils.disableNonTestMouseEvents(true);
}
// Install mock drag service.
if (!dragController) {
info("No dragController was given so creating mock drag service");
const oldDragService = _EU_Cc[
"@mozilla.org/widget/dragservice;1"
].getService(_EU_Ci.nsIDragService);
dragController = oldDragService.getMockDragController();
dragServiceCid = MockRegistrar.register(
"@mozilla.org/widget/dragservice;1",
dragController.mockDragService
);
ok(dragServiceCid, "MockDragService was registered");
// If the mock failed then don't continue or else we will trigger native
// DND behavior.
if (!dragServiceCid) {
throw new Error("MockDragService failed to register");
}
}
const mockDragService = _EU_Cc[
"@mozilla.org/widget/dragservice;1"
].getService(_EU_Ci.nsIDragService);
let runChecks = globalThis.hasOwnProperty("SpecialPowers");
if (runChecks) {
// Variables that are added to the child actor objects.
const srcVars = {
expectCancelDragStart,
expectSrcElementDisconnected,
expectNoDragEvents,
expectProtectedDataTransferAccess:
expectProtectedDataTransferAccessSource,
dragElementId: srcElement,
};
const targetVars = {
expectDragLeave,
expectNoDragTargetEvents,
expectProtectedDataTransferAccess:
expectProtectedDataTransferAccessTarget,
dragElementId: targetElement,
};
const bothVars = {
contextLabel,
throwOnExtraMessage,
relevantEvents: [
"mousedown",
"mouseup",
"dragstart",
"dragenter",
"dragover",
"drop",
"dragleave",
"dragend",
],
};
const makeDragSourceContext = async (aBC, aRemoteVars) => {
let { DragSourceParentContext } = ChromeUtils.importESModule(
"chrome://mochikit/content/tests/SimpleTest/DragSourceParentContext.sys.mjs"
);
let ret = new DragSourceParentContext(aBC, aRemoteVars, SpecialPowers);
await ret.initialize();
return ret;
};
const makeDragTargetContext = async (aBC, aRemoteVars) => {
let { DragTargetParentContext } = ChromeUtils.importESModule(
"chrome://mochikit/content/tests/SimpleTest/DragTargetParentContext.sys.mjs"
);
let ret = new DragTargetParentContext(aBC, aRemoteVars, SpecialPowers);
await ret.initialize();
return ret;
};
[sourceCxt, targetCxt] = await Promise.all([
makeDragSourceContext(sourceBrowsingCxt, { ...srcVars, ...bothVars }),
makeDragTargetContext(targetBrowsingCxt, {
...targetVars,
...bothVars,
}),
]);
} else {
// We don't have SpecialPowers so we cannot perform DND checks. Make
// them empty functions.
info("synthesizeMockDragAndDrop will skip DND checks");
let dragParentBaseCxt = {
expect: () => {},
checkExpected: () => {},
checkHasDrag: () => {},
checkSessionHasAction: () => {},
synchronize: () => {},
cleanup: () => {},
};
sourceCxt = {
getElementPositions: () => {
return { screenPos: [0, 0] };
},
checkMouseDown: () => {},
checkDragStart: () => {},
checkDragEnd: () => {},
...dragParentBaseCxt,
};
targetCxt = {
getElementPositions: () => {
return { screenPos: [0, 0] };
},
checkDropOrDragLeave: () => {},
...dragParentBaseCxt,
};
}
// Get element positions in screen coords
let add2d = (a, b) => {
return [a[0] + b[0], a[1] + b[1]];
};
let srcPos = add2d(
(await sourceCxt.getElementPositions()).screenPos,
sourceOffset
);
let targetPos = add2d(
(await targetCxt.getElementPositions()).screenPos,
targetOffset
);
info(`screenSrcPos: ${srcPos} | screenTargetPos: ${targetPos}`);
// Send and verify the mousedown on src.
if (!expectNoDragEvents) {
sourceCxt.expect("mousedown");
}
// Take ceiling of ccoordinates to make sure that the integer coordinates
// are over the element.
let currentSrcScreenPos = [Math.ceil(srcPos[0]), Math.ceil(srcPos[1])];
info(
`sending mousedown at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseDown,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`mousedown sent`);
await sourceCxt.synchronize();
await sourceCxt.checkMouseDown();
let contentInvokedDragPromise;
info("setting up content-invoked-drag observer and expecting dragstart");
if (!expectNoDragEvents) {
sourceCxt.expect("dragstart");
// Set up observable for content-invoked-drag, which is sent when the
// parent learns that content has begun a drag session.
contentInvokedDragPromise = new Promise(cb => {
Services.obs.addObserver(function observe() {
info("content-invoked-drag observer received message");
Services.obs.removeObserver(observe, "content-invoked-drag");
cb();
}, "content-invoked-drag");
});
}
// It takes two mouse-moves to initiate a drag session.
currentSrcScreenPos = [
currentSrcScreenPos[0] + step[0],
currentSrcScreenPos[1] + step[1],
];
info(
`first mousemove at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseMove,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`first mousemove sent`);
currentSrcScreenPos = [
currentSrcScreenPos[0] + step[0],
currentSrcScreenPos[1] + step[1],
];
info(
`second mousemove at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseMove,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`second mousemove sent`);
if (!expectNoDragEvents) {
info("waiting for content-invoked-drag observable");
await contentInvokedDragPromise;
ok(true, "content-invoked-drag was received");
}
info("checking dragstart");
await sourceCxt.checkDragStart();
if (expectNoDragEvents) {
ok(
!mockDragService.getCurrentSession(),
"Drag was properly blocked from starting."
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseUp,
cancel[0],
cancel[1]
);
return;
}
// Another move creates the drag session in the parent process (but we need
// to wait for the src process to get there).
currentSrcScreenPos = [
currentSrcScreenPos[0] + step[0],
currentSrcScreenPos[1] + step[1],
];
info(
`third mousemove at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseMove,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`third mousemove sent`);
ok(mockDragService.getCurrentSession(), `Parent process has drag session.`);
if (expectCancelDragStart) {
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseUp,
cancel[0],
cancel[1]
);
return;
}
await sourceCxt.checkExpected();
// Implementation detail: EventStateManager::GenerateDragDropEnterExit
// expects the source to get at least one dragover before leaving the
// widget or else it fails to send dragenter/dragleave events to the
// browsers.
info("synthesizing dragover inside source");
sourceCxt.expect("dragenter");
sourceCxt.expect("dragover");
currentSrcScreenPos = [
currentSrcScreenPos[0] + step[0],
currentSrcScreenPos[1] + step[1],
];
info(`dragover at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eDragOver,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`dragover sent`);
await sourceCxt.checkExpected();
let currentTargetScreenPos = [
Math.ceil(targetPos[0]),
Math.ceil(targetPos[1]),
];
// The next step is to drag to the target element.
if (!expectNoDragTargetEvents) {
sourceCxt.expect("dragleave");
}
if (
sourceBrowsingCxt.top.embedderElement !==
targetBrowsingCxt.top.embedderElement
) {
// Send dragexit and dragenter only if we are dragging to another widget.
// If we are dragging in the same widget then dragenter does not involve
// the parent process. This mirrors the native behavior. In the
// widget-to-widget case, the source gets the dragexit immediately but
// the target won't get a dragenter in content until we send a dragover --
// this is because dragenters are generated by the EventStateManager and
// are not forwarded remotely.
// NB: dragleaves are synthesized by Gecko from dragexits.
info("synthesizing dragexit and dragenter to enter new widget");
if (!expectNoDragTargetEvents) {
info("This will generate dragleave on the source");
}
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eDragExit,
currentTargetScreenPos[0],
currentTargetScreenPos[1]
);
dragController.sendEvent(
targetBrowsingCxt,
Ci.nsIMockDragServiceController.eDragEnter,
currentTargetScreenPos[0],
currentTargetScreenPos[1]
);
await sourceCxt.synchronize();
await sourceCxt.checkExpected();
await targetCxt.checkExpected();
}
info(
"Synthesizing dragover over target. This will first generate a dragenter."
);
if (!expectNoDragTargetEvents) {
targetCxt.expect("dragenter");
targetCxt.expect("dragover");
}
dragController.sendEvent(
targetBrowsingCxt,
Ci.nsIMockDragServiceController.eDragOver,
currentTargetScreenPos[0],
currentTargetScreenPos[1]
);
await targetCxt.checkExpected();
let expectedMessage = expectDragLeave ? "dragleave" : "drop";
if (expectNoDragTargetEvents) {
await targetCxt.checkHasDrag(false);
} else {
await targetCxt.checkSessionHasAction();
targetCxt.expect(expectedMessage);
}
if (!expectSrcElementDisconnected) {
await sourceCxt.checkHasDrag(true);
sourceCxt.expect("dragend");
}
info(
`issuing drop event that should be ` +
`${
!expectNoDragTargetEvents
? `received as a ${expectedMessage} event`
: "ignored"
}, followed by a dragend event`
);
currentTargetScreenPos = [
currentTargetScreenPos[0] + step[0],
currentTargetScreenPos[1] + step[1],
];
dragController.sendEvent(
targetBrowsingCxt,
Ci.nsIMockDragServiceController.eDrop,
currentTargetScreenPos[0],
currentTargetScreenPos[1]
);
// Wait for any caller-supplied dropPromise before continuing.
await dropPromise;
if (!expectNoDragTargetEvents) {
await targetCxt.checkDropOrDragLeave();
} else {
await targetCxt.checkExpected();
}
if (!expectSrcElementDisconnected) {
await sourceCxt.checkDragEnd();
} else {
await sourceCxt.checkExpected();
}
ok(
!mockDragService.getCurrentSession(),
`Parent process does not have a drag session.`
);
} catch (e) {
// Any exception is a test failure.
record(false, e.toString(), null, e.stack);
throw e;
} finally {
if (sourceCxt) {
await sourceCxt.cleanup();
}
if (targetCxt) {
await targetCxt.cleanup();
}
if (dragServiceCid) {
MockRegistrar.unregister(dragServiceCid);
}
if (srcWindowUtils) {
srcWindowUtils.disableNonTestMouseEvents(false);
}
if (targetWindowUtils) {
targetWindowUtils.disableNonTestMouseEvents(false);
}
info("synthesizeMockDragAndDrop() -- END");
}
}
class EventCounter {
constructor(aTarget, aType, aOptions = {}) {
this.target = aTarget;
this.type = aType;
this.options = aOptions;
this.eventCount = 0;
// Bug 1512817:
// SpecialPowers is picky and needs to be passed an explicit reference to
// the function to be called. To avoid having to bind "this", we therefore
// define the method this way, via a property.
this.handleEvent = () => {
this.eventCount++;
};
SpecialPowers.wrap(aTarget).addEventListener(
aType,
this.handleEvent,
aOptions
);
}
unregister() {
SpecialPowers.wrap(this.target).removeEventListener(
this.type,
this.handleEvent,
this.options
);
}
get count() {
return this.eventCount;
}
}
|