1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "EventStateManager.h"
#include "ContentEventHandler.h"
#include "IMEContentObserver.h"
#include "RemoteDragStartData.h"
#include "Units.h"
#include "WheelHandlingHelper.h"
#include "imgIContainer.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Attributes.h"
#include "mozilla/ConnectedAncestorTracker.h"
#include "mozilla/EditorBase.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventForwards.h"
#include "mozilla/FocusModel.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/Hal.h"
#include "mozilla/IMEStateManager.h"
#include "mozilla/Likely.h"
#include "mozilla/Logging.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/MiscEvents.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/PointerLockManager.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/ScrollContainerFrame.h"
#include "mozilla/ScrollTypes.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_accessibility.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_mousewheel.h"
#include "mozilla/StaticPrefs_ui.h"
#include "mozilla/StaticPrefs_zoom.h"
#include "mozilla/TextComposition.h"
#include "mozilla/TextControlElement.h"
#include "mozilla/TextEditor.h"
#include "mozilla/TextEvents.h"
#include "mozilla/TouchEvents.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/BrowserBridgeChild.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/DOMIntersectionObserver.h"
#include "mozilla/dom/DataTransfer.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DragEvent.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/FrameLoaderBinding.h"
#include "mozilla/dom/HTMLDialogElement.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/HTMLLabelElement.h"
#include "mozilla/dom/MouseEventBinding.h"
#include "mozilla/dom/PointerEventHandler.h"
#include "mozilla/dom/Record.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/UIEvent.h"
#include "mozilla/dom/UIEventBinding.h"
#include "mozilla/dom/UserActivation.h"
#include "mozilla/dom/WheelEventBinding.h"
#include "mozilla/glean/ProcesstoolsMetrics.h"
#include "nsCOMPtr.h"
#include "nsComboboxControlFrame.h"
#include "nsCommandParams.h"
#include "nsContentAreaDragDrop.h"
#include "nsContentUtils.h"
#include "nsCopySupport.h"
#include "nsFocusManager.h"
#include "nsFontMetrics.h"
#include "nsFrameLoaderOwner.h"
#include "nsFrameManager.h"
#include "nsFrameSelection.h"
#include "nsGenericHTMLElement.h"
#include "nsGkAtoms.h"
#include "nsIBaseWindow.h"
#include "nsIBrowserChild.h"
#include "nsIClipboard.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsIController.h"
#include "nsICookieJarSettings.h"
#include "nsIDOMXULControlElement.h"
#include "nsIDocShell.h"
#include "nsIDocumentViewer.h"
#include "nsIDragService.h"
#include "nsIDragSession.h"
#include "nsIFormControl.h"
#include "nsIFrame.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIObserverService.h"
#include "nsIProperties.h"
#include "nsISupportsPrimitives.h"
#include "nsITimer.h"
#include "nsIWeakReferenceUtils.h"
#include "nsIWebNavigation.h"
#include "nsIWidget.h"
#include "nsLayoutUtils.h"
#include "nsLiteralString.h"
#include "nsMenuPopupFrame.h"
#include "nsNameSpaceManager.h"
#include "nsPIDOMWindow.h"
#include "nsPIWindowRoot.h"
#include "nsPresContext.h"
#include "nsServiceManagerUtils.h"
#include "nsSubDocumentFrame.h"
#include "nsTArray.h"
#include "nsTreeBodyFrame.h"
#include "nsUnicharUtils.h"
#ifdef XP_MACOSX
# import <ApplicationServices/ApplicationServices.h>
#endif
namespace mozilla {
using namespace dom;
// Log the mouse cursor updates. That should be updated only by the events for
// the last pointer which is actually handled as a user input. I.e., should not
// be updated by synthesized mouse/pointer move events which are not for the
// last pointer.
// - MouseCursorUpdate:3 logs only when EventStateManager and BrowserParent
// updated the cursor.
// - MouseCursorUpdate:4 logs any results when BrowserParent handles that.
// - MouseCursorUpdate:5 logs when UpdateCursor() stopped updating the cursor.
//
// NOTE: This can work only on debug builds for avoiding to the damage to the
// performance.
LazyLogModule gMouseCursorUpdates("MouseCursorUpdates");
#ifdef DEBUG
# define MOZ_LOG_IF_DEBUG(_module, _level, _args) \
MOZ_LOG(_module, _level, _args)
#else
# define MOZ_LOG_IF_DEBUG(_module, _level, _args)
#endif
static const LayoutDeviceIntPoint kInvalidRefPoint =
LayoutDeviceIntPoint(-1, -1);
static uint32_t gMouseOrKeyboardEventCounter = 0;
static nsITimer* gUserInteractionTimer = nullptr;
static nsITimerCallback* gUserInteractionTimerCallback = nullptr;
static const double kCursorLoadingTimeout = 1000; // ms
MOZ_RUNINIT static AutoWeakFrame gLastCursorSourceFrame;
static TimeStamp gLastCursorUpdateTime;
static TimeStamp gTypingStartTime;
static TimeStamp gTypingEndTime;
static int32_t gTypingInteractionKeyPresses = 0;
MOZ_RUNINIT static dom::InteractionData gTypingInteraction = {};
static inline int32_t RoundDown(double aDouble) {
return (aDouble > 0) ? static_cast<int32_t>(floor(aDouble))
: static_cast<int32_t>(ceil(aDouble));
}
static bool IsSelectingLink(nsIFrame* aTargetFrame) {
if (!aTargetFrame) {
return false;
}
const nsFrameSelection* frameSel = aTargetFrame->GetConstFrameSelection();
if (!frameSel || !frameSel->GetDragState()) {
return false;
}
if (!nsContentUtils::GetClosestLinkInFlatTree(aTargetFrame->GetContent())) {
return false;
}
return true;
}
static UniquePtr<WidgetMouseEvent> CreateMouseOrPointerWidgetEvent(
WidgetMouseEvent* aMouseEvent, EventMessage aMessage,
EventTarget* aRelatedTarget);
/**
* Returns the common ancestor for mouseup purpose, given the
* current mouseup target and the previous mousedown target.
*/
static nsINode* GetCommonAncestorForMouseUp(
nsINode* aCurrentMouseUpTarget, nsINode* aLastMouseDownTarget,
const Maybe<FormControlType>& aLastMouseDownInputControlType) {
if (!aCurrentMouseUpTarget || !aLastMouseDownTarget) {
return nullptr;
}
if (aCurrentMouseUpTarget == aLastMouseDownTarget) {
return aCurrentMouseUpTarget;
}
// Build the chain of parents
AutoTArray<nsINode*, 30> parents1;
do {
parents1.AppendElement(aCurrentMouseUpTarget);
aCurrentMouseUpTarget = aCurrentMouseUpTarget->GetFlattenedTreeParentNode();
} while (aCurrentMouseUpTarget);
AutoTArray<nsINode*, 30> parents2;
do {
parents2.AppendElement(aLastMouseDownTarget);
if (aLastMouseDownTarget == parents1.LastElement()) {
break;
}
aLastMouseDownTarget = aLastMouseDownTarget->GetFlattenedTreeParentNode();
} while (aLastMouseDownTarget);
// Find where the parent chain differs
uint32_t pos1 = parents1.Length();
uint32_t pos2 = parents2.Length();
nsINode* parent = nullptr;
for (uint32_t len = std::min(pos1, pos2); len > 0; --len) {
nsINode* child1 = parents1.ElementAt(--pos1);
nsINode* child2 = parents2.ElementAt(--pos2);
if (child1 != child2) {
break;
}
// If the input control type is different between mouseup and mousedown,
// this is not a valid click.
if (HTMLInputElement* input = HTMLInputElement::FromNodeOrNull(child1)) {
if (aLastMouseDownInputControlType.isSome() &&
aLastMouseDownInputControlType.ref() != input->ControlType()) {
break;
}
}
parent = child1;
}
return parent;
}
static bool HasNativeKeyBindings(nsIContent* aContent,
WidgetKeyboardEvent* aEvent) {
MOZ_ASSERT(aEvent->mMessage == eKeyPress);
if (!aContent) {
return false;
}
const RefPtr<dom::Element> targetElement = aContent->AsElement();
if (!targetElement) {
return false;
}
const auto type = [&]() -> Maybe<NativeKeyBindingsType> {
if (BrowserParent::GetFrom(targetElement)) {
const nsCOMPtr<nsIWidget> widget = aEvent->mWidget;
if (MOZ_UNLIKELY(!widget)) {
return Nothing();
}
widget::InputContext context = widget->GetInputContext();
return context.mIMEState.IsEditable()
? Some(context.GetNativeKeyBindingsType())
: Nothing();
}
const auto* const textControlElement =
TextControlElement::FromNode(targetElement);
if (textControlElement &&
textControlElement->IsSingleLineTextControlOrTextArea() &&
!textControlElement->IsInDesignMode()) {
return textControlElement->IsTextArea()
? Some(NativeKeyBindingsType::MultiLineEditor)
: Some(NativeKeyBindingsType::SingleLineEditor);
}
return targetElement->IsEditable()
? Some(NativeKeyBindingsType::RichTextEditor)
: Nothing();
}();
if (type.isNothing()) {
return false;
}
const nsTArray<CommandInt>& commands =
aEvent->EditCommandsConstRef(type.value());
return !commands.IsEmpty();
}
LazyLogModule sMouseBoundaryLog("MouseBoundaryEvents");
LazyLogModule sPointerBoundaryLog("PointerBoundaryEvents");
/******************************************************************/
/* mozilla::UITimerCallback */
/******************************************************************/
class UITimerCallback final : public nsITimerCallback, public nsINamed {
public:
UITimerCallback() : mPreviousCount(0) {}
NS_DECL_ISUPPORTS
NS_DECL_NSITIMERCALLBACK
NS_DECL_NSINAMED
private:
~UITimerCallback() = default;
uint32_t mPreviousCount;
};
NS_IMPL_ISUPPORTS(UITimerCallback, nsITimerCallback, nsINamed)
// If aTimer is nullptr, this method always sends "user-interaction-inactive"
// notification.
NS_IMETHODIMP
UITimerCallback::Notify(nsITimer* aTimer) {
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (!obs) return NS_ERROR_FAILURE;
if ((gMouseOrKeyboardEventCounter == mPreviousCount) || !aTimer) {
gMouseOrKeyboardEventCounter = 0;
obs->NotifyObservers(nullptr, "user-interaction-inactive", nullptr);
if (gUserInteractionTimer) {
gUserInteractionTimer->Cancel();
NS_RELEASE(gUserInteractionTimer);
}
} else {
obs->NotifyObservers(nullptr, "user-interaction-active", nullptr);
EventStateManager::UpdateUserActivityTimer();
if (XRE_IsParentProcess()) {
hal::BatteryInformation batteryInfo;
hal::GetCurrentBatteryInformation(&batteryInfo);
glean::power_battery::percentage_when_user_active.AccumulateSingleSample(
uint64_t(batteryInfo.level() * 100));
}
}
mPreviousCount = gMouseOrKeyboardEventCounter;
return NS_OK;
}
NS_IMETHODIMP
UITimerCallback::GetName(nsACString& aName) {
aName.AssignLiteral("UITimerCallback_timer");
return NS_OK;
}
/******************************************************************/
/* mozilla::OverOutElementsWrapper */
/******************************************************************/
NS_IMPL_CYCLE_COLLECTION(OverOutElementsWrapper, mDeepestEnterEventTarget,
mDispatchingOverEventTarget,
mDispatchingOutOrDeepestLeaveEventTarget)
NS_IMPL_CYCLE_COLLECTING_ADDREF(OverOutElementsWrapper)
NS_IMPL_CYCLE_COLLECTING_RELEASE(OverOutElementsWrapper)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(OverOutElementsWrapper)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
already_AddRefed<nsIWidget> OverOutElementsWrapper::GetLastOverWidget() const {
nsCOMPtr<nsIWidget> widget = do_QueryReferent(mLastOverWidget);
return widget.forget();
}
void OverOutElementsWrapper::ContentRemoved(nsIContent& aContent) {
if (!mDeepestEnterEventTarget) {
return;
}
if (!nsContentUtils::ContentIsFlattenedTreeDescendantOf(
mDeepestEnterEventTarget, &aContent)) {
return;
}
LogModule* const logModule = mType == BoundaryEventType::Mouse
? sMouseBoundaryLog
: sPointerBoundaryLog;
if (mDispatchingOverEventTarget &&
(mDeepestEnterEventTarget == mDispatchingOverEventTarget ||
nsContentUtils::ContentIsFlattenedTreeDescendantOf(
mDispatchingOverEventTarget, &aContent))) {
if (mDispatchingOverEventTarget ==
mDispatchingOutOrDeepestLeaveEventTarget) {
MOZ_LOG(logModule, LogLevel::Info,
("The dispatching \"%s\" event target (%p) is removed",
LastOverEventTargetIsOutEventTarget() ? "out" : "leave",
mDispatchingOutOrDeepestLeaveEventTarget.get()));
mDispatchingOutOrDeepestLeaveEventTarget = nullptr;
}
MOZ_LOG(logModule, LogLevel::Info,
("The dispatching \"over\" event target (%p) is removed",
mDispatchingOverEventTarget.get()));
mDispatchingOverEventTarget = nullptr;
}
if (mDispatchingOutOrDeepestLeaveEventTarget &&
(mDeepestEnterEventTarget == mDispatchingOutOrDeepestLeaveEventTarget ||
nsContentUtils::ContentIsFlattenedTreeDescendantOf(
mDispatchingOutOrDeepestLeaveEventTarget, &aContent))) {
MOZ_LOG(logModule, LogLevel::Info,
("The dispatching \"%s\" event target (%p) is removed",
LastOverEventTargetIsOutEventTarget() ? "out" : "leave",
mDispatchingOutOrDeepestLeaveEventTarget.get()));
mDispatchingOutOrDeepestLeaveEventTarget = nullptr;
}
MOZ_LOG(logModule, LogLevel::Info,
("The last \"%s\" event target (%p) is removed and now the last "
"deepest enter target becomes %s(%p)",
LastOverEventTargetIsOutEventTarget() ? "over" : "enter",
mDeepestEnterEventTarget.get(),
aContent.GetFlattenedTreeParent()
? ToString(*aContent.GetFlattenedTreeParent()).c_str()
: "nullptr",
aContent.GetFlattenedTreeParent()));
UpdateDeepestEnterEventTarget(aContent.GetFlattenedTreeParent());
}
void OverOutElementsWrapper::TryToRestorePendingRemovedOverTarget(
const WidgetEvent* aEvent) {
if (!MaybeHasPendingRemovingOverEventTarget()) {
return;
}
LogModule* const logModule = mType == BoundaryEventType::Mouse
? sMouseBoundaryLog
: sPointerBoundaryLog;
// If we receive a mouse event immediately, let's try to restore the last
// "over" event target as the following "out" event target. We assume that a
// synthesized mousemove or another mouse event is being dispatched at latest
// the next animation frame from the removal. However, synthesized mouse move
// which is enqueued by ContentRemoved() may not sent to this instance because
// the target is considered with the latest layout, so the document of this
// instance may be moved somewhere before the next animation frame.
// Therefore, we should not restore the last "over" target if we receive an
// unexpected event like a keyboard event, a wheel event, etc.
if (aEvent->AsMouseEvent()) {
// Restore the original "over" event target should be allowed only when it's
// reconnected under the last deepest "enter" event target because we need
// to dispatch "leave" events later at least on the ancestors which have
// never been removed from the tree.
// XXX If new ancestor is inserted between mDeepestEnterEventTarget and
// mPendingToRemoveLastOverEventTarget, we will dispatch "leave" event even
// though we have not dispatched "enter" event on the element. For fixing
// this, we need to store the full path of the last "out" event target when
// it's removed from the tree. I guess we can be relax for this issue
// because this hack is required for web apps which reconnect the target
// to the same position immediately.
// XXX Should be IsInclusiveFlatTreeDescendantOf()? However, it may
// be reconnected into a subtree which is different from where the
// last over element was.
nsCOMPtr<nsIContent> pendingRemovingOverEventTarget =
GetPendingRemovingOverEventTarget();
if (pendingRemovingOverEventTarget &&
pendingRemovingOverEventTarget->IsInclusiveDescendantOf(
mDeepestEnterEventTarget)) {
// StoreOverEventTargetAndDeepestEnterEventTarget() always resets
// mLastOverWidget. When we restore the pending removing "over" event
// target, we need to keep storing the original "over" widget too.
nsCOMPtr<nsIWeakReference> widget = std::move(mLastOverWidget);
StoreOverEventTargetAndDeepestEnterEventTarget(
pendingRemovingOverEventTarget);
mLastOverWidget = std::move(widget);
MOZ_LOG(logModule, LogLevel::Info,
("The \"over\" event target (%p) is restored",
mDeepestEnterEventTarget.get()));
return;
}
MOZ_LOG(logModule, LogLevel::Debug,
("Forgetting the last \"over\" event target (%p) because it is not "
"reconnected under the deepest enter event target (%p)",
mPendingRemovingOverEventTarget.get(),
mDeepestEnterEventTarget.get()));
} else {
MOZ_LOG(logModule, LogLevel::Debug,
("Forgetting the last \"over\" event target (%p) because an "
"unexpected event (%s) is being dispatched, that means that "
"EventStateManager didn't receive a synthesized mousemove which "
"should be dispatched at next animation frame from the removal",
mPendingRemovingOverEventTarget.get(), ToChar(aEvent->mMessage)));
}
// Now, we should not restore mPendingRemovingOverEventTarget to
// mDeepestEnterEventTarget anymore since mPendingRemovingOverEventTarget was
// moved outside the subtree of mDeepestEnterEventTarget.
mPendingRemovingOverEventTarget = nullptr;
}
void OverOutElementsWrapper::WillDispatchOverAndEnterEvent(
nsIContent* aOverEventTarget) {
StoreOverEventTargetAndDeepestEnterEventTarget(aOverEventTarget);
// Store the first "over" event target we fire and don't refire "over" event
// to that element while the first "over" event is still ongoing.
mDispatchingOverEventTarget = aOverEventTarget;
}
void OverOutElementsWrapper::DidDispatchOverAndEnterEvent(
nsIContent* aOriginalOverTargetInComposedDoc,
nsIWidget* aOverEventTargetWidget) {
mDispatchingOverEventTarget = nullptr;
mLastOverWidget = do_GetWeakReference(aOverEventTargetWidget);
// Pointer Events define that once the `pointerover` event target is removed
// from the tree, `pointerout` should not be fired on that and the closest
// connected ancestor at the target removal should be kept as the deepest
// `pointerleave` target. Therefore, we don't need the special handling for
// `pointerout` event target if the last `pointerover` target is temporarily
// removed from the tree.
if (mType == OverOutElementsWrapper::BoundaryEventType::Pointer) {
return;
}
// Assume that the caller checks whether aOriginalOverTarget is in the
// original document. If we don't enable the strict mouse/pointer event
// boundary event dispatching by the pref (see below),
// mDeepestEnterEventTarget is set to nullptr when the last "over" target is
// removed. Therefore, we cannot check whether aOriginalOverTarget is in the
// original document here.
if (!aOriginalOverTargetInComposedDoc) {
return;
}
MOZ_ASSERT_IF(mDeepestEnterEventTarget,
mDeepestEnterEventTarget->GetComposedDoc() ==
aOriginalOverTargetInComposedDoc->GetComposedDoc());
// If the "mouseover" event target is removed temporarily while we're
// dispatching "mouseover" and "mouseenter" events and the target gets back
// under the deepest enter event target, we should restore the "mouseover"
// target.
if (!LastOverEventTargetIsOutEventTarget() && mDeepestEnterEventTarget &&
nsContentUtils::ContentIsFlattenedTreeDescendantOf(
aOriginalOverTargetInComposedDoc, mDeepestEnterEventTarget)) {
StoreOverEventTargetAndDeepestEnterEventTarget(
aOriginalOverTargetInComposedDoc);
LogModule* const logModule = mType == BoundaryEventType::Mouse
? sMouseBoundaryLog
: sPointerBoundaryLog;
MOZ_LOG(logModule, LogLevel::Info,
("The \"over\" event target (%p) is restored",
mDeepestEnterEventTarget.get()));
}
}
void OverOutElementsWrapper::StoreOverEventTargetAndDeepestEnterEventTarget(
nsIContent* aOverEventTargetAndDeepestEnterEventTarget) {
mDeepestEnterEventTarget = aOverEventTargetAndDeepestEnterEventTarget;
mPendingRemovingOverEventTarget = nullptr;
mDeepestEnterEventTargetIsOverEventTarget = !!mDeepestEnterEventTarget;
mLastOverWidget = nullptr; // Set it after dispatching the "over" event.
}
void OverOutElementsWrapper::UpdateDeepestEnterEventTarget(
nsIContent* aDeepestEnterEventTarget) {
if (MOZ_UNLIKELY(mDeepestEnterEventTarget == aDeepestEnterEventTarget)) {
return;
}
if (!aDeepestEnterEventTarget) {
// If the root element is removed, we don't need to dispatch "leave"
// events on any elements. Therefore, we can forget everything.
StoreOverEventTargetAndDeepestEnterEventTarget(nullptr);
return;
}
if (LastOverEventTargetIsOutEventTarget()) {
MOZ_ASSERT(mDeepestEnterEventTarget);
if (mType == BoundaryEventType::Pointer) {
// The spec of Pointer Events defines that once the `pointerover` event
// target is removed from the tree, `pointerout` should not be fired on
// that and the closest connected ancestor at the target removal should be
// kept as the deepest `pointerleave` target. All browsers considers the
// last `pointerover` event target is removed immediately when it occurs.
// Therefore, we don't need the special handling which we do for the
// `mouseout` event target below for considering whether we'll dispatch
// `pointerout` on the last `pointerover` target.
mPendingRemovingOverEventTarget = nullptr;
} else if (
!StaticPrefs::
dom_event_mouse_boundary_restore_last_over_target_from_temporary_removal()) {
// The spec of UI Events do not define that browsers should keep storing
// the last `mouseover` target when it's removed temporarily and
// reconnected immediately. We've decided to follow Chrome's behavior for
// now. However, there is a pref to bring back the old behavior if
// needed.
mPendingRemovingOverEventTarget = nullptr;
} else {
// However, Safari and old Chrome restore the last `mouseover` target when
// it's temporarily removed and reconnected immediately. Therefore, we
// should follow them by default. However, we should keep the old
// behavior for making it easier to backout the new behavior with
// disabling the pref.
MOZ_ASSERT(!mPendingRemovingOverEventTarget);
MOZ_ASSERT(mDeepestEnterEventTarget);
mPendingRemovingOverEventTarget =
do_GetWeakReference(mDeepestEnterEventTarget);
}
} else {
MOZ_ASSERT(!mDeepestEnterEventTargetIsOverEventTarget);
// If mDeepestEnterEventTarget is not the last "over" event target, we've
// already done the complicated state managing above. Therefore, we only
// need to update mDeepestEnterEventTarget in this case.
}
mDeepestEnterEventTarget = aDeepestEnterEventTarget;
mDeepestEnterEventTargetIsOverEventTarget = false;
// Do not update mLastOverWidget here because it's required to ignore some
// following pointer events which are fired on widget under different top
// level widget.
}
/******************************************************************/
/* mozilla::EventStateManager */
/******************************************************************/
static uint32_t sESMInstanceCount = 0;
bool EventStateManager::sNormalLMouseEventInProcess = false;
int16_t EventStateManager::sCurrentMouseBtn = MouseButton::eNotPressed;
EventStateManager* EventStateManager::sActiveESM = nullptr;
EventStateManager* EventStateManager::sCursorSettingManager = nullptr;
MOZ_RUNINIT AutoWeakFrame EventStateManager::sLastDragOverFrame = nullptr;
LayoutDeviceIntPoint EventStateManager::sPreLockScreenPoint =
LayoutDeviceIntPoint(0, 0);
LayoutDeviceIntPoint EventStateManager::sLastRefPoint = kInvalidRefPoint;
CSSIntPoint EventStateManager::sLastScreenPoint = CSSIntPoint(0, 0);
LayoutDeviceIntPoint EventStateManager::sSynthCenteringPoint = kInvalidRefPoint;
CSSIntPoint EventStateManager::sLastClientPoint = CSSIntPoint(0, 0);
MOZ_RUNINIT nsCOMPtr<nsIContent> EventStateManager::sDragOverContent = nullptr;
EventStateManager::WheelPrefs* EventStateManager::WheelPrefs::sInstance =
nullptr;
EventStateManager::DeltaAccumulator*
EventStateManager::DeltaAccumulator::sInstance = nullptr;
constexpr const StyleCursorKind kInvalidCursorKind =
static_cast<StyleCursorKind>(255);
EventStateManager::EventStateManager()
: mLockCursor(kInvalidCursorKind),
mCurrentTarget(nullptr),
// init d&d gesture state machine variables
mGestureDownPoint(0, 0),
mGestureModifiers(0),
mGestureDownButtons(0),
mGestureDownButton(0),
mPresContext(nullptr),
mShouldAlwaysUseLineDeltas(false),
mShouldAlwaysUseLineDeltasInitialized(false),
mGestureDownInTextControl(false),
mInTouchDrag(false),
m_haveShutdown(false) {
if (sESMInstanceCount == 0) {
gUserInteractionTimerCallback = new UITimerCallback();
if (gUserInteractionTimerCallback) NS_ADDREF(gUserInteractionTimerCallback);
UpdateUserActivityTimer();
}
++sESMInstanceCount;
}
// static
LazyLogModule& EventStateManager::MouseCursorUpdateLogRef() {
return gMouseCursorUpdates;
}
nsresult EventStateManager::UpdateUserActivityTimer() {
if (!gUserInteractionTimerCallback) return NS_OK;
if (!gUserInteractionTimer) {
gUserInteractionTimer = NS_NewTimer().take();
}
if (gUserInteractionTimer) {
gUserInteractionTimer->InitWithCallback(
gUserInteractionTimerCallback,
StaticPrefs::dom_events_user_interaction_interval(),
nsITimer::TYPE_ONE_SHOT);
}
return NS_OK;
}
nsresult EventStateManager::Init() {
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (!observerService) return NS_ERROR_FAILURE;
observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
return NS_OK;
}
bool EventStateManager::ShouldAlwaysUseLineDeltas() {
if (MOZ_UNLIKELY(!mShouldAlwaysUseLineDeltasInitialized)) {
mShouldAlwaysUseLineDeltasInitialized = true;
mShouldAlwaysUseLineDeltas =
!StaticPrefs::dom_event_wheel_deltaMode_lines_disabled();
if (!mShouldAlwaysUseLineDeltas && mDocument) {
if (nsIPrincipal* principal =
mDocument->GetPrincipalForPrefBasedHacks()) {
mShouldAlwaysUseLineDeltas = principal->IsURIInPrefList(
"dom.event.wheel-deltaMode-lines.always-enabled");
}
}
}
return mShouldAlwaysUseLineDeltas;
}
EventStateManager::~EventStateManager() {
ReleaseCurrentIMEContentObserver();
if (sActiveESM == this) {
sActiveESM = nullptr;
}
if (StaticPrefs::ui_click_hold_context_menus()) {
KillClickHoldTimer();
}
if (sCursorSettingManager == this) {
sCursorSettingManager = nullptr;
}
--sESMInstanceCount;
if (sESMInstanceCount == 0) {
WheelTransaction::Shutdown();
if (gUserInteractionTimerCallback) {
gUserInteractionTimerCallback->Notify(nullptr);
NS_RELEASE(gUserInteractionTimerCallback);
}
if (gUserInteractionTimer) {
gUserInteractionTimer->Cancel();
NS_RELEASE(gUserInteractionTimer);
}
WheelPrefs::Shutdown();
DeltaAccumulator::Shutdown();
}
if (sDragOverContent && sDragOverContent->OwnerDoc() == mDocument) {
sDragOverContent = nullptr;
}
if (!m_haveShutdown) {
Shutdown();
// Don't remove from Observer service in Shutdown because Shutdown also
// gets called from xpcom shutdown observer. And we don't want to remove
// from the service in that case.
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
observerService->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
}
}
}
nsresult EventStateManager::Shutdown() {
m_haveShutdown = true;
return NS_OK;
}
NS_IMETHODIMP
EventStateManager::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* someData) {
if (!nsCRT::strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
Shutdown();
}
return NS_OK;
}
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(EventStateManager)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIObserver)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(EventStateManager)
NS_IMPL_CYCLE_COLLECTING_RELEASE(EventStateManager)
NS_IMPL_CYCLE_COLLECTION_WEAK(EventStateManager, mCurrentTargetContent,
mGestureDownContent, mGestureDownFrameOwner,
mLastLeftMouseDownInfo.mLastMouseDownContent,
mLastMiddleMouseDownInfo.mLastMouseDownContent,
mLastRightMouseDownInfo.mLastMouseDownContent,
mActiveContent, mHoverContent, mURLTargetContent,
mPopoverPointerDownTarget, mMouseEnterLeaveHelper,
mPointersEnterLeaveHelper, mDocument,
mIMEContentObserver, mAccessKeys)
void EventStateManager::ReleaseCurrentIMEContentObserver() {
if (mIMEContentObserver) {
mIMEContentObserver->DisconnectFromEventStateManager();
}
mIMEContentObserver = nullptr;
}
void EventStateManager::OnStartToObserveContent(
IMEContentObserver* aIMEContentObserver) {
if (mIMEContentObserver == aIMEContentObserver) {
return;
}
ReleaseCurrentIMEContentObserver();
mIMEContentObserver = aIMEContentObserver;
}
void EventStateManager::OnStopObservingContent(
IMEContentObserver* aIMEContentObserver) {
aIMEContentObserver->DisconnectFromEventStateManager();
NS_ENSURE_TRUE_VOID(mIMEContentObserver == aIMEContentObserver);
mIMEContentObserver = nullptr;
}
void EventStateManager::TryToFlushPendingNotificationsToIME() {
if (mIMEContentObserver) {
mIMEContentObserver->TryToFlushPendingNotifications(true);
}
}
static bool IsMessageMouseUserActivity(EventMessage aMessage) {
return aMessage == eMouseMove || aMessage == eMouseUp ||
aMessage == eMouseDown || aMessage == ePointerAuxClick ||
aMessage == eMouseDoubleClick || aMessage == ePointerClick ||
aMessage == eMouseActivate || aMessage == eMouseLongTap;
}
static bool IsMessageGamepadUserActivity(EventMessage aMessage) {
return aMessage == eGamepadButtonDown || aMessage == eGamepadButtonUp ||
aMessage == eGamepadAxisMove;
}
// static
bool EventStateManager::IsKeyboardEventUserActivity(WidgetEvent* aEvent) {
// We ignore things that shouldn't cause popups, but also things that look
// like shortcut presses. In some obscure cases these may actually be
// website input, but any meaningful website will have other input anyway,
// and we can't very well tell whether shortcut input was supposed to be
// directed at chrome or the document.
WidgetKeyboardEvent* keyEvent = aEvent->AsKeyboardEvent();
// Access keys should be treated as page interaction.
if (keyEvent->ModifiersMatchWithAccessKey(AccessKeyType::eContent)) {
return true;
}
if (!keyEvent->CanTreatAsUserInput() || keyEvent->IsControl() ||
keyEvent->IsMeta() || keyEvent->IsAlt()) {
return false;
}
// Deal with function keys:
switch (keyEvent->mKeyNameIndex) {
case KEY_NAME_INDEX_F1:
case KEY_NAME_INDEX_F2:
case KEY_NAME_INDEX_F3:
case KEY_NAME_INDEX_F4:
case KEY_NAME_INDEX_F5:
case KEY_NAME_INDEX_F6:
case KEY_NAME_INDEX_F7:
case KEY_NAME_INDEX_F8:
case KEY_NAME_INDEX_F9:
case KEY_NAME_INDEX_F10:
case KEY_NAME_INDEX_F11:
case KEY_NAME_INDEX_F12:
case KEY_NAME_INDEX_F13:
case KEY_NAME_INDEX_F14:
case KEY_NAME_INDEX_F15:
case KEY_NAME_INDEX_F16:
case KEY_NAME_INDEX_F17:
case KEY_NAME_INDEX_F18:
case KEY_NAME_INDEX_F19:
case KEY_NAME_INDEX_F20:
case KEY_NAME_INDEX_F21:
case KEY_NAME_INDEX_F22:
case KEY_NAME_INDEX_F23:
case KEY_NAME_INDEX_F24:
return false;
default:
return true;
}
}
static void OnTypingInteractionEnded() {
// We don't consider a single keystroke to be typing.
if (gTypingInteractionKeyPresses > 1) {
gTypingInteraction.mInteractionCount += gTypingInteractionKeyPresses;
gTypingInteraction.mInteractionTimeInMilliseconds += static_cast<uint32_t>(
std::ceil((gTypingEndTime - gTypingStartTime).ToMilliseconds()));
}
gTypingInteractionKeyPresses = 0;
gTypingStartTime = TimeStamp();
gTypingEndTime = TimeStamp();
}
static void HandleKeyUpInteraction(WidgetKeyboardEvent* aKeyEvent) {
if (EventStateManager::IsKeyboardEventUserActivity(aKeyEvent)) {
TimeStamp now = TimeStamp::Now();
if (gTypingEndTime.IsNull()) {
gTypingEndTime = now;
}
TimeDuration delay = now - gTypingEndTime;
// Has it been too long since the last keystroke to be considered typing?
if (gTypingInteractionKeyPresses > 0 &&
delay >
TimeDuration::FromMilliseconds(
StaticPrefs::browser_places_interactions_typing_timeout_ms())) {
OnTypingInteractionEnded();
}
gTypingInteractionKeyPresses++;
if (gTypingStartTime.IsNull()) {
gTypingStartTime = now;
}
gTypingEndTime = now;
}
}
nsresult EventStateManager::PreHandleEvent(nsPresContext* aPresContext,
WidgetEvent* aEvent,
nsIFrame* aTargetFrame,
nsIContent* aTargetContent,
nsEventStatus* aStatus,
nsIContent* aOverrideClickTarget) {
AUTO_PROFILER_LABEL("EventStateManager::PreHandleEvent", DOM);
NS_ENSURE_ARG_POINTER(aStatus);
NS_ENSURE_ARG(aPresContext);
if (!aEvent) {
NS_ERROR("aEvent is null. This should never happen.");
return NS_ERROR_NULL_POINTER;
}
NS_WARNING_ASSERTION(
!aTargetFrame || !aTargetFrame->GetContent() ||
aTargetFrame->GetContent() == aTargetContent ||
aTargetFrame->GetContent()->GetFlattenedTreeParent() ==
aTargetContent ||
aTargetFrame->IsGeneratedContentFrame(),
"aTargetFrame should be related with aTargetContent");
#if DEBUG
if (aTargetFrame && aTargetFrame->IsGeneratedContentFrame()) {
MOZ_ASSERT(aTargetContent == aTargetFrame->GetContentForEvent(aEvent),
"Unexpected target for generated content frame!");
}
#endif
mCurrentTarget = aTargetFrame;
mCurrentTargetContent = nullptr;
// Do not take account eMouseEnterIntoWidget/ExitFromWidget so that loading
// a page when user is not active doesn't change the state to active.
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
if (aEvent->IsTrusted() &&
((mouseEvent && mouseEvent->IsReal() &&
IsMessageMouseUserActivity(mouseEvent->mMessage)) ||
aEvent->mClass == eWheelEventClass ||
aEvent->mClass == ePointerEventClass ||
aEvent->mClass == eTouchEventClass ||
aEvent->mClass == eKeyboardEventClass ||
(aEvent->mClass == eDragEventClass && aEvent->mMessage == eDrop) ||
IsMessageGamepadUserActivity(aEvent->mMessage))) {
if (gMouseOrKeyboardEventCounter == 0) {
nsCOMPtr<nsIObserverService> obs =
mozilla::services::GetObserverService();
if (obs) {
obs->NotifyObservers(nullptr, "user-interaction-active", nullptr);
UpdateUserActivityTimer();
}
}
++gMouseOrKeyboardEventCounter;
nsCOMPtr<nsINode> node = aTargetContent;
if (node &&
((aEvent->mMessage == eKeyUp && IsKeyboardEventUserActivity(aEvent)) ||
aEvent->mMessage == eMouseUp || aEvent->mMessage == eWheel ||
aEvent->mMessage == eTouchEnd || aEvent->mMessage == ePointerUp ||
aEvent->mMessage == eDrop)) {
Document* doc = node->OwnerDoc();
while (doc) {
doc->SetUserHasInteracted();
doc = nsContentUtils::IsChildOfSameType(doc)
? doc->GetInProcessParentDocument()
: nullptr;
}
}
}
WheelTransaction::OnEvent(aEvent);
// Focus events don't necessarily need a frame.
if (!mCurrentTarget && !aTargetContent) {
NS_ERROR("mCurrentTarget and aTargetContent are null");
return NS_ERROR_NULL_POINTER;
}
#ifdef DEBUG
if (aEvent->HasDragEventMessage() && PointerLockManager::IsLocked()) {
NS_ASSERTION(PointerLockManager::IsLocked(),
"Pointer is locked. Drag events should be suppressed when "
"the pointer is locked.");
}
#endif
// Store last known screenPoint and clientPoint so pointer lock
// can use these values as constants.
if (aEvent->IsTrusted() &&
((mouseEvent && mouseEvent->IsReal()) ||
aEvent->mClass == eWheelEventClass) &&
!PointerLockManager::IsLocked()) {
// XXX Probably doesn't matter much, but storing these in CSS pixels instead
// of device pixels means behavior can be a bit odd if you zoom while
// pointer-locked.
sLastScreenPoint = RoundedToInt(
Event::GetScreenCoords(aPresContext, aEvent, aEvent->mRefPoint)
.extract());
sLastClientPoint = RoundedToInt(Event::GetClientCoords(
aPresContext, aEvent, aEvent->mRefPoint, CSSDoublePoint{0, 0}));
}
*aStatus = nsEventStatus_eIgnore;
if (aEvent->mClass == eQueryContentEventClass) {
HandleQueryContentEvent(aEvent->AsQueryContentEvent());
return NS_OK;
}
WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent();
if (touchEvent && mInTouchDrag) {
if (touchEvent->mMessage == eTouchMove) {
GenerateDragGesture(aPresContext, touchEvent);
} else {
MOZ_ASSERT(touchEvent->mMessage != eTouchRawUpdate);
mInTouchDrag = false;
StopTrackingDragGesture(true);
}
}
if (mMouseEnterLeaveHelper && aEvent->IsTrusted()) {
// When the last `mouseover` event target is removed from the document,
// we makes mMouseEnterLeaveHelper update the last deepest `mouseenter`
// event target to the removed node parent and mark it as not the following
// `mouseout` event target. However, the other browsers may dispatch
// `mouseout` on it if it's restored "immediately". Therefore, we use
// the next animation frame as the deadline. ContentRemoved() enqueues a
// synthesized `mousemove` to dispatch mouse boundary events under the
// mouse cursor soon and the synthesized event (or eMouseExitFromWidget if
// our window is moved) will reach here at latest the next animation frame.
// Therefore, we can use the event as the deadline. If the removed last
// `mouseover` target is reconnected before a synthesized mouse event or
// a real mouse event, let's restore it as the following `mouseout` event
// target. Otherwise, e.g., a keyboard event, let's forget it.
mMouseEnterLeaveHelper->TryToRestorePendingRemovedOverTarget(aEvent);
}
static constexpr auto const allowSynthesisForTests = []() -> bool {
nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1");
return dragService &&
!dragService->GetNeverAllowSessionIsSynthesizedForTests();
};
switch (aEvent->mMessage) {
case eContextMenu:
if (PointerLockManager::IsLocked()) {
return NS_ERROR_DOM_INVALID_STATE_ERR;
}
break;
case eMouseTouchDrag:
mInTouchDrag = true;
BeginTrackingDragGesture(aPresContext, mouseEvent, aTargetFrame);
break;
case eMouseDown: {
switch (mouseEvent->mButton) {
case MouseButton::ePrimary:
BeginTrackingDragGesture(aPresContext, mouseEvent, aTargetFrame);
mLastLeftMouseDownInfo.mClickCount = mouseEvent->mClickCount;
PrepareForFollowingClickEvent(*mouseEvent);
sNormalLMouseEventInProcess = true;
break;
case MouseButton::eMiddle:
mLastMiddleMouseDownInfo.mClickCount = mouseEvent->mClickCount;
PrepareForFollowingClickEvent(*mouseEvent);
break;
case MouseButton::eSecondary:
mLastRightMouseDownInfo.mClickCount = mouseEvent->mClickCount;
PrepareForFollowingClickEvent(*mouseEvent);
break;
case MouseButton::eX1:
case MouseButton::eX2:
// XXX FIXME: We won't dispatch `auxclick` for 4th nor 5th button.
break;
default:
break;
}
break;
}
case eMouseUp: {
switch (mouseEvent->mButton) {
case MouseButton::ePrimary:
if (StaticPrefs::ui_click_hold_context_menus()) {
KillClickHoldTimer();
}
mInTouchDrag = false;
StopTrackingDragGesture(true);
sNormalLMouseEventInProcess = false;
// then fall through...
[[fallthrough]];
case MouseButton::eSecondary:
case MouseButton::eMiddle: {
RefPtr<EventStateManager> esm =
ESMFromContentOrThis(aOverrideClickTarget);
esm->PrepareForFollowingClickEvent(*mouseEvent, aOverrideClickTarget);
break;
}
case MouseButton::eX1:
case MouseButton::eX2:
// XXX FIXME: We won't dispatch `auxclick` for 4th nor 5th button.
break;
default:
break;
}
break;
}
case eMouseEnterIntoWidget:
PointerEventHandler::UpdatePointerActiveState(mouseEvent, aTargetContent);
// In some cases on e10s eMouseEnterIntoWidget
// event was sent twice into child process of content.
// (From specific widget code (sending is not permanent) and
// from ESM::DispatchMouseOrPointerBoundaryEvent (sending is permanent)).
// IsCrossProcessForwardingStopped() helps to suppress sending accidental
// event from widget code.
aEvent->StopCrossProcessForwarding();
break;
case eMouseExitFromWidget:
// If this is a remote frame, we receive eMouseExitFromWidget from the
// parent the mouse exits our content. Since the parent may update the
// cursor while the mouse is outside our frame, and since PuppetWidget
// caches the current cursor internally, re-entering our content (say from
// over a window edge) wont update the cursor if the cached value and the
// current cursor match. So when the mouse exits a remote frame, clear the
// cached widget cursor so a proper update will occur when the mouse
// re-enters.
if (XRE_IsContentProcess()) {
ClearCachedWidgetCursor(mCurrentTarget);
}
// IsCrossProcessForwardingStopped() helps to suppress double event
// sending into process of content. For more information see comment
// above, at eMouseEnterIntoWidget case.
aEvent->StopCrossProcessForwarding();
// If the event is not a top-level window or puppet widget exit, then it's
// not really an exit --- we may have traversed widget boundaries but
// we're still in our toplevel window or puppet widget.
if (mouseEvent->mExitFrom.value() !=
WidgetMouseEvent::ePlatformTopLevel &&
mouseEvent->mExitFrom.value() != WidgetMouseEvent::ePuppet) {
// Treat it as a synthetic move so we don't generate spurious
// "exit" or "move" events. Any necessary "out" or "over" events
// will be generated by GenerateMouseEnterExit
mouseEvent->mMessage = eMouseMove;
mouseEvent->mReason = WidgetMouseEvent::eSynthesized;
// then fall through...
} else {
MOZ_ASSERT_IF(XRE_IsParentProcess(),
mouseEvent->mExitFrom.value() ==
WidgetMouseEvent::ePlatformTopLevel);
MOZ_ASSERT_IF(XRE_IsContentProcess(), mouseEvent->mExitFrom.value() ==
WidgetMouseEvent::ePuppet);
// We should synthetize corresponding pointer events
GeneratePointerEnterExit(ePointerLeave, mouseEvent);
GenerateMouseEnterExit(mouseEvent);
// Remove the pointer from the active pointerId table.
PointerEventHandler::UpdatePointerActiveState(mouseEvent);
// This is really an exit and should stop here
aEvent->mMessage = eVoidEvent;
break;
}
[[fallthrough]];
case ePointerDown:
if (aEvent->mMessage == ePointerDown) {
PointerEventHandler::UpdatePointerActiveState(mouseEvent,
aTargetContent);
PointerEventHandler::ImplicitlyCapturePointer(aTargetFrame, aEvent);
// https://html.spec.whatwg.org/multipage/interaction.html#activation-triggering-input-event
if (mouseEvent->mInputSource == MouseEvent_Binding::MOZ_SOURCE_MOUSE) {
NotifyTargetUserActivation(aEvent, aTargetContent);
}
LightDismissOpenPopovers(aEvent, aTargetContent);
LightDismissOpenDialogs(aEvent, aTargetContent);
}
[[fallthrough]];
case eMouseMove:
case ePointerMove:
case ePointerRawUpdate: {
if (aEvent->mMessage == ePointerMove) {
PointerEventHandler::UpdatePointerActiveState(mouseEvent,
aTargetContent);
}
if (!mInTouchDrag &&
PointerEventHandler::IsDragAndDropEnabled(*mouseEvent)) {
GenerateDragGesture(aPresContext, mouseEvent);
}
// on the Mac, GenerateDragGesture() may not return until the drag
// has completed and so |aTargetFrame| may have been deleted (moving
// a bookmark, for example). If this is the case, however, we know
// that ClearFrameRefs() has been called and it cleared out
// |mCurrentTarget|. As a result, we should pass |mCurrentTarget|
// into UpdateCursor().
UpdateCursor(aPresContext, mouseEvent, mCurrentTarget, aStatus);
UpdateLastRefPointOfMouseEvent(mouseEvent);
if (PointerLockManager::IsLocked()) {
ResetPointerToWindowCenterWhilePointerLocked(mouseEvent);
}
UpdateLastPointerPosition(mouseEvent);
GenerateMouseEnterExit(mouseEvent);
// Flush pending layout changes, so that later mouse move events
// will go to the right nodes.
FlushLayout(aPresContext);
break;
}
case ePointerUp:
LightDismissOpenPopovers(aEvent, aTargetContent);
LightDismissOpenDialogs(aEvent, aTargetContent);
GenerateMouseEnterExit(mouseEvent);
if (mouseEvent->mInputSource != MouseEvent_Binding::MOZ_SOURCE_MOUSE) {
NotifyTargetUserActivation(aEvent, aTargetContent);
}
break;
case ePointerGotCapture:
GenerateMouseEnterExit(mouseEvent);
break;
case eDragStart:
if (StaticPrefs::ui_click_hold_context_menus()) {
// an external drag gesture event came in, not generated internally
// by Gecko. Make sure we get rid of the click-hold timer.
KillClickHoldTimer();
}
break;
case eDragOver: {
WidgetDragEvent* dragEvent = aEvent->AsDragEvent();
MOZ_ASSERT(dragEvent);
if (dragEvent->mFlags.mIsSynthesizedForTests &&
allowSynthesisForTests()) {
dragEvent->InitDropEffectForTests();
}
// Send the enter/exit events before eDrop.
GenerateDragDropEnterExit(aPresContext, dragEvent);
break;
}
case eDrop: {
if (aEvent->mFlags.mIsSynthesizedForTests && allowSynthesisForTests()) {
MOZ_ASSERT(aEvent->AsDragEvent());
aEvent->AsDragEvent()->InitDropEffectForTests();
}
break;
}
case eKeyPress: {
WidgetKeyboardEvent* keyEvent = aEvent->AsKeyboardEvent();
if ((keyEvent->ModifiersMatchWithAccessKey(AccessKeyType::eChrome) ||
keyEvent->ModifiersMatchWithAccessKey(AccessKeyType::eContent)) &&
// If the key binding of this event is a native key binding, we
// prioritize it.
!HasNativeKeyBindings(aTargetContent, keyEvent)) {
// If the eKeyPress event will be sent to a remote process, this
// process needs to wait reply from the remote process for checking if
// preceding eKeyDown event is consumed. If preceding eKeyDown event
// is consumed in the remote process, BrowserChild won't send the event
// back to this process. So, only when this process receives a reply
// eKeyPress event in BrowserParent, we should handle accesskey in this
// process.
if (IsTopLevelRemoteTarget(GetFocusedElement())) {
// However, if there is no accesskey target for the key combination,
// we don't need to wait reply from the remote process. Otherwise,
// Mark the event as waiting reply from remote process and stop
// propagation in this process.
if (CheckIfEventMatchesAccessKey(keyEvent, aPresContext)) {
keyEvent->StopPropagation();
keyEvent->MarkAsWaitingReplyFromRemoteProcess();
}
}
// If the event target is in this process, we can handle accesskey now
// since if preceding eKeyDown event was consumed, eKeyPress event
// won't be dispatched by widget. So, coming eKeyPress event means
// that the preceding eKeyDown event wasn't consumed in this case.
else {
AutoTArray<uint32_t, 10> accessCharCodes;
keyEvent->GetAccessKeyCandidates(accessCharCodes);
if (HandleAccessKey(keyEvent, aPresContext, accessCharCodes)) {
*aStatus = nsEventStatus_eConsumeNoDefault;
}
}
}
}
// then fall through...
[[fallthrough]];
case eKeyDown:
if (aEvent->mMessage == eKeyDown) {
NotifyTargetUserActivation(aEvent, aTargetContent);
}
[[fallthrough]];
case eKeyUp: {
Element* element = GetFocusedElement();
if (element) {
mCurrentTargetContent = element;
}
// NOTE: Don't refer TextComposition::IsComposing() since UI Events
// defines that KeyboardEvent.isComposing is true when it's
// dispatched after compositionstart and compositionend.
// TextComposition::IsComposing() is false even before
// compositionend if there is no composing string.
// And also don't expose other document's composition state.
// A native IME context is typically shared by multiple documents.
// So, don't use GetTextCompositionFor(nsIWidget*) here.
RefPtr<TextComposition> composition =
IMEStateManager::GetTextCompositionFor(aPresContext);
aEvent->AsKeyboardEvent()->mIsComposing = !!composition;
// Widget may need to perform default action for specific keyboard
// event if it's not consumed. In this case, widget has already marked
// the event as "waiting reply from remote process". However, we need
// to reset it if the target (focused content) isn't in a remote process
// because PresShell needs to check if it's marked as so before
// dispatching events into the DOM tree.
if (aEvent->IsWaitingReplyFromRemoteProcess() &&
!aEvent->PropagationStopped() && !IsTopLevelRemoteTarget(element)) {
aEvent->ResetWaitingReplyFromRemoteProcessState();
}
} break;
case eWheel:
case eWheelOperationStart:
case eWheelOperationEnd: {
NS_ASSERTION(aEvent->IsTrusted(),
"Untrusted wheel event shouldn't be here");
using DeltaModeCheckingState = WidgetWheelEvent::DeltaModeCheckingState;
if (Element* element = GetFocusedElement()) {
mCurrentTargetContent = element;
}
if (aEvent->mMessage != eWheel) {
break;
}
WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent();
WheelPrefs::GetInstance()->ApplyUserPrefsToDelta(wheelEvent);
// If we won't dispatch a DOM event for this event, nothing to do anymore.
if (!wheelEvent->IsAllowedToDispatchDOMEvent()) {
break;
}
if (StaticPrefs::dom_event_wheel_deltaMode_lines_always_disabled()) {
wheelEvent->mDeltaModeCheckingState = DeltaModeCheckingState::Unchecked;
} else if (ShouldAlwaysUseLineDeltas()) {
wheelEvent->mDeltaModeCheckingState = DeltaModeCheckingState::Checked;
} else {
wheelEvent->mDeltaModeCheckingState = DeltaModeCheckingState::Unknown;
}
// Init lineOrPageDelta values for line scroll events for some devices
// on some platforms which might dispatch wheel events which don't
// have lineOrPageDelta values. And also, if delta values are
// customized by prefs, this recomputes them.
DeltaAccumulator::GetInstance()->InitLineOrPageDelta(aTargetFrame, this,
wheelEvent);
} break;
case eSetSelection: {
RefPtr<Element> focuedElement = GetFocusedElement();
IMEStateManager::HandleSelectionEvent(aPresContext, focuedElement,
aEvent->AsSelectionEvent());
break;
}
case eContentCommandCut:
case eContentCommandCopy:
case eContentCommandPaste:
case eContentCommandDelete:
case eContentCommandUndo:
case eContentCommandRedo:
case eContentCommandPasteTransferable:
case eContentCommandLookUpDictionary:
DoContentCommandEvent(aEvent->AsContentCommandEvent());
break;
case eContentCommandInsertText:
DoContentCommandInsertTextEvent(aEvent->AsContentCommandEvent());
break;
case eContentCommandReplaceText:
DoContentCommandReplaceTextEvent(aEvent->AsContentCommandEvent());
break;
case eContentCommandScroll:
DoContentCommandScrollEvent(aEvent->AsContentCommandEvent());
break;
case eCompositionStart:
if (aEvent->IsTrusted()) {
// If the event is trusted event, set the selected text to data of
// composition event.
WidgetCompositionEvent* compositionEvent = aEvent->AsCompositionEvent();
WidgetQueryContentEvent querySelectedTextEvent(
true, eQuerySelectedText, compositionEvent->mWidget);
HandleQueryContentEvent(&querySelectedTextEvent);
if (querySelectedTextEvent.FoundSelection()) {
compositionEvent->mData = querySelectedTextEvent.mReply->DataRef();
}
NS_ASSERTION(querySelectedTextEvent.Succeeded(),
"Failed to get selected text");
}
break;
case eTouchStart:
SetGestureDownPoint(aEvent->AsTouchEvent());
break;
default:
break;
}
return NS_OK;
}
// Returns true if this event is likely an user activation for a link or
// a link-like button, where modifier keys are likely be used for controlling
// where the link is opened.
//
// The modifiers associated with the user activation is used for controlling
// where the `window.open` is opened into.
static bool CanReflectModifiersToUserActivation(WidgetInputEvent* aEvent) {
MOZ_ASSERT(aEvent->mMessage == eKeyDown || aEvent->mMessage == ePointerDown ||
aEvent->mMessage == ePointerUp);
WidgetKeyboardEvent* keyEvent = aEvent->AsKeyboardEvent();
if (keyEvent) {
return keyEvent->CanReflectModifiersToUserActivation();
}
return true;
}
void EventStateManager::NotifyTargetUserActivation(WidgetEvent* aEvent,
nsIContent* aTargetContent) {
if (!aEvent->IsTrusted()) {
return;
}
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
if (mouseEvent && !mouseEvent->IsReal()) {
return;
}
nsCOMPtr<nsINode> node = aTargetContent;
if (!node) {
return;
}
Document* doc = node->OwnerDoc();
if (!doc) {
return;
}
// Don't gesture activate for key events for keys which are likely
// to be interaction with the browser, OS.
WidgetKeyboardEvent* keyEvent = aEvent->AsKeyboardEvent();
if (keyEvent && !keyEvent->CanUserGestureActivateTarget()) {
return;
}
// Touch gestures that end outside the drag target were touches that turned
// into scroll/pan/swipe actions. We don't want to gesture activate on such
// actions, we want to only gesture activate on touches that are taps.
// That is, touches that end in roughly the same place that they started.
if ((aEvent->mMessage == eTouchEnd ||
(aEvent->mMessage == ePointerUp &&
aEvent->AsPointerEvent()->mInputSource ==
MouseEvent_Binding::MOZ_SOURCE_TOUCH)) &&
IsEventOutsideDragThreshold(aEvent->AsInputEvent())) {
return;
}
// Do not treat the click on scrollbar as a user interaction with the web
// content.
if (StaticPrefs::dom_user_activation_ignore_scrollbars() &&
(aEvent->mMessage == ePointerDown || aEvent->mMessage == ePointerUp) &&
aTargetContent->IsInNativeAnonymousSubtree()) {
nsIContent* current = aTargetContent;
do {
nsIContent* root = current->GetClosestNativeAnonymousSubtreeRoot();
if (!root) {
break;
}
if (root->IsXULElement(nsGkAtoms::scrollbar)) {
return;
}
current = root->GetParent();
} while (current);
}
MOZ_ASSERT(aEvent->mMessage == eKeyDown || aEvent->mMessage == ePointerDown ||
aEvent->mMessage == ePointerUp);
UserActivation::Modifiers modifiers;
if (WidgetInputEvent* inputEvent = aEvent->AsInputEvent()) {
if (CanReflectModifiersToUserActivation(inputEvent)) {
if (inputEvent->IsShift()) {
modifiers.SetShift();
}
if (inputEvent->IsMeta()) {
modifiers.SetMeta();
}
if (inputEvent->IsControl()) {
modifiers.SetControl();
}
if (inputEvent->IsAlt()) {
modifiers.SetAlt();
}
WidgetMouseEvent* mouseEvent = inputEvent->AsMouseEvent();
if (mouseEvent) {
if (mouseEvent->mButton == MouseButton::eMiddle) {
modifiers.SetMiddleMouse();
}
}
}
}
doc->NotifyUserGestureActivation(modifiers);
}
// https://html.spec.whatwg.org/multipage/popover.html#popover-light-dismiss
void EventStateManager::LightDismissOpenPopovers(WidgetEvent* aEvent,
nsIContent* aTargetContent) {
MOZ_ASSERT(aEvent->mMessage == ePointerDown || aEvent->mMessage == ePointerUp,
"Light dismiss must be called for pointer up/down only");
if (!aEvent->IsTrusted() || !aTargetContent) {
return;
}
Element* topmostPopover = aTargetContent->OwnerDoc()->GetTopmostAutoPopover();
if (!topmostPopover) {
return;
}
// Pointerdown: set document's popover pointerdown target to the result of
// running topmost clicked popover given target.
if (aEvent->mMessage == ePointerDown) {
mPopoverPointerDownTarget = aTargetContent->GetTopmostClickedPopover();
return;
}
// Pointerup: hide open popovers.
RefPtr<nsINode> ancestor = aTargetContent->GetTopmostClickedPopover();
bool sameTarget = mPopoverPointerDownTarget == ancestor;
mPopoverPointerDownTarget = nullptr;
if (!sameTarget) {
return;
}
if (!ancestor) {
ancestor = aTargetContent->OwnerDoc();
}
RefPtr<Document> doc(ancestor->OwnerDoc());
doc->HideAllPopoversUntil(*ancestor, false, true);
}
// https://html.spec.whatwg.org/multipage/interactive-elements.html#run-light-dismiss-activities
// https://html.spec.whatwg.org/multipage/interactive-elements.html#light-dismiss-open-dialogs
void EventStateManager::LightDismissOpenDialogs(WidgetEvent* aEvent,
nsIContent* aTargetContent) {
// 1. Assert: event's isTrusted attribute is true.
// 2. Let document be event's target's node document.
// (Skipped - not applicable)
if (!StaticPrefs::dom_dialog_light_dismiss_enabled()) {
return;
}
MOZ_ASSERT(aEvent->mMessage == ePointerDown || aEvent->mMessage == ePointerUp,
"Light dismiss must be called for pointer up/down only");
if (aEvent->mFlags.mDefaultPrevented || !aEvent->IsTrusted() ||
!aTargetContent) {
return;
}
auto* doc = aTargetContent->OwnerDoc();
// 3. If document's open dialogs list is empty, then return.
if (!doc->HasOpenDialogs()) {
return;
}
// 4. Let ancestor be the result of running nearest clicked dialog given
// event.
RefPtr<HTMLDialogElement> ancestor =
aTargetContent->NearestClickedDialog(aEvent);
// 5. If event's type is "pointerdown", then set document's dialog pointerdown
// target to ancestor.
if (aEvent->mMessage == ePointerDown) {
// XXX: "document's dialog pointerdown target" can be null, but
// `SetLastDialogPointerdownTarget` takes `&` to avoid incidental nullptrs,
// meaning we need to nullcheck `ancestor` & call
// `ClearLastDialogPointerdownTarget` instead.
if (!ancestor) {
doc->ClearLastDialogPointerdownTarget();
} else {
doc->SetLastDialogPointerdownTarget(*ancestor);
}
return;
}
MOZ_ASSERT(aEvent->mMessage == ePointerUp);
// 6.1 Let sameTarget be true if ancestor is document's dialog pointerdown
// target.
RefPtr<HTMLDialogElement> lastDialog = doc->GetLastDialogPointerdownTarget();
bool sameTarget = ancestor == lastDialog;
// 6.2 Set document's dialog pointerdown target to null.
doc->ClearLastDialogPointerdownTarget();
// 6.3 If sameTarget is false, then return.
if (!sameTarget) {
return;
}
// 6.4 Let topmostDialog be the last element of document's open dialogs list.
RefPtr<HTMLDialogElement> topmostDialog = doc->GetTopMostOpenDialog();
// 6.5 If ancestor is topmostDialog, then return.
if (ancestor == topmostDialog) {
return;
}
// 6.6 If topmostDialog's computed closed-by state is not Any, then return.
if (!topmostDialog ||
topmostDialog->GetClosedBy() != HTMLDialogElement::ClosedBy::Any) {
return;
}
// 7. Assert: topmostDialog's close watcher is not null.
// 8. Request to close topmostDialog's close watcher with false.
const mozilla::dom::Optional<nsAString> returnValue;
topmostDialog->RequestClose(returnValue);
}
already_AddRefed<EventStateManager> EventStateManager::ESMFromContentOrThis(
nsIContent* aContent) {
if (aContent) {
PresShell* presShell = aContent->OwnerDoc()->GetPresShell();
if (presShell) {
nsPresContext* prescontext = presShell->GetPresContext();
if (prescontext) {
RefPtr<EventStateManager> esm = prescontext->EventStateManager();
if (esm) {
return esm.forget();
}
}
}
}
RefPtr<EventStateManager> esm = this;
return esm.forget();
}
EventStateManager::LastMouseDownInfo& EventStateManager::GetLastMouseDownInfo(
int16_t aButton) {
switch (aButton) {
case MouseButton::ePrimary:
return mLastLeftMouseDownInfo;
case MouseButton::eMiddle:
return mLastMiddleMouseDownInfo;
case MouseButton::eSecondary:
return mLastRightMouseDownInfo;
default:
MOZ_ASSERT_UNREACHABLE("This button shouldn't use this method");
return mLastLeftMouseDownInfo;
}
}
void EventStateManager::HandleQueryContentEvent(
WidgetQueryContentEvent* aEvent) {
switch (aEvent->mMessage) {
case eQuerySelectedText:
case eQueryTextContent:
case eQueryCaretRect:
case eQueryTextRect:
case eQueryEditorRect:
if (!IsTargetCrossProcess(aEvent)) {
break;
}
// Will not be handled locally, remote the event
GetCrossProcessTarget()->HandleQueryContentEvent(*aEvent);
return;
// Following events have not been supported in e10s mode yet.
case eQueryContentState:
case eQuerySelectionAsTransferable:
case eQueryCharacterAtPoint:
case eQueryDOMWidgetHittest:
case eQueryTextRectArray:
case eQueryDropTargetHittest:
break;
default:
return;
}
// If there is an IMEContentObserver, we need to handle QueryContentEvent
// with it.
// eQueryDropTargetHittest is not really an IME event, though
if (mIMEContentObserver && aEvent->mMessage != eQueryDropTargetHittest) {
RefPtr<IMEContentObserver> contentObserver = mIMEContentObserver;
contentObserver->HandleQueryContentEvent(aEvent);
return;
}
ContentEventHandler handler(mPresContext);
handler.HandleQueryContentEvent(aEvent);
}
static AccessKeyType GetAccessKeyTypeFor(nsISupports* aDocShell) {
nsCOMPtr<nsIDocShellTreeItem> treeItem(do_QueryInterface(aDocShell));
if (!treeItem) {
return AccessKeyType::eNone;
}
switch (treeItem->ItemType()) {
case nsIDocShellTreeItem::typeChrome:
return AccessKeyType::eChrome;
case nsIDocShellTreeItem::typeContent:
return AccessKeyType::eContent;
default:
return AccessKeyType::eNone;
}
}
static bool IsAccessKeyTarget(Element* aElement, nsAString& aKey) {
// Use GetAttr because we want Unicode case=insensitive matching
// XXXbz shouldn't this be case-sensitive, per spec?
nsString contentKey;
if (!aElement || !aElement->GetAttr(nsGkAtoms::accesskey, contentKey) ||
!contentKey.Equals(aKey, nsCaseInsensitiveStringComparator)) {
return false;
}
if (!aElement->IsXULElement()) {
return true;
}
// For XUL we do visibility checks.
nsIFrame* frame = aElement->GetPrimaryFrame();
if (!frame) {
return false;
}
if (frame->IsFocusable()) {
return true;
}
if (!frame->IsVisibleConsideringAncestors()) {
return false;
}
// XUL controls can be activated.
nsCOMPtr<nsIDOMXULControlElement> control = aElement->AsXULControl();
if (control) {
return true;
}
// XUL label elements are never focusable, so we need to check for them
// explicitly before giving up.
if (aElement->IsXULElement(nsGkAtoms::label)) {
return true;
}
return false;
}
bool EventStateManager::CheckIfEventMatchesAccessKey(
WidgetKeyboardEvent* aEvent, nsPresContext* aPresContext) {
AutoTArray<uint32_t, 10> accessCharCodes;
aEvent->GetAccessKeyCandidates(accessCharCodes);
return WalkESMTreeToHandleAccessKey(aEvent, aPresContext, accessCharCodes,
nullptr, eAccessKeyProcessingNormal,
false);
}
bool EventStateManager::LookForAccessKeyAndExecute(
nsTArray<uint32_t>& aAccessCharCodes, bool aIsTrustedEvent, bool aIsRepeat,
bool aExecute) {
int32_t count, start = -1;
if (Element* focusedElement = GetFocusedElement()) {
start = mAccessKeys.IndexOf(focusedElement);
if (start == -1 && focusedElement->IsInNativeAnonymousSubtree()) {
start = mAccessKeys.IndexOf(Element::FromNodeOrNull(
focusedElement->GetClosestNativeAnonymousSubtreeRootParentOrHost()));
}
}
RefPtr<Element> element;
int32_t length = mAccessKeys.Count();
for (uint32_t i = 0; i < aAccessCharCodes.Length(); ++i) {
uint32_t ch = aAccessCharCodes[i];
nsAutoString accessKey;
AppendUCS4ToUTF16(ch, accessKey);
for (count = 1; count <= length; ++count) {
// mAccessKeys always stores Element instances.
MOZ_DIAGNOSTIC_ASSERT(length == mAccessKeys.Count());
element = mAccessKeys[(start + count) % length];
if (IsAccessKeyTarget(element, accessKey)) {
if (!aExecute) {
return true;
}
Document* doc = element->OwnerDoc();
const bool shouldActivate = [&] {
if (!StaticPrefs::accessibility_accesskeycausesactivation()) {
return false;
}
if (aIsRepeat && nsContentUtils::IsChromeDoc(doc)) {
return false;
}
// XXXedgar, Bug 1700646, maybe we could use other data structure to
// make searching target with same accesskey easier, and current setup
// could not ensure we cycle the target with tree order.
int32_t j = 0;
while (++j < length) {
Element* el = mAccessKeys[(start + count + j) % length];
if (IsAccessKeyTarget(el, accessKey)) {
return false;
}
}
return true;
}();
// TODO(bug 1641171): This shouldn't be needed if we considered the
// accesskey combination properly.
if (aIsTrustedEvent) {
doc->NotifyUserGestureActivation();
}
auto result =
element->PerformAccesskey(shouldActivate, aIsTrustedEvent);
if (result.isOk()) {
if (result.unwrap() && aIsTrustedEvent) {
// If this is a child process, inform the parent that we want the
// focus, but pass false since we don't want to change the window
// order.
nsIDocShell* docShell = mPresContext->GetDocShell();
nsCOMPtr<nsIBrowserChild> child =
docShell ? docShell->GetBrowserChild() : nullptr;
if (child) {
child->SendRequestFocus(false, CallerType::System);
}
}
return true;
}
}
}
}
return false;
}
// static
void EventStateManager::GetAccessKeyLabelPrefix(Element* aElement,
nsAString& aPrefix) {
aPrefix.Truncate();
nsAutoString separator, modifierText;
nsContentUtils::GetModifierSeparatorText(separator);
AccessKeyType accessKeyType =
GetAccessKeyTypeFor(aElement->OwnerDoc()->GetDocShell());
if (accessKeyType == AccessKeyType::eNone) {
return;
}
Modifiers modifiers = WidgetKeyboardEvent::AccessKeyModifiers(accessKeyType);
if (modifiers == MODIFIER_NONE) {
return;
}
if (modifiers & MODIFIER_CONTROL) {
nsContentUtils::GetControlText(modifierText);
aPrefix.Append(modifierText + separator);
}
if (modifiers & MODIFIER_META) {
nsContentUtils::GetCommandOrWinText(modifierText);
aPrefix.Append(modifierText + separator);
}
if (modifiers & MODIFIER_ALT) {
nsContentUtils::GetAltText(modifierText);
aPrefix.Append(modifierText + separator);
}
if (modifiers & MODIFIER_SHIFT) {
nsContentUtils::GetShiftText(modifierText);
aPrefix.Append(modifierText + separator);
}
}
struct MOZ_STACK_CLASS AccessKeyInfo {
WidgetKeyboardEvent* event;
nsTArray<uint32_t>& charCodes;
AccessKeyInfo(WidgetKeyboardEvent* aEvent, nsTArray<uint32_t>& aCharCodes)
: event(aEvent), charCodes(aCharCodes) {}
};
bool EventStateManager::WalkESMTreeToHandleAccessKey(
WidgetKeyboardEvent* aEvent, nsPresContext* aPresContext,
nsTArray<uint32_t>& aAccessCharCodes, nsIDocShellTreeItem* aBubbledFrom,
ProcessingAccessKeyState aAccessKeyState, bool aExecute) {
EnsureDocument(mPresContext);
nsCOMPtr<nsIDocShell> docShell = aPresContext->GetDocShell();
if (NS_WARN_IF(!docShell) || NS_WARN_IF(!mDocument)) {
return false;
}
AccessKeyType accessKeyType = GetAccessKeyTypeFor(docShell);
if (accessKeyType == AccessKeyType::eNone) {
return false;
}
// Alt or other accesskey modifier is down, we may need to do an accesskey.
if (mAccessKeys.Count() > 0 &&
aEvent->ModifiersMatchWithAccessKey(accessKeyType)) {
// Someone registered an accesskey. Find and activate it.
if (LookForAccessKeyAndExecute(aAccessCharCodes, aEvent->IsTrusted(),
aEvent->mIsRepeat, aExecute)) {
return true;
}
}
int32_t childCount;
docShell->GetInProcessChildCount(&childCount);
for (int32_t counter = 0; counter < childCount; counter++) {
// Not processing the child which bubbles up the handling
nsCOMPtr<nsIDocShellTreeItem> subShellItem;
docShell->GetInProcessChildAt(counter, getter_AddRefs(subShellItem));
if (aAccessKeyState == eAccessKeyProcessingUp &&
subShellItem == aBubbledFrom) {
continue;
}
nsCOMPtr<nsIDocShell> subDS = do_QueryInterface(subShellItem);
if (subDS && IsShellVisible(subDS)) {
// Guarantee subPresShell lifetime while we're handling access key
// since somebody may assume that it won't be deleted before the
// corresponding nsPresContext and EventStateManager.
RefPtr<PresShell> subPresShell = subDS->GetPresShell();
// Docshells need not have a presshell (eg. display:none
// iframes, docshells in transition between documents, etc).
if (!subPresShell) {
// Oh, well. Just move on to the next child
continue;
}
RefPtr<nsPresContext> subPresContext = subPresShell->GetPresContext();
RefPtr<EventStateManager> esm =
static_cast<EventStateManager*>(subPresContext->EventStateManager());
if (esm && esm->WalkESMTreeToHandleAccessKey(
aEvent, subPresContext, aAccessCharCodes, nullptr,
eAccessKeyProcessingDown, aExecute)) {
return true;
}
}
} // if end . checking all sub docshell ends here.
// bubble up the process to the parent docshell if necessary
if (eAccessKeyProcessingDown != aAccessKeyState) {
nsCOMPtr<nsIDocShellTreeItem> parentShellItem;
docShell->GetInProcessParent(getter_AddRefs(parentShellItem));
nsCOMPtr<nsIDocShell> parentDS = do_QueryInterface(parentShellItem);
if (parentDS) {
// Guarantee parentPresShell lifetime while we're handling access key
// since somebody may assume that it won't be deleted before the
// corresponding nsPresContext and EventStateManager.
RefPtr<PresShell> parentPresShell = parentDS->GetPresShell();
NS_ASSERTION(parentPresShell,
"Our PresShell exists but the parent's does not?");
RefPtr<nsPresContext> parentPresContext =
parentPresShell->GetPresContext();
NS_ASSERTION(parentPresContext, "PresShell without PresContext");
RefPtr<EventStateManager> esm = static_cast<EventStateManager*>(
parentPresContext->EventStateManager());
if (esm && esm->WalkESMTreeToHandleAccessKey(
aEvent, parentPresContext, aAccessCharCodes, docShell,
eAccessKeyProcessingDown, aExecute)) {
return true;
}
}
} // if end. bubble up process
// If the content access key modifier is pressed, try remote children
if (aExecute &&
aEvent->ModifiersMatchWithAccessKey(AccessKeyType::eContent) &&
mDocument && mDocument->GetWindow()) {
// If the focus is currently on a node with a BrowserParent, the key event
// should've gotten forwarded to the child process and HandleAccessKey
// called from there.
if (BrowserParent::GetFrom(GetFocusedElement())) {
// If access key may be only in remote contents, this method won't handle
// access key synchronously. In this case, only reply event should reach
// here.
MOZ_ASSERT(aEvent->IsHandledInRemoteProcess() ||
!aEvent->IsWaitingReplyFromRemoteProcess());
}
// If focus is somewhere else, then we need to check the remote children.
// However, if the event has already been handled in a remote process,
// then, focus is moved from the remote process after posting the event.
// In such case, we shouldn't retry to handle access keys in remote
// processes.
else if (!aEvent->IsHandledInRemoteProcess()) {
AccessKeyInfo accessKeyInfo(aEvent, aAccessCharCodes);
nsContentUtils::CallOnAllRemoteChildren(
mDocument->GetWindow(),
[&accessKeyInfo](BrowserParent* aBrowserParent) -> CallState {
// Only forward accesskeys for the active tab.
if (aBrowserParent->GetDocShellIsActive()) {
// Even if there is no target for the accesskey in this process,
// the event may match with a content accesskey. If so, the
// keyboard event should be handled with reply event for
// preventing double action. (e.g., Alt+Shift+F on Windows may
// focus a content in remote and open "File" menu.)
accessKeyInfo.event->StopPropagation();
accessKeyInfo.event->MarkAsWaitingReplyFromRemoteProcess();
aBrowserParent->HandleAccessKey(*accessKeyInfo.event,
accessKeyInfo.charCodes);
return CallState::Stop;
}
return CallState::Continue;
});
}
}
return false;
} // end of HandleAccessKey
static BrowserParent* GetBrowserParentAncestor(BrowserParent* aBrowserParent) {
MOZ_ASSERT(aBrowserParent);
BrowserBridgeParent* bbp = aBrowserParent->GetBrowserBridgeParent();
if (!bbp) {
return nullptr;
}
return bbp->Manager();
}
static void DispatchCrossProcessMouseExitEvents(WidgetMouseEvent* aMouseEvent,
BrowserParent* aRemoteTarget,
BrowserParent* aStopAncestor,
bool aIsReallyExit) {
MOZ_ASSERT(aMouseEvent);
MOZ_ASSERT(aRemoteTarget);
MOZ_ASSERT(aRemoteTarget != aStopAncestor);
MOZ_ASSERT_IF(aStopAncestor, nsContentUtils::GetCommonBrowserParentAncestor(
aRemoteTarget, aStopAncestor));
while (aRemoteTarget != aStopAncestor) {
UniquePtr<WidgetMouseEvent> mouseExitEvent =
CreateMouseOrPointerWidgetEvent(aMouseEvent, eMouseExitFromWidget,
aMouseEvent->mRelatedTarget);
mouseExitEvent->mExitFrom =
Some(aIsReallyExit ? WidgetMouseEvent::ePuppet
: WidgetMouseEvent::ePuppetParentToPuppetChild);
auto ContentReactsToPointerEvents = [](BrowserParent* aRemoteTarget) {
if (Element* owner = aRemoteTarget->GetOwnerElement()) {
if (nsSubDocumentFrame* subDocFrame =
do_QueryFrame(owner->GetPrimaryFrame())) {
return subDocFrame->ContentReactsToPointerEvents();
}
}
return true;
};
if (ContentReactsToPointerEvents(aRemoteTarget)) {
aRemoteTarget->SendRealMouseEvent(*mouseExitEvent);
}
aRemoteTarget = GetBrowserParentAncestor(aRemoteTarget);
}
}
void EventStateManager::DispatchCrossProcessEvent(WidgetEvent* aEvent,
BrowserParent* aRemoteTarget,
nsEventStatus* aStatus) {
MOZ_ASSERT(aEvent);
MOZ_ASSERT(aRemoteTarget);
MOZ_ASSERT(aStatus);
BrowserParent* remote = aRemoteTarget;
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
bool isContextMenuKey = mouseEvent && mouseEvent->IsContextMenuKeyEvent();
if (aEvent->mClass == eKeyboardEventClass || isContextMenuKey) {
// APZ attaches a LayersId to hit-testable events, for keyboard events,
// we use focus.
BrowserParent* preciseRemote = BrowserParent::GetFocused();
if (preciseRemote) {
remote = preciseRemote;
}
// else there is a race between layout and focus tracking,
// so fall back to delivering the event to the topmost child process.
} else if (aEvent->mLayersId.IsValid()) {
BrowserParent* preciseRemote =
BrowserParent::GetBrowserParentFromLayersId(aEvent->mLayersId);
if (preciseRemote) {
remote = preciseRemote;
}
// else there is a race between APZ and the LayersId to BrowserParent
// mapping, so fall back to delivering the event to the topmost child
// process.
}
MOZ_ASSERT(aEvent->mMessage != ePointerClick);
MOZ_ASSERT(aEvent->mMessage != ePointerAuxClick);
// SendReal* will transform the coordinate to the child process coordinate
// space. So restore the coordinate after the event has been dispatched to the
// child process to avoid using the transformed coordinate afterward.
AutoRestore<LayoutDeviceIntPoint> restore(aEvent->mRefPoint);
switch (aEvent->mClass) {
case ePointerEventClass:
MOZ_ASSERT(aEvent->mMessage == eContextMenu);
[[fallthrough]];
case eMouseEventClass: {
BrowserParent* oldRemote = BrowserParent::GetLastMouseRemoteTarget();
// If this is a eMouseExitFromWidget event, need to redirect the event to
// the last remote and and notify all its ancestors about the exit, if
// any.
if (mouseEvent->mMessage == eMouseExitFromWidget) {
MOZ_ASSERT(mouseEvent->mExitFrom.value() == WidgetMouseEvent::ePuppet);
MOZ_ASSERT(mouseEvent->mReason == WidgetMouseEvent::eReal);
MOZ_ASSERT(!mouseEvent->mLayersId.IsValid());
MOZ_ASSERT(remote->GetBrowserHost());
if (oldRemote && oldRemote != remote) {
Unused << NS_WARN_IF(nsContentUtils::GetCommonBrowserParentAncestor(
remote, oldRemote) != remote);
remote = oldRemote;
}
DispatchCrossProcessMouseExitEvents(mouseEvent, remote, nullptr, true);
return;
}
if (BrowserParent* pointerLockedRemote =
PointerLockManager::GetLockedRemoteTarget()) {
remote = pointerLockedRemote;
} else if (BrowserParent* pointerCapturedRemote =
PointerEventHandler::GetPointerCapturingRemoteTarget(
mouseEvent->pointerId)) {
remote = pointerCapturedRemote;
} else if (BrowserParent* capturingRemote =
PresShell::GetCapturingRemoteTarget()) {
remote = capturingRemote;
}
// If a mouse is over a remote target A, and then moves to
// remote target B, we'd deliver the event directly to remote target B
// after the moving, A would never get notified that the mouse left.
// So we generate a exit event to notify A after the move.
// XXXedgar, if the synthesized mouse events could deliver to the correct
// process directly (see
// https://bugzilla.mozilla.org/show_bug.cgi?id=1549355), we probably
// don't need to check mReason then.
if (mouseEvent->mReason == WidgetMouseEvent::eReal &&
remote != oldRemote) {
MOZ_ASSERT(mouseEvent->mMessage != eMouseExitFromWidget);
if (oldRemote) {
BrowserParent* commonAncestor =
nsContentUtils::GetCommonBrowserParentAncestor(remote, oldRemote);
if (commonAncestor == oldRemote) {
// Mouse moves to the inner OOP frame, it is not a really exit.
DispatchCrossProcessMouseExitEvents(
mouseEvent, GetBrowserParentAncestor(remote),
GetBrowserParentAncestor(commonAncestor), false);
} else if (commonAncestor == remote) {
// Mouse moves to the outer OOP frame, it is a really exit.
DispatchCrossProcessMouseExitEvents(mouseEvent, oldRemote,
commonAncestor, true);
} else {
// Mouse moves to OOP frame in other subtree, it is a really exit,
// need to notify all its ancestors before common ancestor about the
// exit.
DispatchCrossProcessMouseExitEvents(mouseEvent, oldRemote,
commonAncestor, true);
if (commonAncestor) {
UniquePtr<WidgetMouseEvent> mouseExitEvent =
CreateMouseOrPointerWidgetEvent(mouseEvent,
eMouseExitFromWidget,
mouseEvent->mRelatedTarget);
mouseExitEvent->mExitFrom =
Some(WidgetMouseEvent::ePuppetParentToPuppetChild);
commonAncestor->SendRealMouseEvent(*mouseExitEvent);
}
}
}
if (mouseEvent->mMessage != eMouseExitFromWidget &&
mouseEvent->mMessage != eMouseEnterIntoWidget) {
// This is to make cursor would be updated correctly.
remote->MouseEnterIntoWidget();
}
}
remote->SendRealMouseEvent(*mouseEvent);
return;
}
case eKeyboardEventClass: {
auto* keyboardEvent = aEvent->AsKeyboardEvent();
if (aEvent->mMessage == eKeyUp) {
HandleKeyUpInteraction(keyboardEvent);
}
remote->SendRealKeyEvent(*keyboardEvent);
return;
}
case eWheelEventClass: {
if (BrowserParent* pointerLockedRemote =
PointerLockManager::GetLockedRemoteTarget()) {
remote = pointerLockedRemote;
}
remote->SendMouseWheelEvent(*aEvent->AsWheelEvent());
return;
}
case eTouchEventClass: {
// Let the child process synthesize a mouse event if needed, and
// ensure we don't synthesize one in this process.
*aStatus = nsEventStatus_eConsumeNoDefault;
remote->SendRealTouchEvent(*aEvent->AsTouchEvent());
return;
}
case eDragEventClass: {
RefPtr<BrowserParent> browserParent = remote;
browserParent->MaybeInvokeDragSession(aEvent->mMessage);
RefPtr<nsIWidget> widget = browserParent->GetTopLevelWidget();
nsCOMPtr<nsIDragSession> dragSession =
nsContentUtils::GetDragSession(widget);
uint32_t dropEffect = nsIDragService::DRAGDROP_ACTION_NONE;
uint32_t action = nsIDragService::DRAGDROP_ACTION_NONE;
nsCOMPtr<nsIPrincipal> principal;
nsCOMPtr<nsIPolicyContainer> policyContainer;
if (dragSession) {
dragSession->DragEventDispatchedToChildProcess();
dragSession->GetDragAction(&action);
dragSession->GetTriggeringPrincipal(getter_AddRefs(principal));
dragSession->GetPolicyContainer(getter_AddRefs(policyContainer));
RefPtr<DataTransfer> initialDataTransfer =
dragSession->GetDataTransfer();
if (initialDataTransfer) {
dropEffect = initialDataTransfer->DropEffectInt();
}
}
browserParent->SendRealDragEvent(*aEvent->AsDragEvent(), action,
dropEffect, principal, policyContainer);
return;
}
default: {
MOZ_CRASH("Attempt to send non-whitelisted event?");
}
}
}
bool EventStateManager::IsRemoteTarget(nsIContent* target) {
return BrowserParent::GetFrom(target) || BrowserBridgeChild::GetFrom(target);
}
bool EventStateManager::IsTopLevelRemoteTarget(nsIContent* target) {
return !!BrowserParent::GetFrom(target);
}
bool EventStateManager::HandleCrossProcessEvent(WidgetEvent* aEvent,
nsEventStatus* aStatus) {
if (!aEvent->CanBeSentToRemoteProcess()) {
return false;
}
MOZ_ASSERT(!aEvent->HasBeenPostedToRemoteProcess(),
"Why do we need to post same event to remote processes again?");
// Collect the remote event targets we're going to forward this
// event to.
//
// NB: the elements of |remoteTargets| must be unique, for correctness.
AutoTArray<RefPtr<BrowserParent>, 1> remoteTargets;
if (aEvent->mClass != eTouchEventClass || aEvent->mMessage == eTouchStart) {
// If this event only has one target, and it's remote, add it to
// the array.
nsIFrame* frame = aEvent->mMessage == eDragExit
? sLastDragOverFrame.GetFrame()
: GetEventTarget();
nsIContent* target = frame ? frame->GetContent() : nullptr;
if (BrowserParent* remoteTarget = BrowserParent::GetFrom(target)) {
remoteTargets.AppendElement(remoteTarget);
}
} else {
// This is a touch event with possibly multiple touch points.
// Each touch point may have its own target. So iterate through
// all of them and collect the unique set of targets for event
// forwarding.
//
// This loop is similar to the one used in
// PresShell::DispatchTouchEvent().
const WidgetTouchEvent::TouchArray& touches =
aEvent->AsTouchEvent()->mTouches;
for (uint32_t i = 0; i < touches.Length(); ++i) {
Touch* touch = touches[i];
// NB: the |mChanged| check is an optimization, subprocesses can
// compute this for themselves. If the touch hasn't changed, we
// may be able to avoid forwarding the event entirely (which is
// not free).
if (!touch || !touch->mChanged) {
continue;
}
nsCOMPtr<EventTarget> targetPtr = touch->mTarget;
if (!targetPtr) {
continue;
}
nsCOMPtr<nsIContent> target = do_QueryInterface(targetPtr);
BrowserParent* remoteTarget = BrowserParent::GetFrom(target);
if (remoteTarget && !remoteTargets.Contains(remoteTarget)) {
remoteTargets.AppendElement(remoteTarget);
}
}
}
if (remoteTargets.Length() == 0) {
return false;
}
// Dispatch the event to the remote target.
for (uint32_t i = 0; i < remoteTargets.Length(); ++i) {
DispatchCrossProcessEvent(aEvent, remoteTargets[i], aStatus);
}
return aEvent->HasBeenPostedToRemoteProcess();
}
//
// CreateClickHoldTimer
//
// Fire off a timer for determining if the user wants click-hold. This timer
// is a one-shot that will be cancelled when the user moves enough to fire
// a drag.
//
void EventStateManager::CreateClickHoldTimer(nsPresContext* inPresContext,
nsIFrame* inDownFrame,
WidgetGUIEvent* inMouseDownEvent) {
if (!inMouseDownEvent->IsTrusted() ||
IsTopLevelRemoteTarget(mGestureDownContent) ||
PointerLockManager::IsLocked()) {
return;
}
// just to be anal (er, safe)
if (mClickHoldTimer) {
mClickHoldTimer->Cancel();
mClickHoldTimer = nullptr;
}
// if content clicked on has a popup, don't even start the timer
// since we'll end up conflicting and both will show.
if (mGestureDownContent &&
nsContentUtils::HasNonEmptyAttr(mGestureDownContent, kNameSpaceID_None,
nsGkAtoms::popup)) {
return;
}
int32_t clickHoldDelay = StaticPrefs::ui_click_hold_context_menus_delay();
NS_NewTimerWithFuncCallback(
getter_AddRefs(mClickHoldTimer), sClickHoldCallback, this, clickHoldDelay,
nsITimer::TYPE_ONE_SHOT, "EventStateManager::CreateClickHoldTimer");
} // CreateClickHoldTimer
//
// KillClickHoldTimer
//
// Stop the timer that would show the context menu dead in its tracks
//
void EventStateManager::KillClickHoldTimer() {
if (mClickHoldTimer) {
mClickHoldTimer->Cancel();
mClickHoldTimer = nullptr;
}
}
//
// sClickHoldCallback
//
// This fires after the mouse has been down for a certain length of time.
//
void EventStateManager::sClickHoldCallback(nsITimer* aTimer, void* aESM) {
RefPtr<EventStateManager> self = static_cast<EventStateManager*>(aESM);
if (self) {
self->FireContextClick();
}
// NOTE: |aTimer| and |self->mAutoHideTimer| are invalid after calling
// ClosePopup();
} // sAutoHideCallback
//
// FireContextClick
//
// If we're this far, our timer has fired, which means the mouse has been down
// for a certain period of time and has not moved enough to generate a
// dragGesture. We can be certain the user wants a context-click at this stage,
// so generate a dom event and fire it in.
//
// After the event fires, check if PreventDefault() has been set on the event
// which means that someone either ate the event or put up a context menu. This
// is our cue to stop tracking the drag gesture. If we always did this,
// draggable items w/out a context menu wouldn't be draggable after a certain
// length of time, which is _not_ what we want.
//
void EventStateManager::FireContextClick() {
if (!mGestureDownContent || !mPresContext || PointerLockManager::IsLocked()) {
return;
}
#ifdef XP_MACOSX
// Hack to ensure that we don't show a context menu when the user
// let go of the mouse after a long cpu-hogging operation prevented
// us from handling any OS events. See bug 117589.
if (!CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState,
kCGMouseButtonLeft))
return;
#endif
nsEventStatus status = nsEventStatus_eIgnore;
// Dispatch to the DOM. We have to fake out the ESM and tell it that the
// current target frame is actually where the mouseDown occurred, otherwise it
// will use the frame the mouse is currently over which may or may not be
// the same. (Note: saari and I have decided that we don't have to reset
// |mCurrentTarget| when we're through because no one else is doing anything
// more with this event and it will get reset on the very next event to the
// correct frame).
mCurrentTarget = mPresContext->GetPrimaryFrameFor(mGestureDownContent);
// make sure the widget sticks around
nsCOMPtr<nsIWidget> targetWidget;
if (mCurrentTarget && (targetWidget = mCurrentTarget->GetNearestWidget())) {
NS_ASSERTION(
mPresContext == mCurrentTarget->PresContext(),
"a prescontext returned a primary frame that didn't belong to it?");
// before dispatching, check that we're not on something that
// doesn't get a context menu
bool allowedToDispatch = true;
if (mGestureDownContent->IsAnyOfXULElements(nsGkAtoms::scrollbar,
nsGkAtoms::scrollbarbutton,
nsGkAtoms::button)) {
allowedToDispatch = false;
} else if (mGestureDownContent->IsXULElement(nsGkAtoms::toolbarbutton)) {
// a <toolbarbutton> that has the container attribute set
// will already have its own dropdown.
if (nsContentUtils::HasNonEmptyAttr(
mGestureDownContent, kNameSpaceID_None, nsGkAtoms::container)) {
allowedToDispatch = false;
} else {
// If the toolbar button has an open menu, don't attempt to open
// a second menu
if (mGestureDownContent->IsElement() &&
mGestureDownContent->AsElement()->AttrValueIs(
kNameSpaceID_None, nsGkAtoms::open, nsGkAtoms::_true,
eCaseMatters)) {
allowedToDispatch = false;
}
}
} else if (mGestureDownContent->IsHTMLElement()) {
if (const auto* formCtrl =
nsIFormControl::FromNode(mGestureDownContent)) {
allowedToDispatch =
formCtrl->IsTextControl(/*aExcludePassword*/ false) ||
formCtrl->ControlType() == FormControlType::InputFile;
} else if (mGestureDownContent->IsAnyOfHTMLElements(
nsGkAtoms::embed, nsGkAtoms::object, nsGkAtoms::label)) {
allowedToDispatch = false;
}
}
if (allowedToDispatch) {
// init the event while mCurrentTarget is still good
WidgetPointerEvent event(true, eContextMenu, targetWidget);
event.mClickCount = 1;
FillInEventFromGestureDown(&event);
// we need to forget the clicking content and click count for the
// following eMouseUp event when click-holding context menus
LastMouseDownInfo& mouseDownInfo = GetLastMouseDownInfo(event.mButton);
mouseDownInfo.mLastMouseDownContent = nullptr;
mouseDownInfo.mClickCount = 0;
mouseDownInfo.mLastMouseDownInputControlType = Nothing();
// stop selection tracking, we're in control now
if (mCurrentTarget) {
RefPtr<nsFrameSelection> frameSel = mCurrentTarget->GetFrameSelection();
if (frameSel && frameSel->GetDragState()) {
// note that this can cause selection changed events to fire if we're
// in a text field, which will null out mCurrentTarget
frameSel->SetDragState(false);
}
}
AutoHandlingUserInputStatePusher userInpStatePusher(true, &event);
// dispatch to DOM
RefPtr<nsPresContext> presContext = mPresContext;
// The contextmenu event handled by PresShell will apply to elements (not
// all nodes) correctly and will be dispatched to EventStateManager for
// further handling preventing click event and stopping tracking drag
// gesture.
if (RefPtr<PresShell> presShell = presContext->GetPresShell()) {
presShell->HandleEvent(mCurrentTarget, &event, false, &status);
}
// We don't need to dispatch to frame handling because no frames
// watch eContextMenu except for nsMenuFrame and that's only for
// dismissal. That's just as well since we don't really know
// which frame to send it to.
}
}
// stop tracking a drag whatever the event has been handled or not.
StopTrackingDragGesture(true);
KillClickHoldTimer();
} // FireContextClick
//
// BeginTrackingDragGesture
//
// Record that the mouse has gone down and that we should move to TRACKING state
// of d&d gesture tracker.
//
// We also use this to track click-hold context menus. When the mouse goes down,
// fire off a short timer. If the timer goes off and we have yet to fire the
// drag gesture (ie, the mouse hasn't moved a certain distance), then we can
// assume the user wants a click-hold, so fire a context-click event. We only
// want to cancel the drag gesture if the context-click event is handled.
//
void EventStateManager::BeginTrackingDragGesture(nsPresContext* aPresContext,
WidgetMouseEvent* inDownEvent,
nsIFrame* inDownFrame) {
if (!inDownEvent->mWidget) {
return;
}
// Note that |inDownEvent| could be either a mouse down event or a
// synthesized mouse move event.
SetGestureDownPoint(inDownEvent);
if (inDownFrame) {
mGestureDownContent = inDownFrame->GetContentForEvent(inDownEvent);
mGestureDownFrameOwner = inDownFrame->GetContent();
if (!mGestureDownFrameOwner) {
mGestureDownFrameOwner = mGestureDownContent;
}
}
mGestureModifiers = inDownEvent->mModifiers;
mGestureDownButtons = inDownEvent->mButtons;
mGestureDownButton = inDownEvent->mButton;
if (inDownEvent->mMessage != eMouseTouchDrag &&
StaticPrefs::ui_click_hold_context_menus()) {
// fire off a timer to track click-hold
CreateClickHoldTimer(aPresContext, inDownFrame, inDownEvent);
}
}
void EventStateManager::SetGestureDownPoint(WidgetGUIEvent* aEvent) {
mGestureDownPoint =
GetEventRefPoint(aEvent) + aEvent->mWidget->WidgetToScreenOffset();
}
LayoutDeviceIntPoint EventStateManager::GetEventRefPoint(
WidgetEvent* aEvent) const {
auto touchEvent = aEvent->AsTouchEvent();
return (touchEvent && !touchEvent->mTouches.IsEmpty())
? aEvent->AsTouchEvent()->mTouches[0]->mRefPoint
: aEvent->mRefPoint;
}
void EventStateManager::BeginTrackingRemoteDragGesture(
nsIContent* aContent, RemoteDragStartData* aDragStartData) {
UpdateGestureContent(aContent);
mGestureDownDragStartData = aDragStartData;
}
//
// StopTrackingDragGesture
//
// Record that the mouse has gone back up so that we should leave the TRACKING
// state of d&d gesture tracker and return to the START state.
//
void EventStateManager::StopTrackingDragGesture(bool aClearInChildProcesses) {
mGestureDownContent = nullptr;
mGestureDownFrameOwner = nullptr;
mGestureDownInTextControl = false;
mGestureDownDragStartData = nullptr;
// If a content process starts a drag but the mouse is released before the
// parent starts the actual drag, the content process will think a drag is
// still happening. Inform any child processes with active drags that the drag
// should be stopped.
if (!aClearInChildProcesses || !XRE_IsParentProcess()) {
return;
}
// Only notify if there is NOT a drag session active in the parent.
RefPtr<nsIDragSession> dragSession =
nsContentUtils::GetDragSession(mPresContext);
if (dragSession) {
return;
}
nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1");
if (!dragService) {
return;
}
dragService->RemoveAllBrowsers();
}
void EventStateManager::FillInEventFromGestureDown(WidgetMouseEvent* aEvent) {
NS_ASSERTION(aEvent->mWidget == mCurrentTarget->GetNearestWidget(),
"Incorrect widget in event");
// Set the coordinates in the new event to the coordinates of
// the old event, adjusted for the fact that the widget might be
// different
aEvent->mRefPoint =
mGestureDownPoint - aEvent->mWidget->WidgetToScreenOffset();
aEvent->mModifiers = mGestureModifiers;
aEvent->mButtons = mGestureDownButtons;
if (aEvent->mMessage == eContextMenu) {
aEvent->mButton = mGestureDownButton;
}
}
void EventStateManager::MaybeDispatchPointerCancel(
const WidgetInputEvent& aSourceEvent, nsIContent& aTargetContent) {
// Dispatching ePointerCancel clears out mCurrentTarget, which may be used in
// the caller GenerateDragGesture. We have to restore mCurrentTarget.
AutoWeakFrame targetFrame = mCurrentTarget;
const auto restoreCurrentTarget =
MakeScopeExit([&]() { mCurrentTarget = targetFrame; });
const RefPtr<Element> targetElement =
aTargetContent.GetAsElementOrParentElement();
// XXX If there is no proper event target, should we retarget ePointerCancel
// somewhere else?
if (NS_WARN_IF(!targetElement)) {
return;
}
if (const WidgetMouseEvent* const mouseEvent = aSourceEvent.AsMouseEvent()) {
PointerEventHandler::DispatchPointerEventWithTarget(
ePointerCancel, *mouseEvent, AutoWeakFrame{}, targetElement);
} else if (const WidgetTouchEvent* const touchEvent =
aSourceEvent.AsTouchEvent()) {
PointerEventHandler::DispatchPointerEventWithTarget(
ePointerCancel, *touchEvent, 0, AutoWeakFrame{}, targetElement);
} else {
MOZ_ASSERT_UNREACHABLE(
"MaybeDispatchPointerCancel() should be called with a mouse event or a "
"touch event");
}
}
bool EventStateManager::IsEventOutsideDragThreshold(
WidgetInputEvent* aEvent) const {
static int32_t sPixelThresholdX = 0;
static int32_t sPixelThresholdY = 0;
if (!sPixelThresholdX) {
sPixelThresholdX =
LookAndFeel::GetInt(LookAndFeel::IntID::DragThresholdX, 0);
sPixelThresholdY =
LookAndFeel::GetInt(LookAndFeel::IntID::DragThresholdY, 0);
if (sPixelThresholdX <= 0) {
sPixelThresholdX = 5;
}
if (sPixelThresholdY <= 0) {
sPixelThresholdY = 5;
}
}
LayoutDeviceIntPoint pt =
aEvent->mWidget->WidgetToScreenOffset() + GetEventRefPoint(aEvent);
LayoutDeviceIntPoint distance = pt - mGestureDownPoint;
return Abs(distance.x) > sPixelThresholdX ||
Abs(distance.y) > sPixelThresholdY;
}
//
// GenerateDragGesture
//
// If we're in the TRACKING state of the d&d gesture tracker, check the current
// position of the mouse in relation to the old one. If we've moved a sufficient
// amount from the mouse down, then fire off a drag gesture event.
void EventStateManager::GenerateDragGesture(nsPresContext* aPresContext,
WidgetInputEvent* aEvent) {
NS_ASSERTION(aPresContext, "This shouldn't happen.");
MOZ_ASSERT_IF(aEvent->AsMouseEvent(), aEvent->AsMouseEvent()->IsReal());
if (!IsTrackingDragGesture()) {
return;
}
AutoWeakFrame targetFrameBefore = mCurrentTarget;
auto autoRestore = MakeScopeExit([&] { mCurrentTarget = targetFrameBefore; });
mCurrentTarget = nullptr;
// Try to find a suitable frame by looping through the ancestors chain.
for (auto* content :
mGestureDownFrameOwner->InclusiveFlatTreeAncestorsOfType<nsIContent>()) {
if (nsIFrame* target = content->GetPrimaryFrame()) {
mCurrentTarget = target;
if (content != mGestureDownFrameOwner) {
UpdateGestureContent(content);
}
break;
}
}
if (!mCurrentTarget || !mCurrentTarget->GetNearestWidget()) {
StopTrackingDragGesture(true);
return;
}
// Check if selection is tracking drag gestures, if so
// don't interfere!
if (mCurrentTarget) {
RefPtr<nsFrameSelection> frameSel = mCurrentTarget->GetFrameSelection();
if (frameSel && frameSel->GetDragState()) {
StopTrackingDragGesture(true);
return;
}
}
// If non-native code is capturing the mouse don't start a drag.
if (PresShell::IsMouseCapturePreventingDrag()) {
StopTrackingDragGesture(true);
return;
}
if (!IsEventOutsideDragThreshold(aEvent)) {
// To keep the old behavior, flush layout even if we don't start dnd.
FlushLayout(aPresContext);
return;
}
if (StaticPrefs::ui_click_hold_context_menus()) {
// stop the click-hold before we fire off the drag gesture, in case
// it takes a long time
KillClickHoldTimer();
}
nsCOMPtr<nsIDocShell> docshell = aPresContext->GetDocShell();
if (!docshell) {
return;
}
nsCOMPtr<nsPIDOMWindowOuter> window = docshell->GetWindow();
if (!window) return;
RefPtr<DataTransfer> dataTransfer =
new DataTransfer(window, eDragStart, /* aIsExternal */ false,
/* aClipboardType */ Nothing());
auto protectDataTransfer = MakeScopeExit([&] {
if (dataTransfer) {
dataTransfer->Disconnect();
}
});
RefPtr<Selection> selection;
RefPtr<RemoteDragStartData> remoteDragStartData;
nsCOMPtr<nsIPrincipal> principal;
nsCOMPtr<nsIPolicyContainer> policyContainer;
nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
nsCOMPtr<nsIContent> eventContent =
mCurrentTarget->GetContentForEvent(aEvent);
nsCOMPtr<nsIContent> targetContent;
bool allowEmptyDataTransfer = false;
if (eventContent) {
// If the content is a text node in a password field, we shouldn't
// allow to drag its raw text. Note that we've supported drag from
// password fields but dragging data was masked text. So, it doesn't
// make sense anyway.
if (eventContent->IsText() && eventContent->HasFlag(NS_MAYBE_MASKED)) {
// However, it makes sense to allow to drag selected password text
// when copying selected password is allowed because users may want
// to use drag and drop rather than copy and paste when web apps
// request to input password twice for conforming new password but
// they used password generator.
const TextEditor* const textEditor =
nsContentUtils::GetExtantTextEditorFromAnonymousNode(eventContent);
if (!textEditor || !textEditor->IsCopyToClipboardAllowed()) {
StopTrackingDragGesture(true);
return;
}
}
DetermineDragTargetAndDefaultData(
window, eventContent, dataTransfer, &allowEmptyDataTransfer,
getter_AddRefs(selection), getter_AddRefs(remoteDragStartData),
getter_AddRefs(targetContent), getter_AddRefs(principal),
getter_AddRefs(policyContainer), getter_AddRefs(cookieJarSettings));
}
// Stop tracking the drag gesture now. This should stop us from
// reentering GenerateDragGesture inside DOM event processing.
// Pass false to avoid clearing the child process state since a real
// drag should be starting.
StopTrackingDragGesture(false);
if (MOZ_UNLIKELY(!targetContent)) {
return;
}
// Use our targetContent, now that we've determined it, as the
// parent object of the DataTransfer.
nsCOMPtr<nsIContent> parentContent =
targetContent->FindFirstNonChromeOnlyAccessContent();
dataTransfer->SetParentObject(parentContent);
sLastDragOverFrame = nullptr;
nsCOMPtr<nsIWidget> widget = mCurrentTarget->GetNearestWidget();
// get the widget from the target frame
WidgetDragEvent startEvent(aEvent->IsTrusted(), eDragStart, widget);
startEvent.mFlags.mIsSynthesizedForTests =
aEvent->mFlags.mIsSynthesizedForTests;
FillInEventFromGestureDown(&startEvent);
startEvent.mDataTransfer = dataTransfer;
if (aEvent->AsMouseEvent()) {
startEvent.mInputSource = aEvent->AsMouseEvent()->mInputSource;
} else if (aEvent->AsTouchEvent()) {
startEvent.mInputSource = MouseEvent_Binding::MOZ_SOURCE_TOUCH;
} else {
MOZ_ASSERT(false);
}
// Dispatch to the DOM. By setting mCurrentTarget we are faking
// out the ESM and telling it that the current target frame is
// actually where the mouseDown occurred, otherwise it will use
// the frame the mouse is currently over which may or may not be
// the same.
// Hold onto old target content through the event and reset after.
nsCOMPtr<nsIContent> targetBeforeEvent = mCurrentTargetContent;
{
AutoConnectedAncestorTracker trackTargetContent(*targetContent);
// Set the current target to the content for the mouse down
mCurrentTargetContent = targetContent;
// Dispatch the dragstart event to the DOM.
nsEventStatus status = nsEventStatus_eIgnore;
EventDispatcher::Dispatch(targetContent, aPresContext, &startEvent, nullptr,
&status);
WidgetDragEvent* event = &startEvent;
// Emit observer event to allow addons to modify the DataTransfer
// object.
if (nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService()) {
observerService->NotifyObservers(dataTransfer,
"on-datatransfer-available", nullptr);
}
if (status != nsEventStatus_eConsumeNoDefault) {
bool dragStarted = DoDefaultDragStart(
aPresContext, event, dataTransfer, allowEmptyDataTransfer,
targetContent, selection, remoteDragStartData, principal,
policyContainer, cookieJarSettings);
if (dragStarted) {
sActiveESM = nullptr;
aEvent->StopPropagation();
// XXX If all elements were removed from the document, we may need to
// dispatch ePointerCancel on the Document node.
if ((targetContent = trackTargetContent.GetConnectedContent())) {
MaybeDispatchPointerCancel(*aEvent, *targetContent);
}
}
}
}
// Reset mCurretTargetContent to what it was
mCurrentTargetContent = targetBeforeEvent;
// Now flush all pending notifications, for better responsiveness
// while dragging.
FlushLayout(aPresContext);
} // GenerateDragGesture
void EventStateManager::DetermineDragTargetAndDefaultData(
nsPIDOMWindowOuter* aWindow, nsIContent* aSelectionTarget,
DataTransfer* aDataTransfer, bool* aAllowEmptyDataTransfer,
Selection** aSelection, RemoteDragStartData** aRemoteDragStartData,
nsIContent** aTargetNode, nsIPrincipal** aPrincipal,
nsIPolicyContainer** aPolicyContainer,
nsICookieJarSettings** aCookieJarSettings) {
*aTargetNode = nullptr;
*aAllowEmptyDataTransfer = false;
nsCOMPtr<nsIContent> dragDataNode;
nsIContent* editingElement = aSelectionTarget->IsEditable()
? aSelectionTarget->GetEditingHost()
: nullptr;
// In chrome, only allow dragging inside editable areas.
bool isChromeContext = !aWindow->GetBrowsingContext()->IsContent();
if (isChromeContext && !editingElement) {
if (mGestureDownDragStartData) {
// A child process started a drag so use any data it assigned for the dnd
// session.
mGestureDownDragStartData->AddInitialDnDDataTo(
aDataTransfer, aPrincipal, aPolicyContainer, aCookieJarSettings);
mGestureDownDragStartData.forget(aRemoteDragStartData);
*aAllowEmptyDataTransfer = true;
}
} else {
mGestureDownDragStartData = nullptr;
// GetDragData determines if a selection, link or image in the content
// should be dragged, and places the data associated with the drag in the
// data transfer.
// mGestureDownContent is the node where the mousedown event for the drag
// occurred, and aSelectionTarget is the node to use when a selection is
// used
bool canDrag;
bool wasAlt = (mGestureModifiers & MODIFIER_ALT) != 0;
nsresult rv = nsContentAreaDragDrop::GetDragData(
aWindow, mGestureDownContent, aSelectionTarget, wasAlt, aDataTransfer,
&canDrag, aSelection, getter_AddRefs(dragDataNode), aPolicyContainer,
aCookieJarSettings);
if (NS_FAILED(rv) || !canDrag) {
return;
}
}
// if GetDragData returned a node, use that as the node being dragged.
// Otherwise, if a selection is being dragged, use the node within the
// selection that was dragged. Otherwise, just use the mousedown target.
nsIContent* dragContent = mGestureDownContent;
if (dragDataNode)
dragContent = dragDataNode;
else if (*aSelection)
dragContent = aSelectionTarget;
nsIContent* originalDragContent = dragContent;
// If a selection isn't being dragged, look for an ancestor with the
// draggable property set. If one is found, use that as the target of the
// drag instead of the node that was clicked on. If a draggable node wasn't
// found, just use the clicked node.
if (!*aSelection) {
while (dragContent) {
if (auto htmlElement = nsGenericHTMLElement::FromNode(dragContent)) {
if (htmlElement->Draggable()) {
// We let draggable elements to trigger dnd even if there is no data
// in the DataTransfer.
*aAllowEmptyDataTransfer = true;
break;
}
} else {
if (dragContent->IsXULElement()) {
// All XUL elements are draggable, so if a XUL element is
// encountered, stop looking for draggable nodes and just use the
// original clicked node instead.
// XXXndeakin
// In the future, we will want to improve this so that XUL has a
// better way to specify whether something is draggable than just
// on/off.
dragContent = mGestureDownContent;
break;
}
// otherwise, it's not an HTML or XUL element, so just keep looking
}
dragContent = dragContent->GetFlattenedTreeParent();
}
}
// if no node in the hierarchy was found to drag, but the GetDragData method
// returned a node, use that returned node. Otherwise, nothing is draggable.
if (!dragContent && dragDataNode) dragContent = dragDataNode;
if (dragContent) {
// if an ancestor node was used instead, clear the drag data
// XXXndeakin rework this a bit. Find a way to just not call GetDragData if
// we don't need to.
if (dragContent != originalDragContent) aDataTransfer->ClearAll();
*aTargetNode = dragContent;
NS_ADDREF(*aTargetNode);
}
}
bool EventStateManager::DoDefaultDragStart(
nsPresContext* aPresContext, WidgetDragEvent* aDragEvent,
DataTransfer* aDataTransfer, bool aAllowEmptyDataTransfer,
nsIContent* aDragTarget, Selection* aSelection,
RemoteDragStartData* aDragStartData, nsIPrincipal* aPrincipal,
nsIPolicyContainer* aPolicyContainer,
nsICookieJarSettings* aCookieJarSettings) {
nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1");
if (!dragService) return false;
// Default handling for the dragstart event.
//
// First, check if a drag session already exists. This means that the drag
// service was called directly within a draggesture handler. In this case,
// don't do anything more, as it is assumed that the handler is managing
// drag and drop manually. Make sure to return true to indicate that a drag
// began. However, if we're handling drag session for synthesized events,
// we need to initialize some information of the session. Therefore, we
// need to keep going for synthesized case.
if (MOZ_UNLIKELY(!mPresContext)) {
return true;
}
nsCOMPtr<nsIDragSession> dragSession =
dragService->GetCurrentSession(mPresContext->GetRootWidget());
if (dragSession && !dragSession->IsSynthesizedForTests()) {
return true;
}
// No drag session is currently active, so check if a handler added
// any items to be dragged. If not, there isn't anything to drag.
uint32_t count = 0;
if (aDataTransfer) {
count = aDataTransfer->MozItemCount();
}
if (!aAllowEmptyDataTransfer && !count) {
return false;
}
// Get the target being dragged, which may not be the same as the
// target of the mouse event. If one wasn't set in the
// aDataTransfer during the event handler, just use the original
// target instead.
nsCOMPtr<nsIContent> dragTarget = aDataTransfer->GetDragTarget();
if (!dragTarget) {
dragTarget = aDragTarget;
if (!dragTarget) {
return false;
}
}
// check which drag effect should initially be used. If the effect was not
// set, just use all actions, otherwise Windows won't allow a drop.
uint32_t action = aDataTransfer->EffectAllowedInt();
if (action == nsIDragService::DRAGDROP_ACTION_UNINITIALIZED) {
action = nsIDragService::DRAGDROP_ACTION_COPY |
nsIDragService::DRAGDROP_ACTION_MOVE |
nsIDragService::DRAGDROP_ACTION_LINK;
}
// get any custom drag image that was set
int32_t imageX, imageY;
RefPtr<Element> dragImage = aDataTransfer->GetDragImage(&imageX, &imageY);
nsCOMPtr<nsIArray> transArray = aDataTransfer->GetTransferables(dragTarget);
if (!transArray) {
return false;
}
RefPtr<DataTransfer> dataTransfer;
if (!dragSession) {
// After this function returns, the DataTransfer will be cleared so it
// appears empty to content. We need to pass a DataTransfer into the Drag
// Session, so we need to make a copy.
aDataTransfer->Clone(aDragTarget, eDrop, aDataTransfer->MozUserCancelled(),
false, getter_AddRefs(dataTransfer));
// Copy over the drop effect, as Clone doesn't copy it for us.
dataTransfer->SetDropEffectInt(aDataTransfer->DropEffectInt());
} else {
MOZ_ASSERT(dragSession->IsSynthesizedForTests());
MOZ_ASSERT(aDragEvent->mFlags.mIsSynthesizedForTests);
// If we're initializing synthesized drag session, we should use given
// DataTransfer as is because it'll be used with following drag events
// in any tests, therefore it should be set to nsIDragSession.dataTransfer
// because it and DragEvent.dataTransfer should be same instance.
dataTransfer = aDataTransfer;
}
// XXXndeakin don't really want to create a new drag DOM event
// here, but we need something to pass to the InvokeDragSession
// methods.
RefPtr<DragEvent> event =
NS_NewDOMDragEvent(dragTarget, aPresContext, aDragEvent);
// Use InvokeDragSessionWithSelection if a selection is being dragged,
// such that the image can be generated from the selected text. However,
// use InvokeDragSessionWithImage if a custom image was set or something
// other than a selection is being dragged.
if (!dragImage && aSelection) {
dragService->InvokeDragSessionWithSelection(
aSelection, aPrincipal, aPolicyContainer, aCookieJarSettings,
transArray, action, event, dataTransfer, dragTarget);
} else if (aDragStartData) {
MOZ_ASSERT(XRE_IsParentProcess());
dragService->InvokeDragSessionWithRemoteImage(
dragTarget, aPrincipal, aPolicyContainer, aCookieJarSettings,
transArray, action, aDragStartData, event, dataTransfer);
} else {
dragService->InvokeDragSessionWithImage(
dragTarget, aPrincipal, aPolicyContainer, aCookieJarSettings,
transArray, action, dragImage, imageX, imageY, event, dataTransfer);
}
return true;
}
void EventStateManager::ChangeZoom(bool aIncrease) {
// Send the zoom change to the top level browser so it will be handled by the
// front end in the same way as other zoom actions.
nsIDocShell* docShell = mDocument->GetDocShell();
if (!docShell) {
return;
}
BrowsingContext* bc = docShell->GetBrowsingContext();
if (!bc) {
return;
}
if (XRE_IsParentProcess()) {
bc->Canonical()->DispatchWheelZoomChange(aIncrease);
} else if (BrowserChild* child = BrowserChild::GetFrom(docShell)) {
child->SendWheelZoomChange(aIncrease);
}
}
void EventStateManager::DoScrollHistory(int32_t direction) {
nsCOMPtr<nsISupports> pcContainer(mPresContext->GetContainerWeak());
if (pcContainer) {
nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(pcContainer));
if (webNav) {
// positive direction to go back one step, nonpositive to go forward
// This is doing user-initiated history traversal, hence we want
// to require that history entries we navigate to have user interaction.
if (direction > 0)
webNav->GoBack(StaticPrefs::browser_navigation_requireUserInteraction(),
true);
else
webNav->GoForward(
StaticPrefs::browser_navigation_requireUserInteraction(), true);
}
}
}
void EventStateManager::DoScrollZoom(nsIFrame* aTargetFrame,
int32_t adjustment) {
// Exclude content in chrome docshells.
nsIContent* content = aTargetFrame->GetContent();
if (content && !nsContentUtils::IsInChromeDocshell(content->OwnerDoc())) {
// Positive adjustment to decrease zoom, negative to increase
const bool increase = adjustment <= 0;
EnsureDocument(mPresContext);
ChangeZoom(increase);
}
}
static nsIFrame* GetParentFrameToScroll(nsIFrame* aFrame) {
if (!aFrame) return nullptr;
if (aFrame->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
nsLayoutUtils::IsReallyFixedPos(aFrame)) {
return aFrame->PresShell()->GetRootScrollContainerFrame();
}
return aFrame->GetParent();
}
void EventStateManager::DispatchLegacyMouseScrollEvents(
nsIFrame* aTargetFrame, WidgetWheelEvent* aEvent, nsEventStatus* aStatus) {
MOZ_ASSERT(aEvent);
MOZ_ASSERT(aStatus);
if (!aTargetFrame || *aStatus == nsEventStatus_eConsumeNoDefault) {
return;
}
// Ignore mouse wheel transaction for computing legacy mouse wheel
// events' delta value.
// DOM event's delta vales are computed from CSS pixels.
auto scrollAmountInCSSPixels =
CSSIntSize::FromAppUnitsRounded(aEvent->mScrollAmount);
// XXX We don't deal with fractional amount in legacy event, though the
// default action handler (DoScrollText()) deals with it.
// If we implemented such strict computation, we would need additional
// accumulated delta values. It would made the code more complicated.
// And also it would computes different delta values from older version.
// It doesn't make sense to implement such code for legacy events and
// rare cases.
int32_t scrollDeltaX, scrollDeltaY, pixelDeltaX, pixelDeltaY;
switch (aEvent->mDeltaMode) {
case WheelEvent_Binding::DOM_DELTA_PAGE:
scrollDeltaX = !aEvent->mLineOrPageDeltaX
? 0
: (aEvent->mLineOrPageDeltaX > 0
? UIEvent_Binding::SCROLL_PAGE_DOWN
: UIEvent_Binding::SCROLL_PAGE_UP);
scrollDeltaY = !aEvent->mLineOrPageDeltaY
? 0
: (aEvent->mLineOrPageDeltaY > 0
? UIEvent_Binding::SCROLL_PAGE_DOWN
: UIEvent_Binding::SCROLL_PAGE_UP);
pixelDeltaX = RoundDown(aEvent->mDeltaX * scrollAmountInCSSPixels.width);
pixelDeltaY = RoundDown(aEvent->mDeltaY * scrollAmountInCSSPixels.height);
break;
case WheelEvent_Binding::DOM_DELTA_LINE:
scrollDeltaX = aEvent->mLineOrPageDeltaX;
scrollDeltaY = aEvent->mLineOrPageDeltaY;
pixelDeltaX = RoundDown(aEvent->mDeltaX * scrollAmountInCSSPixels.width);
pixelDeltaY = RoundDown(aEvent->mDeltaY * scrollAmountInCSSPixels.height);
break;
case WheelEvent_Binding::DOM_DELTA_PIXEL:
scrollDeltaX = aEvent->mLineOrPageDeltaX;
scrollDeltaY = aEvent->mLineOrPageDeltaY;
pixelDeltaX = RoundDown(aEvent->mDeltaX);
pixelDeltaY = RoundDown(aEvent->mDeltaY);
break;
default:
MOZ_CRASH("Invalid deltaMode value comes");
}
// Send the legacy events in following order:
// 1. Vertical scroll
// 2. Vertical pixel scroll (even if #1 isn't consumed)
// 3. Horizontal scroll (even if #1 and/or #2 are consumed)
// 4. Horizontal pixel scroll (even if #3 isn't consumed)
AutoWeakFrame targetFrame(aTargetFrame);
MOZ_ASSERT(*aStatus != nsEventStatus_eConsumeNoDefault &&
!aEvent->DefaultPrevented(),
"If you make legacy events dispatched for default prevented wheel "
"event, you need to initialize stateX and stateY");
EventState stateX, stateY;
if (scrollDeltaY) {
SendLineScrollEvent(aTargetFrame, aEvent, stateY, scrollDeltaY,
DELTA_DIRECTION_Y);
if (!targetFrame.IsAlive()) {
*aStatus = nsEventStatus_eConsumeNoDefault;
return;
}
}
if (pixelDeltaY) {
SendPixelScrollEvent(aTargetFrame, aEvent, stateY, pixelDeltaY,
DELTA_DIRECTION_Y);
if (!targetFrame.IsAlive()) {
*aStatus = nsEventStatus_eConsumeNoDefault;
return;
}
}
if (scrollDeltaX) {
SendLineScrollEvent(aTargetFrame, aEvent, stateX, scrollDeltaX,
DELTA_DIRECTION_X);
if (!targetFrame.IsAlive()) {
*aStatus = nsEventStatus_eConsumeNoDefault;
return;
}
}
if (pixelDeltaX) {
SendPixelScrollEvent(aTargetFrame, aEvent, stateX, pixelDeltaX,
DELTA_DIRECTION_X);
if (!targetFrame.IsAlive()) {
*aStatus = nsEventStatus_eConsumeNoDefault;
return;
}
}
if (stateY.mDefaultPrevented) {
*aStatus = nsEventStatus_eConsumeNoDefault;
aEvent->PreventDefault(!stateY.mDefaultPreventedByContent);
}
if (stateX.mDefaultPrevented) {
*aStatus = nsEventStatus_eConsumeNoDefault;
aEvent->PreventDefault(!stateX.mDefaultPreventedByContent);
}
}
void EventStateManager::SendLineScrollEvent(nsIFrame* aTargetFrame,
WidgetWheelEvent* aEvent,
EventState& aState, int32_t aDelta,
DeltaDirection aDeltaDirection) {
nsCOMPtr<nsIContent> targetContent = aTargetFrame->GetContent();
if (!targetContent) {
targetContent = GetFocusedElement();
if (!targetContent) {
return;
}
}
while (targetContent->IsText()) {
targetContent = targetContent->GetFlattenedTreeParent();
}
WidgetMouseScrollEvent event(aEvent->IsTrusted(),
eLegacyMouseLineOrPageScroll, aEvent->mWidget);
event.mFlags.mDefaultPrevented = aState.mDefaultPrevented;
event.mFlags.mDefaultPreventedByContent = aState.mDefaultPreventedByContent;
event.mRefPoint = aEvent->mRefPoint;
event.mTimeStamp = aEvent->mTimeStamp;
event.mModifiers = aEvent->mModifiers;
event.mButtons = aEvent->mButtons;
event.mIsHorizontal = (aDeltaDirection == DELTA_DIRECTION_X);
event.mDelta = aDelta;
event.mInputSource = aEvent->mInputSource;
RefPtr<nsPresContext> presContext = aTargetFrame->PresContext();
nsEventStatus status = nsEventStatus_eIgnore;
EventDispatcher::Dispatch(targetContent, presContext, &event, nullptr,
&status);
aState.mDefaultPrevented =
event.DefaultPrevented() || status == nsEventStatus_eConsumeNoDefault;
aState.mDefaultPreventedByContent = event.DefaultPreventedByContent();
}
void EventStateManager::SendPixelScrollEvent(nsIFrame* aTargetFrame,
WidgetWheelEvent* aEvent,
EventState& aState,
int32_t aPixelDelta,
DeltaDirection aDeltaDirection) {
nsCOMPtr<nsIContent> targetContent = aTargetFrame->GetContent();
if (!targetContent) {
targetContent = GetFocusedElement();
if (!targetContent) {
return;
}
}
while (targetContent->IsText()) {
targetContent = targetContent->GetFlattenedTreeParent();
}
WidgetMouseScrollEvent event(aEvent->IsTrusted(), eLegacyMousePixelScroll,
aEvent->mWidget);
event.mFlags.mDefaultPrevented = aState.mDefaultPrevented;
event.mFlags.mDefaultPreventedByContent = aState.mDefaultPreventedByContent;
event.mRefPoint = aEvent->mRefPoint;
event.mTimeStamp = aEvent->mTimeStamp;
event.mModifiers = aEvent->mModifiers;
event.mButtons = aEvent->mButtons;
event.mIsHorizontal = (aDeltaDirection == DELTA_DIRECTION_X);
event.mDelta = aPixelDelta;
event.mInputSource = aEvent->mInputSource;
RefPtr<nsPresContext> presContext = aTargetFrame->PresContext();
nsEventStatus status = nsEventStatus_eIgnore;
EventDispatcher::Dispatch(targetContent, presContext, &event, nullptr,
&status);
aState.mDefaultPrevented =
event.DefaultPrevented() || status == nsEventStatus_eConsumeNoDefault;
aState.mDefaultPreventedByContent = event.DefaultPreventedByContent();
}
ScrollContainerFrame*
EventStateManager::ComputeScrollTargetAndMayAdjustWheelEvent(
nsIFrame* aTargetFrame, WidgetWheelEvent* aEvent,
ComputeScrollTargetOptions aOptions) {
return ComputeScrollTargetAndMayAdjustWheelEvent(
aTargetFrame, aEvent->mDeltaX, aEvent->mDeltaY, aEvent, aOptions);
}
// Overload ComputeScrollTargetAndMayAdjustWheelEvent method to allow passing
// "test" dx and dy when looking for which scrollbarmediators to activate when
// two finger down on trackpad and before any actual motion
ScrollContainerFrame*
EventStateManager::ComputeScrollTargetAndMayAdjustWheelEvent(
nsIFrame* aTargetFrame, double aDirectionX, double aDirectionY,
WidgetWheelEvent* aEvent, ComputeScrollTargetOptions aOptions) {
bool isAutoDir = false;
bool honoursRoot = false;
if (MAY_BE_ADJUSTED_BY_AUTO_DIR & aOptions) {
// If the scroll is respected as auto-dir, aDirection* should always be
// equivalent to the event's delta vlaues(Currently, there are only one case
// where aDirection*s have different values from the widget wheel event's
// original delta values and the only case isn't auto-dir, see
// ScrollbarsForWheel::TemporarilyActivateAllPossibleScrollTargets).
MOZ_ASSERT(aDirectionX == aEvent->mDeltaX &&
aDirectionY == aEvent->mDeltaY);
WheelDeltaAdjustmentStrategy strategy =
GetWheelDeltaAdjustmentStrategy(*aEvent);
switch (strategy) {
case WheelDeltaAdjustmentStrategy::eAutoDir:
isAutoDir = true;
honoursRoot = false;
break;
case WheelDeltaAdjustmentStrategy::eAutoDirWithRootHonour:
isAutoDir = true;
honoursRoot = true;
break;
default:
break;
}
}
if (aOptions & PREFER_MOUSE_WHEEL_TRANSACTION) {
// If the user recently scrolled with the mousewheel, then they probably
// want to scroll the same view as before instead of the view under the
// cursor. WheelTransaction tracks the frame currently being
// scrolled with the mousewheel. We consider the transaction ended when the
// mouse moves more than "mousewheel.transaction.ignoremovedelay"
// milliseconds after the last scroll operation, or any time the mouse moves
// out of the frame, or when more than "mousewheel.transaction.timeout"
// milliseconds have passed after the last operation, even if the mouse
// hasn't moved.
nsIFrame* lastScrollFrame = WheelTransaction::GetScrollTargetFrame();
if (lastScrollFrame) {
ScrollContainerFrame* scrollContainerFrame =
lastScrollFrame->GetScrollTargetFrame();
if (scrollContainerFrame) {
if (isAutoDir) {
ESMAutoDirWheelDeltaAdjuster adjuster(*aEvent, *lastScrollFrame,
honoursRoot);
// Note that calling this function will not always cause the delta to
// be adjusted, it only adjusts the delta when it should, because
// Adjust() internally calls ShouldBeAdjusted() before making
// adjustment.
adjuster.Adjust();
}
return scrollContainerFrame;
}
}
}
// If the event doesn't cause scroll actually, we cannot find scroll target
// because we check if the event can cause scroll actually on each found
// scrollable frame.
if (!aDirectionX && !aDirectionY) {
return nullptr;
}
bool checkIfScrollableX;
bool checkIfScrollableY;
if (isAutoDir) {
// Always check the frame's scrollability in both the two directions for an
// auto-dir scroll. That is, for an auto-dir scroll,
// PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_X_AXIS and
// PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_Y_AXIS should be ignored.
checkIfScrollableX = true;
checkIfScrollableY = true;
} else {
checkIfScrollableX =
aDirectionX &&
(aOptions & PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_X_AXIS);
checkIfScrollableY =
aDirectionY &&
(aOptions & PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_Y_AXIS);
}
nsIFrame* scrollFrame = !(aOptions & START_FROM_PARENT)
? aTargetFrame
: GetParentFrameToScroll(aTargetFrame);
for (; scrollFrame; scrollFrame = GetParentFrameToScroll(scrollFrame)) {
// Check whether the frame wants to provide us with a scrollable view.
ScrollContainerFrame* scrollContainerFrame =
scrollFrame->GetScrollTargetFrame();
if (!scrollContainerFrame) {
nsMenuPopupFrame* menuPopupFrame = do_QueryFrame(scrollFrame);
if (menuPopupFrame) {
return nullptr;
}
continue;
}
if (!checkIfScrollableX && !checkIfScrollableY) {
return scrollContainerFrame;
}
// If the frame disregards the direction the user is trying to scroll, then
// it should just bubbles the scroll event up to its parental scroll frame
Maybe<layers::ScrollDirection> disregardedDirection =
WheelHandlingUtils::GetDisregardedWheelScrollDirection(scrollFrame);
if (disregardedDirection) {
switch (disregardedDirection.ref()) {
case layers::ScrollDirection::eHorizontal:
if (checkIfScrollableX) {
continue;
}
break;
case layers::ScrollDirection::eVertical:
if (checkIfScrollableY) {
continue;
}
break;
}
}
layers::ScrollDirections directions =
scrollContainerFrame
->GetAvailableScrollingDirectionsForUserInputEvents();
if ((!(directions.contains(layers::ScrollDirection::eVertical)) &&
!(directions.contains(layers::ScrollDirection::eHorizontal))) ||
(checkIfScrollableY && !checkIfScrollableX &&
!(directions.contains(layers::ScrollDirection::eVertical))) ||
(checkIfScrollableX && !checkIfScrollableY &&
!(directions.contains(layers::ScrollDirection::eHorizontal)))) {
continue;
}
// Computes whether the currently checked frame is scrollable by this wheel
// event.
bool canScroll = false;
if (isAutoDir) {
ESMAutoDirWheelDeltaAdjuster adjuster(*aEvent, *scrollFrame, honoursRoot);
if (adjuster.ShouldBeAdjusted()) {
adjuster.Adjust();
canScroll = true;
} else if (WheelHandlingUtils::CanScrollOn(scrollContainerFrame,
aDirectionX, aDirectionY)) {
canScroll = true;
}
} else if (WheelHandlingUtils::CanScrollOn(scrollContainerFrame,
aDirectionX, aDirectionY)) {
canScroll = true;
}
if (canScroll) {
return scrollContainerFrame;
}
// Where we are at is the block ending in a for loop.
// The current frame has been checked to be unscrollable by this wheel
// event, continue the loop to check its parent, if any.
}
nsIFrame* newFrame = nsLayoutUtils::GetCrossDocParentFrameInProcess(
aTargetFrame->PresShell()->GetRootFrame());
aOptions =
static_cast<ComputeScrollTargetOptions>(aOptions & ~START_FROM_PARENT);
if (!newFrame) {
return nullptr;
}
return ComputeScrollTargetAndMayAdjustWheelEvent(newFrame, aEvent, aOptions);
}
nsSize EventStateManager::GetScrollAmount(
nsPresContext* aPresContext, WidgetWheelEvent* aEvent,
ScrollContainerFrame* aScrollContainerFrame) {
MOZ_ASSERT(aPresContext);
MOZ_ASSERT(aEvent);
const bool isPage = aEvent->mDeltaMode == WheelEvent_Binding::DOM_DELTA_PAGE;
if (!aScrollContainerFrame) {
// If there is no scrollable frame, we should use root, see below.
aScrollContainerFrame =
aPresContext->PresShell()->GetRootScrollContainerFrame();
}
if (aScrollContainerFrame) {
return isPage ? aScrollContainerFrame->GetPageScrollAmount()
: aScrollContainerFrame->GetLineScrollAmount();
}
// If there is no scrollable frame and page scrolling, use viewport size.
if (isPage) {
return aPresContext->GetVisibleArea().Size();
}
// Otherwise use root frame's font metrics.
//
// FIXME(emilio): Should this use the root element's style frame? The root
// frame will always have the initial font. Then again it should never matter
// for content, we should always have a root scrollable frame in html
// documents.
nsIFrame* rootFrame = aPresContext->PresShell()->GetRootFrame();
if (!rootFrame) {
return nsSize(0, 0);
}
RefPtr<nsFontMetrics> fm =
nsLayoutUtils::GetInflatedFontMetricsForFrame(rootFrame);
NS_ENSURE_TRUE(fm, nsSize(0, 0));
return nsSize(fm->AveCharWidth(), fm->MaxHeight());
}
void EventStateManager::DoScrollText(
ScrollContainerFrame* aScrollContainerFrame, WidgetWheelEvent* aEvent) {
MOZ_ASSERT(aScrollContainerFrame);
MOZ_ASSERT(aEvent);
AutoWeakFrame scrollFrameWeak(aScrollContainerFrame);
AutoWeakFrame eventFrameWeak(mCurrentTarget);
if (!WheelTransaction::WillHandleDefaultAction(aEvent, scrollFrameWeak,
eventFrameWeak)) {
return;
}
// Default action's actual scroll amount should be computed from device
// pixels.
nsPresContext* pc = aScrollContainerFrame->PresContext();
nsSize scrollAmount = GetScrollAmount(pc, aEvent, aScrollContainerFrame);
nsIntSize scrollAmountInDevPixels(
pc->AppUnitsToDevPixels(scrollAmount.width),
pc->AppUnitsToDevPixels(scrollAmount.height));
nsIntPoint actualDevPixelScrollAmount =
DeltaAccumulator::GetInstance()->ComputeScrollAmountForDefaultAction(
aEvent, scrollAmountInDevPixels);
// Don't scroll around the axis whose overflow style is hidden.
ScrollStyles overflowStyle = aScrollContainerFrame->GetScrollStyles();
if (overflowStyle.mHorizontal == StyleOverflow::Hidden) {
actualDevPixelScrollAmount.x = 0;
}
if (overflowStyle.mVertical == StyleOverflow::Hidden) {
actualDevPixelScrollAmount.y = 0;
}
ScrollSnapFlags snapFlags = ScrollSnapFlags::Disabled;
mozilla::ScrollOrigin origin = mozilla::ScrollOrigin::NotSpecified;
switch (aEvent->mDeltaMode) {
case WheelEvent_Binding::DOM_DELTA_LINE:
origin = mozilla::ScrollOrigin::MouseWheel;
snapFlags = ScrollSnapFlags::IntendedDirection;
break;
case WheelEvent_Binding::DOM_DELTA_PAGE:
origin = mozilla::ScrollOrigin::Pages;
snapFlags = ScrollSnapFlags::IntendedDirection |
ScrollSnapFlags::IntendedEndPosition;
break;
case WheelEvent_Binding::DOM_DELTA_PIXEL:
origin = mozilla::ScrollOrigin::Pixels;
break;
default:
MOZ_CRASH("Invalid deltaMode value comes");
}
// We shouldn't scroll more one page at once except when over one page scroll
// is allowed for the event.
nsSize pageSize = aScrollContainerFrame->GetPageScrollAmount();
nsIntSize devPixelPageSize(pc->AppUnitsToDevPixels(pageSize.width),
pc->AppUnitsToDevPixels(pageSize.height));
if (!WheelPrefs::GetInstance()->IsOverOnePageScrollAllowedX(aEvent) &&
DeprecatedAbs(actualDevPixelScrollAmount.x.value) >
devPixelPageSize.width) {
actualDevPixelScrollAmount.x = (actualDevPixelScrollAmount.x >= 0)
? devPixelPageSize.width
: -devPixelPageSize.width;
}
if (!WheelPrefs::GetInstance()->IsOverOnePageScrollAllowedY(aEvent) &&
DeprecatedAbs(actualDevPixelScrollAmount.y.value) >
devPixelPageSize.height) {
actualDevPixelScrollAmount.y = (actualDevPixelScrollAmount.y >= 0)
? devPixelPageSize.height
: -devPixelPageSize.height;
}
bool isDeltaModePixel =
(aEvent->mDeltaMode == WheelEvent_Binding::DOM_DELTA_PIXEL);
ScrollMode mode;
switch (aEvent->mScrollType) {
case WidgetWheelEvent::SCROLL_DEFAULT:
if (isDeltaModePixel) {
mode = ScrollMode::Normal;
} else if (aEvent->mFlags.mHandledByAPZ) {
mode = ScrollMode::SmoothMsd;
} else {
mode = ScrollMode::Smooth;
}
break;
case WidgetWheelEvent::SCROLL_SYNCHRONOUSLY:
mode = ScrollMode::Instant;
break;
case WidgetWheelEvent::SCROLL_ASYNCHRONOUSLY:
mode = ScrollMode::Normal;
break;
case WidgetWheelEvent::SCROLL_SMOOTHLY:
mode = ScrollMode::Smooth;
break;
default:
MOZ_CRASH("Invalid mScrollType value comes");
}
ScrollContainerFrame::ScrollMomentum momentum =
aEvent->mIsMomentum ? ScrollContainerFrame::SYNTHESIZED_MOMENTUM_EVENT
: ScrollContainerFrame::NOT_MOMENTUM;
nsIntPoint overflow;
aScrollContainerFrame->ScrollBy(actualDevPixelScrollAmount,
ScrollUnit::DEVICE_PIXELS, mode, &overflow,
origin, momentum, snapFlags);
if (!scrollFrameWeak.IsAlive()) {
// If the scroll causes changing the layout, we can think that the event
// has been completely consumed by the content. Then, users probably don't
// want additional action.
aEvent->mOverflowDeltaX = aEvent->mOverflowDeltaY = 0;
} else if (isDeltaModePixel) {
aEvent->mOverflowDeltaX = overflow.x;
aEvent->mOverflowDeltaY = overflow.y;
} else {
aEvent->mOverflowDeltaX =
static_cast<double>(overflow.x) / scrollAmountInDevPixels.width;
aEvent->mOverflowDeltaY =
static_cast<double>(overflow.y) / scrollAmountInDevPixels.height;
}
// If CSS overflow properties caused not to scroll, the overflowDelta* values
// should be same as delta* values since they may be used as gesture event by
// widget. However, if there is another scrollable element in the ancestor
// along the axis, probably users don't want the operation to cause
// additional action such as moving history. In such case, overflowDelta
// values should stay zero.
if (scrollFrameWeak.IsAlive()) {
if (aEvent->mDeltaX && overflowStyle.mHorizontal == StyleOverflow::Hidden &&
!ComputeScrollTargetAndMayAdjustWheelEvent(
aScrollContainerFrame, aEvent,
COMPUTE_SCROLLABLE_ANCESTOR_ALONG_X_AXIS_WITH_AUTO_DIR)) {
aEvent->mOverflowDeltaX = aEvent->mDeltaX;
}
if (aEvent->mDeltaY && overflowStyle.mVertical == StyleOverflow::Hidden &&
!ComputeScrollTargetAndMayAdjustWheelEvent(
aScrollContainerFrame, aEvent,
COMPUTE_SCROLLABLE_ANCESTOR_ALONG_Y_AXIS_WITH_AUTO_DIR)) {
aEvent->mOverflowDeltaY = aEvent->mDeltaY;
}
}
NS_ASSERTION(
aEvent->mOverflowDeltaX == 0 ||
(aEvent->mOverflowDeltaX > 0) == (aEvent->mDeltaX > 0),
"The sign of mOverflowDeltaX is different from the scroll direction");
NS_ASSERTION(
aEvent->mOverflowDeltaY == 0 ||
(aEvent->mOverflowDeltaY > 0) == (aEvent->mDeltaY > 0),
"The sign of mOverflowDeltaY is different from the scroll direction");
WheelPrefs::GetInstance()->CancelApplyingUserPrefsFromOverflowDelta(aEvent);
}
void EventStateManager::DecideGestureEvent(WidgetGestureNotifyEvent* aEvent,
nsIFrame* targetFrame) {
NS_ASSERTION(aEvent->mMessage == eGestureNotify,
"DecideGestureEvent called with a non-gesture event");
/* Check the ancestor tree to decide if any frame is willing* to receive
* a MozPixelScroll event. If that's the case, the current touch gesture
* will be used as a pan gesture; otherwise it will be a regular
* mousedown/mousemove/click event.
*
* *willing: determine if it makes sense to pan the element using scroll
* events:
* - For web content: if there are any visible scrollbars on the touch point
* - For XUL: if it's an scrollable element that can currently scroll in some
* direction.
*
* Note: we'll have to one-off various cases to ensure a good usable behavior
*/
WidgetGestureNotifyEvent::PanDirection panDirection =
WidgetGestureNotifyEvent::ePanNone;
bool displayPanFeedback = false;
for (nsIFrame* current = targetFrame; current;
current = nsLayoutUtils::GetCrossDocParentFrame(current)) {
// e10s - mark remote content as pannable. This is a work around since
// we don't have access to remote frame scroll info here. Apz data may
// assist is solving this.
if (current && IsTopLevelRemoteTarget(current->GetContent())) {
panDirection = WidgetGestureNotifyEvent::ePanBoth;
// We don't know when we reach bounds, so just disable feedback for now.
displayPanFeedback = false;
break;
}
LayoutFrameType currentFrameType = current->Type();
// Scrollbars should always be draggable
if (currentFrameType == LayoutFrameType::Scrollbar) {
panDirection = WidgetGestureNotifyEvent::ePanNone;
break;
}
// Special check for trees
if (nsTreeBodyFrame* treeFrame = do_QueryFrame(current)) {
if (treeFrame->GetVerticalOverflow()) {
panDirection = WidgetGestureNotifyEvent::ePanVertical;
}
break;
}
if (ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(current)) {
layers::ScrollDirections scrollbarVisibility =
scrollContainerFrame->GetScrollbarVisibility();
// Check if we have visible scrollbars
if (scrollbarVisibility.contains(layers::ScrollDirection::eVertical)) {
panDirection = WidgetGestureNotifyEvent::ePanVertical;
displayPanFeedback = true;
break;
}
if (scrollbarVisibility.contains(layers::ScrollDirection::eHorizontal)) {
panDirection = WidgetGestureNotifyEvent::ePanHorizontal;
displayPanFeedback = true;
}
}
} // ancestor chain
aEvent->mDisplayPanFeedback = displayPanFeedback;
aEvent->mPanDirection = panDirection;
}
#ifdef XP_MACOSX
static nsINode* GetCrossDocParentNode(nsINode* aChild) {
MOZ_ASSERT(aChild, "The child is null!");
MOZ_ASSERT(XRE_IsParentProcess());
nsINode* parent = aChild->GetParentNode();
if (parent && parent->IsContent() && aChild->IsContent()) {
parent = aChild->AsContent()->GetFlattenedTreeParent();
}
if (parent || !aChild->IsDocument()) {
return parent;
}
return aChild->AsDocument()->GetEmbedderElement();
}
static bool NodeAllowsClickThrough(nsINode* aNode) {
while (aNode) {
if (aNode->IsAnyOfXULElements(nsGkAtoms::browser, nsGkAtoms::tree)) {
return false;
}
if (aNode->IsAnyOfXULElements(nsGkAtoms::scrollbar, nsGkAtoms::resizer)) {
return true;
}
aNode = GetCrossDocParentNode(aNode);
}
return true;
}
#endif
void EventStateManager::PostHandleKeyboardEvent(
WidgetKeyboardEvent* aKeyboardEvent, nsIFrame* aTargetFrame,
nsEventStatus& aStatus) {
if (aStatus == nsEventStatus_eConsumeNoDefault) {
return;
}
RefPtr<nsPresContext> presContext = mPresContext;
if (!aKeyboardEvent->HasBeenPostedToRemoteProcess()) {
if (aKeyboardEvent->IsWaitingReplyFromRemoteProcess()) {
RefPtr<BrowserParent> remote =
aTargetFrame ? BrowserParent::GetFrom(aTargetFrame->GetContent())
: nullptr;
if (remote) {
// remote is null-checked above in order to let pre-existing event
// targeting code's chrome vs. content decision override in case of
// disagreement in order not to disrupt non-Fission e10s mode in case
// there are still bugs in the Fission-mode code. That is, if remote
// is nullptr, the pre-existing event targeting code has deemed this
// event to belong to chrome rather than content.
BrowserParent* preciseRemote = BrowserParent::GetFocused();
if (preciseRemote) {
remote = preciseRemote;
}
// else there was a race between layout and focus tracking
}
if (remote && !remote->IsReadyToHandleInputEvents()) {
// We need to dispatch the event to the browser element again if we were
// waiting for the key reply but the event wasn't sent to the content
// process due to the remote browser wasn't ready.
WidgetKeyboardEvent keyEvent(*aKeyboardEvent);
aKeyboardEvent->MarkAsHandledInRemoteProcess();
RefPtr<Element> ownerElement = remote->GetOwnerElement();
EventDispatcher::Dispatch(ownerElement, presContext, &keyEvent);
if (keyEvent.DefaultPrevented()) {
aKeyboardEvent->PreventDefault(!keyEvent.DefaultPreventedByContent());
aStatus = nsEventStatus_eConsumeNoDefault;
return;
}
}
}
// The widget expects a reply for every keyboard event. If the event wasn't
// dispatched to a content process (non-e10s or no content process
// running), we need to short-circuit here. Otherwise, we need to wait for
// the content process to handle the event.
if (aKeyboardEvent->mWidget) {
aKeyboardEvent->mWidget->PostHandleKeyEvent(aKeyboardEvent);
}
if (aKeyboardEvent->DefaultPrevented()) {
aStatus = nsEventStatus_eConsumeNoDefault;
return;
}
}
// XXX Currently, our automated tests don't support mKeyNameIndex.
// Therefore, we still need to handle this with keyCode.
switch (aKeyboardEvent->mKeyCode) {
case NS_VK_TAB:
case NS_VK_F6:
// This is to prevent keyboard scrolling while alt modifier in use.
if (!aKeyboardEvent->IsAlt()) {
aStatus = nsEventStatus_eConsumeNoDefault;
// Handling the tab event after it was sent to content is bad,
// because to the FocusManager the remote-browser looks like one
// element, so we would just move the focus to the next element
// in chrome, instead of handling it in content.
if (aKeyboardEvent->HasBeenPostedToRemoteProcess()) {
break;
}
EnsureDocument(presContext);
nsFocusManager* fm = nsFocusManager::GetFocusManager();
if (fm && mDocument) {
// Shift focus forward or back depending on shift key
bool isDocMove = aKeyboardEvent->IsControl() ||
aKeyboardEvent->mKeyCode == NS_VK_F6;
uint32_t dir =
aKeyboardEvent->IsShift()
? (isDocMove ? static_cast<uint32_t>(
nsIFocusManager::MOVEFOCUS_BACKWARDDOC)
: static_cast<uint32_t>(
nsIFocusManager::MOVEFOCUS_BACKWARD))
: (isDocMove ? static_cast<uint32_t>(
nsIFocusManager::MOVEFOCUS_FORWARDDOC)
: static_cast<uint32_t>(
nsIFocusManager::MOVEFOCUS_FORWARD));
RefPtr<Element> result;
fm->MoveFocus(mDocument->GetWindow(), nullptr, dir,
nsIFocusManager::FLAG_BYKEY, getter_AddRefs(result));
}
}
return;
case 0:
// We handle keys with no specific keycode value below.
break;
default:
return;
}
switch (aKeyboardEvent->mKeyNameIndex) {
case KEY_NAME_INDEX_ZoomIn:
case KEY_NAME_INDEX_ZoomOut:
ChangeZoom(aKeyboardEvent->mKeyNameIndex == KEY_NAME_INDEX_ZoomIn);
aStatus = nsEventStatus_eConsumeNoDefault;
break;
default:
break;
}
}
static bool NeedsActiveContentChange(const WidgetMouseEvent* aMouseEvent) {
// If the mouse event is a synthesized mouse event due to a touch, do
// not set/clear the activation state. Element activation is handled by APZ.
return !aMouseEvent ||
aMouseEvent->mInputSource != MouseEvent_Binding::MOZ_SOURCE_TOUCH;
}
nsresult EventStateManager::PostHandleEvent(nsPresContext* aPresContext,
WidgetEvent* aEvent,
nsIFrame* aTargetFrame,
nsEventStatus* aStatus,
nsIContent* aOverrideClickTarget) {
AUTO_PROFILER_LABEL("EventStateManager::PostHandleEvent", DOM);
NS_ENSURE_ARG(aPresContext);
NS_ENSURE_ARG_POINTER(aStatus);
mCurrentTarget = aTargetFrame;
mCurrentTargetContent = nullptr;
HandleCrossProcessEvent(aEvent, aStatus);
// NOTE: the above call may have destroyed aTargetFrame, please use
// mCurrentTarget henceforth. This is to avoid using it accidentally:
aTargetFrame = nullptr;
// Most of the events we handle below require a frame.
// Add special cases here.
if (!mCurrentTarget && aEvent->mMessage != eMouseUp &&
aEvent->mMessage != eMouseDown && aEvent->mMessage != eDragEnter &&
aEvent->mMessage != eDragOver && aEvent->mMessage != ePointerUp &&
aEvent->mMessage != ePointerCancel) {
return NS_OK;
}
// Keep the prescontext alive, we might need it after event dispatch
RefPtr<nsPresContext> presContext = aPresContext;
nsresult ret = NS_OK;
switch (aEvent->mMessage) {
case eMouseDown: {
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
if (mouseEvent->mButton == MouseButton::ePrimary &&
!sNormalLMouseEventInProcess) {
// We got a mouseup event while a mousedown event was being processed.
// Make sure that the capturing content is cleared.
PresShell::ReleaseCapturingContent();
break;
}
// For remote content, capture the event in the parent process at the
// <xul:browser remote> element. This will ensure that subsequent
// mousemove/mouseup events will continue to be dispatched to this element
// and therefore forwarded to the child.
if (aEvent->HasBeenPostedToRemoteProcess() &&
!PresShell::GetCapturingContent()) {
if (nsIContent* content =
mCurrentTarget ? mCurrentTarget->GetContent() : nullptr) {
PresShell::SetCapturingContent(content, CaptureFlags::None, aEvent);
} else {
PresShell::ReleaseCapturingContent();
}
}
// If MouseEvent::PreventClickEvent() was called by chrome script,
// we need to forget the clicking content and click count for the
// following eMouseUp event.
if (mouseEvent->mClickEventPrevented) {
switch (mouseEvent->mButton) {
case MouseButton::ePrimary:
case MouseButton::eSecondary:
case MouseButton::eMiddle: {
LastMouseDownInfo& mouseDownInfo =
GetLastMouseDownInfo(mouseEvent->mButton);
mouseDownInfo.mLastMouseDownContent = nullptr;
mouseDownInfo.mClickCount = 0;
mouseDownInfo.mLastMouseDownInputControlType = Nothing();
break;
}
default:
break;
}
}
nsCOMPtr<nsIContent> activeContent;
// When content calls PreventDefault on pointerdown, we also call
// PreventDefault on the subsequent mouse events to suppress default
// behaviors. Normally, aStatus should be nsEventStatus_eConsumeNoDefault
// when the event is DefaultPrevented but it's reset to
// nsEventStatus_eIgnore in EventStateManager::PreHandleEvent. So we also
// check if the event is DefaultPrevented.
if (nsEventStatus_eConsumeNoDefault != *aStatus &&
!aEvent->DefaultPrevented()) {
nsCOMPtr<nsIContent> newFocus;
bool suppressBlur = false;
if (mCurrentTarget) {
newFocus = mCurrentTarget->GetContentForEvent(aEvent);
activeContent = mCurrentTarget->GetContent();
// In some cases, we do not want to even blur the current focused
// element. Those cases are:
// 1. -moz-user-focus CSS property is set to 'ignore';
// 2. XUL control element has the disabled property set to 'true'.
//
// We can't use nsIFrame::IsFocusable() because we want to blur when
// we click on a visibility: none element.
// We can't use nsIContent::IsFocusable() because we want to blur when
// we click on a non-focusable element like a <div>.
// We have to use |aEvent->mTarget| to not make sure we do not check
// an anonymous node of the targeted element.
suppressBlur =
mCurrentTarget->StyleUI()->UserFocus() == StyleUserFocus::Ignore;
if (!suppressBlur) {
if (Element* element =
Element::FromEventTargetOrNull(aEvent->mTarget)) {
if (nsCOMPtr<nsIDOMXULControlElement> xulControl =
element->AsXULControl()) {
bool disabled = false;
xulControl->GetDisabled(&disabled);
suppressBlur = disabled;
}
}
}
}
// When a root content which isn't editable but has an editable HTML
// <body> element is clicked, we should redirect the focus to the
// the <body> element. E.g., when an user click bottom of the editor
// where is outside of the <body> element, the <body> should be focused
// and the user can edit immediately after that.
//
// NOTE: The newFocus isn't editable that also means it's not in
// designMode. In designMode, all contents are not focusable.
if (newFocus && !newFocus->IsEditable()) {
Document* doc = newFocus->GetComposedDoc();
if (doc && newFocus == doc->GetRootElement()) {
nsIContent* bodyContent =
nsLayoutUtils::GetEditableRootContentByContentEditable(doc);
if (bodyContent && bodyContent->GetPrimaryFrame()) {
newFocus = bodyContent;
}
}
}
// When the mouse is pressed, the default action is to focus the
// target. Look for the nearest enclosing focusable frame.
//
// TODO: Probably this should be moved to Element::PostHandleEvent.
for (; newFocus; newFocus = newFocus->GetFlattenedTreeParent()) {
if (!newFocus->IsElement()) {
continue;
}
nsIFrame* frame = newFocus->GetPrimaryFrame();
if (!frame) {
continue;
}
// If the mousedown happened inside a popup, don't try to set focus on
// one of its containing elements
if (frame->IsMenuPopupFrame()) {
newFocus = nullptr;
break;
}
auto flags = IsFocusableFlags::WithMouse;
if (frame->IsFocusable(flags)) {
break;
}
if (ShadowRoot* root = newFocus->GetShadowRoot()) {
if (root->DelegatesFocus()) {
if (Element* firstFocusable = root->GetFocusDelegate(flags)) {
newFocus = firstFocusable;
break;
}
}
}
}
MOZ_ASSERT_IF(newFocus, newFocus->IsElement());
if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
// if something was found to focus, focus it. Otherwise, if the
// element that was clicked doesn't have -moz-user-focus: ignore,
// clear the existing focus. For -moz-user-focus: ignore, the focus
// is just left as is.
// Another effect of mouse clicking, handled in Selection, is that
// it should update the caret position to where the mouse was
// clicked. Because the focus is cleared when clicking on a
// non-focusable node, the next press of the tab key will cause
// focus to be shifted from the caret position instead of the root.
if (newFocus) {
// use the mouse flag and the noscroll flag so that the content
// doesn't unexpectedly scroll when clicking an element that is
// only half visible
uint32_t flags =
nsIFocusManager::FLAG_BYMOUSE | nsIFocusManager::FLAG_NOSCROLL;
// If this was a touch-generated event, pass that information:
if (mouseEvent->mInputSource ==
MouseEvent_Binding::MOZ_SOURCE_TOUCH) {
flags |= nsIFocusManager::FLAG_BYTOUCH;
}
fm->SetFocus(MOZ_KnownLive(newFocus->AsElement()), flags);
} else if (!suppressBlur) {
// clear the focus within the frame and then set it as the
// focused frame
EnsureDocument(mPresContext);
if (mDocument) {
nsCOMPtr<nsPIDOMWindowOuter> outerWindow = mDocument->GetWindow();
#ifdef XP_MACOSX
if (!activeContent || !activeContent->IsXULElement())
#endif
fm->ClearFocus(outerWindow);
// Prevent switch frame if we're already not in the foreground tab
// and we're in a content process.
// TODO: If we were inactive frame in this tab, and now in
// background tab, we shouldn't make the tab foreground, but
// we should set focus to clicked document in the background
// tab. However, nsFocusManager does not have proper method
// for doing this. Therefore, we should skip setting focus
// to clicked document for now.
if (XRE_IsParentProcess() || IsInActiveTab(mDocument)) {
fm->SetFocusedWindow(outerWindow);
}
}
}
}
// The rest is left button-specific.
if (mouseEvent->mButton != MouseButton::ePrimary) {
break;
}
// The nearest enclosing element goes into the :active state. If we're
// not an element (so we're text or something) we need to obtain
// our parent element and put it into :active instead.
if (activeContent && !activeContent->IsElement()) {
if (nsIContent* par = activeContent->GetFlattenedTreeParent()) {
activeContent = par;
}
}
} else {
// if we're here, the event handler returned false, so stop
// any of our own processing of a drag. Workaround for bug 43258.
StopTrackingDragGesture(true);
}
// XXX Why do we always set this is active? Active window may be changed
// by a mousedown event listener.
if (NeedsActiveContentChange(mouseEvent)) {
SetActiveManager(this, activeContent);
}
} break;
case ePointerCancel:
case ePointerUp: {
WidgetPointerEvent* pointerEvent = aEvent->AsPointerEvent();
MOZ_ASSERT(pointerEvent);
// Implicitly releasing capture for given pointer. ePointerLostCapture
// should be send after ePointerUp or ePointerCancel.
PointerEventHandler::ImplicitlyReleasePointerCapture(pointerEvent);
PointerEventHandler::UpdatePointerActiveState(pointerEvent);
if (
// After pointercancel, pointer becomes invalid so we can remove
// relevant helper from table.
pointerEvent->mMessage == ePointerCancel ||
// pointerup for non-hoverable pointer needs to dispatch pointerout
// and pointerleave events because the pointer is valid only while the
// pointer is "down".
!pointerEvent->InputSourceSupportsHover()) {
GenerateMouseEnterExit(pointerEvent);
mPointersEnterLeaveHelper.Remove(pointerEvent->pointerId);
}
break;
}
case eMouseUp: {
// We can unconditionally stop capturing because
// we should never be capturing when the mouse button is up
PresShell::ReleaseCapturingContent();
WidgetMouseEvent* mouseUpEvent = aEvent->AsMouseEvent();
if (NeedsActiveContentChange(mouseUpEvent)) {
ClearGlobalActiveContent(this);
}
if (mouseUpEvent && EventCausesClickEvents(*mouseUpEvent)) {
// Make sure to dispatch the click even if there is no frame for
// the current target element. This is required for Web compatibility.
RefPtr<EventStateManager> esm =
ESMFromContentOrThis(aOverrideClickTarget);
ret =
esm->PostHandleMouseUp(mouseUpEvent, aStatus, aOverrideClickTarget);
}
// After dispatching click events for this eMouseUp, nobody needs to refer
// to the preceding ePointerUp event target anymore because it was
// required by the click event dispatcher to consider the target.
// Therefore, PointerEventHandler should forget the target now.
PointerEventHandler::ReleasePointerCapturingElementAtLastPointerUp();
if (PresShell* presShell = presContext->GetPresShell()) {
RefPtr<nsFrameSelection> frameSelection = presShell->FrameSelection();
frameSelection->SetDragState(false);
}
} break;
case eWheelOperationEnd: {
MOZ_ASSERT(aEvent->IsTrusted());
ScrollbarsForWheel::MayInactivate();
WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent();
ScrollContainerFrame* scrollTarget =
ComputeScrollTargetAndMayAdjustWheelEvent(
mCurrentTarget, wheelEvent,
COMPUTE_DEFAULT_ACTION_TARGET_WITH_AUTO_DIR);
// If the wheel event was handled by APZ, APZ will perform the scroll
// snap.
if (scrollTarget && !WheelTransaction::HandledByApz()) {
scrollTarget->ScrollSnap();
}
} break;
case eWheel:
case eWheelOperationStart: {
MOZ_ASSERT(aEvent->IsTrusted());
if (*aStatus == nsEventStatus_eConsumeNoDefault) {
ScrollbarsForWheel::Inactivate();
break;
}
WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent();
MOZ_ASSERT(wheelEvent);
// When APZ is enabled, the actual scroll animation might be handled by
// the compositor.
WheelPrefs::Action action =
wheelEvent->mFlags.mHandledByAPZ
? WheelPrefs::ACTION_NONE
: WheelPrefs::GetInstance()->ComputeActionFor(wheelEvent);
WheelDeltaAdjustmentStrategy strategy =
GetWheelDeltaAdjustmentStrategy(*wheelEvent);
// Adjust the delta values of the wheel event if the current default
// action is to horizontalize scrolling. I.e., deltaY values are set to
// deltaX and deltaY and deltaZ values are set to 0.
// If horizontalized, the delta values will be restored and its overflow
// deltaX will become 0 when the WheelDeltaHorizontalizer instance is
// being destroyed.
WheelDeltaHorizontalizer horizontalizer(*wheelEvent);
if (WheelDeltaAdjustmentStrategy::eHorizontalize == strategy) {
horizontalizer.Horizontalize();
}
// Since ComputeScrollTargetAndMayAdjustWheelEvent() may adjust the delta
// if the event is auto-dir. So we use |ESMAutoDirWheelDeltaRestorer|
// here.
// An instance of |ESMAutoDirWheelDeltaRestorer| is used to monitor
// auto-dir adjustment which may happen during its lifetime. If the delta
// values is adjusted during its lifetime, the instance will restore the
// adjusted delta when it's being destrcuted.
ESMAutoDirWheelDeltaRestorer restorer(*wheelEvent);
ScrollContainerFrame* scrollTarget =
ComputeScrollTargetAndMayAdjustWheelEvent(
mCurrentTarget, wheelEvent,
COMPUTE_DEFAULT_ACTION_TARGET_WITH_AUTO_DIR);
switch (action) {
case WheelPrefs::ACTION_SCROLL:
case WheelPrefs::ACTION_HORIZONTALIZED_SCROLL: {
// For scrolling of default action, we should honor the mouse wheel
// transaction.
ScrollbarsForWheel::PrepareToScrollText(this, mCurrentTarget,
wheelEvent);
if (aEvent->mMessage != eWheel ||
(!wheelEvent->mDeltaX && !wheelEvent->mDeltaY)) {
break;
}
ScrollbarsForWheel::SetActiveScrollTarget(scrollTarget);
ScrollContainerFrame* rootScrollContainerFrame =
!mCurrentTarget
? nullptr
: mCurrentTarget->PresShell()->GetRootScrollContainerFrame();
if (!scrollTarget || scrollTarget == rootScrollContainerFrame) {
wheelEvent->mViewPortIsOverscrolled = true;
}
wheelEvent->mOverflowDeltaX = wheelEvent->mDeltaX;
wheelEvent->mOverflowDeltaY = wheelEvent->mDeltaY;
WheelPrefs::GetInstance()->CancelApplyingUserPrefsFromOverflowDelta(
wheelEvent);
if (scrollTarget) {
DoScrollText(scrollTarget, wheelEvent);
} else {
WheelTransaction::EndTransaction();
ScrollbarsForWheel::Inactivate();
}
break;
}
case WheelPrefs::ACTION_HISTORY: {
// If this event doesn't cause eLegacyMouseLineOrPageScroll event or
// the direction is oblique, don't perform history back/forward.
int32_t intDelta = wheelEvent->GetPreferredIntDelta();
if (!intDelta) {
break;
}
DoScrollHistory(intDelta);
break;
}
case WheelPrefs::ACTION_ZOOM: {
// If this event doesn't cause eLegacyMouseLineOrPageScroll event or
// the direction is oblique, don't perform zoom in/out.
int32_t intDelta = wheelEvent->GetPreferredIntDelta();
if (!intDelta) {
break;
}
DoScrollZoom(mCurrentTarget, intDelta);
break;
}
case WheelPrefs::ACTION_NONE:
default:
bool allDeltaOverflown = false;
if (StaticPrefs::dom_event_wheel_event_groups_enabled() &&
(wheelEvent->mDeltaX != 0.0 || wheelEvent->mDeltaY != 0.0)) {
if (scrollTarget) {
WheelTransaction::WillHandleDefaultAction(
wheelEvent, scrollTarget, mCurrentTarget);
} else {
WheelTransaction::EndTransaction();
}
}
if (wheelEvent->mFlags.mHandledByAPZ) {
if (wheelEvent->mCanTriggerSwipe) {
// For events that can trigger swipes, APZ needs to know whether
// scrolling is possible in the requested direction. It does this
// by looking at the scroll overflow values on mCanTriggerSwipe
// events after they have been processed. When determining if
// a swipe should occur, we should not prefer the current wheel
// transaction.
nsIFrame* lastScrollFrame =
WheelTransaction::GetScrollTargetFrame();
bool wheelTransactionHandlesInput = false;
if (lastScrollFrame) {
ScrollContainerFrame* scrollContainerFrame =
lastScrollFrame->GetScrollTargetFrame();
if (scrollContainerFrame->IsRootScrollFrameOfDocument()) {
// If the current wheel transaction target is the root scroll
// frame and is not scrollable on the x-axis, all delta is
// overflown and swipe-to-nav may occur.
wheelTransactionHandlesInput = true;
allDeltaOverflown = !WheelHandlingUtils::CanScrollOn(
scrollContainerFrame, wheelEvent->mDeltaX, 0.0);
} else if (WheelHandlingUtils::CanScrollOn(
scrollContainerFrame, wheelEvent->mDeltaX,
wheelEvent->mDeltaY)) {
// If the current wheel transaction target is not the root
// scroll frame, ensure that swipe to nav does not occur if
// the scroll frame is scrollable on the x or y axis. If the
// scroll frame cannot scroll, all delta _may_ be overflown.
wheelTransactionHandlesInput = true;
allDeltaOverflown = false;
}
}
if (!wheelTransactionHandlesInput) {
allDeltaOverflown = !ComputeScrollTarget(
mCurrentTarget, wheelEvent,
COMPUTE_DEFAULT_ACTION_TARGET_WITHOUT_WHEEL_TRANSACTION);
}
}
} else {
// The event was processed neither by APZ nor by us, so all of the
// delta values must be overflown delta values.
allDeltaOverflown = true;
}
if (!allDeltaOverflown) {
break;
}
wheelEvent->mOverflowDeltaX = wheelEvent->mDeltaX;
wheelEvent->mOverflowDeltaY = wheelEvent->mDeltaY;
WheelPrefs::GetInstance()->CancelApplyingUserPrefsFromOverflowDelta(
wheelEvent);
wheelEvent->mViewPortIsOverscrolled = true;
break;
}
*aStatus = nsEventStatus_eConsumeNoDefault;
} break;
case eGestureNotify: {
if (nsEventStatus_eConsumeNoDefault != *aStatus) {
DecideGestureEvent(aEvent->AsGestureNotifyEvent(), mCurrentTarget);
}
} break;
case eDragEnter:
case eDragOver: {
NS_ASSERTION(aEvent->mClass == eDragEventClass, "Expected a drag event");
// Check if the drag is occurring inside a scrollable area. If so, scroll
// the area when the mouse is near the edges.
if (mCurrentTarget && aEvent->mMessage == eDragOver) {
nsIFrame* checkFrame = mCurrentTarget;
while (checkFrame) {
ScrollContainerFrame* scrollFrame = do_QueryFrame(checkFrame);
// Break out so only the innermost scrollframe is scrolled.
if (scrollFrame && scrollFrame->DragScroll(aEvent)) {
break;
}
checkFrame = checkFrame->GetParent();
}
}
nsCOMPtr<nsIDragSession> dragSession =
nsContentUtils::GetDragSession(mPresContext);
if (!dragSession) break;
// Reset the flag.
dragSession->SetOnlyChromeDrop(false);
if (mPresContext) {
EnsureDocument(mPresContext);
}
bool isChromeDoc = nsContentUtils::IsChromeDoc(mDocument);
// the initial dataTransfer is the one from the dragstart event that
// was set on the dragSession when the drag began.
RefPtr<DataTransfer> dataTransfer;
RefPtr<DataTransfer> initialDataTransfer = dragSession->GetDataTransfer();
WidgetDragEvent* dragEvent = aEvent->AsDragEvent();
// collect any changes to moz cursor settings stored in the event's
// data transfer.
UpdateDragDataTransfer(dragEvent);
// cancelling a dragenter or dragover event means that a drop should be
// allowed, so update the dropEffect and the canDrop state to indicate
// that a drag is allowed. If the event isn't cancelled, a drop won't be
// allowed. Essentially, to allow a drop somewhere, specify the effects
// using the effectAllowed and dropEffect properties in a dragenter or
// dragover event and cancel the event. To not allow a drop somewhere,
// don't cancel the event or set the effectAllowed or dropEffect to
// "none". This way, if the event is just ignored, no drop will be
// allowed.
uint32_t dropEffect = nsIDragService::DRAGDROP_ACTION_NONE;
uint32_t action = nsIDragService::DRAGDROP_ACTION_NONE;
if (nsEventStatus_eConsumeNoDefault == *aStatus) {
// If the event has initialized its mDataTransfer, use it.
// Or the event has not been initialized its mDataTransfer, but
// it's set before dispatch because of synthesized, but without
// testing session (e.g., emulating drag from another app), use it
// coming from outside.
// XXX Perhaps, for the latter case, we need new API because we don't
// have a chance to initialize allowed effects of the session.
if (dragEvent->mDataTransfer) {
// get the dataTransfer and the dropEffect that was set on it
dataTransfer = dragEvent->mDataTransfer;
dropEffect = dataTransfer->DropEffectInt();
} else {
// if dragEvent->mDataTransfer is null, it means that no attempt was
// made to access the dataTransfer during the event, yet the event
// was cancelled. Instead, use the initial data transfer available
// from the drag session. The drop effect would not have been
// initialized (which is done in DragEvent::GetDataTransfer),
// so set it from the drag action. We'll still want to filter it
// based on the effectAllowed below.
dataTransfer = initialDataTransfer;
dragSession->GetDragAction(&action);
// filter the drop effect based on the action. Use UNINITIALIZED as
// any effect is allowed.
dropEffect = nsContentUtils::FilterDropEffect(
action, nsIDragService::DRAGDROP_ACTION_UNINITIALIZED);
}
// At this point, if the dataTransfer is null, it means that the
// drag was originally started by directly calling the drag service.
// Just assume that all effects are allowed.
uint32_t effectAllowed = nsIDragService::DRAGDROP_ACTION_UNINITIALIZED;
if (dataTransfer) {
effectAllowed = dataTransfer->EffectAllowedInt();
}
// set the drag action based on the drop effect and effect allowed.
// The drop effect field on the drag transfer object specifies the
// desired current drop effect. However, it cannot be used if the
// effectAllowed state doesn't include that type of action. If the
// dropEffect is "none", then the action will be 'none' so a drop will
// not be allowed.
if (effectAllowed == nsIDragService::DRAGDROP_ACTION_UNINITIALIZED ||
dropEffect & effectAllowed)
action = dropEffect;
if (action == nsIDragService::DRAGDROP_ACTION_NONE)
dropEffect = nsIDragService::DRAGDROP_ACTION_NONE;
// inform the drag session that a drop is allowed on this node.
dragSession->SetDragAction(action);
dragSession->SetCanDrop(action != nsIDragService::DRAGDROP_ACTION_NONE);
// For now, do this only for dragover.
// XXXsmaug dragenter needs some more work.
if (aEvent->mMessage == eDragOver && !isChromeDoc) {
// Someone has called preventDefault(), check whether is was on
// content or chrome.
dragSession->SetOnlyChromeDrop(
!dragEvent->mDefaultPreventedOnContent);
}
} else if (aEvent->mMessage == eDragOver && !isChromeDoc) {
// No one called preventDefault(), so handle drop only in chrome.
dragSession->SetOnlyChromeDrop(true);
}
if (auto* bc = BrowserChild::GetFrom(presContext->GetDocShell())) {
bc->SendUpdateDropEffect(action, dropEffect);
}
if (aEvent->HasBeenPostedToRemoteProcess()) {
dragSession->SetCanDrop(true);
} else if (initialDataTransfer) {
// Now set the drop effect in the initial dataTransfer. This ensures
// that we can get the desired drop effect in the drop event. For events
// dispatched to content, the content process will take care of setting
// this.
initialDataTransfer->SetDropEffectInt(dropEffect);
}
} break;
case eDrop: {
if (aEvent->mFlags.mIsSynthesizedForTests) {
nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1");
nsCOMPtr<nsIDragSession> dragSession =
nsContentUtils::GetDragSession(mPresContext);
if (dragSession && dragService &&
!dragService->GetNeverAllowSessionIsSynthesizedForTests()) {
MOZ_ASSERT(dragSession->IsSynthesizedForTests());
RefPtr<WindowContext> sourceWC;
DebugOnly<nsresult> rvIgnored =
dragSession->GetSourceWindowContext(getter_AddRefs(sourceWC));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsIDragSession::GetSourceDocument() failed, but ignored");
// If the drag source hasn't been initialized, i.e., dragstart was
// consumed by the test, the test needs to dispatch "dragend" event
// instead of the drag session. Therefore, it does not make sense
// to set drag end point in such case (you hit assersion if you do
// it).
if (sourceWC) {
const CSSIntPoint dropPointInScreen = RoundedToInt(
Event::GetScreenCoords(aPresContext, aEvent, aEvent->mRefPoint)
.extract());
dragSession->SetDragEndPointForTests(dropPointInScreen.x,
dropPointInScreen.y);
}
}
}
sLastDragOverFrame = nullptr;
ClearGlobalActiveContent(this);
break;
}
case eDragExit: {
// make sure to fire the enter and exit_synth events after the
// eDragExit event, otherwise we'll clean up too early
GenerateDragDropEnterExit(presContext, aEvent->AsDragEvent());
if (auto* bc = BrowserChild::GetFrom(presContext->GetDocShell())) {
// SendUpdateDropEffect to prevent nsIDragService from waiting for
// response of forwarded dragexit event.
bc->SendUpdateDropEffect(nsIDragService::DRAGDROP_ACTION_NONE,
nsIDragService::DRAGDROP_ACTION_NONE);
}
break;
}
case eKeyUp:
// If space key is released, we need to inactivate the element which was
// activated by preceding space key down.
// XXX Currently, we don't store the reason of activation. Therefore,
// this may cancel what is activated by a mousedown, but it must not
// cause actual problem in web apps in the wild since it must be
// rare case that users release space key during a mouse click/drag.
if (aEvent->AsKeyboardEvent()->ShouldWorkAsSpaceKey()) {
ClearGlobalActiveContent(this);
}
break;
case eKeyPress: {
WidgetKeyboardEvent* keyEvent = aEvent->AsKeyboardEvent();
PostHandleKeyboardEvent(keyEvent, mCurrentTarget, *aStatus);
} break;
case eMouseEnterIntoWidget:
if (mCurrentTarget) {
nsCOMPtr<nsIContent> targetContent =
mCurrentTarget->GetContentForEvent(aEvent);
SetContentState(targetContent, ElementState::HOVER);
}
break;
case eMouseExitFromWidget:
MOZ_ASSERT_UNREACHABLE(
"Should've already been handled in PreHandleEvent()");
break;
#ifdef XP_MACOSX
case eMouseActivate:
if (mCurrentTarget) {
nsCOMPtr<nsIContent> targetContent =
mCurrentTarget->GetContentForEvent(aEvent);
if (!NodeAllowsClickThrough(targetContent)) {
*aStatus = nsEventStatus_eConsumeNoDefault;
}
}
break;
#endif
default:
break;
}
// Reset target frame to null to avoid mistargeting after reentrant event
mCurrentTarget = nullptr;
mCurrentTargetContent = nullptr;
return ret;
}
BrowserParent* EventStateManager::GetCrossProcessTarget() {
return IMEStateManager::GetActiveBrowserParent();
}
bool EventStateManager::IsTargetCrossProcess(WidgetGUIEvent* aEvent) {
// Check to see if there is a focused, editable content in chrome,
// in that case, do not forward IME events to content
Element* focusedElement = GetFocusedElement();
if (focusedElement && focusedElement->IsEditable()) {
return false;
}
return IMEStateManager::GetActiveBrowserParent() != nullptr;
}
void EventStateManager::NotifyDestroyPresContext(nsPresContext* aPresContext) {
RefPtr<nsPresContext> presContext = aPresContext;
if (presContext) {
IMEStateManager::OnDestroyPresContext(*presContext);
}
// Bug 70855: Presentation is going away, possibly for a reframe.
// Reset the hover state so that if we're recreating the presentation,
// we won't have the old hover state still set in the new presentation,
// as if the new presentation is resized, a new element may be hovered.
ResetHoverState();
mMouseEnterLeaveHelper = nullptr;
mPointersEnterLeaveHelper.Clear();
PointerEventHandler::NotifyDestroyPresContext(presContext);
}
void EventStateManager::ResetHoverState() {
if (mHoverContent) {
SetContentState(nullptr, ElementState::HOVER);
}
}
void EventStateManager::SetPresContext(nsPresContext* aPresContext) {
mPresContext = aPresContext;
}
void EventStateManager::ClearFrameRefs(nsIFrame* aFrame) {
if (aFrame && aFrame == mCurrentTarget) {
mCurrentTargetContent = aFrame->GetContent();
}
}
struct CursorImage {
gfx::IntPoint mHotspot;
nsCOMPtr<imgIContainer> mContainer;
ImageResolution mResolution;
bool mEarlierCursorLoading = false;
};
// Given the event that we're processing, and the computed cursor and hotspot,
// determine whether the custom CSS cursor should be blocked (that is, not
// honored).
//
// We will not honor it all of the following are true:
//
// * the size of the custom cursor is bigger than layout.cursor.block.max-size.
// * the bounds of the cursor would end up outside of the viewport of the
// top-level content document.
//
// This is done in order to prevent hijacking the cursor, see bug 1445844 and
// co.
static bool ShouldBlockCustomCursor(nsPresContext* aPresContext,
WidgetEvent* aEvent,
const CursorImage& aCursor) {
int32_t width = 0;
int32_t height = 0;
aCursor.mContainer->GetWidth(&width);
aCursor.mContainer->GetHeight(&height);
aCursor.mResolution.ApplyTo(width, height);
int32_t maxSize = StaticPrefs::layout_cursor_block_max_size();
if (width <= maxSize && height <= maxSize) {
return false;
}
auto input = DOMIntersectionObserver::ComputeInput(*aPresContext->Document(),
nullptr, nullptr, nullptr);
if (!input.mRootFrame) {
return false;
}
nsPoint point = nsLayoutUtils::GetEventCoordinatesRelativeTo(
aEvent, RelativeTo{input.mRootFrame});
// The cursor size won't be affected by our full zoom in the parent process,
// so undo that before checking the rect.
float zoom = aPresContext->GetFullZoom();
// Also adjust for accessibility cursor scaling factor.
zoom /= LookAndFeel::GetFloat(LookAndFeel::FloatID::CursorScale, 1.0f);
nsSize size(CSSPixel::ToAppUnits(width / zoom),
CSSPixel::ToAppUnits(height / zoom));
nsPoint hotspot(
CSSPixel::ToAppUnits(ViewAs<CSSPixel>(aCursor.mHotspot.x / zoom)),
CSSPixel::ToAppUnits(ViewAs<CSSPixel>(aCursor.mHotspot.y / zoom)));
const nsRect cursorRect(point - hotspot, size);
auto output = DOMIntersectionObserver::Intersect(input, cursorRect);
return !output.mIntersectionRect ||
!(*output.mIntersectionRect == cursorRect);
}
static gfx::IntPoint ComputeHotspot(imgIContainer* aContainer,
const Maybe<gfx::Point>& aHotspot) {
MOZ_ASSERT(aContainer);
// css3-ui says to use the CSS-specified hotspot if present,
// otherwise use the intrinsic hotspot, otherwise use the top left
// corner.
if (aHotspot) {
int32_t imgWidth, imgHeight;
aContainer->GetWidth(&imgWidth);
aContainer->GetHeight(&imgHeight);
auto hotspot = gfx::IntPoint::Round(*aHotspot);
return {std::max(std::min(hotspot.x.value, imgWidth - 1), 0),
std::max(std::min(hotspot.y.value, imgHeight - 1), 0)};
}
gfx::IntPoint hotspot;
aContainer->GetHotspotX(&hotspot.x.value);
aContainer->GetHotspotY(&hotspot.y.value);
return hotspot;
}
static CursorImage ComputeCustomCursor(nsPresContext* aPresContext,
WidgetEvent* aEvent,
const nsIFrame& aFrame,
const nsIFrame::Cursor& aCursor) {
if (aCursor.mAllowCustomCursor == nsIFrame::AllowCustomCursorImage::No) {
return {};
}
const ComputedStyle& style =
aCursor.mStyle ? *aCursor.mStyle : *aFrame.Style();
// If we are falling back because any cursor before us is loading, let the
// consumer know.
bool loading = false;
for (const auto& image : style.StyleUI()->Cursor().images.AsSpan()) {
MOZ_ASSERT(image.image.IsImageRequestType(),
"Cursor image should only parse url() types");
uint32_t status;
imgRequestProxy* req = image.image.GetImageRequest();
if (!req || NS_FAILED(req->GetImageStatus(&status))) {
continue;
}
if (!(status & imgIRequest::STATUS_LOAD_COMPLETE)) {
loading = true;
continue;
}
if (status & imgIRequest::STATUS_ERROR) {
continue;
}
nsCOMPtr<imgIContainer> container;
req->GetImage(getter_AddRefs(container));
if (!container) {
continue;
}
StyleImageOrientation orientation =
aFrame.StyleVisibility()->UsedImageOrientation(req);
container = nsLayoutUtils::OrientImage(container, orientation);
Maybe<gfx::Point> specifiedHotspot =
image.has_hotspot ? Some(gfx::Point{image.hotspot_x, image.hotspot_y})
: Nothing();
gfx::IntPoint hotspot = ComputeHotspot(container, specifiedHotspot);
CursorImage result{hotspot, std::move(container),
image.image.GetResolution(&style), loading};
if (ShouldBlockCustomCursor(aPresContext, aEvent, result)) {
continue;
}
// This is the one we want!
return result;
}
return {{}, nullptr, {}, loading};
}
void EventStateManager::UpdateCursor(nsPresContext* aPresContext,
WidgetMouseEvent* aEvent,
nsIFrame* aTargetFrame,
nsEventStatus* aStatus) {
if (!PointerEventHandler::IsLastPointerId(aEvent->pointerId)) {
MOZ_LOG_IF_DEBUG(
gMouseCursorUpdates, LogLevel::Verbose,
("EventStateManager::UpdateCursor(aEvent=${pointerId=%u, source=%s, "
"message=%s, reason=%s}): Stopped updating cursor for the pointer "
"because of %s, ESM: %p, in-process root PresShell: %p",
aEvent->pointerId, InputSourceToString(aEvent->mInputSource).get(),
ToChar(aEvent->mMessage), aEvent->IsReal() ? "Real" : "Synthesized",
!PointerEventHandler::GetLastPointerId()
? "no last pointerId"
: nsPrintfCString("different from last pointerId (%u)",
*PointerEventHandler::GetLastPointerId())
.get(),
this, GetRootPresShell()));
return;
}
// XXX This is still not entirely correct, e.g. when mouse hover over the
// broder of a cross-origin iframe, we should show the cursor specified on the
// iframe (see bug 1943530).
if (nsSubDocumentFrame* f = do_QueryFrame(aTargetFrame)) {
if (auto* fl = f->FrameLoader();
fl && fl->IsRemoteFrame() && f->ContentReactsToPointerEvents()) {
// The sub-frame will update the cursor if needed.
MOZ_LOG_IF_DEBUG(
gMouseCursorUpdates, LogLevel::Verbose,
("EventStateManager::UpdateCursor(aEvent=${pointerId=%u, source=%s, "
"message=%s, reason=%s}): Stopped updating cursor for the pointer "
"because of over a remote frame, ESM: %p, in-process root "
"PresShell: %p",
aEvent->pointerId, InputSourceToString(aEvent->mInputSource).get(),
ToChar(aEvent->mMessage), aEvent->IsReal() ? "Real" : "Synthesized",
this, GetRootPresShell()));
return;
}
}
auto cursor = StyleCursorKind::Default;
nsCOMPtr<imgIContainer> container;
ImageResolution resolution;
Maybe<gfx::IntPoint> hotspot;
if (mHidingCursorWhileTyping && aEvent->IsReal()) {
// Any non-synthetic mouse event makes us show the cursor again.
mHidingCursorWhileTyping = false;
}
if (mHidingCursorWhileTyping) {
cursor = StyleCursorKind::None;
} else if (mLockCursor != kInvalidCursorKind) {
// If cursor is locked just use the locked one
cursor = mLockCursor;
} else if (aTargetFrame) {
// If not locked, look for correct cursor
nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
aEvent, RelativeTo{aTargetFrame});
const nsIFrame::Cursor framecursor = aTargetFrame->GetCursor(pt);
const CursorImage customCursor =
ComputeCustomCursor(aPresContext, aEvent, *aTargetFrame, framecursor);
// If the current cursor is from the same frame, and it is now
// loading some new image for the cursor, we should wait for a
// while rather than taking its fallback cursor directly.
if (customCursor.mEarlierCursorLoading &&
gLastCursorSourceFrame == aTargetFrame &&
TimeStamp::NowLoRes() - gLastCursorUpdateTime <
TimeDuration::FromMilliseconds(kCursorLoadingTimeout)) {
return;
}
cursor = framecursor.mCursor;
container = std::move(customCursor.mContainer);
resolution = customCursor.mResolution;
hotspot = Some(customCursor.mHotspot);
}
if (aTargetFrame) {
if (cursor == StyleCursorKind::Pointer && IsSelectingLink(aTargetFrame)) {
cursor = aTargetFrame->GetWritingMode().IsVertical()
? StyleCursorKind::VerticalText
: StyleCursorKind::Text;
}
SetCursor(cursor, container, resolution, hotspot,
aTargetFrame->GetNearestWidget(), false);
gLastCursorSourceFrame = aTargetFrame;
gLastCursorUpdateTime = TimeStamp::NowLoRes();
MOZ_LOG_IF_DEBUG(
gMouseCursorUpdates, LogLevel::Info,
("EventStateManager::UpdateCursor(aEvent=${pointerId=%u, source=%s, "
"message=%s, reason=%s}): Updated the cursor to %u, ESM: %p, "
"in-process root PresShell: %p",
aEvent->pointerId, InputSourceToString(aEvent->mInputSource).get(),
ToChar(aEvent->mMessage), aEvent->IsReal() ? "Real" : "Synthesized",
static_cast<uint32_t>(cursor), this, GetRootPresShell()));
}
if (mLockCursor != kInvalidCursorKind || StyleCursorKind::Auto != cursor) {
*aStatus = nsEventStatus_eConsumeDoDefault;
}
}
void EventStateManager::ClearCachedWidgetCursor(nsIFrame* aTargetFrame) {
if (!aTargetFrame) {
return;
}
nsIWidget* aWidget = aTargetFrame->GetNearestWidget();
if (!aWidget) {
return;
}
aWidget->ClearCachedCursor();
}
void EventStateManager::StartHidingCursorWhileTyping(nsIWidget* aWidget) {
if (mHidingCursorWhileTyping || sCursorSettingManager != this) {
return;
}
mHidingCursorWhileTyping = true;
SetCursor(StyleCursorKind::None, nullptr, {}, {}, aWidget, false);
}
nsresult EventStateManager::SetCursor(StyleCursorKind aCursor,
imgIContainer* aContainer,
const ImageResolution& aResolution,
const Maybe<gfx::IntPoint>& aHotspot,
nsIWidget* aWidget, bool aLockCursor) {
EnsureDocument(mPresContext);
NS_ENSURE_TRUE(mDocument, NS_ERROR_FAILURE);
sCursorSettingManager = this;
NS_ENSURE_TRUE(aWidget, NS_ERROR_FAILURE);
if (aLockCursor) {
if (StyleCursorKind::Auto != aCursor) {
mLockCursor = aCursor;
} else {
// If cursor style is set to auto we unlock the cursor again.
mLockCursor = kInvalidCursorKind;
}
}
nsCursor c;
switch (aCursor) {
case StyleCursorKind::Auto:
case StyleCursorKind::Default:
c = eCursor_standard;
break;
case StyleCursorKind::Pointer:
c = eCursor_hyperlink;
break;
case StyleCursorKind::Crosshair:
c = eCursor_crosshair;
break;
case StyleCursorKind::Move:
c = eCursor_move;
break;
case StyleCursorKind::Text:
c = eCursor_select;
break;
case StyleCursorKind::Wait:
c = eCursor_wait;
break;
case StyleCursorKind::Help:
c = eCursor_help;
break;
case StyleCursorKind::NResize:
c = eCursor_n_resize;
break;
case StyleCursorKind::SResize:
c = eCursor_s_resize;
break;
case StyleCursorKind::WResize:
c = eCursor_w_resize;
break;
case StyleCursorKind::EResize:
c = eCursor_e_resize;
break;
case StyleCursorKind::NwResize:
c = eCursor_nw_resize;
break;
case StyleCursorKind::SeResize:
c = eCursor_se_resize;
break;
case StyleCursorKind::NeResize:
c = eCursor_ne_resize;
break;
case StyleCursorKind::SwResize:
c = eCursor_sw_resize;
break;
case StyleCursorKind::Copy: // CSS3
c = eCursor_copy;
break;
case StyleCursorKind::Alias:
c = eCursor_alias;
break;
case StyleCursorKind::ContextMenu:
c = eCursor_context_menu;
break;
case StyleCursorKind::Cell:
c = eCursor_cell;
break;
case StyleCursorKind::Grab:
c = eCursor_grab;
break;
case StyleCursorKind::Grabbing:
c = eCursor_grabbing;
break;
case StyleCursorKind::Progress:
c = eCursor_spinning;
break;
case StyleCursorKind::ZoomIn:
c = eCursor_zoom_in;
break;
case StyleCursorKind::ZoomOut:
c = eCursor_zoom_out;
break;
case StyleCursorKind::NotAllowed:
c = eCursor_not_allowed;
break;
case StyleCursorKind::ColResize:
c = eCursor_col_resize;
break;
case StyleCursorKind::RowResize:
c = eCursor_row_resize;
break;
case StyleCursorKind::NoDrop:
c = eCursor_no_drop;
break;
case StyleCursorKind::VerticalText:
c = eCursor_vertical_text;
break;
case StyleCursorKind::AllScroll:
c = eCursor_all_scroll;
break;
case StyleCursorKind::NeswResize:
c = eCursor_nesw_resize;
break;
case StyleCursorKind::NwseResize:
c = eCursor_nwse_resize;
break;
case StyleCursorKind::NsResize:
c = eCursor_ns_resize;
break;
case StyleCursorKind::EwResize:
c = eCursor_ew_resize;
break;
case StyleCursorKind::None:
c = eCursor_none;
break;
default:
MOZ_ASSERT_UNREACHABLE("Unknown cursor kind");
c = eCursor_standard;
break;
}
uint32_t x = aHotspot ? aHotspot->x.value : 0;
uint32_t y = aHotspot ? aHotspot->y.value : 0;
aWidget->SetCursor(nsIWidget::Cursor{c, aContainer, x, y, aResolution});
return NS_OK;
}
bool EventStateManager::CursorSettingManagerHasLockedCursor() {
return sCursorSettingManager &&
sCursorSettingManager->mLockCursor != kInvalidCursorKind;
}
class MOZ_STACK_CLASS ESMEventCB : public EventDispatchingCallback {
public:
explicit ESMEventCB(nsIContent* aTarget) : mTarget(aTarget) {}
MOZ_CAN_RUN_SCRIPT
void HandleEvent(EventChainPostVisitor& aVisitor) override {
if (aVisitor.mPresContext) {
nsIFrame* frame = aVisitor.mPresContext->GetPrimaryFrameFor(mTarget);
if (frame) {
frame->HandleEvent(aVisitor.mPresContext, aVisitor.mEvent->AsGUIEvent(),
&aVisitor.mEventStatus);
}
}
}
nsCOMPtr<nsIContent> mTarget;
};
static UniquePtr<WidgetMouseEvent> CreateMouseOrPointerWidgetEvent(
WidgetMouseEvent* aMouseEvent, EventMessage aMessage,
EventTarget* aRelatedTarget) {
// This method does not support creating a mouse/pointer button change event
// because of no data about the changing state.
MOZ_ASSERT(aMessage != eMouseDown);
MOZ_ASSERT(aMessage != eMouseUp);
MOZ_ASSERT(aMessage != ePointerDown);
MOZ_ASSERT(aMessage != ePointerUp);
// This method is currently designed to create the following events.
MOZ_ASSERT(aMessage == eMouseOver || aMessage == eMouseEnter ||
aMessage == eMouseOut || aMessage == eMouseLeave ||
aMessage == ePointerOver || aMessage == ePointerEnter ||
aMessage == ePointerOut || aMessage == ePointerLeave ||
aMessage == eMouseEnterIntoWidget ||
aMessage == eMouseExitFromWidget);
WidgetPointerEvent* sourcePointer = aMouseEvent->AsPointerEvent();
UniquePtr<WidgetMouseEvent> newEvent;
if (sourcePointer) {
AUTO_PROFILER_LABEL("CreateMouseOrPointerWidgetEvent", OTHER);
WidgetPointerEvent* newPointerEvent = new WidgetPointerEvent(
aMouseEvent->IsTrusted(), aMessage, aMouseEvent->mWidget);
newPointerEvent->mIsPrimary = sourcePointer->mIsPrimary;
newPointerEvent->mWidth = sourcePointer->mWidth;
newPointerEvent->mHeight = sourcePointer->mHeight;
newPointerEvent->mInputSource = sourcePointer->mInputSource;
newEvent = WrapUnique(newPointerEvent);
} else {
newEvent = MakeUnique<WidgetMouseEvent>(aMouseEvent->IsTrusted(), aMessage,
aMouseEvent->mWidget,
WidgetMouseEvent::eReal);
}
// Inherit whether the event is synthesized by the test API or not.
// Then, when the event is synthesized by a test API and handled in a remote
// process, it won't be ignored. See PresShell::HandleEvent().
newEvent->mFlags.mIsSynthesizedForTests =
aMouseEvent->mFlags.mIsSynthesizedForTests;
newEvent->mRelatedTarget = aRelatedTarget;
newEvent->mRefPoint = aMouseEvent->mRefPoint;
newEvent->mModifiers = aMouseEvent->mModifiers;
// NOTE: If you need to change this if-expression, you need to update
// WidgetMouseEventBase::ComputeMouseButtonPressure() too.
if (!aMouseEvent->mFlags.mDispatchedAtLeastOnce &&
aMouseEvent->InputSourceSupportsHover()) {
// If we synthesize a pointer event or a mouse event from another event
// which changes a button state whose input soucre supports hover state and
// the source event has not been dispatched yet, we should set to the button
// state of the synthesizing event to previous one.
// Note that we don't need to do this if the input source does not support
// hover state because a WPT check the behavior (see below) and the other
// browsers pass the test even though this is inconsistent behavior.
newEvent->mButton =
sourcePointer ? MouseButton::eNotPressed : MouseButton::ePrimary;
if (aMouseEvent->IsPressingButton()) {
// If the source event has not been dispatched into the DOM yet, we
// need to remove the flag which is being pressed.
newEvent->mButtons = static_cast<decltype(WidgetMouseEvent::mButtons)>(
aMouseEvent->mButtons &
~MouseButtonsFlagToChange(
static_cast<MouseButton>(aMouseEvent->mButton)));
} else if (aMouseEvent->IsReleasingButton()) {
// If the source event has not been dispatched into the DOM yet, we
// need to add the flag which is being released.
newEvent->mButtons = static_cast<decltype(WidgetMouseEvent::mButtons)>(
aMouseEvent->mButtons |
MouseButtonsFlagToChange(
static_cast<MouseButton>(aMouseEvent->mButton)));
} else {
// The source event does not change the buttons state so that we can
// set mButtons value as-is.
newEvent->mButtons = aMouseEvent->mButtons;
}
// Adjust pressure if it does not matches with mButtons.
// FIXME: We may use wrong pressure value if the source event has not been
// dispatched into the DOM yet. However, fixing this requires to store the
// last pressure value somewhere (bug 1953669).
newEvent->mPressure = newEvent->ComputeMouseButtonPressure();
} else {
// If the event has already been dispatched into the tree, web apps has
// already handled the button state change, so the button state of the
// source event has already synced.
// If the input source does not have hover state, we don't need to modify
// the state because the other browsers behave so and tested by
// pointerevent_attributes_nohover_pointers.html even though this is
// different expectation from
// pointerevent_attributes_hoverable_pointers.html, but the other browsers
// pass both of them.
newEvent->mButton = aMouseEvent->mButton;
newEvent->mButtons = aMouseEvent->mButtons;
newEvent->mPressure = aMouseEvent->mPressure;
}
newEvent->mInputSource = aMouseEvent->mInputSource;
newEvent->pointerId = aMouseEvent->pointerId;
return newEvent;
}
already_AddRefed<nsIWidget>
EventStateManager::DispatchMouseOrPointerBoundaryEvent(
WidgetMouseEvent* aMouseEvent, EventMessage aMessage,
nsIContent* aTargetContent, nsIContent* aRelatedContent) {
MOZ_ASSERT(aMessage == eMouseEnter || aMessage == ePointerEnter ||
aMessage == eMouseLeave || aMessage == ePointerLeave ||
aMessage == eMouseOver || aMessage == ePointerOver ||
aMessage == eMouseOut || aMessage == ePointerOut);
// https://w3c.github.io/pointerlock/#dom-element-requestpointerlock
// "[Once in the locked state...E]vents that require the concept
// of a mouse cursor must not be dispatched (for example: mouseover,
// mouseout...).
// XXXedgar should we also block pointer events?
if (PointerLockManager::IsLocked() &&
(aMessage == eMouseLeave || aMessage == eMouseEnter ||
aMessage == eMouseOver || aMessage == eMouseOut)) {
mCurrentTargetContent = nullptr;
nsCOMPtr<Element> pointerLockedElement =
PointerLockManager::GetLockedElement();
if (!pointerLockedElement) {
NS_WARNING("Should have pointer locked element, but didn't.");
return nullptr;
}
nsIFrame* const pointerLockedFrame =
mPresContext->GetPrimaryFrameFor(pointerLockedElement);
if (NS_WARN_IF(!pointerLockedFrame)) {
return nullptr;
}
return do_AddRef(pointerLockedFrame->GetNearestWidget());
}
mCurrentTargetContent = nullptr;
if (!aTargetContent) {
return nullptr;
}
// Store the widget before dispatching the event because some event listeners
// of the dispatching event may cause reframe the target or remove the target
// from the tree.
nsCOMPtr<nsIWidget> targetWidget;
if (nsIFrame* const targetFrame =
mPresContext->GetPrimaryFrameFor(aTargetContent)) {
targetWidget = targetFrame->GetNearestWidget();
}
nsCOMPtr<nsIContent> targetContent = aTargetContent;
nsCOMPtr<nsIContent> relatedContent = aRelatedContent;
UniquePtr<WidgetMouseEvent> dispatchEvent =
CreateMouseOrPointerWidgetEvent(aMouseEvent, aMessage, relatedContent);
AutoWeakFrame previousTarget = mCurrentTarget;
mCurrentTargetContent = targetContent;
nsEventStatus status = nsEventStatus_eIgnore;
ESMEventCB callback(targetContent);
RefPtr<nsPresContext> presContext = mPresContext;
EventDispatcher::Dispatch(targetContent, presContext, dispatchEvent.get(),
nullptr, &status, &callback);
if (mPresContext) {
// If we are entering/leaving remote content, dispatch a mouse enter/exit
// event to the remote frame.
if (IsTopLevelRemoteTarget(targetContent)) {
if (aMessage == eMouseOut) {
// For remote content, send a puppet widget mouse exit event.
UniquePtr<WidgetMouseEvent> remoteEvent =
CreateMouseOrPointerWidgetEvent(aMouseEvent, eMouseExitFromWidget,
relatedContent);
remoteEvent->mExitFrom = Some(WidgetMouseEvent::ePuppet);
// mCurrentTarget is set to the new target, so we must reset it to the
// old target and then dispatch a cross-process event. (mCurrentTarget
// will be set back below.) HandleCrossProcessEvent will query for the
// proper target via GetEventTarget which will return mCurrentTarget.
mCurrentTarget = mPresContext->GetPrimaryFrameFor(targetContent);
HandleCrossProcessEvent(remoteEvent.get(), &status);
} else if (aMessage == eMouseOver) {
UniquePtr<WidgetMouseEvent> remoteEvent =
CreateMouseOrPointerWidgetEvent(aMouseEvent, eMouseEnterIntoWidget,
relatedContent);
HandleCrossProcessEvent(remoteEvent.get(), &status);
}
}
}
mCurrentTargetContent = nullptr;
mCurrentTarget = previousTarget;
return targetWidget.forget();
}
static nsIContent* FindCommonAncestor(nsIContent* aNode1, nsIContent* aNode2) {
if (!aNode1 || !aNode2) {
return nullptr;
}
return nsContentUtils::GetCommonFlattenedTreeAncestor(aNode1, aNode2);
}
class EnterLeaveDispatcher {
public:
EnterLeaveDispatcher(EventStateManager* aESM, nsIContent* aTarget,
nsIContent* aRelatedTarget,
WidgetMouseEvent* aMouseEvent,
EventMessage aEventMessage)
: mESM(aESM), mMouseEvent(aMouseEvent), mEventMessage(aEventMessage) {
nsPIDOMWindowInner* win =
aTarget ? aTarget->OwnerDoc()->GetInnerWindow() : nullptr;
if (aMouseEvent->AsPointerEvent()
? win && win->HasPointerEnterLeaveEventListeners()
: win && win->HasMouseEnterLeaveEventListeners()) {
mRelatedTarget =
aRelatedTarget ? aRelatedTarget->FindFirstNonChromeOnlyAccessContent()
: nullptr;
nsINode* commonParent = FindCommonAncestor(aTarget, aRelatedTarget);
nsIContent* current = aTarget;
// Note, it is ok if commonParent is null!
while (current && current != commonParent) {
if (!current->ChromeOnlyAccess()) {
mTargets.AppendObject(current);
}
// mouseenter/leave is fired only on elements.
current = current->GetFlattenedTreeParent();
}
}
}
// TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
MOZ_CAN_RUN_SCRIPT_BOUNDARY void Dispatch() {
if (mEventMessage == eMouseEnter || mEventMessage == ePointerEnter) {
for (int32_t i = mTargets.Count() - 1; i >= 0; --i) {
nsCOMPtr<nsIWidget> widget = mESM->DispatchMouseOrPointerBoundaryEvent(
mMouseEvent, mEventMessage, MOZ_KnownLive(mTargets[i]),
mRelatedTarget);
}
} else {
for (int32_t i = 0; i < mTargets.Count(); ++i) {
nsCOMPtr<nsIWidget> widget = mESM->DispatchMouseOrPointerBoundaryEvent(
mMouseEvent, mEventMessage, MOZ_KnownLive(mTargets[i]),
mRelatedTarget);
}
}
}
// Nothing overwrites anything after constructor. Please remove MOZ_KnownLive
// and MOZ_KNOWN_LIVE if anything marked as such becomes mutable.
const RefPtr<EventStateManager> mESM;
nsCOMArray<nsIContent> mTargets;
MOZ_KNOWN_LIVE nsCOMPtr<nsIContent> mRelatedTarget;
WidgetMouseEvent* mMouseEvent;
EventMessage mEventMessage;
};
void EventStateManager::NotifyMouseOut(WidgetMouseEvent* aMouseEvent,
nsIContent* aMovingInto) {
const bool isPointer = aMouseEvent->mClass == ePointerEventClass;
LogModule* const logModule =
isPointer ? sPointerBoundaryLog : sMouseBoundaryLog;
RefPtr<OverOutElementsWrapper> wrapper = GetWrapperByEventID(aMouseEvent);
// If there is no deepest "leave" event target, that means the last "over"
// target has already been removed from the tree. Therefore, checking only
// the "leave" event target is enough.
if (!wrapper || !wrapper->GetDeepestLeaveEventTarget()) {
return;
}
// Before firing "out" and/or "leave" events, check for recursion
if (wrapper->IsDispatchingOutEventOnLastOverEventTarget()) {
return;
}
MOZ_LOG(logModule, LogLevel::Info,
("NotifyMouseOut: the source event is %s (IsReal()=%s)",
ToChar(aMouseEvent->mMessage),
aMouseEvent->IsReal() ? "true" : "false"));
// XXX If a content node is a container of remove content, it should be
// replaced with them and its children should not be visible. Therefore,
// if the deepest "enter" target is not the last "over" target, i.e., the
// last "over" target has been removed from the DOM tree, it means that the
// child/descendant was not replaced by remote content. So,
// wrapper->GetOutEventTaget() may be enough here.
if (RefPtr<nsFrameLoaderOwner> flo =
do_QueryObject(wrapper->GetDeepestLeaveEventTarget())) {
if (BrowsingContext* bc = flo->GetExtantBrowsingContext()) {
if (nsIDocShell* docshell = bc->GetDocShell()) {
if (RefPtr<nsPresContext> presContext = docshell->GetPresContext()) {
EventStateManager* kidESM = presContext->EventStateManager();
// Not moving into any element in this subdocument
MOZ_LOG(logModule, LogLevel::Info,
("Notifying child EventStateManager (%p) of \"out\" "
"event...",
kidESM));
kidESM->NotifyMouseOut(aMouseEvent, nullptr);
}
}
}
}
// That could have caused DOM events which could wreak havoc. Reverify
// things and be careful.
if (!wrapper->GetDeepestLeaveEventTarget()) {
return;
}
wrapper->WillDispatchOutAndOrLeaveEvent();
// Don't touch hover state if aMovingInto is non-null. Caller will update
// hover state itself, and we have optimizations for hover switching between
// two nearby elements both deep in the DOM tree that would be defeated by
// switching the hover state to null here.
if (!aMovingInto && !isPointer) {
// Unset :hover
SetContentState(nullptr, ElementState::HOVER);
}
EnterLeaveDispatcher leaveDispatcher(
this, wrapper->GetDeepestLeaveEventTarget(), aMovingInto, aMouseEvent,
isPointer ? ePointerLeave : eMouseLeave);
// "out" events hould be fired only when the deepest "leave" event target
// is the last "over" event target.
if (nsCOMPtr<nsIContent> outEventTarget = wrapper->GetOutEventTarget()) {
MOZ_LOG(logModule, LogLevel::Info,
("Dispatching %s event to %s (%p)",
isPointer ? "ePointerOut" : "eMouseOut",
outEventTarget ? ToString(*outEventTarget).c_str() : "nullptr",
outEventTarget.get()));
nsCOMPtr<nsIWidget> widget = DispatchMouseOrPointerBoundaryEvent(
aMouseEvent, isPointer ? ePointerOut : eMouseOut, outEventTarget,
aMovingInto);
}
MOZ_LOG(logModule, LogLevel::Info,
("Dispatching %s event to %s (%p) and its ancestors",
isPointer ? "ePointerLeave" : "eMouseLeave",
wrapper->GetDeepestLeaveEventTarget()
? ToString(*wrapper->GetDeepestLeaveEventTarget()).c_str()
: "nullptr",
wrapper->GetDeepestLeaveEventTarget()));
leaveDispatcher.Dispatch();
MOZ_LOG(logModule, LogLevel::Info,
("Dispatched \"out\" and/or \"leave\" events"));
wrapper->DidDispatchOutAndOrLeaveEvent();
}
void EventStateManager::RecomputeMouseEnterStateForRemoteFrame(
Element& aElement) {
if (!mMouseEnterLeaveHelper ||
mMouseEnterLeaveHelper->GetDeepestLeaveEventTarget() != &aElement) {
return;
}
if (BrowserParent* remote = BrowserParent::GetFrom(&aElement)) {
remote->MouseEnterIntoWidget();
}
}
void EventStateManager::NotifyMouseOver(WidgetMouseEvent* aMouseEvent,
nsIContent* aContent) {
NS_ASSERTION(aContent, "Mouse must be over something");
const bool isPointer = aMouseEvent->mClass == ePointerEventClass;
LogModule* const logModule =
isPointer ? sPointerBoundaryLog : sMouseBoundaryLog;
RefPtr<OverOutElementsWrapper> wrapper = GetWrapperByEventID(aMouseEvent);
// If we have next "out" event target and it's the new "over" target, we don't
// need to dispatch "out" nor "enter" event.
if (!wrapper || aContent == wrapper->GetOutEventTarget()) {
return;
}
// Before firing "over" and "enter" events, check for recursion
if (wrapper->IsDispatchingOverEventOn(aContent)) {
return;
}
MOZ_LOG(logModule, LogLevel::Info,
("NotifyMouseOver: the source event is %s (IsReal()=%s)",
ToChar(aMouseEvent->mMessage),
aMouseEvent->IsReal() ? "true" : "false"));
// Check to see if we're a subdocument and if so update the parent
// document's ESM state to indicate that the mouse is over the
// content associated with our subdocument.
EnsureDocument(mPresContext);
if (Document* parentDoc = mDocument->GetInProcessParentDocument()) {
if (nsCOMPtr<nsIContent> docContent = mDocument->GetEmbedderElement()) {
if (PresShell* parentPresShell = parentDoc->GetPresShell()) {
RefPtr<EventStateManager> parentESM =
parentPresShell->GetPresContext()->EventStateManager();
MOZ_LOG(logModule, LogLevel::Info,
("Notifying parent EventStateManager (%p) of \"over\" "
"event...",
parentESM.get()));
parentESM->NotifyMouseOver(aMouseEvent, docContent);
}
}
}
// Firing the DOM event in the parent document could cause all kinds
// of havoc. Reverify and take care.
if (aContent == wrapper->GetOutEventTarget()) {
return;
}
// Remember the deepest leave event target as the related content for the
// DispatchMouseOrPointerBoundaryEvent() call below, since NotifyMouseOut()
// resets it, bug 298477.
nsCOMPtr<nsIContent> deepestLeaveEventTarget =
wrapper->GetDeepestLeaveEventTarget();
EnterLeaveDispatcher enterDispatcher(this, aContent, deepestLeaveEventTarget,
aMouseEvent,
isPointer ? ePointerEnter : eMouseEnter);
if (!isPointer) {
SetContentState(aContent, ElementState::HOVER);
}
NotifyMouseOut(aMouseEvent, aContent);
wrapper->WillDispatchOverAndEnterEvent(aContent);
// Fire mouseover
// XXX If aContent has already been removed from the DOM tree, what should we
// do? At least, dispatching `mouseover` on it is odd.
MOZ_LOG(logModule, LogLevel::Info,
("Dispatching %s event to %s (%p)",
isPointer ? "ePointerOver" : "eMouseOver",
aContent ? ToString(*aContent).c_str() : "nullptr", aContent));
nsCOMPtr<nsIWidget> targetWidget = DispatchMouseOrPointerBoundaryEvent(
aMouseEvent, isPointer ? ePointerOver : eMouseOver, aContent,
deepestLeaveEventTarget);
MOZ_LOG(logModule, LogLevel::Info,
("Dispatching %s event to %s (%p) and its ancestors",
isPointer ? "ePointerEnter" : "eMouseEnter",
aContent ? ToString(*aContent).c_str() : "nullptr", aContent));
enterDispatcher.Dispatch();
MOZ_LOG(logModule, LogLevel::Info,
("Dispatched \"over\" and \"enter\" events (the original \"over\" "
"event target was in the document %p, and now in %p)",
aContent->GetComposedDoc(), mDocument.get()));
wrapper->DidDispatchOverAndEnterEvent(
aContent->GetComposedDoc() == mDocument ? aContent : nullptr,
targetWidget);
}
// Returns the center point of the window's client area. This is
// in widget coordinates, i.e. relative to the widget's top-left
// corner, not in screen coordinates, the same units that UIEvent::
// refpoint is in. It may not be the exact center of the window if
// the platform requires rounding the coordinate.
static LayoutDeviceIntPoint GetWindowClientRectCenter(nsIWidget* aWidget) {
NS_ENSURE_TRUE(aWidget, LayoutDeviceIntPoint(0, 0));
LayoutDeviceIntRect rect = aWidget->GetClientBounds();
LayoutDeviceIntPoint point(rect.width / 2, rect.height / 2);
int32_t round = aWidget->RoundsWidgetCoordinatesTo();
point.x = point.x / round * round;
point.y = point.y / round * round;
return point;
}
void EventStateManager::GeneratePointerEnterExit(EventMessage aMessage,
WidgetMouseEvent* aEvent) {
WidgetPointerEvent pointerEvent(*aEvent);
pointerEvent.mMessage = aMessage;
GenerateMouseEnterExit(&pointerEvent);
}
/* static */
void EventStateManager::UpdateLastRefPointOfMouseEvent(
WidgetMouseEvent* aMouseEvent) {
if (aMouseEvent->mMessage != ePointerRawUpdate &&
aMouseEvent->mMessage != eMouseMove &&
aMouseEvent->mMessage != ePointerMove) {
return;
}
// Mouse movement is reported on the MouseEvent.movement{X,Y} fields.
// Movement is calculated in UIEvent::GetMovementPoint() as:
// previous_mousemove_mRefPoint - current_mousemove_mRefPoint.
if (PointerLockManager::IsLocked() && aMouseEvent->mWidget) {
// The pointer is locked. If the pointer is not located at the center of
// the window, dispatch a synthetic mousemove to return the pointer there.
// Doing this between "real" pointer moves gives the impression that the
// (locked) pointer can continue moving and won't stop at the screen
// boundary. We cancel the synthetic event so that we don't end up
// dispatching the centering move event to content.
aMouseEvent->mLastRefPoint =
GetWindowClientRectCenter(aMouseEvent->mWidget);
} else if (sLastRefPoint == kInvalidRefPoint) {
// We don't have a valid previous mousemove mRefPoint. This is either
// the first move we've encountered, or the mouse has just re-entered
// the application window. We should report (0,0) movement for this
// case, so make the current and previous mRefPoints the same.
aMouseEvent->mLastRefPoint = aMouseEvent->mRefPoint;
} else {
aMouseEvent->mLastRefPoint = sLastRefPoint;
}
}
/* static */
void EventStateManager::ResetPointerToWindowCenterWhilePointerLocked(
WidgetMouseEvent* aMouseEvent) {
MOZ_ASSERT(PointerLockManager::IsLocked());
if ((aMouseEvent->mMessage != ePointerRawUpdate &&
aMouseEvent->mMessage != eMouseMove &&
aMouseEvent->mMessage != ePointerMove) ||
!aMouseEvent->mWidget) {
return;
}
// We generate pointermove from mousemove event, so only synthesize native
// mouse move and update sSynthCenteringPoint by mousemove event.
bool updateSynthCenteringPoint = aMouseEvent->mMessage == eMouseMove;
// The pointer is locked. If the pointer is not located at the center of
// the window, dispatch a synthetic mousemove to return the pointer there.
// Doing this between "real" pointer moves gives the impression that the
// (locked) pointer can continue moving and won't stop at the screen
// boundary. We cancel the synthetic event so that we don't end up
// dispatching the centering move event to content.
LayoutDeviceIntPoint center = GetWindowClientRectCenter(aMouseEvent->mWidget);
if (aMouseEvent->mRefPoint != center && updateSynthCenteringPoint) {
// Mouse move doesn't finish at the center of the window. Dispatch a
// synthetic native mouse event to move the pointer back to the center
// of the window, to faciliate more movement. But first, record that
// we've dispatched a synthetic mouse movement, so we can cancel it
// in the other branch here.
sSynthCenteringPoint = center;
// XXX Once we fix XXX comments in SetPointerLock about this API, we could
// restrict that this API works only in the automation mode or in the
// pointer locked situation.
aMouseEvent->mWidget->SynthesizeNativeMouseMove(
center + aMouseEvent->mWidget->WidgetToScreenOffset(), nullptr);
} else if (aMouseEvent->mRefPoint == sSynthCenteringPoint) {
// This is the "synthetic native" event we dispatched to re-center the
// pointer. Cancel it so we don't expose the centering move to content.
aMouseEvent->StopPropagation();
// Clear sSynthCenteringPoint so we don't cancel other events
// targeted at the center.
if (updateSynthCenteringPoint) {
sSynthCenteringPoint = kInvalidRefPoint;
}
}
}
/* static */
void EventStateManager::UpdateLastPointerPosition(
WidgetMouseEvent* aMouseEvent) {
if (aMouseEvent->mMessage != eMouseMove) {
return;
}
sLastRefPoint = aMouseEvent->mRefPoint;
}
void EventStateManager::GenerateMouseEnterExit(WidgetMouseEvent* aMouseEvent) {
EnsureDocument(mPresContext);
if (!mDocument) return;
// Hold onto old target content through the event and reset after.
nsCOMPtr<nsIContent> targetBeforeEvent = mCurrentTargetContent;
switch (aMouseEvent->mMessage) {
case eMouseMove:
case ePointerMove:
case ePointerRawUpdate:
case ePointerDown:
case ePointerGotCapture: {
// Get the target content target (mousemove target == mouseover target)
nsCOMPtr<nsIContent> targetElement = GetEventTargetContent(aMouseEvent);
if (!targetElement) {
// We're always over the document root, even if we're only
// over dead space in a page (whose frame is not associated with
// any content) or in print preview dead space
targetElement = mDocument->GetRootElement();
}
if (targetElement) {
NotifyMouseOver(aMouseEvent, targetElement);
}
break;
}
case ePointerUp: {
if (aMouseEvent->mFlags.mDispatchedAtLeastOnce) {
// If we've already dispatched the pointerup event caused by
// non-hoverable input device like touch, we need to synthesize
// pointerout and pointerleave events because the poiner is valid only
// while it's "down".
if (!aMouseEvent->InputSourceSupportsHover()) {
NotifyMouseOut(aMouseEvent, nullptr);
}
break;
}
// If we're going to dispatch the pointerup event and the element under
// the pointer is changed from the previous pointer event dispatching, we
// need to dispatch pointer boundary events. If the pointing device is
// hoverable, we always need to do it. Otherwise, an element captures the
// pointer by default. If so, we don't need the boundary events, but if
// the capture has already been released, e.g., by the capturing element
// is removed, we need to dispatch the pointer boundary event the same
// way as with hoverable pointer.
if (aMouseEvent->InputSourceSupportsHover() ||
!PointerEventHandler::GetPointerCapturingElement(
aMouseEvent->pointerId)) {
nsCOMPtr<nsIContent> targetElement = GetEventTargetContent(aMouseEvent);
if (!targetElement) {
targetElement = mDocument->GetRootElement();
}
if (targetElement) {
NotifyMouseOver(aMouseEvent, targetElement);
}
break;
}
break;
}
case ePointerLeave:
case ePointerCancel:
case eMouseExitFromWidget: {
// This is actually the window mouse exit or pointer leave event. We're
// not moving into any new element.
RefPtr<OverOutElementsWrapper> helper = GetWrapperByEventID(aMouseEvent);
if (helper) {
nsCOMPtr<nsIWidget> lastOverWidget = helper->GetLastOverWidget();
if (lastOverWidget &&
nsContentUtils::GetTopLevelWidget(aMouseEvent->mWidget) !=
nsContentUtils::GetTopLevelWidget(lastOverWidget)) {
// the Mouse/PointerOut event widget doesn't have same top widget with
// the last over event target, it's a spurious event for the frame for
// the target.
break;
}
}
// Reset sLastRefPoint, so that we'll know not to report any
// movement the next time we re-enter the window.
sLastRefPoint = kInvalidRefPoint;
NotifyMouseOut(aMouseEvent, nullptr);
break;
}
default:
break;
}
// reset mCurretTargetContent to what it was
mCurrentTargetContent = targetBeforeEvent;
}
OverOutElementsWrapper* EventStateManager::GetWrapperByEventID(
WidgetMouseEvent* aMouseEvent) {
MOZ_ASSERT(aMouseEvent);
WidgetPointerEvent* pointer = aMouseEvent->AsPointerEvent();
if (!pointer) {
if (!mMouseEnterLeaveHelper) {
mMouseEnterLeaveHelper = new OverOutElementsWrapper(
OverOutElementsWrapper::BoundaryEventType::Mouse);
}
return mMouseEnterLeaveHelper;
}
return mPointersEnterLeaveHelper.GetOrInsertNew(
pointer->pointerId, OverOutElementsWrapper::BoundaryEventType::Pointer);
}
/* static */
void EventStateManager::SetPointerLock(nsIWidget* aWidget,
nsPresContext* aPresContext) {
// Reset mouse wheel transaction
WheelTransaction::EndTransaction();
// Deal with DnD events
nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1");
if (PointerLockManager::IsLocked()) {
MOZ_ASSERT(aWidget, "Locking pointer requires a widget");
MOZ_ASSERT(aPresContext, "Locking pointer requires a presContext");
// Release all pointer capture when a pointer lock is successfully applied
// on an element.
PointerEventHandler::ReleaseAllPointerCapture();
// Store the last known ref point so we can reposition the pointer after
// unlock.
sPreLockScreenPoint = LayoutDeviceIntPoint::Round(
sLastScreenPoint * aPresContext->CSSToDevPixelScale());
// Fire a synthetic mouse move to ensure event state is updated. We first
// set the mouse to the center of the window, so that the mouse event
// doesn't report any movement.
// XXX Cannot we do synthesize the native mousemove in the parent process
// with calling LockNativePointer below? Then, we could make this API
// work only in the automation mode.
sLastRefPoint = GetWindowClientRectCenter(aWidget);
aWidget->SynthesizeNativeMouseMove(
sLastRefPoint + aWidget->WidgetToScreenOffset(), nullptr);
// Suppress DnD
if (dragService) {
dragService->Suppress();
}
// Activate native pointer lock on platforms where it is required (Wayland)
aWidget->LockNativePointer();
} else {
if (aWidget) {
// Deactivate native pointer lock on platforms where it is required
aWidget->UnlockNativePointer();
}
// Reset SynthCenteringPoint to invalid so that next time we start
// locking pointer, it has its initial value.
sSynthCenteringPoint = kInvalidRefPoint;
if (aWidget) {
// Unlocking, so return pointer to the original position by firing a
// synthetic mouse event. We first reset sLastRefPoint to its
// pre-pointerlock position, so that the synthetic mouse event reports
// no movement.
sLastRefPoint = sPreLockScreenPoint - aWidget->WidgetToScreenOffset();
// XXX Cannot we do synthesize the native mousemove in the parent process
// with calling `UnlockNativePointer` above? Then, we could make this
// API work only in the automation mode.
aWidget->SynthesizeNativeMouseMove(sPreLockScreenPoint, nullptr);
}
// Unsuppress DnD
if (dragService) {
dragService->Unsuppress();
}
}
}
void EventStateManager::GenerateDragDropEnterExit(nsPresContext* aPresContext,
WidgetDragEvent* aDragEvent) {
// Hold onto old target content through the event and reset after.
nsCOMPtr<nsIContent> targetBeforeEvent = mCurrentTargetContent;
switch (aDragEvent->mMessage) {
case eDragOver: {
// when dragging from one frame to another, events are fired in the
// order: dragexit, dragenter, dragleave
if (sLastDragOverFrame != mCurrentTarget) {
// We'll need the content, too, to check if it changed separately from
// the frames.
nsCOMPtr<nsIContent> lastContent;
nsCOMPtr<nsIContent> targetContent =
mCurrentTarget->GetContentForEvent(aDragEvent);
if (targetContent && targetContent->IsText()) {
targetContent = targetContent->GetFlattenedTreeParent();
}
if (sLastDragOverFrame) {
// The frame has changed but the content may not have. Check before
// dispatching to content
lastContent = sLastDragOverFrame->GetContentForEvent(aDragEvent);
if (lastContent && lastContent->IsText()) {
lastContent = lastContent->GetFlattenedTreeParent();
}
RefPtr<nsPresContext> presContext = sLastDragOverFrame->PresContext();
FireDragEnterOrExit(presContext, aDragEvent, eDragExit, targetContent,
lastContent, sLastDragOverFrame);
nsIContent* target = sLastDragOverFrame
? sLastDragOverFrame.GetFrame()->GetContent()
: nullptr;
// XXXedgar, look like we need to consider fission OOP iframe, too.
if (IsTopLevelRemoteTarget(target)) {
// Dragging something and moving from web content to chrome only
// fires dragexit and dragleave to xul:browser. We have to forward
// dragexit to sLastDragOverFrame when its content is a remote
// target. We don't forward dragleave since it's generated from
// dragexit.
WidgetDragEvent remoteEvent(aDragEvent->IsTrusted(), eDragExit,
aDragEvent->mWidget);
remoteEvent.AssignDragEventData(*aDragEvent, true);
remoteEvent.mFlags.mIsSynthesizedForTests =
aDragEvent->mFlags.mIsSynthesizedForTests;
nsEventStatus remoteStatus = nsEventStatus_eIgnore;
HandleCrossProcessEvent(&remoteEvent, &remoteStatus);
}
}
AutoWeakFrame currentTraget = mCurrentTarget;
FireDragEnterOrExit(aPresContext, aDragEvent, eDragEnter, lastContent,
targetContent, currentTraget);
if (sLastDragOverFrame) {
RefPtr<nsPresContext> presContext = sLastDragOverFrame->PresContext();
FireDragEnterOrExit(presContext, aDragEvent, eDragLeave,
targetContent, lastContent, sLastDragOverFrame);
}
sLastDragOverFrame = mCurrentTarget;
}
} break;
case eDragExit: {
// This is actually the window mouse exit event.
if (sLastDragOverFrame) {
nsCOMPtr<nsIContent> lastContent =
sLastDragOverFrame->GetContentForEvent(aDragEvent);
RefPtr<nsPresContext> lastDragOverFramePresContext =
sLastDragOverFrame->PresContext();
FireDragEnterOrExit(lastDragOverFramePresContext, aDragEvent, eDragExit,
nullptr, lastContent, sLastDragOverFrame);
FireDragEnterOrExit(lastDragOverFramePresContext, aDragEvent,
eDragLeave, nullptr, lastContent,
sLastDragOverFrame);
sLastDragOverFrame = nullptr;
}
} break;
default:
break;
}
// reset mCurretTargetContent to what it was
mCurrentTargetContent = targetBeforeEvent;
// Now flush all pending notifications, for better responsiveness.
FlushLayout(aPresContext);
}
void EventStateManager::FireDragEnterOrExit(nsPresContext* aPresContext,
WidgetDragEvent* aDragEvent,
EventMessage aMessage,
nsIContent* aRelatedTarget,
nsIContent* aTargetContent,
AutoWeakFrame& aTargetFrame) {
MOZ_ASSERT(aMessage == eDragLeave || aMessage == eDragExit ||
aMessage == eDragEnter);
nsEventStatus status = nsEventStatus_eIgnore;
WidgetDragEvent event(aDragEvent->IsTrusted(), aMessage, aDragEvent->mWidget);
event.AssignDragEventData(*aDragEvent, false);
event.mFlags.mIsSynthesizedForTests =
aDragEvent->mFlags.mIsSynthesizedForTests;
event.mRelatedTarget = aRelatedTarget;
if (aMessage == eDragExit && !StaticPrefs::dom_event_dragexit_enabled()) {
event.mFlags.mOnlyChromeDispatch = true;
}
mCurrentTargetContent = aTargetContent;
if (aTargetContent != aRelatedTarget) {
// XXX This event should still go somewhere!!
if (aTargetContent) {
EventDispatcher::Dispatch(aTargetContent, aPresContext, &event, nullptr,
&status);
}
// adjust the drag hover if the dragenter event was cancelled or this is a
// drag exit
if (status == nsEventStatus_eConsumeNoDefault || aMessage == eDragExit) {
SetContentState((aMessage == eDragEnter) ? aTargetContent : nullptr,
ElementState::DRAGOVER);
}
// collect any changes to moz cursor settings stored in the event's
// data transfer.
UpdateDragDataTransfer(&event);
}
// Finally dispatch the event to the frame
if (aTargetFrame) {
aTargetFrame->HandleEvent(aPresContext, &event, &status);
}
}
void EventStateManager::UpdateDragDataTransfer(WidgetDragEvent* dragEvent) {
NS_ASSERTION(dragEvent, "drag event is null in UpdateDragDataTransfer!");
if (!dragEvent->mDataTransfer) {
return;
}
nsCOMPtr<nsIDragSession> dragSession =
nsContentUtils::GetDragSession(mPresContext);
if (dragSession) {
// the initial dataTransfer is the one from the dragstart event that
// was set on the dragSession when the drag began.
RefPtr<DataTransfer> initialDataTransfer = dragSession->GetDataTransfer();
if (initialDataTransfer) {
// retrieve the current moz cursor setting and save it.
nsAutoString mozCursor;
dragEvent->mDataTransfer->GetMozCursor(mozCursor);
initialDataTransfer->SetMozCursor(mozCursor);
}
}
}
void EventStateManager::PrepareForFollowingClickEvent(
WidgetMouseEvent& aEvent, nsIContent* aOverrideClickTarget) {
nsCOMPtr<nsIContent> mouseContent = aOverrideClickTarget;
if (!mouseContent && mCurrentTarget) {
mouseContent = mCurrentTarget->GetContentForEvent(&aEvent);
}
if (mouseContent && mouseContent->IsText()) {
nsINode* parent = mouseContent->GetFlattenedTreeParentNode();
if (parent && parent->IsContent()) {
mouseContent = parent->AsContent();
}
}
LastMouseDownInfo& mouseDownInfo = GetLastMouseDownInfo(aEvent.mButton);
if (aEvent.mMessage == eMouseDown) {
mouseDownInfo.mLastMouseDownContent =
!aEvent.mClickEventPrevented ? mouseContent : nullptr;
if (mouseDownInfo.mLastMouseDownContent) {
if (HTMLInputElement* input = HTMLInputElement::FromNodeOrNull(
mouseDownInfo.mLastMouseDownContent)) {
mouseDownInfo.mLastMouseDownInputControlType =
Some(input->ControlType());
} else if (mouseDownInfo.mLastMouseDownContent
->IsInNativeAnonymousSubtree()) {
if (HTMLInputElement* input = HTMLInputElement::FromNodeOrNull(
mouseDownInfo.mLastMouseDownContent
->GetFlattenedTreeParent())) {
mouseDownInfo.mLastMouseDownInputControlType =
Some(input->ControlType());
}
}
}
} else {
MOZ_ASSERT(aEvent.mMessage == eMouseUp);
aEvent.mClickTarget = [&]() -> EventTarget* {
if (aEvent.mClickEventPrevented || !mouseDownInfo.mLastMouseDownContent) {
return nullptr;
}
// If an element was capturing the pointer at dispatching ePointerUp, we
// should dispatch click/auxclick/contextmenu event on it to conform to
// Pointer Events. https://w3c.github.io/pointerevents/#event-dispatch
if (PointerEventHandler::ShouldDispatchClickEventOnCapturingElement(
&aEvent)) {
const RefPtr<Element> capturingElementAtLastPointerUp =
PointerEventHandler::GetPointerCapturingElementAtLastPointerUp();
if (capturingElementAtLastPointerUp &&
capturingElementAtLastPointerUp->GetPresContext(
Element::PresContextFor::eForComposedDoc) == mPresContext) {
return capturingElementAtLastPointerUp;
}
}
return GetCommonAncestorForMouseUp(
mouseContent, mouseDownInfo.mLastMouseDownContent,
mouseDownInfo.mLastMouseDownInputControlType);
}();
if (aEvent.mClickTarget) {
aEvent.mClickCount = mouseDownInfo.mClickCount;
mouseDownInfo.mClickCount = 0;
} else {
aEvent.mClickCount = 0;
}
mouseDownInfo.mLastMouseDownContent = nullptr;
mouseDownInfo.mLastMouseDownInputControlType = Nothing();
}
}
// static
bool EventStateManager::EventCausesClickEvents(
const WidgetMouseEvent& aMouseEvent) {
if (NS_WARN_IF(aMouseEvent.mMessage != eMouseUp)) {
return false;
}
// If the mouseup event is synthesized event, we don't need to dispatch
// click events.
if (!aMouseEvent.IsReal()) {
return false;
}
// If mouse is still over same element, clickcount will be > 1.
// If it has moved it will be zero, so no click.
if (!aMouseEvent.mClickCount || !aMouseEvent.mClickTarget) {
return false;
}
// If click event was explicitly prevented, we shouldn't dispatch it.
if (aMouseEvent.mClickEventPrevented) {
return false;
}
// Check that the window isn't disabled before firing a click
// (see bug 366544).
return !(aMouseEvent.mWidget && !aMouseEvent.mWidget->IsEnabled());
}
nsresult EventStateManager::InitAndDispatchClickEvent(
WidgetMouseEvent* aMouseUpEvent, nsEventStatus* aStatus,
EventMessage aMessage, PresShell* aPresShell, nsIContent* aMouseUpContent,
AutoWeakFrame aCurrentTarget, bool aNoContentDispatch,
nsIContent* aOverrideClickTarget) {
MOZ_ASSERT(aMouseUpEvent);
MOZ_ASSERT(EventCausesClickEvents(*aMouseUpEvent));
MOZ_ASSERT(aMouseUpContent || aCurrentTarget || aOverrideClickTarget);
Maybe<WidgetPointerEvent> pointerEvent;
Maybe<WidgetMouseEvent> mouseEvent;
if (IsPointerEventMessage(aMessage)) {
pointerEvent.emplace(aMouseUpEvent->IsTrusted(), aMessage,
aMouseUpEvent->mWidget);
} else {
mouseEvent.emplace(aMouseUpEvent->IsTrusted(), aMessage,
aMouseUpEvent->mWidget, WidgetMouseEvent::eReal);
}
WidgetMouseEvent& mouseOrPointerEvent =
pointerEvent.isSome() ? pointerEvent.ref() : mouseEvent.ref();
mouseOrPointerEvent.mRefPoint = aMouseUpEvent->mRefPoint;
mouseOrPointerEvent.mClickCount = aMouseUpEvent->mClickCount;
mouseOrPointerEvent.mModifiers = aMouseUpEvent->mModifiers;
mouseOrPointerEvent.mButtons = aMouseUpEvent->mButtons;
mouseOrPointerEvent.mTimeStamp = aMouseUpEvent->mTimeStamp;
mouseOrPointerEvent.mFlags.mOnlyChromeDispatch = aNoContentDispatch;
mouseOrPointerEvent.mFlags.mNoContentDispatch = aNoContentDispatch;
mouseOrPointerEvent.mButton = aMouseUpEvent->mButton;
mouseOrPointerEvent.pointerId = aMouseUpEvent->pointerId;
mouseOrPointerEvent.mInputSource = aMouseUpEvent->mInputSource;
nsIContent* target = aMouseUpContent;
nsIFrame* targetFrame = aCurrentTarget;
if (aOverrideClickTarget) {
target = aOverrideClickTarget;
targetFrame = aOverrideClickTarget->GetPrimaryFrame();
}
if (!target->IsInComposedDoc()) {
return NS_OK;
}
// Use local event status for each click event dispatching since it'll be
// cleared by EventStateManager::PreHandleEvent(). Therefore, dispatching
// an event means that previous event status will be ignored.
nsEventStatus status = nsEventStatus_eIgnore;
nsresult rv = aPresShell->HandleEventWithTarget(
&mouseOrPointerEvent, targetFrame, MOZ_KnownLive(target), &status);
// Copy mMultipleActionsPrevented flag from a click event to the mouseup
// event only when it's set to true. It may be set to true if an editor has
// already handled it. This is important to avoid two or more default
// actions handled here.
aMouseUpEvent->mFlags.mMultipleActionsPrevented |=
mouseOrPointerEvent.mFlags.mMultipleActionsPrevented;
// If current status is nsEventStatus_eConsumeNoDefault, we don't need to
// overwrite it.
if (*aStatus == nsEventStatus_eConsumeNoDefault) {
return rv;
}
// If new status is nsEventStatus_eConsumeNoDefault or
// nsEventStatus_eConsumeDoDefault, use it.
if (status == nsEventStatus_eConsumeNoDefault ||
status == nsEventStatus_eConsumeDoDefault) {
*aStatus = status;
return rv;
}
// Otherwise, keep the original status.
return rv;
}
nsresult EventStateManager::PostHandleMouseUp(
WidgetMouseEvent* aMouseUpEvent, nsEventStatus* aStatus,
nsIContent* aOverrideClickTarget) {
MOZ_ASSERT(aMouseUpEvent);
MOZ_ASSERT(EventCausesClickEvents(*aMouseUpEvent));
MOZ_ASSERT(aStatus);
RefPtr<PresShell> presShell = mPresContext->GetPresShell();
if (!presShell) {
return NS_OK;
}
nsCOMPtr<nsIContent> clickTarget =
nsIContent::FromEventTargetOrNull(aMouseUpEvent->mClickTarget);
NS_ENSURE_STATE(clickTarget);
// Fire click events if the event target is still available.
// Note that do not include the eMouseUp event's status since we ignore it
// for compatibility with the other browsers.
nsEventStatus status = nsEventStatus_eIgnore;
nsresult rv = DispatchClickEvents(presShell, aMouseUpEvent, &status,
clickTarget, aOverrideClickTarget);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// Do not do anything if preceding click events are consumed.
// Note that Chromium dispatches "paste" event and actually pates clipboard
// text into focused editor even if the preceding click events are consumed.
// However, this is different from our traditional behavior and does not
// conform to DOM events. If we need to keep compatibility with Chromium,
// we should change it later.
if (status == nsEventStatus_eConsumeNoDefault) {
*aStatus = nsEventStatus_eConsumeNoDefault;
return NS_OK;
}
// Handle middle click paste if it's enabled and the mouse button is middle.
if (aMouseUpEvent->mButton != MouseButton::eMiddle ||
!WidgetMouseEvent::IsMiddleClickPasteEnabled()) {
return NS_OK;
}
DebugOnly<nsresult> rvIgnored =
HandleMiddleClickPaste(presShell, aMouseUpEvent, &status, nullptr);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"Failed to paste for a middle click");
// If new status is nsEventStatus_eConsumeNoDefault or
// nsEventStatus_eConsumeDoDefault, use it.
if (*aStatus != nsEventStatus_eConsumeNoDefault &&
(status == nsEventStatus_eConsumeNoDefault ||
status == nsEventStatus_eConsumeDoDefault)) {
*aStatus = status;
}
// Don't return error even if middle mouse paste fails since we haven't
// handled it here.
return NS_OK;
}
nsresult EventStateManager::DispatchClickEvents(
PresShell* aPresShell, WidgetMouseEvent* aMouseUpEvent,
nsEventStatus* aStatus, nsIContent* aClickTarget,
nsIContent* aOverrideClickTarget) {
MOZ_ASSERT(aPresShell);
MOZ_ASSERT(aMouseUpEvent);
MOZ_ASSERT(EventCausesClickEvents(*aMouseUpEvent));
MOZ_ASSERT(aStatus);
MOZ_ASSERT(aClickTarget || aOverrideClickTarget);
bool notDispatchToContents =
(aMouseUpEvent->mButton == MouseButton::eMiddle ||
aMouseUpEvent->mButton == MouseButton::eSecondary);
bool fireAuxClick = notDispatchToContents;
AutoWeakFrame currentTarget = aClickTarget->GetPrimaryFrame();
nsresult rv = InitAndDispatchClickEvent(
aMouseUpEvent, aStatus, ePointerClick, aPresShell, aClickTarget,
currentTarget, notDispatchToContents, aOverrideClickTarget);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// Fire auxclick event if necessary.
if (fireAuxClick && *aStatus != nsEventStatus_eConsumeNoDefault &&
aClickTarget && aClickTarget->IsInComposedDoc()) {
rv = InitAndDispatchClickEvent(aMouseUpEvent, aStatus, ePointerAuxClick,
aPresShell, aClickTarget, currentTarget,
false, aOverrideClickTarget);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Failed to dispatch ePointerAuxClick");
}
// Fire double click event if click count is 2.
if (aMouseUpEvent->mClickCount == 2 && !fireAuxClick && aClickTarget &&
aClickTarget->IsInComposedDoc()) {
rv = InitAndDispatchClickEvent(aMouseUpEvent, aStatus, eMouseDoubleClick,
aPresShell, aClickTarget, currentTarget,
notDispatchToContents, aOverrideClickTarget);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
return rv;
}
nsresult EventStateManager::HandleMiddleClickPaste(
PresShell* aPresShell, WidgetMouseEvent* aMouseEvent,
nsEventStatus* aStatus, EditorBase* aEditorBase) {
MOZ_ASSERT(aPresShell);
MOZ_ASSERT(aMouseEvent);
MOZ_ASSERT((aMouseEvent->mMessage == ePointerAuxClick &&
aMouseEvent->mButton == MouseButton::eMiddle) ||
EventCausesClickEvents(*aMouseEvent));
MOZ_ASSERT(aStatus);
MOZ_ASSERT(*aStatus != nsEventStatus_eConsumeNoDefault);
// Even if we're called twice or more for a mouse operation, we should
// handle only once. Although mMultipleActionsPrevented may be set to
// true by different event handler in the future, we can use it for now.
if (aMouseEvent->mFlags.mMultipleActionsPrevented) {
return NS_OK;
}
aMouseEvent->mFlags.mMultipleActionsPrevented = true;
RefPtr<Selection> selection;
if (aEditorBase) {
selection = aEditorBase->GetSelection();
if (NS_WARN_IF(!selection)) {
return NS_ERROR_FAILURE;
}
} else {
Document* document = aPresShell->GetDocument();
if (NS_WARN_IF(!document)) {
return NS_ERROR_FAILURE;
}
selection = nsCopySupport::GetSelectionForCopy(document);
if (NS_WARN_IF(!selection)) {
return NS_ERROR_FAILURE;
}
const nsRange* range = selection->GetRangeAt(0);
if (range) {
nsINode* target = range->GetStartContainer();
if (target && target->OwnerDoc()->IsInChromeDocShell()) {
// In Chrome document, limit middle-click pasting to only the editor
// because it looks odd if pasting works in the focused editor when you
// middle-click toolbar or something which are far from the editor.
// However, as DevTools especially Web Console module assumes that paste
// event will be fired when middle-click even on not editor, don't limit
// it.
return NS_OK;
}
}
}
// Don't modify selection here because we've already set caret to the point
// at "mousedown" event.
nsIClipboard::ClipboardType clipboardType = nsIClipboard::kGlobalClipboard;
nsCOMPtr<nsIClipboard> clipboardService =
do_GetService("@mozilla.org/widget/clipboard;1");
if (clipboardService && clipboardService->IsClipboardTypeSupported(
nsIClipboard::kSelectionClipboard)) {
clipboardType = nsIClipboard::kSelectionClipboard;
}
RefPtr<DataTransfer> dataTransfer;
if (aEditorBase) {
// Create the same DataTransfer object here so we can share it between
// the clipboard event and the call to HandlePaste below. This prevents
// race conditions with Content Analysis on like we see in bug 1918027.
dataTransfer =
aEditorBase->CreateDataTransferForPaste(ePaste, clipboardType);
}
const auto clearDataTransfer = MakeScopeExit([&] {
if (dataTransfer) {
dataTransfer->ClearForPaste();
}
});
// Fire ePaste event by ourselves since we need to dispatch "paste" event
// even if the middle click event was consumed for compatibility with
// Chromium.
if (!nsCopySupport::FireClipboardEvent(ePaste, Some(clipboardType),
aPresShell, selection, dataTransfer)) {
*aStatus = nsEventStatus_eConsumeNoDefault;
return NS_OK;
}
// Although we've fired "paste" event, there is no editor to accept the
// clipboard content.
if (!aEditorBase) {
return NS_OK;
}
// Check if the editor is still the good target to paste.
if (aEditorBase->Destroyed() || aEditorBase->IsReadonly()) {
// XXX Should we consume the event when the editor is readonly and/or
// disabled?
return NS_OK;
}
// The selection may have been modified during reflow. Therefore, we
// should adjust event target to pass IsAcceptableInputEvent().
const nsRange* range = selection->GetRangeAt(0);
if (!range) {
return NS_OK;
}
WidgetMouseEvent mouseEvent(*aMouseEvent);
mouseEvent.mOriginalTarget = range->GetStartContainer();
if (NS_WARN_IF(!mouseEvent.mOriginalTarget) ||
!aEditorBase->IsAcceptableInputEvent(&mouseEvent)) {
return NS_OK;
}
// If Control key is pressed, we should paste clipboard content as
// quotation. Otherwise, paste it as is.
if (aMouseEvent->IsControl()) {
DebugOnly<nsresult> rv = aEditorBase->PasteAsQuotationAsAction(
clipboardType, EditorBase::DispatchPasteEvent::No, dataTransfer);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to paste as quotation");
} else {
DebugOnly<nsresult> rv = aEditorBase->PasteAsAction(
clipboardType, EditorBase::DispatchPasteEvent::No, dataTransfer);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to paste");
}
*aStatus = nsEventStatus_eConsumeNoDefault;
return NS_OK;
}
void EventStateManager::ConsumeInteractionData(
Record<nsString, dom::InteractionData>& aInteractions) {
OnTypingInteractionEnded();
aInteractions.Entries().Clear();
auto newEntry = aInteractions.Entries().AppendElement();
newEntry->mKey = u"Typing"_ns;
newEntry->mValue = gTypingInteraction;
gTypingInteraction = {};
}
nsIFrame* EventStateManager::GetEventTarget() {
PresShell* presShell;
if (mCurrentTarget || !mPresContext ||
!(presShell = mPresContext->GetPresShell())) {
return mCurrentTarget;
}
if (mCurrentTargetContent) {
mCurrentTarget = mPresContext->GetPrimaryFrameFor(mCurrentTargetContent);
if (mCurrentTarget) {
return mCurrentTarget;
}
}
nsIFrame* frame = presShell->GetCurrentEventFrame();
return (mCurrentTarget = frame);
}
already_AddRefed<nsIContent> EventStateManager::GetEventTargetContent(
WidgetEvent* aEvent) {
if (aEvent && (aEvent->mMessage == eFocus || aEvent->mMessage == eBlur)) {
nsCOMPtr<nsIContent> content = GetFocusedElement();
return content.forget();
}
if (mCurrentTargetContent) {
nsCOMPtr<nsIContent> content = mCurrentTargetContent;
return content.forget();
}
nsCOMPtr<nsIContent> content;
if (PresShell* presShell = mPresContext->GetPresShell()) {
content = presShell->GetEventTargetContent(aEvent);
}
// Some events here may set mCurrentTarget but not set the corresponding
// event target in the PresShell.
if (!content && mCurrentTarget) {
content = mCurrentTarget->GetContentForEvent(aEvent);
}
return content.forget();
}
static Element* GetLabelTarget(nsIContent* aPossibleLabel) {
mozilla::dom::HTMLLabelElement* label =
mozilla::dom::HTMLLabelElement::FromNode(aPossibleLabel);
if (!label) return nullptr;
return label->GetLabeledElement();
}
/* static */
inline void EventStateManager::DoStateChange(Element* aElement,
ElementState aState,
bool aAddState) {
if (aAddState) {
aElement->AddStates(aState);
} else {
aElement->RemoveStates(aState);
}
}
/* static */
inline void EventStateManager::DoStateChange(nsIContent* aContent,
ElementState aState,
bool aStateAdded) {
if (aContent->IsElement()) {
DoStateChange(aContent->AsElement(), aState, aStateAdded);
}
}
/* static */
void EventStateManager::UpdateAncestorState(nsIContent* aStartNode,
nsIContent* aStopBefore,
ElementState aState,
bool aAddState) {
for (; aStartNode && aStartNode != aStopBefore;
aStartNode = aStartNode->GetFlattenedTreeParent()) {
// We might be starting with a non-element (e.g. a text node) and
// if someone is doing something weird might be ending with a
// non-element too (e.g. a document fragment)
if (!aStartNode->IsElement()) {
continue;
}
Element* element = aStartNode->AsElement();
DoStateChange(element, aState, aAddState);
Element* labelTarget = GetLabelTarget(element);
if (labelTarget) {
DoStateChange(labelTarget, aState, aAddState);
}
}
if (aAddState) {
// We might be in a situation where a node was in hover both
// because it was hovered and because the label for it was
// hovered, and while we stopped hovering the node the label is
// still hovered. Or we might have had two nested labels for the
// same node, and while one is no longer hovered the other still
// is. In that situation, the label that's still hovered will be
// aStopBefore or some ancestor of it, and the call we just made
// to UpdateAncestorState with aAddState = false would have
// removed the hover state from the node. But the node should
// still be in hover state. To handle this situation we need to
// keep walking up the tree and any time we find a label mark its
// corresponding node as still in our state.
for (; aStartNode; aStartNode = aStartNode->GetFlattenedTreeParent()) {
if (!aStartNode->IsElement()) {
continue;
}
Element* labelTarget = GetLabelTarget(aStartNode->AsElement());
if (labelTarget && !labelTarget->State().HasState(aState)) {
DoStateChange(labelTarget, aState, true);
}
}
}
}
// static
bool CanContentHaveActiveState(nsIContent& aContent) {
// Editable content can never become active since their default actions
// are disabled. Watch out for editable content in native anonymous
// subtrees though, as they belong to text controls.
return !aContent.IsEditable() || aContent.IsInNativeAnonymousSubtree();
}
bool EventStateManager::SetContentState(nsIContent* aContent,
ElementState aState) {
MOZ_ASSERT(ManagesState(aState), "Unexpected state");
nsCOMPtr<nsIContent> notifyContent1;
nsCOMPtr<nsIContent> notifyContent2;
bool updateAncestors;
if (aState == ElementState::HOVER || aState == ElementState::ACTIVE) {
// Hover and active are hierarchical
updateAncestors = true;
if (aState == ElementState::ACTIVE) {
if (aContent && !CanContentHaveActiveState(*aContent)) {
aContent = nullptr;
}
if (aContent != mActiveContent) {
notifyContent1 = aContent;
notifyContent2 = mActiveContent;
mActiveContent = aContent;
}
} else {
NS_ASSERTION(aState == ElementState::HOVER, "How did that happen?");
nsIContent* newHover;
if (mPresContext->IsDynamic()) {
newHover = aContent;
} else {
NS_ASSERTION(!aContent || aContent->GetComposedDoc() ==
mPresContext->PresShell()->GetDocument(),
"Unexpected document");
nsIFrame* frame = aContent ? aContent->GetPrimaryFrame() : nullptr;
if (frame && nsLayoutUtils::IsViewportScrollbarFrame(frame)) {
// The scrollbars of viewport should not ignore the hover state.
// Because they are *not* the content of the web page.
newHover = aContent;
} else {
// All contents of the web page should ignore the hover state.
newHover = nullptr;
}
}
if (newHover != mHoverContent) {
notifyContent1 = newHover;
notifyContent2 = mHoverContent;
mHoverContent = newHover;
}
}
} else {
updateAncestors = false;
if (aState == ElementState::DRAGOVER) {
if (aContent != sDragOverContent) {
notifyContent1 = aContent;
notifyContent2 = sDragOverContent;
sDragOverContent = aContent;
}
} else if (aState == ElementState::URLTARGET) {
if (aContent != mURLTargetContent) {
notifyContent1 = aContent;
notifyContent2 = mURLTargetContent;
mURLTargetContent = aContent;
}
}
}
// We need to keep track of which of notifyContent1 and notifyContent2 is
// getting the state set and which is getting it unset. If both are
// non-null, then notifyContent1 is having the state set and notifyContent2
// is having it unset. But if one of them is null, we need to keep track of
// the right thing for notifyContent1 explicitly.
bool content1StateSet = true;
if (!notifyContent1) {
// This is ok because FindCommonAncestor wouldn't find anything
// anyway if notifyContent1 is null.
notifyContent1 = notifyContent2;
notifyContent2 = nullptr;
content1StateSet = false;
}
if (notifyContent1 && mPresContext) {
EnsureDocument(mPresContext);
if (mDocument) {
nsAutoScriptBlocker scriptBlocker;
if (updateAncestors) {
nsCOMPtr<nsIContent> commonAncestor =
FindCommonAncestor(notifyContent1, notifyContent2);
if (notifyContent2) {
// It's very important to first notify the state removal and
// then the state addition, because due to labels it's
// possible that we're removing state from some element but
// then adding it again (say because mHoverContent changed
// from a control to its label).
UpdateAncestorState(notifyContent2, commonAncestor, aState, false);
}
UpdateAncestorState(notifyContent1, commonAncestor, aState,
content1StateSet);
} else {
if (notifyContent2) {
DoStateChange(notifyContent2, aState, false);
}
DoStateChange(notifyContent1, aState, content1StateSet);
}
}
}
return true;
}
void EventStateManager::RemoveNodeFromChainIfNeeded(ElementState aState,
nsIContent* aContentRemoved,
bool aNotify) {
MOZ_ASSERT(aState == ElementState::HOVER || aState == ElementState::ACTIVE);
if (!aContentRemoved->IsElement() ||
!aContentRemoved->AsElement()->State().HasState(aState)) {
return;
}
nsCOMPtr<nsIContent>& leaf =
aState == ElementState::HOVER ? mHoverContent : mActiveContent;
MOZ_ASSERT(leaf);
// These two NS_ASSERTIONS below can fail for Shadow DOM sometimes, and it's
// not clear how to best handle it, see
// https://github.com/whatwg/html/issues/4795 and bug 1551621.
NS_ASSERTION(
nsContentUtils::ContentIsFlattenedTreeDescendantOf(leaf, aContentRemoved),
"Flat tree and active / hover chain got out of sync");
nsIContent* newLeaf = aContentRemoved->GetFlattenedTreeParent();
MOZ_ASSERT(!newLeaf || newLeaf->IsElement());
NS_ASSERTION(!newLeaf || newLeaf->AsElement()->State().HasState(aState),
"State got out of sync because of shadow DOM");
if (aNotify) {
SetContentState(newLeaf, aState);
} else {
// We don't update the removed content's state here, since removing NAC
// happens from layout and we don't really want to notify at that point or
// what not.
//
// Also, NAC is not observable and NAC being removed will go away soon.
leaf = newLeaf;
}
MOZ_ASSERT(leaf == newLeaf || (aState == ElementState::ACTIVE && !leaf &&
!CanContentHaveActiveState(*newLeaf)));
}
void EventStateManager::NativeAnonymousContentRemoved(nsIContent* aContent) {
MOZ_ASSERT(aContent->IsRootOfNativeAnonymousSubtree());
RemoveNodeFromChainIfNeeded(ElementState::HOVER, aContent, false);
RemoveNodeFromChainIfNeeded(ElementState::ACTIVE, aContent, false);
nsCOMPtr<nsIContent>& lastLeftMouseDownContent =
mLastLeftMouseDownInfo.mLastMouseDownContent;
if (lastLeftMouseDownContent &&
nsContentUtils::ContentIsFlattenedTreeDescendantOf(
lastLeftMouseDownContent, aContent)) {
lastLeftMouseDownContent = aContent->GetFlattenedTreeParent();
}
nsCOMPtr<nsIContent>& lastMiddleMouseDownContent =
mLastMiddleMouseDownInfo.mLastMouseDownContent;
if (lastMiddleMouseDownContent &&
nsContentUtils::ContentIsFlattenedTreeDescendantOf(
lastMiddleMouseDownContent, aContent)) {
lastMiddleMouseDownContent = aContent->GetFlattenedTreeParent();
}
nsCOMPtr<nsIContent>& lastRightMouseDownContent =
mLastRightMouseDownInfo.mLastMouseDownContent;
if (lastRightMouseDownContent &&
nsContentUtils::ContentIsFlattenedTreeDescendantOf(
lastRightMouseDownContent, aContent)) {
lastRightMouseDownContent = aContent->GetFlattenedTreeParent();
}
}
void EventStateManager::ContentInserted(nsIContent* aChild,
const ContentInsertInfo& aInfo) {
if (nsFocusManager* fm = nsFocusManager::GetFocusManager()) {
fm->ContentInserted(aChild, aInfo);
}
}
void EventStateManager::ContentAppended(nsIContent* aFirstNewContent,
const ContentAppendInfo& aInfo) {
if (nsFocusManager* fm = nsFocusManager::GetFocusManager()) {
fm->ContentAppended(aFirstNewContent, aInfo);
}
}
void EventStateManager::ContentRemoved(Document* aDocument,
nsIContent* aContent,
const ContentRemoveInfo& aInfo) {
/*
* Anchor and area elements when focused or hovered might make the UI to show
* the current link. We want to make sure that the UI gets informed when they
* are actually removed from the DOM.
*/
if (aContent->IsAnyOfHTMLElements(nsGkAtoms::a, nsGkAtoms::area) &&
(aContent->AsElement()->State().HasAtLeastOneOfStates(
ElementState::FOCUS | ElementState::HOVER))) {
Element* element = aContent->AsElement();
element->LeaveLink(element->GetPresContext(Element::eForComposedDoc));
}
if (aContent->IsElement()) {
if (RefPtr<nsPresContext> presContext = mPresContext) {
IMEStateManager::OnRemoveContent(*presContext,
MOZ_KnownLive(*aContent->AsElement()));
}
WheelTransaction::OnRemoveElement(aContent);
}
// inform the focus manager that the content is being removed. If this
// content is focused, the focus will be removed without firing events.
if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
fm->ContentRemoved(aDocument, aContent, aInfo);
}
RemoveNodeFromChainIfNeeded(ElementState::HOVER, aContent, true);
RemoveNodeFromChainIfNeeded(ElementState::ACTIVE, aContent, true);
if (sDragOverContent &&
sDragOverContent->OwnerDoc() == aContent->OwnerDoc() &&
nsContentUtils::ContentIsFlattenedTreeDescendantOf(sDragOverContent,
aContent)) {
sDragOverContent = nullptr;
}
if (!aInfo.mNewParent) {
PointerEventHandler::ReleaseIfCaptureByDescendant(aContent);
}
if (mMouseEnterLeaveHelper) {
const bool hadMouseOutTarget =
mMouseEnterLeaveHelper->GetOutEventTarget() != nullptr;
mMouseEnterLeaveHelper->ContentRemoved(*aContent);
// If we lose the mouseout target, we need to dispatch mouseover on an
// ancestor. For ensuring the chance to do it before next user input, we
// need a synthetic mouse move.
if (hadMouseOutTarget && !mMouseEnterLeaveHelper->GetOutEventTarget()) {
if (PresShell* presShell =
mPresContext ? mPresContext->GetPresShell() : nullptr) {
presShell->SynthesizeMouseMove(false);
}
}
}
for (const auto& entry : mPointersEnterLeaveHelper) {
if (entry.GetData()) {
entry.GetData()->ContentRemoved(*aContent);
}
}
NotifyContentWillBeRemovedForGesture(*aContent);
}
void EventStateManager::TextControlRootWillBeRemoved(
TextControlElement& aTextControlElement) {
if (!mGestureDownInTextControl || !mGestureDownFrameOwner ||
!mGestureDownFrameOwner->IsInNativeAnonymousSubtree()) {
return;
}
// If we track gesture to start drag in aTextControlElement, we should keep
// tracking it with aTextContrlElement itself for now because this may be
// caused by reframing aTextControlElement which may not be intended by the
// user.
if (&aTextControlElement ==
mGestureDownFrameOwner
->GetClosestNativeAnonymousSubtreeRootParentOrHost()) {
mGestureDownFrameOwner = &aTextControlElement;
}
}
void EventStateManager::TextControlRootAdded(
Element& aAnonymousDivElement, TextControlElement& aTextControlElement) {
if (!mGestureDownInTextControl ||
mGestureDownFrameOwner != &aTextControlElement) {
return;
}
// If we track gesture to start drag in aTextControlElement, but the frame
// owner is the text control element itself, the anonymous nodes in it are
// recreated by a reframe. If so, we should keep tracking it with the
// recreated native anonymous node.
mGestureDownFrameOwner =
aAnonymousDivElement.GetFirstChild()
? aAnonymousDivElement.GetFirstChild()
: static_cast<nsIContent*>(&aAnonymousDivElement);
}
bool EventStateManager::EventStatusOK(WidgetGUIEvent* aEvent) {
return !(aEvent->mMessage == eMouseDown &&
aEvent->AsMouseEvent()->mButton == MouseButton::ePrimary &&
!sNormalLMouseEventInProcess);
}
//-------------------------------------------
// Access Key Registration
//-------------------------------------------
void EventStateManager::RegisterAccessKey(Element* aElement, uint32_t aKey) {
if (aElement && !mAccessKeys.Contains(aElement)) {
mAccessKeys.AppendObject(aElement);
}
}
void EventStateManager::UnregisterAccessKey(Element* aElement, uint32_t aKey) {
if (aElement) {
mAccessKeys.RemoveObject(aElement);
}
}
uint32_t EventStateManager::GetRegisteredAccessKey(Element* aElement) {
MOZ_ASSERT(aElement);
if (!mAccessKeys.Contains(aElement)) {
return 0;
}
nsAutoString accessKey;
aElement->GetAttr(nsGkAtoms::accesskey, accessKey);
return accessKey.First();
}
PresShell* EventStateManager::GetRootPresShell() const {
PresShell* const presShell = GetPresShell();
return presShell ? presShell->GetRootPresShell() : nullptr;
}
void EventStateManager::EnsureDocument(nsPresContext* aPresContext) {
if (!mDocument) mDocument = aPresContext->Document();
}
void EventStateManager::FlushLayout(nsPresContext* aPresContext) {
MOZ_ASSERT(aPresContext, "nullptr ptr");
if (RefPtr<PresShell> presShell = aPresContext->GetPresShell()) {
presShell->FlushPendingNotifications(FlushType::InterruptibleLayout);
}
}
Element* EventStateManager::GetFocusedElement() {
nsFocusManager* fm = nsFocusManager::GetFocusManager();
EnsureDocument(mPresContext);
if (!fm || !mDocument) {
return nullptr;
}
nsCOMPtr<nsPIDOMWindowOuter> focusedWindow;
return nsFocusManager::GetFocusedDescendant(
mDocument->GetWindow(), nsFocusManager::eOnlyCurrentWindow,
getter_AddRefs(focusedWindow));
}
//-------------------------------------------------------
// Return true if the docshell is visible
bool EventStateManager::IsShellVisible(nsIDocShell* aShell) {
NS_ASSERTION(aShell, "docshell is null");
nsCOMPtr<nsIBaseWindow> basewin = do_QueryInterface(aShell);
if (!basewin) return true;
bool isVisible = true;
basewin->GetVisibility(&isVisible);
// We should be doing some additional checks here so that
// we don't tab into hidden tabs of tabbrowser. -bryner
return isVisible;
}
nsresult EventStateManager::DoContentCommandEvent(
WidgetContentCommandEvent* aEvent) {
EnsureDocument(mPresContext);
NS_ENSURE_TRUE(mDocument, NS_ERROR_FAILURE);
nsCOMPtr<nsPIDOMWindowOuter> window(mDocument->GetWindow());
NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
nsCOMPtr<nsPIWindowRoot> root = window->GetTopWindowRoot();
NS_ENSURE_TRUE(root, NS_ERROR_FAILURE);
const char* cmd;
bool maybeNeedToHandleInRemote = false;
switch (aEvent->mMessage) {
case eContentCommandCut:
cmd = "cmd_cut";
maybeNeedToHandleInRemote = true;
break;
case eContentCommandCopy:
cmd = "cmd_copy";
maybeNeedToHandleInRemote = true;
break;
case eContentCommandPaste:
cmd = "cmd_paste";
maybeNeedToHandleInRemote = true;
break;
case eContentCommandDelete:
cmd = "cmd_delete";
maybeNeedToHandleInRemote = true;
break;
case eContentCommandUndo:
cmd = "cmd_undo";
maybeNeedToHandleInRemote = true;
break;
case eContentCommandRedo:
cmd = "cmd_redo";
maybeNeedToHandleInRemote = true;
break;
case eContentCommandPasteTransferable:
cmd = "cmd_pasteTransferable";
break;
case eContentCommandLookUpDictionary:
cmd = "cmd_lookUpDictionary";
break;
default:
return NS_ERROR_NOT_IMPLEMENTED;
}
if (XRE_IsParentProcess() && maybeNeedToHandleInRemote) {
if (BrowserParent* remote = BrowserParent::GetFocused()) {
if (!aEvent->mOnlyEnabledCheck) {
remote->SendSimpleContentCommandEvent(*aEvent);
}
// XXX The command may be disabled in the parent process. Perhaps, we
// should set actual enabled state in the parent process here and there
// should be another bool flag which indicates whether the content is sent
// to a remote process.
aEvent->mIsEnabled = true;
aEvent->mSucceeded = true;
return NS_OK;
}
}
// If user tries to do something, user must try to do it in visible window.
// So, let's retrieve controller of visible window.
nsCOMPtr<nsIController> controller;
nsresult rv =
root->GetControllerForCommand(cmd, true, getter_AddRefs(controller));
NS_ENSURE_SUCCESS(rv, rv);
if (!controller) {
// When GetControllerForCommand succeeded but there is no controller, the
// command isn't supported.
aEvent->mIsEnabled = false;
} else {
bool canDoIt;
rv = controller->IsCommandEnabled(cmd, &canDoIt);
NS_ENSURE_SUCCESS(rv, rv);
aEvent->mIsEnabled = canDoIt;
if (canDoIt && !aEvent->mOnlyEnabledCheck) {
switch (aEvent->mMessage) {
case eContentCommandPasteTransferable: {
BrowserParent* remote = BrowserParent::GetFocused();
if (remote) {
IPCTransferable ipcTransferable;
nsContentUtils::TransferableToIPCTransferable(
aEvent->mTransferable, &ipcTransferable, false,
remote->Manager());
remote->SendPasteTransferable(std::move(ipcTransferable));
rv = NS_OK;
} else {
nsCOMPtr<nsICommandController> commandController =
do_QueryInterface(controller);
NS_ENSURE_STATE(commandController);
RefPtr<nsCommandParams> params = new nsCommandParams();
rv = params->SetISupports("transferable", aEvent->mTransferable);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = commandController->DoCommandWithParams(cmd, params);
}
break;
}
case eContentCommandLookUpDictionary: {
nsCOMPtr<nsICommandController> commandController =
do_QueryInterface(controller);
if (NS_WARN_IF(!commandController)) {
return NS_ERROR_FAILURE;
}
RefPtr<nsCommandParams> params = new nsCommandParams();
rv = params->SetInt("x", aEvent->mRefPoint.x);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = params->SetInt("y", aEvent->mRefPoint.y);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = commandController->DoCommandWithParams(cmd, params);
break;
}
default:
rv = controller->DoCommand(cmd);
break;
}
NS_ENSURE_SUCCESS(rv, rv);
}
}
aEvent->mSucceeded = true;
return NS_OK;
}
nsresult EventStateManager::DoContentCommandInsertTextEvent(
WidgetContentCommandEvent* aEvent) {
MOZ_ASSERT(aEvent);
MOZ_ASSERT(aEvent->mMessage == eContentCommandInsertText);
MOZ_DIAGNOSTIC_ASSERT(aEvent->mString.isSome());
MOZ_DIAGNOSTIC_ASSERT(!aEvent->mString.ref().IsEmpty());
aEvent->mIsEnabled = false;
aEvent->mSucceeded = false;
NS_ENSURE_TRUE(mPresContext, NS_ERROR_NOT_AVAILABLE);
if (XRE_IsParentProcess()) {
// Handle it in focused content process if there is.
if (BrowserParent* remote = BrowserParent::GetFocused()) {
if (!aEvent->mOnlyEnabledCheck) {
remote->SendInsertText(*aEvent);
}
// XXX The remote process may be not editable right now. Therefore, this
// may be different from actual state in the remote process.
aEvent->mIsEnabled = true;
aEvent->mSucceeded = true;
return NS_OK;
}
}
// If there is no active editor in this process, we should treat the command
// is disabled.
RefPtr<EditorBase> activeEditor =
nsContentUtils::GetActiveEditor(mPresContext);
if (!activeEditor) {
aEvent->mSucceeded = true;
return NS_OK;
}
nsresult rv = activeEditor->InsertTextAsAction(aEvent->mString.ref());
aEvent->mIsEnabled = rv != NS_SUCCESS_DOM_NO_OPERATION;
aEvent->mSucceeded = NS_SUCCEEDED(rv);
return NS_OK;
}
nsresult EventStateManager::DoContentCommandReplaceTextEvent(
WidgetContentCommandEvent* aEvent) {
MOZ_ASSERT(aEvent);
MOZ_ASSERT(aEvent->mMessage == eContentCommandReplaceText);
MOZ_DIAGNOSTIC_ASSERT(aEvent->mString.isSome());
MOZ_DIAGNOSTIC_ASSERT(!aEvent->mString.ref().IsEmpty());
aEvent->mIsEnabled = false;
aEvent->mSucceeded = false;
NS_ENSURE_TRUE(mPresContext, NS_ERROR_NOT_AVAILABLE);
if (XRE_IsParentProcess()) {
// Handle it in focused content process if there is.
if (BrowserParent* remote = BrowserParent::GetFocused()) {
if (!aEvent->mOnlyEnabledCheck) {
Unused << remote->SendReplaceText(*aEvent);
}
// XXX The remote process may be not editable right now. Therefore, this
// may be different from actual state in the remote process.
aEvent->mIsEnabled = true;
aEvent->mSucceeded = true;
return NS_OK;
}
}
// If there is no active editor in this process, we should treat the command
// is disabled.
RefPtr<EditorBase> activeEditor =
nsContentUtils::GetActiveEditor(mPresContext);
if (NS_WARN_IF(!activeEditor)) {
aEvent->mSucceeded = true;
return NS_OK;
}
RefPtr<TextComposition> composition =
IMEStateManager::GetTextCompositionFor(mPresContext);
if (NS_WARN_IF(composition)) {
// We don't support replace text action during composition.
aEvent->mSucceeded = true;
return NS_OK;
}
ContentEventHandler handler(mPresContext);
RefPtr<nsRange> range = handler.GetRangeFromFlatTextOffset(
aEvent, aEvent->mSelection.mOffset,
aEvent->mSelection.mReplaceSrcString.Length());
if (NS_WARN_IF(!range)) {
aEvent->mSucceeded = false;
return NS_OK;
}
// If original replacement text isn't matched with selection text, throws
// error.
nsAutoString targetStr;
nsresult rv = handler.GenerateFlatTextContent(range, targetStr);
if (NS_WARN_IF(NS_FAILED(rv))) {
aEvent->mSucceeded = false;
return NS_OK;
}
if (!aEvent->mSelection.mReplaceSrcString.Equals(targetStr)) {
aEvent->mSucceeded = false;
return NS_OK;
}
rv = activeEditor->ReplaceTextAsAction(
aEvent->mString.ref(), range,
TextEditor::AllowBeforeInputEventCancelable::Yes,
aEvent->mSelection.mPreventSetSelection
? EditorBase::PreventSetSelection::Yes
: EditorBase::PreventSetSelection::No);
if (NS_WARN_IF(NS_FAILED(rv))) {
aEvent->mSucceeded = false;
return NS_OK;
}
aEvent->mIsEnabled = rv != NS_SUCCESS_DOM_NO_OPERATION;
aEvent->mSucceeded = true;
return NS_OK;
}
nsresult EventStateManager::DoContentCommandScrollEvent(
WidgetContentCommandEvent* aEvent) {
NS_ENSURE_TRUE(mPresContext, NS_ERROR_NOT_AVAILABLE);
PresShell* presShell = mPresContext->GetPresShell();
NS_ENSURE_TRUE(presShell, NS_ERROR_NOT_AVAILABLE);
NS_ENSURE_TRUE(aEvent->mScroll.mAmount != 0, NS_ERROR_INVALID_ARG);
ScrollUnit scrollUnit;
switch (aEvent->mScroll.mUnit) {
case WidgetContentCommandEvent::eCmdScrollUnit_Line:
scrollUnit = ScrollUnit::LINES;
break;
case WidgetContentCommandEvent::eCmdScrollUnit_Page:
scrollUnit = ScrollUnit::PAGES;
break;
case WidgetContentCommandEvent::eCmdScrollUnit_Whole:
scrollUnit = ScrollUnit::WHOLE;
break;
default:
return NS_ERROR_INVALID_ARG;
}
aEvent->mSucceeded = true;
ScrollContainerFrame* sf =
presShell->GetScrollContainerFrameToScroll(layers::EitherScrollDirection);
aEvent->mIsEnabled =
sf ? (aEvent->mScroll.mIsHorizontal ? WheelHandlingUtils::CanScrollOn(
sf, aEvent->mScroll.mAmount, 0)
: WheelHandlingUtils::CanScrollOn(
sf, 0, aEvent->mScroll.mAmount))
: false;
if (!aEvent->mIsEnabled || aEvent->mOnlyEnabledCheck) {
return NS_OK;
}
nsIntPoint pt(0, 0);
if (aEvent->mScroll.mIsHorizontal) {
pt.x = aEvent->mScroll.mAmount;
} else {
pt.y = aEvent->mScroll.mAmount;
}
// The caller may want synchronous scrolling.
sf->ScrollBy(pt, scrollUnit, ScrollMode::Instant);
return NS_OK;
}
void EventStateManager::SetActiveManager(EventStateManager* aNewESM,
nsIContent* aContent) {
if (sActiveESM && aNewESM != sActiveESM) {
sActiveESM->SetContentState(nullptr, ElementState::ACTIVE);
}
sActiveESM = aNewESM;
if (sActiveESM && aContent) {
sActiveESM->SetContentState(aContent, ElementState::ACTIVE);
}
}
void EventStateManager::ClearGlobalActiveContent(EventStateManager* aClearer) {
if (aClearer) {
aClearer->SetContentState(nullptr, ElementState::ACTIVE);
if (sDragOverContent) {
aClearer->SetContentState(nullptr, ElementState::DRAGOVER);
}
}
if (sActiveESM && aClearer != sActiveESM) {
sActiveESM->SetContentState(nullptr, ElementState::ACTIVE);
}
sActiveESM = nullptr;
}
/******************************************************************/
/* mozilla::EventStateManager::DeltaAccumulator */
/******************************************************************/
void EventStateManager::DeltaAccumulator::InitLineOrPageDelta(
nsIFrame* aTargetFrame, EventStateManager* aESM, WidgetWheelEvent* aEvent) {
MOZ_ASSERT(aESM);
MOZ_ASSERT(aEvent);
// Reset if the previous wheel event is too old.
if (!mLastTime.IsNull()) {
TimeDuration duration = TimeStamp::Now() - mLastTime;
if (duration.ToMilliseconds() >
StaticPrefs::mousewheel_transaction_timeout()) {
Reset();
}
}
// If we have accumulated delta, we may need to reset it.
if (IsInTransaction()) {
// If wheel event type is changed, reset the values.
if (mHandlingDeltaMode != aEvent->mDeltaMode ||
mIsNoLineOrPageDeltaDevice != aEvent->mIsNoLineOrPageDelta) {
Reset();
} else {
// If the delta direction is changed, we should reset only the
// accumulated values.
if (mX && aEvent->mDeltaX && ((aEvent->mDeltaX > 0.0) != (mX > 0.0))) {
mX = mPendingScrollAmountX = 0.0;
}
if (mY && aEvent->mDeltaY && ((aEvent->mDeltaY > 0.0) != (mY > 0.0))) {
mY = mPendingScrollAmountY = 0.0;
}
}
}
mHandlingDeltaMode = aEvent->mDeltaMode;
mIsNoLineOrPageDeltaDevice = aEvent->mIsNoLineOrPageDelta;
{
ScrollContainerFrame* scrollTarget = aESM->ComputeScrollTarget(
aTargetFrame, aEvent, COMPUTE_DEFAULT_ACTION_TARGET);
nsPresContext* pc = scrollTarget ? scrollTarget->PresContext()
: aTargetFrame->PresContext();
aEvent->mScrollAmount = aESM->GetScrollAmount(pc, aEvent, scrollTarget);
}
// If it's handling neither a device that does not provide line or page deltas
// nor delta values multiplied by prefs, we must not modify lineOrPageDelta
// values.
// TODO(emilio): Does this care about overridden scroll speed?
if (!mIsNoLineOrPageDeltaDevice &&
!EventStateManager::WheelPrefs::GetInstance()
->NeedToComputeLineOrPageDelta(aEvent)) {
// Set the delta values to mX and mY. They would be used when above block
// resets mX/mY/mPendingScrollAmountX/mPendingScrollAmountY if the direction
// is changed.
// NOTE: We shouldn't accumulate the delta values, it might could cause
// overflow even though it's not a realistic situation.
if (aEvent->mDeltaX) {
mX = aEvent->mDeltaX;
}
if (aEvent->mDeltaY) {
mY = aEvent->mDeltaY;
}
mLastTime = TimeStamp::Now();
return;
}
mX += aEvent->mDeltaX;
mY += aEvent->mDeltaY;
if (mHandlingDeltaMode == WheelEvent_Binding::DOM_DELTA_PIXEL) {
// Records pixel delta values and init mLineOrPageDeltaX and
// mLineOrPageDeltaY for wheel events which are caused by pixel only
// devices. Ignore mouse wheel transaction for computing this. The
// lineOrPageDelta values will be used by dispatching legacy
// eMouseScrollEventClass (DOMMouseScroll) but not be used for scrolling
// of default action. The transaction should be used only for the default
// action.
auto scrollAmountInCSSPixels =
CSSIntSize::FromAppUnitsRounded(aEvent->mScrollAmount);
aEvent->mLineOrPageDeltaX = RoundDown(mX) / scrollAmountInCSSPixels.width;
aEvent->mLineOrPageDeltaY = RoundDown(mY) / scrollAmountInCSSPixels.height;
mX -= aEvent->mLineOrPageDeltaX * scrollAmountInCSSPixels.width;
mY -= aEvent->mLineOrPageDeltaY * scrollAmountInCSSPixels.height;
} else {
aEvent->mLineOrPageDeltaX = RoundDown(mX);
aEvent->mLineOrPageDeltaY = RoundDown(mY);
mX -= aEvent->mLineOrPageDeltaX;
mY -= aEvent->mLineOrPageDeltaY;
}
mLastTime = TimeStamp::Now();
}
void EventStateManager::DeltaAccumulator::Reset() {
mX = mY = 0.0;
mPendingScrollAmountX = mPendingScrollAmountY = 0.0;
mHandlingDeltaMode = UINT32_MAX;
mIsNoLineOrPageDeltaDevice = false;
}
nsIntPoint
EventStateManager::DeltaAccumulator::ComputeScrollAmountForDefaultAction(
WidgetWheelEvent* aEvent, const nsIntSize& aScrollAmountInDevPixels) {
MOZ_ASSERT(aEvent);
DeltaValues acceleratedDelta = WheelTransaction::AccelerateWheelDelta(aEvent);
nsIntPoint result(0, 0);
if (aEvent->mDeltaMode == WheelEvent_Binding::DOM_DELTA_PIXEL) {
mPendingScrollAmountX += acceleratedDelta.deltaX;
mPendingScrollAmountY += acceleratedDelta.deltaY;
} else {
mPendingScrollAmountX +=
aScrollAmountInDevPixels.width * acceleratedDelta.deltaX;
mPendingScrollAmountY +=
aScrollAmountInDevPixels.height * acceleratedDelta.deltaY;
}
result.x = RoundDown(mPendingScrollAmountX);
result.y = RoundDown(mPendingScrollAmountY);
mPendingScrollAmountX -= result.x;
mPendingScrollAmountY -= result.y;
return result;
}
/******************************************************************/
/* mozilla::EventStateManager::WheelPrefs */
/******************************************************************/
// static
EventStateManager::WheelPrefs* EventStateManager::WheelPrefs::GetInstance() {
if (!sInstance) {
sInstance = new WheelPrefs();
}
return sInstance;
}
// static
void EventStateManager::WheelPrefs::Shutdown() {
delete sInstance;
sInstance = nullptr;
}
// static
void EventStateManager::WheelPrefs::OnPrefChanged(const char* aPrefName,
void* aClosure) {
// forget all prefs, it's not problem for performance.
sInstance->Reset();
DeltaAccumulator::GetInstance()->Reset();
}
EventStateManager::WheelPrefs::WheelPrefs() {
Reset();
Preferences::RegisterPrefixCallback(OnPrefChanged, "mousewheel.");
}
EventStateManager::WheelPrefs::~WheelPrefs() {
Preferences::UnregisterPrefixCallback(OnPrefChanged, "mousewheel.");
}
void EventStateManager::WheelPrefs::Reset() { memset(mInit, 0, sizeof(mInit)); }
EventStateManager::WheelPrefs::Index EventStateManager::WheelPrefs::GetIndexFor(
const WidgetWheelEvent* aEvent) {
if (!aEvent) {
return INDEX_DEFAULT;
}
Modifiers modifiers = (aEvent->mModifiers & (MODIFIER_ALT | MODIFIER_CONTROL |
MODIFIER_META | MODIFIER_SHIFT));
switch (modifiers) {
case MODIFIER_ALT:
return INDEX_ALT;
case MODIFIER_CONTROL:
return INDEX_CONTROL;
case MODIFIER_META:
return INDEX_META;
case MODIFIER_SHIFT:
return INDEX_SHIFT;
default:
// If two or more modifier keys are pressed, we should use default
// settings.
return INDEX_DEFAULT;
}
}
void EventStateManager::WheelPrefs::GetBasePrefName(
EventStateManager::WheelPrefs::Index aIndex, nsACString& aBasePrefName) {
aBasePrefName.AssignLiteral("mousewheel.");
switch (aIndex) {
case INDEX_ALT:
aBasePrefName.AppendLiteral("with_alt.");
break;
case INDEX_CONTROL:
aBasePrefName.AppendLiteral("with_control.");
break;
case INDEX_META:
aBasePrefName.AppendLiteral("with_meta.");
break;
case INDEX_SHIFT:
aBasePrefName.AppendLiteral("with_shift.");
break;
case INDEX_DEFAULT:
default:
aBasePrefName.AppendLiteral("default.");
break;
}
}
void EventStateManager::WheelPrefs::Init(
EventStateManager::WheelPrefs::Index aIndex) {
if (mInit[aIndex]) {
return;
}
mInit[aIndex] = true;
nsAutoCString basePrefName;
GetBasePrefName(aIndex, basePrefName);
nsAutoCString prefNameX(basePrefName);
prefNameX.AppendLiteral("delta_multiplier_x");
mMultiplierX[aIndex] =
static_cast<double>(Preferences::GetInt(prefNameX.get(), 100)) / 100;
nsAutoCString prefNameY(basePrefName);
prefNameY.AppendLiteral("delta_multiplier_y");
mMultiplierY[aIndex] =
static_cast<double>(Preferences::GetInt(prefNameY.get(), 100)) / 100;
nsAutoCString prefNameZ(basePrefName);
prefNameZ.AppendLiteral("delta_multiplier_z");
mMultiplierZ[aIndex] =
static_cast<double>(Preferences::GetInt(prefNameZ.get(), 100)) / 100;
nsAutoCString prefNameAction(basePrefName);
prefNameAction.AppendLiteral("action");
int32_t action = Preferences::GetInt(prefNameAction.get(), ACTION_SCROLL);
if (action < int32_t(ACTION_NONE) || action > int32_t(ACTION_LAST)) {
NS_WARNING("Unsupported action pref value, replaced with 'Scroll'.");
action = ACTION_SCROLL;
}
mActions[aIndex] = static_cast<Action>(action);
// Compute action values overridden by .override_x pref.
// At present, override is possible only for the x-direction
// because this pref is introduced mainly for tilt wheels.
// Note that ACTION_HORIZONTALIZED_SCROLL isn't a valid value for this pref
// because it affects only to deltaY.
prefNameAction.AppendLiteral(".override_x");
int32_t actionOverrideX = Preferences::GetInt(prefNameAction.get(), -1);
if (actionOverrideX < -1 || actionOverrideX > int32_t(ACTION_LAST) ||
actionOverrideX == ACTION_HORIZONTALIZED_SCROLL) {
NS_WARNING("Unsupported action override pref value, didn't override.");
actionOverrideX = -1;
}
mOverriddenActionsX[aIndex] = (actionOverrideX == -1)
? static_cast<Action>(action)
: static_cast<Action>(actionOverrideX);
}
void EventStateManager::WheelPrefs::GetMultiplierForDeltaXAndY(
const WidgetWheelEvent* aEvent, Index aIndex, double* aMultiplierForDeltaX,
double* aMultiplierForDeltaY) {
*aMultiplierForDeltaX = mMultiplierX[aIndex];
*aMultiplierForDeltaY = mMultiplierY[aIndex];
// If the event has been horizontalized(I.e. treated as a horizontal wheel
// scroll for a vertical wheel scroll), then we should swap mMultiplierX and
// mMultiplierY. By doing this, multipliers will still apply to the delta
// values they origianlly corresponded to.
if (aEvent->mDeltaValuesHorizontalizedForDefaultHandler &&
ComputeActionFor(aEvent) == ACTION_HORIZONTALIZED_SCROLL) {
std::swap(*aMultiplierForDeltaX, *aMultiplierForDeltaY);
}
}
void EventStateManager::WheelPrefs::ApplyUserPrefsToDelta(
WidgetWheelEvent* aEvent) {
if (aEvent->mCustomizedByUserPrefs) {
return;
}
Index index = GetIndexFor(aEvent);
Init(index);
double multiplierForDeltaX = 1.0, multiplierForDeltaY = 1.0;
GetMultiplierForDeltaXAndY(aEvent, index, &multiplierForDeltaX,
&multiplierForDeltaY);
aEvent->mDeltaX *= multiplierForDeltaX;
aEvent->mDeltaY *= multiplierForDeltaY;
aEvent->mDeltaZ *= mMultiplierZ[index];
// If the multiplier is 1.0 or -1.0, i.e., it doesn't change the absolute
// value, we should use lineOrPageDelta values which were set by widget.
// Otherwise, we need to compute them from accumulated delta values.
if (!NeedToComputeLineOrPageDelta(aEvent)) {
aEvent->mLineOrPageDeltaX *= static_cast<int32_t>(multiplierForDeltaX);
aEvent->mLineOrPageDeltaY *= static_cast<int32_t>(multiplierForDeltaY);
} else {
aEvent->mLineOrPageDeltaX = 0;
aEvent->mLineOrPageDeltaY = 0;
}
aEvent->mCustomizedByUserPrefs =
((mMultiplierX[index] != 1.0) || (mMultiplierY[index] != 1.0) ||
(mMultiplierZ[index] != 1.0));
}
void EventStateManager::WheelPrefs::CancelApplyingUserPrefsFromOverflowDelta(
WidgetWheelEvent* aEvent) {
Index index = GetIndexFor(aEvent);
Init(index);
// XXX If the multiplier pref value is negative, the scroll direction was
// changed and caused to scroll different direction. In such case,
// this method reverts the sign of overflowDelta. Does it make widget
// happy? Although, widget can know the pref applied delta values by
// referrencing the deltaX and deltaY of the event.
double multiplierForDeltaX = 1.0, multiplierForDeltaY = 1.0;
GetMultiplierForDeltaXAndY(aEvent, index, &multiplierForDeltaX,
&multiplierForDeltaY);
if (multiplierForDeltaX) {
aEvent->mOverflowDeltaX /= multiplierForDeltaX;
}
if (multiplierForDeltaY) {
aEvent->mOverflowDeltaY /= multiplierForDeltaY;
}
}
EventStateManager::WheelPrefs::Action
EventStateManager::WheelPrefs::ComputeActionFor(
const WidgetWheelEvent* aEvent) {
Index index = GetIndexFor(aEvent);
Init(index);
bool deltaXPreferred = (Abs(aEvent->mDeltaX) > Abs(aEvent->mDeltaY) &&
Abs(aEvent->mDeltaX) > Abs(aEvent->mDeltaZ));
Action* actions = deltaXPreferred ? mOverriddenActionsX : mActions;
if (actions[index] == ACTION_NONE || actions[index] == ACTION_SCROLL ||
actions[index] == ACTION_HORIZONTALIZED_SCROLL) {
return actions[index];
}
// Momentum events shouldn't run special actions.
if (aEvent->mIsMomentum) {
// Use the default action. Note that user might kill the wheel scrolling.
Init(INDEX_DEFAULT);
if (actions[INDEX_DEFAULT] == ACTION_SCROLL ||
actions[INDEX_DEFAULT] == ACTION_HORIZONTALIZED_SCROLL) {
return actions[INDEX_DEFAULT];
}
return ACTION_NONE;
}
return actions[index];
}
bool EventStateManager::WheelPrefs::NeedToComputeLineOrPageDelta(
const WidgetWheelEvent* aEvent) {
Index index = GetIndexFor(aEvent);
Init(index);
return (mMultiplierX[index] != 1.0 && mMultiplierX[index] != -1.0) ||
(mMultiplierY[index] != 1.0 && mMultiplierY[index] != -1.0);
}
void EventStateManager::WheelPrefs::GetUserPrefsForEvent(
const WidgetWheelEvent* aEvent, double* aOutMultiplierX,
double* aOutMultiplierY) {
Index index = GetIndexFor(aEvent);
Init(index);
double multiplierForDeltaX = 1.0, multiplierForDeltaY = 1.0;
GetMultiplierForDeltaXAndY(aEvent, index, &multiplierForDeltaX,
&multiplierForDeltaY);
*aOutMultiplierX = multiplierForDeltaX;
*aOutMultiplierY = multiplierForDeltaY;
}
// static
Maybe<layers::APZWheelAction> EventStateManager::APZWheelActionFor(
const WidgetWheelEvent* aEvent) {
if (aEvent->mMessage != eWheel) {
return Nothing();
}
WheelPrefs::Action action =
WheelPrefs::GetInstance()->ComputeActionFor(aEvent);
switch (action) {
case WheelPrefs::ACTION_SCROLL:
case WheelPrefs::ACTION_HORIZONTALIZED_SCROLL:
return Some(layers::APZWheelAction::Scroll);
case WheelPrefs::ACTION_PINCH_ZOOM:
return Some(layers::APZWheelAction::PinchZoom);
default:
return Nothing();
}
}
// static
WheelDeltaAdjustmentStrategy EventStateManager::GetWheelDeltaAdjustmentStrategy(
const WidgetWheelEvent& aEvent) {
if (aEvent.mMessage != eWheel) {
return WheelDeltaAdjustmentStrategy::eNone;
}
switch (WheelPrefs::GetInstance()->ComputeActionFor(&aEvent)) {
case WheelPrefs::ACTION_SCROLL:
if (StaticPrefs::mousewheel_autodir_enabled() && 0 == aEvent.mDeltaZ) {
if (StaticPrefs::mousewheel_autodir_honourroot()) {
return WheelDeltaAdjustmentStrategy::eAutoDirWithRootHonour;
}
return WheelDeltaAdjustmentStrategy::eAutoDir;
}
return WheelDeltaAdjustmentStrategy::eNone;
case WheelPrefs::ACTION_HORIZONTALIZED_SCROLL:
return WheelDeltaAdjustmentStrategy::eHorizontalize;
default:
break;
}
return WheelDeltaAdjustmentStrategy::eNone;
}
void EventStateManager::GetUserPrefsForWheelEvent(
const WidgetWheelEvent* aEvent, double* aOutMultiplierX,
double* aOutMultiplierY) {
WheelPrefs::GetInstance()->GetUserPrefsForEvent(aEvent, aOutMultiplierX,
aOutMultiplierY);
}
bool EventStateManager::WheelPrefs::IsOverOnePageScrollAllowedX(
const WidgetWheelEvent* aEvent) {
Index index = GetIndexFor(aEvent);
Init(index);
return Abs(mMultiplierX[index]) >=
MIN_MULTIPLIER_VALUE_ALLOWING_OVER_ONE_PAGE_SCROLL;
}
bool EventStateManager::WheelPrefs::IsOverOnePageScrollAllowedY(
const WidgetWheelEvent* aEvent) {
Index index = GetIndexFor(aEvent);
Init(index);
return Abs(mMultiplierY[index]) >=
MIN_MULTIPLIER_VALUE_ALLOWING_OVER_ONE_PAGE_SCROLL;
}
void EventStateManager::UpdateGestureContent(nsIContent* aContent) {
mGestureDownContent = aContent;
mGestureDownFrameOwner = aContent;
mGestureDownInTextControl =
aContent && aContent->IsInNativeAnonymousSubtree() &&
TextControlElement::FromNodeOrNull(
aContent->GetClosestNativeAnonymousSubtreeRootParentOrHost());
}
void EventStateManager::NotifyContentWillBeRemovedForGesture(
nsIContent& aContent) {
if (!mGestureDownContent) {
return;
}
if (!nsContentUtils::ContentIsFlattenedTreeDescendantOf(mGestureDownContent,
&aContent)) {
return;
}
UpdateGestureContent(aContent.GetFlattenedTreeParent());
}
} // namespace mozilla
#undef MOZ_LOG_IF_DEBUG
|