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
|
/* -*- 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 "BrowserChild.h"
#ifdef ACCESSIBILITY
# include "mozilla/a11y/DocAccessibleChild.h"
#endif
#include <utility>
#include "BrowserParent.h"
#include "ContentChild.h"
#include "EventStateManager.h"
#include "MMPrinter.h"
#include "PuppetWidget.h"
#include "StructuredCloneData.h"
#include "UnitTransforms.h"
#include "Units.h"
#include "VRManagerChild.h"
#include "mozilla/Assertions.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/EventForwards.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/IMEStateManager.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MediaFeatureChange.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/NativeKeyBindingsType.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/PointerLockManager.h"
#include "mozilla/PresShell.h"
#include "mozilla/ProcessHangMonitor.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/SchedulerGroup.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/TextEvents.h"
#include "mozilla/ToString.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/AutoPrintEventDispatcher.h"
#include "mozilla/dom/BrowserBridgeChild.h"
#include "mozilla/dom/DataTransfer.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/ImageDocument.h"
#include "mozilla/dom/JSWindowActorChild.h"
#include "mozilla/dom/LoadURIOptionsBinding.h"
#include "mozilla/dom/MessageManagerBinding.h"
#include "mozilla/dom/MouseEventBinding.h"
#include "mozilla/dom/Nullable.h"
#include "mozilla/dom/PBrowser.h"
#include "mozilla/dom/PaymentRequestChild.h"
#include "mozilla/dom/PointerEventHandler.h"
#include "mozilla/dom/SessionStoreChild.h"
#include "mozilla/dom/SessionStoreUtils.h"
#include "mozilla/dom/UserActivation.h"
#include "mozilla/dom/ViewTransition.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/WindowProxyHolder.h"
#include "mozilla/gfx/CrossProcessPaint.h"
#include "mozilla/gfx/Matrix.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/layers/APZCCallbackHelper.h"
#include "mozilla/layers/APZCTreeManagerChild.h"
#include "mozilla/layers/APZChild.h"
#include "mozilla/layers/APZEventState.h"
#include "mozilla/layers/CompositorBridgeChild.h"
#include "mozilla/layers/ContentProcessController.h"
#include "mozilla/layers/DoubleTapToZoom.h"
#include "mozilla/layers/IAPZCTreeManager.h"
#include "mozilla/layers/ImageBridgeChild.h"
#include "mozilla/layers/InputAPZContext.h"
#include "mozilla/layers/TouchActionHelper.h"
#include "mozilla/layers/WebRenderLayerManager.h"
#include "mozilla/widget/ScreenManager.h"
#include "mozilla/widget/WidgetLogging.h"
#include "nsCommandParams.h"
#include "nsContentPermissionHelper.h"
#include "nsContentUtils.h"
#include "nsDeviceContext.h"
#include "nsDocShell.h"
#include "nsDocShellLoadState.h"
#include "nsDragServiceProxy.h"
#include "nsExceptionHandler.h"
#include "nsFilePickerProxy.h"
#include "nsFocusManager.h"
#include "nsGlobalWindowOuter.h"
#include "nsIBaseWindow.h"
#include "nsIBrowserDOMWindow.h"
#include "nsIClassifiedChannel.h"
#include "nsIDocShell.h"
#include "nsIFrame.h"
#include "nsILoadContext.h"
#include "nsIOpenWindowInfo.h"
#include "nsISHEntry.h"
#include "nsISHistory.h"
#include "nsIScreenManager.h"
#include "nsIScriptError.h"
#include "nsIURI.h"
#include "nsIURIMutator.h"
#include "nsIWeakReferenceUtils.h"
#include "nsIWebBrowser.h"
#include "nsIWebProgress.h"
#include "nsIXULRuntime.h"
#include "nsLayoutUtils.h"
#include "nsNetUtil.h"
#include "nsPIDOMWindow.h"
#include "nsPIWindowRoot.h"
#include "nsPrintfCString.h"
#include "nsRefreshDriver.h"
#include "nsThreadManager.h"
#include "nsThreadUtils.h"
#include "nsVariant.h"
#include "nsViewManager.h"
#include "nsWebBrowser.h"
#include "nsWindowWatcher.h"
#ifdef MOZ_WAYLAND
# include "nsAppRunner.h"
#endif
#ifdef NS_PRINTING
# include "mozilla/layout/RemotePrintJobChild.h"
# include "nsIPrintSettings.h"
# include "nsIPrintSettingsService.h"
# include "nsIWebBrowserPrint.h"
#endif
static mozilla::LazyLogModule sApzChildLog("apz.child");
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::dom::ipc;
using namespace mozilla::ipc;
using namespace mozilla::layers;
using namespace mozilla::layout;
using namespace mozilla::widget;
using mozilla::layers::GeckoContentController;
static const char BEFORE_FIRST_PAINT[] = "before-first-paint";
static uint32_t sConsecutiveTouchMoveCount = 0;
using BrowserChildMap = nsTHashMap<nsUint64HashKey, BrowserChild*>;
static BrowserChildMap* sBrowserChildren;
StaticMutex sBrowserChildrenMutex;
already_AddRefed<Document> BrowserChild::GetTopLevelDocument() const {
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
nsCOMPtr<Document> doc = docShell ? docShell->GetExtantDocument() : nullptr;
return doc.forget();
}
PresShell* BrowserChild::GetTopLevelPresShell() const {
if (RefPtr<Document> doc = GetTopLevelDocument()) {
return doc->GetPresShell();
}
return nullptr;
}
bool BrowserChild::UpdateFrame(const RepaintRequest& aRequest) {
MOZ_ASSERT(aRequest.GetScrollId() != ScrollableLayerGuid::NULL_SCROLL_ID);
if (aRequest.IsRootContent()) {
if (PresShell* presShell = GetTopLevelPresShell()) {
// Guard against stale updates (updates meant for a pres shell which
// has since been torn down and destroyed).
if (aRequest.GetPresShellId() == presShell->GetPresShellId()) {
APZCCallbackHelper::UpdateRootFrame(aRequest);
return true;
}
}
} else {
// aRequest.mIsRoot is false, so we are trying to update a subframe.
// This requires special handling.
APZCCallbackHelper::UpdateSubFrame(aRequest);
return true;
}
return true;
}
class BrowserChild::DelayedDeleteRunnable final : public Runnable,
public nsIRunnablePriority {
RefPtr<BrowserChild> mBrowserChild;
// In order to try that this runnable runs after everything that could
// possibly touch this tab, we send it through the event queue twice.
bool mReadyToDelete = false;
public:
explicit DelayedDeleteRunnable(BrowserChild* aBrowserChild)
: Runnable("BrowserChild::DelayedDeleteRunnable"),
mBrowserChild(aBrowserChild) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aBrowserChild);
}
NS_DECL_ISUPPORTS_INHERITED
private:
~DelayedDeleteRunnable() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(!mBrowserChild);
}
NS_IMETHOD GetPriority(uint32_t* aPriority) override {
*aPriority = nsIRunnablePriority::PRIORITY_NORMAL;
return NS_OK;
}
NS_IMETHOD
Run() override {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mBrowserChild);
if (!mReadyToDelete) {
// This time run this runnable at input priority.
mReadyToDelete = true;
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(this));
return NS_OK;
}
// Check in case ActorDestroy was called after RecvDestroy message.
if (mBrowserChild->IPCOpen()) {
Unused << PBrowserChild::Send__delete__(mBrowserChild);
}
mBrowserChild = nullptr;
return NS_OK;
}
};
NS_IMPL_ISUPPORTS_INHERITED(BrowserChild::DelayedDeleteRunnable, Runnable,
nsIRunnablePriority)
namespace {
std::map<TabId, RefPtr<BrowserChild>>& NestedBrowserChildMap() {
MOZ_ASSERT(NS_IsMainThread());
static std::map<TabId, RefPtr<BrowserChild>> sNestedBrowserChildMap;
return sNestedBrowserChildMap;
}
} // namespace
already_AddRefed<BrowserChild> BrowserChild::FindBrowserChild(
const TabId& aTabId) {
auto iter = NestedBrowserChildMap().find(aTabId);
if (iter == NestedBrowserChildMap().end()) {
return nullptr;
}
RefPtr<BrowserChild> browserChild = iter->second;
return browserChild.forget();
}
/*static*/
already_AddRefed<BrowserChild> BrowserChild::Create(
ContentChild* aManager, const TabId& aTabId, const TabContext& aContext,
BrowsingContext* aBrowsingContext, uint32_t aChromeFlags,
bool aIsTopLevel) {
RefPtr<BrowserChild> iframe = new BrowserChild(
aManager, aTabId, aContext, aBrowsingContext, aChromeFlags, aIsTopLevel);
return iframe.forget();
}
BrowserChild::BrowserChild(ContentChild* aManager, const TabId& aTabId,
const TabContext& aContext,
BrowsingContext* aBrowsingContext,
uint32_t aChromeFlags, bool aIsTopLevel)
: TabContext(aContext),
mBrowserChildMessageManager(nullptr),
mManager(aManager),
mBrowsingContext(aBrowsingContext),
mChromeFlags(aChromeFlags),
mMaxTouchPoints(0),
mLayersId{0},
mEffectsInfo{EffectsInfo::FullyHidden()},
mDynamicToolbarMaxHeight(0),
mKeyboardHeight(0),
mUniqueId(aTabId),
mDidFakeShow(false),
mTriedBrowserInit(false),
mHasValidInnerSize(false),
mDestroyed(false),
mInAndroidPipMode(false),
mIsTopLevel(aIsTopLevel),
mIsTransparent(false),
mIPCOpen(false),
mDidSetRealShowInfo(false),
mDidLoadURLInit(false),
mSkipKeyPress(false),
mShouldSendWebProgressEventsToParent(false),
mRenderLayers(true),
mIsPreservingLayers(false),
#if defined(XP_WIN) && defined(ACCESSIBILITY)
mNativeWindowHandle(0),
#endif
mCancelContentJSEpoch(0) {
mozilla::HoldJSObjects(this);
// preloaded BrowserChild should not be added to child map
if (mUniqueId) {
MOZ_ASSERT(NestedBrowserChildMap().find(mUniqueId) ==
NestedBrowserChildMap().end());
NestedBrowserChildMap()[mUniqueId] = this;
}
mCoalesceMouseMoveEvents = StaticPrefs::dom_events_coalesce_mousemove();
if (mCoalesceMouseMoveEvents) {
mCoalescedMouseEventFlusher = new CoalescedMouseMoveFlusher(this);
}
if (StaticPrefs::dom_events_coalesce_touchmove()) {
mCoalescedTouchMoveEventFlusher = new CoalescedTouchMoveFlusher(this);
}
}
const CompositorOptions& BrowserChild::GetCompositorOptions() const {
// If you're calling this before mCompositorOptions is set, well.. don't.
MOZ_ASSERT(mCompositorOptions);
return mCompositorOptions.ref();
}
bool BrowserChild::AsyncPanZoomEnabled() const {
// This might get called by the TouchEvent::PrefEnabled code before we have
// mCompositorOptions populated (bug 1370089). In that case we just assume
// APZ is enabled because we're in a content process (because BrowserChild)
// and APZ is probably going to be enabled here since e10s is enabled.
return mCompositorOptions ? mCompositorOptions->UseAPZ() : true;
}
NS_IMETHODIMP
BrowserChild::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
if (!strcmp(aTopic, BEFORE_FIRST_PAINT)) {
if (AsyncPanZoomEnabled()) {
nsCOMPtr<Document> subject(do_QueryInterface(aSubject));
nsCOMPtr<Document> doc(GetTopLevelDocument());
if (subject == doc) {
RefPtr<PresShell> presShell = doc->GetPresShell();
if (presShell) {
presShell->SetIsFirstPaint(true);
}
APZCCallbackHelper::InitializeRootDisplayport(presShell);
}
}
}
return NS_OK;
}
void BrowserChild::ContentReceivedInputBlock(uint64_t aInputBlockId,
bool aPreventDefault) const {
if (mApzcTreeManager) {
mApzcTreeManager->ContentReceivedInputBlock(aInputBlockId, aPreventDefault);
}
}
void BrowserChild::SetTargetAPZC(
uint64_t aInputBlockId,
const nsTArray<ScrollableLayerGuid>& aTargets) const {
if (mApzcTreeManager) {
mApzcTreeManager->SetTargetAPZC(aInputBlockId, aTargets);
}
}
bool BrowserChild::DoUpdateZoomConstraints(
const uint32_t& aPresShellId, const ViewID& aViewId,
const Maybe<ZoomConstraints>& aConstraints) {
if (!mApzcTreeManager || mDestroyed) {
return false;
}
ScrollableLayerGuid guid =
ScrollableLayerGuid(mLayersId, aPresShellId, aViewId);
mApzcTreeManager->UpdateZoomConstraints(guid, aConstraints);
return true;
}
nsresult BrowserChild::Init(mozIDOMWindowProxy* aParent,
WindowGlobalChild* aInitialWindowChild) {
MOZ_ASSERT_IF(aInitialWindowChild,
aInitialWindowChild->BrowsingContext() == mBrowsingContext);
nsCOMPtr<nsIWidget> widget = nsIWidget::CreatePuppetWidget(this);
mPuppetWidget = static_cast<PuppetWidget*>(widget.get());
if (!mPuppetWidget) {
NS_ERROR("couldn't create fake widget");
return NS_ERROR_FAILURE;
}
mPuppetWidget->InfallibleCreate(nullptr, // No parent
LayoutDeviceIntRect(0, 0, 0, 0),
nullptr); // HandleWidgetEvent
mWebBrowser = nsWebBrowser::Create(this, mPuppetWidget, mBrowsingContext,
aInitialWindowChild);
nsIWebBrowser* webBrowser = mWebBrowser;
mWebNav = do_QueryInterface(webBrowser);
NS_ASSERTION(mWebNav, "nsWebBrowser doesn't implement nsIWebNavigation?");
// IPC uses a WebBrowser object for which DNS prefetching is turned off
// by default. But here we really want it, so enable it explicitly
mWebBrowser->SetAllowDNSPrefetch(true);
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
MOZ_ASSERT(docShell);
#ifdef DEBUG
nsCOMPtr<nsILoadContext> loadContext = do_GetInterface(WebNavigation());
MOZ_ASSERT(loadContext);
MOZ_ASSERT(loadContext->UseRemoteTabs() ==
!!(mChromeFlags & nsIWebBrowserChrome::CHROME_REMOTE_WINDOW));
MOZ_ASSERT(loadContext->UseRemoteSubframes() ==
!!(mChromeFlags & nsIWebBrowserChrome::CHROME_FISSION_WINDOW));
#endif // defined(DEBUG)
// Few lines before, baseWindow->Create() will end up creating a new
// window root in nsGlobalWindowOuter::SetDocShell.
// Then this chrome event handler, will be inherited to inner windows.
// We want to also set it to the docshell so that inner windows
// and any code that has access to the docshell
// can all listen to the same chrome event handler.
// XXX: ideally, we would set a chrome event handler earlier,
// and all windows, even the root one, will use the docshell one.
nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(WebNavigation());
NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
nsCOMPtr<EventTarget> chromeHandler = window->GetChromeEventHandler();
docShell->SetChromeEventHandler(chromeHandler);
// Window scrollbar flags only affect top level remote frames, not fission
// frames.
if (mIsTopLevel) {
nsContentUtils::SetScrollbarsVisibility(
docShell, !!(mChromeFlags & nsIWebBrowserChrome::CHROME_SCROLLBARS));
}
nsWeakPtr weakPtrThis = do_GetWeakReference(
static_cast<nsIBrowserChild*>(this)); // for capture by the lambda
ContentReceivedInputBlockCallback callback(
[weakPtrThis](uint64_t aInputBlockId, bool aPreventDefault) {
if (nsCOMPtr<nsIBrowserChild> browserChild =
do_QueryReferent(weakPtrThis)) {
static_cast<BrowserChild*>(browserChild.get())
->ContentReceivedInputBlock(aInputBlockId, aPreventDefault);
}
});
mAPZEventState = new APZEventState(mPuppetWidget, std::move(callback));
mIPCOpen = true;
if (SessionStorePlatformCollection()) {
mSessionStoreChild = SessionStoreChild::GetOrCreate(mBrowsingContext);
}
// We've all set up, make sure our visibility state is consistent. This is
// important for OOP iframes, which start off as hidden.
UpdateVisibility();
return NS_OK;
}
NS_IMPL_CYCLE_COLLECTION_CLASS(BrowserChild)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(BrowserChild)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBrowserChildMessageManager)
tmp->nsMessageManagerScriptExecutor::Unlink();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mWebBrowser)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mWebNav)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBrowsingContext)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSessionStoreChild)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mContentTransformPromise)
NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(BrowserChild)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBrowserChildMessageManager)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWebBrowser)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWebNav)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBrowsingContext)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSessionStoreChild)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContentTransformPromise)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(BrowserChild)
tmp->nsMessageManagerScriptExecutor::Trace(aCallbacks, aClosure);
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(BrowserChild)
NS_INTERFACE_MAP_ENTRY_CONCRETE(BrowserChild)
NS_INTERFACE_MAP_ENTRY(nsIWebBrowserChrome)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(nsIWindowProvider)
NS_INTERFACE_MAP_ENTRY(nsIBrowserChild)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY(nsITooltipListener)
NS_INTERFACE_MAP_ENTRY(nsIWebProgressListener)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIBrowserChild)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(BrowserChild)
NS_IMPL_CYCLE_COLLECTING_RELEASE(BrowserChild)
NS_IMETHODIMP
BrowserChild::GetChromeFlags(uint32_t* aChromeFlags) {
*aChromeFlags = mChromeFlags;
return NS_OK;
}
NS_IMETHODIMP
BrowserChild::SetChromeFlags(uint32_t aChromeFlags) {
NS_WARNING("trying to SetChromeFlags from content process?");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
BrowserChild::RemoteDropLinks(
const nsTArray<RefPtr<nsIDroppedLinkItem>>& aLinks) {
nsTArray<nsString> linksArray;
nsresult rv = NS_OK;
for (nsIDroppedLinkItem* link : aLinks) {
nsString tmp;
rv = link->GetUrl(tmp);
if (NS_FAILED(rv)) {
return rv;
}
linksArray.AppendElement(tmp);
rv = link->GetName(tmp);
if (NS_FAILED(rv)) {
return rv;
}
linksArray.AppendElement(tmp);
rv = link->GetType(tmp);
if (NS_FAILED(rv)) {
return rv;
}
linksArray.AppendElement(tmp);
}
bool sent = SendDropLinks(linksArray);
return sent ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP
BrowserChild::ShowAsModal() {
NS_WARNING("BrowserChild::ShowAsModal not supported in BrowserChild");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
BrowserChild::IsWindowModal(bool* aRetVal) {
*aRetVal = false;
return NS_OK;
}
NS_IMETHODIMP
BrowserChild::SetLinkStatus(const nsAString& aStatusText) {
// We can only send the status after the ipc machinery is set up
if (IPCOpen()) {
SendSetLinkStatus(aStatusText);
}
return NS_OK;
}
NS_IMETHODIMP
BrowserChild::SetDimensions(DimensionRequest&& aRequest) {
// The parent is in charge of the dimension changes. If JS code wants to
// change the dimensions (moveTo, screenX, etc.) we send a message to the
// parent about the new requested dimension, the parent does the resize/move
// then send a message to the child to update itself. For APIs like screenX
// this function is called with only the changed values. In a series of calls
// like window.screenX = 10; window.screenY = 10; for the second call, since
// screenX is not yet updated we might accidentally reset back screenX to it's
// old value. To avoid this, if a parameter did not change, we want the parent
// to handle the unchanged values.
double scale = mPuppetWidget ? mPuppetWidget->GetDefaultScale().scale : 1.0;
SendSetDimensions(aRequest, scale);
return NS_OK;
}
NS_IMETHODIMP
BrowserChild::GetDimensions(DimensionKind aDimensionKind, int32_t* aX,
int32_t* aY, int32_t* aCx, int32_t* aCy) {
LayoutDeviceIntRect rect = GetOuterRect();
if (aDimensionKind == DimensionKind::Inner) {
if (aX || aY) {
return NS_ERROR_NOT_IMPLEMENTED;
}
rect.SizeTo(GetInnerSize());
}
if (aX) {
*aX = rect.x;
}
if (aY) {
*aY = rect.y;
}
if (aCx) {
*aCx = rect.width;
}
if (aCy) {
*aCy = rect.height;
}
return NS_OK;
}
NS_IMETHODIMP
BrowserChild::Blur() { return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP
BrowserChild::GetInterface(const nsIID& aIID, void** aSink) {
// XXXbz should we restrict the set of interfaces we hand out here?
// See bug 537429
return QueryInterface(aIID, aSink);
}
NS_IMETHODIMP
BrowserChild::ProvideWindow(nsIOpenWindowInfo* aOpenWindowInfo,
uint32_t aChromeFlags, bool aCalledFromJS,
nsIURI* aURI, const nsAString& aName,
const nsACString& aFeatures,
const UserActivation::Modifiers& aModifiers,
bool aForceNoOpener, bool aForceNoReferrer,
bool aIsPopupRequested,
nsDocShellLoadState* aLoadState, bool* aWindowIsNew,
BrowsingContext** aReturn) {
*aReturn = nullptr;
RefPtr<BrowsingContext> parent = aOpenWindowInfo->GetParent();
int32_t openLocation = nsWindowWatcher::GetWindowOpenLocation(
parent->GetDOMWindow(), aChromeFlags, aModifiers, aCalledFromJS,
aOpenWindowInfo->GetIsForPrinting());
// If it turns out we're opening in the current browser, just hand over the
// current browser's docshell.
if (openLocation == nsIBrowserDOMWindow::OPEN_CURRENTWINDOW) {
nsCOMPtr<nsIWebBrowser> browser = do_GetInterface(WebNavigation());
*aWindowIsNew = false;
nsCOMPtr<mozIDOMWindowProxy> win;
MOZ_TRY(browser->GetContentDOMWindow(getter_AddRefs(win)));
RefPtr<BrowsingContext> bc(
nsPIDOMWindowOuter::From(win)->GetBrowsingContext());
bc.forget(aReturn);
return NS_OK;
}
// Note that ProvideWindowCommon may return NS_ERROR_ABORT if the
// open window call was canceled. It's important that we pass this error
// code back to our caller.
ContentChild* cc = ContentChild::GetSingleton();
return cc->ProvideWindowCommon(
WrapNotNull(this), aOpenWindowInfo, aChromeFlags, aCalledFromJS, aURI,
aName, aFeatures, aModifiers, aForceNoOpener, aForceNoReferrer,
aIsPopupRequested, aLoadState, aWindowIsNew, aReturn);
}
void BrowserChild::DestroyWindow() {
mBrowsingContext = nullptr;
if (mCoalescedMouseEventFlusher) {
mCoalescedMouseEventFlusher->RemoveObserver();
mCoalescedMouseEventFlusher = nullptr;
}
if (mCoalescedTouchMoveEventFlusher) {
mCoalescedTouchMoveEventFlusher->RemoveObserver();
mCoalescedTouchMoveEventFlusher = nullptr;
}
if (mSessionStoreChild) {
mSessionStoreChild->Stop();
mSessionStoreChild = nullptr;
}
// In case we don't have chance to process all entries, clean all data in
// the queue.
while (mToBeDispatchedMouseData.GetSize() > 0) {
UniquePtr<CoalescedMouseData> data(
static_cast<CoalescedMouseData*>(mToBeDispatchedMouseData.PopFront()));
data.reset();
}
nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(WebNavigation());
if (baseWindow) baseWindow->Destroy();
if (mPuppetWidget) {
mPuppetWidget->Destroy();
}
mLayersConnected = Nothing();
if (mLayersId.IsValid()) {
StaticMutexAutoLock lock(sBrowserChildrenMutex);
MOZ_ASSERT(sBrowserChildren);
sBrowserChildren->Remove(uint64_t(mLayersId));
if (!sBrowserChildren->Count()) {
delete sBrowserChildren;
sBrowserChildren = nullptr;
}
mLayersId = layers::LayersId{0};
}
if (mAPZEventState) {
mAPZEventState->Destroy();
mAPZEventState = nullptr;
}
}
void BrowserChild::ActorDestroy(ActorDestroyReason why) {
mIPCOpen = false;
DestroyWindow();
if (mBrowserChildMessageManager) {
// We should have a message manager if the global is alive, but it
// seems sometimes we don't. Assert in aurora/nightly, but don't
// crash in release builds.
MOZ_DIAGNOSTIC_ASSERT(mBrowserChildMessageManager->GetMessageManager());
if (mBrowserChildMessageManager->GetMessageManager()) {
// The messageManager relays messages via the BrowserChild which
// no longer exists.
mBrowserChildMessageManager->DisconnectMessageManager();
}
}
if (GetTabId() != 0) {
NestedBrowserChildMap().erase(GetTabId());
}
}
BrowserChild::~BrowserChild() {
mAnonymousGlobalScopes.Clear();
DestroyWindow();
nsCOMPtr<nsIWebBrowser> webBrowser = do_QueryInterface(WebNavigation());
if (webBrowser) {
webBrowser->SetContainerWindow(nullptr);
}
mozilla::DropJSObjects(this);
}
mozilla::ipc::IPCResult BrowserChild::RecvWillChangeProcess() {
if (mWebBrowser) {
mWebBrowser->SetWillChangeProcess();
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvLoadURL(
nsDocShellLoadState* aLoadState, const ParentShowInfo& aInfo) {
if (!mDidLoadURLInit) {
mDidLoadURLInit = true;
if (!InitBrowserChildMessageManager()) {
return IPC_FAIL_NO_REASON(this);
}
ApplyParentShowInfo(aInfo);
}
nsAutoCString spec;
aLoadState->URI()->GetSpec(spec);
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
if (!docShell) {
NS_WARNING("WebNavigation does not have a docshell");
return IPC_OK();
}
docShell->LoadURI(aLoadState, true);
CrashReporter::RecordAnnotationNSCString(CrashReporter::Annotation::URL,
spec);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvCreateAboutBlankDocumentViewer(
nsIPrincipal* aPrincipal, nsIPrincipal* aPartitionedPrincipal) {
if (aPrincipal->GetIsExpandedPrincipal() ||
aPartitionedPrincipal->GetIsExpandedPrincipal()) {
return IPC_FAIL(this, "Cannot create document with an expanded principal");
}
if (aPrincipal->IsSystemPrincipal() ||
aPartitionedPrincipal->IsSystemPrincipal()) {
MOZ_ASSERT_UNREACHABLE(
"Cannot use CreateAboutBlankDocumentViewer to create system principal "
"document in content");
return IPC_OK();
}
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
if (!docShell) {
MOZ_ASSERT_UNREACHABLE("WebNavigation does not have a docshell");
return IPC_OK();
}
nsCOMPtr<nsIURI> currentURI;
MOZ_ALWAYS_SUCCEEDS(
WebNavigation()->GetCurrentURI(getter_AddRefs(currentURI)));
if (!currentURI || !NS_IsAboutBlank(currentURI)) {
NS_WARNING("Can't create a DocumentViewer unless on about:blank");
return IPC_OK();
}
docShell->CreateAboutBlankDocumentViewer(aPrincipal, aPartitionedPrincipal,
nullptr);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvResumeLoad(
const uint64_t& aPendingSwitchID, const ParentShowInfo& aInfo) {
if (!mDidLoadURLInit) {
mDidLoadURLInit = true;
if (!InitBrowserChildMessageManager()) {
return IPC_FAIL_NO_REASON(this);
}
ApplyParentShowInfo(aInfo);
}
nsresult rv = WebNavigation()->ResumeRedirectedLoad(aPendingSwitchID, -1);
if (NS_FAILED(rv)) {
NS_WARNING("WebNavigation()->ResumeRedirectedLoad failed");
}
return IPC_OK();
}
nsresult BrowserChild::CloneDocumentTreeIntoSelf(
const MaybeDiscarded<BrowsingContext>& aSourceBC,
const embedding::PrintData& aPrintData) {
#ifdef NS_PRINTING
if (NS_WARN_IF(aSourceBC.IsNullOrDiscarded())) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<Document> sourceDocument = aSourceBC.get()->GetDocument();
if (NS_WARN_IF(!sourceDocument)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIDocShell> ourDocShell = do_GetInterface(WebNavigation());
if (NS_WARN_IF(!ourDocShell)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIDocumentViewer> viewer;
ourDocShell->GetDocViewer(getter_AddRefs(viewer));
if (NS_WARN_IF(!viewer)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIPrintSettingsService> printSettingsSvc =
do_GetService("@mozilla.org/gfx/printsettings-service;1");
if (NS_WARN_IF(!printSettingsSvc)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIPrintSettings> printSettings;
nsresult rv =
printSettingsSvc->CreateNewPrintSettings(getter_AddRefs(printSettings));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
printSettingsSvc->DeserializeToPrintSettings(aPrintData, printSettings);
RefPtr<Document> clone;
{
AutoPrintEventDispatcher dispatcher(*sourceDocument);
nsAutoScriptBlocker scriptBlocker;
bool hasInProcessCallbacks = false;
clone = sourceDocument->CreateStaticClone(
ourDocShell, viewer, printSettings, &hasInProcessCallbacks);
if (NS_WARN_IF(!clone)) {
return NS_ERROR_FAILURE;
}
}
rv = UpdateRemotePrintSettings(aPrintData);
if (NS_FAILED(rv)) {
return rv;
}
#endif
return NS_OK;
}
mozilla::ipc::IPCResult BrowserChild::RecvCloneDocumentTreeIntoSelf(
const MaybeDiscarded<BrowsingContext>& aSourceBC,
const embedding::PrintData& aPrintData,
CloneDocumentTreeIntoSelfResolver&& aResolve) {
nsresult rv = NS_OK;
#ifdef NS_PRINTING
rv = CloneDocumentTreeIntoSelf(aSourceBC, aPrintData);
#endif
aResolve(NS_SUCCEEDED(rv));
return IPC_OK();
}
nsresult BrowserChild::UpdateRemotePrintSettings(
const embedding::PrintData& aPrintData) {
#ifdef NS_PRINTING
nsCOMPtr<nsIDocShell> ourDocShell = do_GetInterface(WebNavigation());
if (NS_WARN_IF(!ourDocShell)) {
return NS_ERROR_FAILURE;
}
RefPtr<Document> doc = ourDocShell->GetExtantDocument();
if (NS_WARN_IF(!doc) || NS_WARN_IF(!doc->IsStaticDocument())) {
return NS_ERROR_FAILURE;
}
RefPtr<BrowsingContext> bc = ourDocShell->GetBrowsingContext();
if (NS_WARN_IF(!bc)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIPrintSettingsService> printSettingsSvc =
do_GetService("@mozilla.org/gfx/printsettings-service;1");
if (NS_WARN_IF(!printSettingsSvc)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIPrintSettings> printSettings;
nsresult rv =
printSettingsSvc->CreateNewPrintSettings(getter_AddRefs(printSettings));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
printSettingsSvc->DeserializeToPrintSettings(aPrintData, printSettings);
bc->PreOrderWalk([&](BrowsingContext* aBc) {
if (nsCOMPtr<nsIDocShell> inProcess = aBc->GetDocShell()) {
nsCOMPtr<nsIDocumentViewer> viewer;
inProcess->GetDocViewer(getter_AddRefs(viewer));
if (NS_WARN_IF(!viewer)) {
return BrowsingContext::WalkFlag::Skip;
}
// The CanRunScript analysis is not smart enough to see across
// the std::function PreOrderWalk uses, so we cheat a bit here, but it is
// fine because PreOrderWalk does deal with arbitrary script changing the
// BC tree, and our code above is simple enough and keeps strong refs to
// everything.
([&]() MOZ_CAN_RUN_SCRIPT_BOUNDARY {
RefPtr<RemotePrintJobChild> printJob =
static_cast<RemotePrintJobChild*>(
aPrintData.remotePrintJob().AsChild());
viewer->SetPrintSettingsForSubdocument(printSettings, printJob);
}());
} else if (RefPtr<BrowserBridgeChild> remoteChild =
BrowserBridgeChild::GetFrom(aBc->GetEmbedderElement())) {
Unused << remoteChild->SendUpdateRemotePrintSettings(aPrintData);
return BrowsingContext::WalkFlag::Skip;
}
return BrowsingContext::WalkFlag::Next;
});
#endif
return NS_OK;
}
mozilla::ipc::IPCResult BrowserChild::RecvUpdateRemotePrintSettings(
const embedding::PrintData& aPrintData) {
#ifdef NS_PRINTING
UpdateRemotePrintSettings(aPrintData);
#endif
return IPC_OK();
}
void BrowserChild::DoFakeShow(const ParentShowInfo& aParentShowInfo) {
OwnerShowInfo ownerInfo{LayoutDeviceIntSize(), ScrollbarPreference::Auto,
nsSizeMode_Normal};
RecvShow(aParentShowInfo, ownerInfo);
mDidFakeShow = true;
}
void BrowserChild::ApplyParentShowInfo(const ParentShowInfo& aInfo) {
// Even if we already set real show info, the dpi / rounding & scale may still
// be invalid (if BrowserParent wasn't able to get widget it would just send
// 0). So better to always set up-to-date values here.
if (aInfo.dpi() > 0) {
mPuppetWidget->UpdateBackingScaleCache(aInfo.dpi(), aInfo.widgetRounding(),
aInfo.defaultScale());
}
if (mDidSetRealShowInfo) {
return;
}
if (!aInfo.fakeShowInfo()) {
// Once we've got one ShowInfo from parent, no need to update the values
// anymore.
mDidSetRealShowInfo = true;
}
mIsTransparent = aInfo.isTransparent();
}
mozilla::ipc::IPCResult BrowserChild::RecvShow(
const ParentShowInfo& aParentInfo, const OwnerShowInfo& aOwnerInfo) {
bool res = true;
mPuppetWidget->SetSizeMode(aOwnerInfo.sizeMode());
if (!mDidFakeShow) {
nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(WebNavigation());
if (!baseWindow) {
NS_ERROR("WebNavigation() doesn't QI to nsIBaseWindow");
return IPC_FAIL_NO_REASON(this);
}
baseWindow->SetVisibility(true);
res = InitBrowserChildMessageManager();
}
ApplyParentShowInfo(aParentInfo);
if (!mIsTopLevel) {
RecvScrollbarPreferenceChanged(aOwnerInfo.scrollbarPreference());
}
if (!res) {
return IPC_FAIL_NO_REASON(this);
}
UpdateVisibility();
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvInitRendering(
const TextureFactoryIdentifier& aTextureFactoryIdentifier,
const layers::LayersId& aLayersId,
const CompositorOptions& aCompositorOptions, const bool& aLayersConnected) {
mLayersConnected = Some(aLayersConnected);
mLayersConnectRequested = Some(aLayersConnected);
InitRenderingState(aTextureFactoryIdentifier, aLayersId, aCompositorOptions);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvScrollbarPreferenceChanged(
ScrollbarPreference aPreference) {
MOZ_ASSERT(!mIsTopLevel,
"Scrollbar visibility should be derived from chrome flags for "
"top-level windows");
if (nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation())) {
nsDocShell::Cast(docShell)->SetScrollbarPreference(aPreference);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvCompositorOptionsChanged(
const CompositorOptions& aNewOptions) {
MOZ_ASSERT(mCompositorOptions);
// The only compositor option we currently support changing is APZ
// enablement. Even that is only partially supported for now:
// * Going from APZ to non-APZ is fine - we just flip the stored flag.
// Note that we keep the actors (mApzcTreeManager, and the APZChild
// created in InitAPZState()) around (read on for why).
// * Going from non-APZ to APZ is only supported if we were using
// APZ initially (at InitRendering() time) and we are transitioning
// back. In this case, we just reuse the actors which we kept around.
// Fully supporting a non-APZ to APZ transition (i.e. even in cases
// where we initialized as non-APZ) would require setting up the actors
// here. (In that case, we would also have the options of destroying
// the actors in the APZ --> non-APZ case, and always re-creating them
// during a non-APZ --> APZ transition).
mCompositorOptions->SetUseAPZ(aNewOptions.UseAPZ());
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvUpdateDimensions(
const DimensionInfo& aDimensionInfo) {
if (mLayersConnected.isNothing()) {
return IPC_OK();
}
mUnscaledOuterRect = aDimensionInfo.rect();
mClientOffset = aDimensionInfo.clientOffset();
mChromeOffset = aDimensionInfo.chromeOffset();
MOZ_ASSERT_IF(!IsTopLevel(), mChromeOffset == LayoutDeviceIntPoint());
SetUnscaledInnerSize(aDimensionInfo.size());
if (!mHasValidInnerSize && aDimensionInfo.size().width != 0 &&
aDimensionInfo.size().height != 0) {
mHasValidInnerSize = true;
}
const LayoutDeviceIntSize innerSize = GetInnerSize();
// Make sure to set the size on the document viewer first. The
// MobileViewportManager needs the content viewer size to be updated before
// the reflow, otherwise it gets a stale size when it computes a new CSS
// viewport.
nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(WebNavigation());
baseWin->SetPositionAndSize(0, 0, innerSize.width, innerSize.height,
nsIBaseWindow::eRepaint);
const LayoutDeviceIntRect outerRect =
GetOuterRect() + mClientOffset + mChromeOffset;
mPuppetWidget->Resize(outerRect.x, outerRect.y, innerSize.width,
innerSize.height, true);
RecvSafeAreaInsetsChanged(mPuppetWidget->GetSafeAreaInsets());
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvSizeModeChanged(
const nsSizeMode& aSizeMode) {
mPuppetWidget->SetSizeMode(aSizeMode);
if (!mPuppetWidget->IsVisible()) {
return IPC_OK();
}
nsCOMPtr<Document> document(GetTopLevelDocument());
if (!document) {
return IPC_OK();
}
nsPresContext* presContext = document->GetPresContext();
if (presContext) {
presContext->SizeModeChanged(aSizeMode);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvChildToParentMatrix(
const Maybe<gfx::Matrix4x4>& aMatrix,
const ScreenRect& aTopLevelViewportVisibleRectInBrowserCoords) {
mChildToParentConversionMatrix =
LayoutDeviceToLayoutDeviceMatrix4x4::FromUnknownMatrix(aMatrix);
mTopLevelViewportVisibleRectInBrowserCoords =
aTopLevelViewportVisibleRectInBrowserCoords;
if (mContentTransformPromise) {
mContentTransformPromise->MaybeResolveWithUndefined();
mContentTransformPromise = nullptr;
}
// Trigger an intersection observation update since ancestor viewports
// changed.
if (RefPtr<Document> toplevelDoc = GetTopLevelDocument()) {
if (nsPresContext* pc = toplevelDoc->GetPresContext()) {
pc->RefreshDriver()->EnsureIntersectionObservationsUpdateHappens();
}
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvUpdateRemoteStyle(
const StyleImageRendering& aImageRendering) {
BrowsingContext* context = GetBrowsingContext();
if (!context) {
return IPC_OK();
}
Document* document = context->GetDocument();
if (!document) {
return IPC_OK();
}
if (document->IsImageDocument()) {
document->AsImageDocument()->UpdateRemoteStyle(aImageRendering);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvDynamicToolbarMaxHeightChanged(
const ScreenIntCoord& aHeight) {
mDynamicToolbarMaxHeight = aHeight;
RefPtr<Document> document = GetTopLevelDocument();
if (!document) {
return IPC_OK();
}
if (RefPtr<nsPresContext> presContext = document->GetPresContext()) {
presContext->SetDynamicToolbarMaxHeight(aHeight);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvDynamicToolbarOffsetChanged(
const ScreenIntCoord& aOffset) {
RefPtr<Document> document = GetTopLevelDocument();
if (!document) {
return IPC_OK();
}
if (nsPresContext* presContext = document->GetPresContext()) {
presContext->UpdateDynamicToolbarOffset(aOffset);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvKeyboardHeightChanged(
const ScreenIntCoord& aHeight) {
#if defined(MOZ_WIDGET_ANDROID)
mKeyboardHeight = aHeight;
RefPtr<Document> document = GetTopLevelDocument();
if (!document) {
return IPC_OK();
}
if (nsPresContext* presContext = document->GetPresContext()) {
presContext->UpdateKeyboardHeight(aHeight);
}
#endif
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvAndroidPipModeChanged(bool aPipMode) {
if (mInAndroidPipMode == aPipMode) {
return IPC_OK();
}
mInAndroidPipMode = aPipMode;
if (RefPtr<Document> document = GetTopLevelDocument()) {
if (nsPresContext* presContext = document->GetPresContext()) {
presContext->MediaFeatureValuesChanged(
{MediaFeatureChangeReason::DisplayModeChange},
MediaFeatureChangePropagation::JustThisDocument);
}
nsContentUtils::DispatchEventOnlyToChrome(
document, document,
aPipMode ? u"MozAndroidPipModeEntered"_ns
: u"MozAndroidPipModeExited"_ns,
CanBubble::eYes, Cancelable::eNo, /* DefaultAction */ nullptr);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvSuppressDisplayport(
const bool& aEnabled) {
if (RefPtr<PresShell> presShell = GetTopLevelPresShell()) {
presShell->SuppressDisplayport(aEnabled);
}
return IPC_OK();
}
void BrowserChild::HandleDoubleTap(const CSSPoint& aPoint,
const Modifiers& aModifiers,
const ScrollableLayerGuid& aGuid,
const DoubleTapToZoomMetrics& aMetrics) {
MOZ_LOG(
sApzChildLog, LogLevel::Debug,
("Handling double tap at %s with %p %p\n", ToString(aPoint).c_str(),
mBrowserChildMessageManager ? mBrowserChildMessageManager->GetWrapper()
: nullptr,
mBrowserChildMessageManager.get()));
if (!mBrowserChildMessageManager) {
return;
}
// Note: there is nothing to do with the modifiers here, as we are not
// synthesizing any sort of mouse event.
RefPtr<Document> document = GetTopLevelDocument();
ZoomTarget zoomTarget = CalculateRectToZoomTo(document, aPoint, aMetrics);
// The double-tap can be dispatched by any scroll frame (so |aGuid| could be
// the guid of any scroll frame), but the zoom-to-rect operation must be
// performed by the root content scroll frame, so query its identifiers
// for the SendZoomToRect() call rather than using the ones from |aGuid|.
uint32_t presShellId;
ViewID viewId;
if (APZCCallbackHelper::GetOrCreateScrollIdentifiers(
document->GetDocumentElement(), &presShellId, &viewId) &&
mApzcTreeManager) {
ScrollableLayerGuid guid(mLayersId, presShellId, viewId);
mApzcTreeManager->ZoomToRect(guid, zoomTarget,
ZoomToRectBehavior::DEFAULT_BEHAVIOR);
}
}
mozilla::ipc::IPCResult BrowserChild::RecvHandleTap(
const GeckoContentController::TapType& aType,
const LayoutDevicePoint& aPoint, const Modifiers& aModifiers,
const ScrollableLayerGuid& aGuid, const uint64_t& aInputBlockId,
const Maybe<DoubleTapToZoomMetrics>& aDoubleTapToZoomMetrics) {
// IPDL doesn't hold a strong reference to protocols as they're not required
// to be refcounted. This function can run script, which may trigger a nested
// event loop, which may release this, so we hold a strong reference here.
RefPtr<BrowserChild> kungFuDeathGrip(this);
RefPtr<PresShell> presShell = GetTopLevelPresShell();
if (!presShell || !presShell->GetPresContext() || !mAPZEventState) {
return IPC_OK();
}
CSSToLayoutDeviceScale scale(
presShell->GetPresContext()->CSSToDevPixelScale());
CSSPoint point = aPoint / scale;
// Stash the guid in InputAPZContext so that when the visual-to-layout
// transform is applied to the event's coordinates, we use the right transform
// based on the scroll frame being targeted.
// The other values don't really matter.
InputAPZContext context(aGuid, aInputBlockId, nsEventStatus_eSentinel);
switch (aType) {
case GeckoContentController::TapType::eSingleTap:
if (mBrowserChildMessageManager) {
RefPtr<APZEventState> eventState(mAPZEventState);
eventState->ProcessSingleTap(point, scale, aModifiers, 1,
aInputBlockId);
}
break;
case GeckoContentController::TapType::eDoubleTap:
HandleDoubleTap(point, aModifiers, aGuid, *aDoubleTapToZoomMetrics);
break;
case GeckoContentController::TapType::eSecondTap:
if (mBrowserChildMessageManager) {
RefPtr<APZEventState> eventState(mAPZEventState);
eventState->ProcessSingleTap(point, scale, aModifiers, 2,
aInputBlockId);
}
break;
case GeckoContentController::TapType::eLongTap:
if (mBrowserChildMessageManager) {
RefPtr<APZEventState> eventState(mAPZEventState);
eventState->ProcessLongTap(presShell, point, scale, aModifiers,
aInputBlockId);
}
break;
case GeckoContentController::TapType::eLongTapUp:
if (mBrowserChildMessageManager) {
RefPtr<APZEventState> eventState(mAPZEventState);
eventState->ProcessLongTapUp(presShell, point, scale, aModifiers);
}
break;
}
// mAPZEventState may not dispatch the compatibility mouse events. Therefore,
// we should release the pointer capturing element at the last ePointerUp
// here.
PointerEventHandler::ReleasePointerCapturingElementAtLastPointerUp();
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityHandleTap(
const GeckoContentController::TapType& aType,
const LayoutDevicePoint& aPoint, const Modifiers& aModifiers,
const ScrollableLayerGuid& aGuid, const uint64_t& aInputBlockId,
const Maybe<DoubleTapToZoomMetrics>& aDoubleTapToZoomMetrics) {
// IPDL doesn't hold a strong reference to protocols as they're not required
// to be refcounted. This function can run script, which may trigger a nested
// event loop, which may release this, so we hold a strong reference here.
RefPtr<BrowserChild> kungFuDeathGrip(this);
return RecvHandleTap(aType, aPoint, aModifiers, aGuid, aInputBlockId,
aDoubleTapToZoomMetrics);
}
void BrowserChild::NotifyAPZStateChange(
const ViewID& aViewId,
const layers::GeckoContentController::APZStateChange& aChange,
const int& aArg, Maybe<uint64_t> aInputBlockId) {
if (mAPZEventState) {
mAPZEventState->ProcessAPZStateChange(aViewId, aChange, aArg,
aInputBlockId);
}
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (aChange ==
layers::GeckoContentController::APZStateChange::eTransformEnd) {
// This is used by tests to determine when the APZ is done doing whatever
// it's doing. XXX generify this as needed when writing additional tests.
observerService->NotifyObservers(nullptr, "APZ:TransformEnd", nullptr);
observerService->NotifyObservers(nullptr, "PanZoom:StateChange",
u"NOTHING");
} else if (aChange ==
layers::GeckoContentController::APZStateChange::eTransformBegin) {
observerService->NotifyObservers(nullptr, "PanZoom:StateChange",
u"PANNING");
}
}
void BrowserChild::StartScrollbarDrag(
const layers::AsyncDragMetrics& aDragMetrics) {
ScrollableLayerGuid guid(mLayersId, aDragMetrics.mPresShellId,
aDragMetrics.mViewId);
if (mApzcTreeManager) {
mApzcTreeManager->StartScrollbarDrag(guid, aDragMetrics);
}
}
void BrowserChild::ZoomToRect(const uint32_t& aPresShellId,
const ScrollableLayerGuid::ViewID& aViewId,
const CSSRect& aRect, const uint32_t& aFlags) {
ScrollableLayerGuid guid(mLayersId, aPresShellId, aViewId);
if (mApzcTreeManager) {
mApzcTreeManager->ZoomToRect(guid, ZoomTarget{aRect}, aFlags);
}
}
mozilla::ipc::IPCResult BrowserChild::RecvActivate(uint64_t aActionId) {
MOZ_ASSERT(mWebBrowser);
mWebBrowser->FocusActivate(aActionId);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvDeactivate(uint64_t aActionId) {
MOZ_ASSERT(mWebBrowser);
mWebBrowser->FocusDeactivate(aActionId);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvStopIMEStateManagement() {
IMEStateManager::StopIMEStateManagement();
return IPC_OK();
}
void BrowserChild::ProcessPendingCoalescedTouchData() {
MOZ_ASSERT(StaticPrefs::dom_events_coalesce_touchmove());
if (mCoalescedTouchData.IsEmpty()) {
return;
}
if (mCoalescedTouchMoveEventFlusher) {
mCoalescedTouchMoveEventFlusher->RemoveObserver();
}
UniquePtr<WidgetTouchEvent> touchMoveEvent =
mCoalescedTouchData.TakeCoalescedEvent();
Unused << RecvRealTouchEvent(*touchMoveEvent,
mCoalescedTouchData.GetScrollableLayerGuid(),
mCoalescedTouchData.GetInputBlockId(),
mCoalescedTouchData.GetApzResponse());
}
void BrowserChild::ProcessPendingCoalescedMouseDataAndDispatchEvents() {
if (!mCoalesceMouseMoveEvents || !mCoalescedMouseEventFlusher) {
// We don't enable mouse coalescing or we are destroying BrowserChild.
return;
}
// We may reentry the event loop and push more data to
// mToBeDispatchedMouseData while dispatching an event.
// We may have some pending coalesced data while dispatch an event and reentry
// the event loop. In that case we don't have chance to consume the remaining
// pending data until we get new mouse events. Get some helps from
// mCoalescedMouseEventFlusher to trigger it.
mCoalescedMouseEventFlusher->StartObserver();
while (mToBeDispatchedMouseData.GetSize() > 0) {
UniquePtr<CoalescedMouseData> data(
static_cast<CoalescedMouseData*>(mToBeDispatchedMouseData.PopFront()));
UniquePtr<WidgetMouseEvent> event = data->TakeCoalescedEvent();
if (event) {
// When the real mouse event receivers put the received event into the
// queue, they should dispatch eMouseRawUpdate event immediately (if and
// only if it's required). Therefore, unless the event is the last one
// of the queue, the pending events should've been marked as "Do not
// convert to "pointerrawupdate".
MOZ_ASSERT_IF(mToBeDispatchedMouseData.GetSize() > 0,
!event->convertToPointerRawUpdate);
// Dispatch the pending events. Using HandleRealMouseButtonEvent
// to bypass the coalesce handling in RecvRealMouseMoveEvent. Can't use
// RecvRealMouseButtonEvent because we may also put some mouse events
// other than mousemove.
HandleRealMouseButtonEvent(*event, data->GetScrollableLayerGuid(),
data->GetInputBlockId());
}
}
// mCoalescedMouseEventFlusher may be destroyed when reentrying the event
// loop.
if (mCoalescedMouseEventFlusher) {
mCoalescedMouseEventFlusher->RemoveObserver();
}
}
LayoutDeviceToLayoutDeviceMatrix4x4
BrowserChild::GetChildToParentConversionMatrix() const {
if (mChildToParentConversionMatrix) {
return *mChildToParentConversionMatrix;
}
LayoutDevicePoint offset(GetChromeOffset());
return LayoutDeviceToLayoutDeviceMatrix4x4::Translation(offset);
}
Maybe<ScreenRect> BrowserChild::GetTopLevelViewportVisibleRectInBrowserCoords()
const {
if (!mChildToParentConversionMatrix) {
return Nothing();
}
return Some(mTopLevelViewportVisibleRectInBrowserCoords);
}
void BrowserChild::FlushAllCoalescedMouseData() {
MOZ_ASSERT(mCoalesceMouseMoveEvents);
// Move all entries from mCoalescedMouseData to mToBeDispatchedMouseData.
for (const auto& data : mCoalescedMouseData.Values()) {
if (!data || data->IsEmpty()) {
continue;
}
UniquePtr<CoalescedMouseData> dispatchData =
MakeUnique<CoalescedMouseData>();
dispatchData->RetrieveDataFrom(*data);
mToBeDispatchedMouseData.Push(dispatchData.release());
}
mCoalescedMouseData.Clear();
}
mozilla::ipc::IPCResult BrowserChild::RecvRealMouseMoveEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
if (mCoalesceMouseMoveEvents && mCoalescedMouseEventFlusher) {
CoalescedMouseData* data =
mCoalescedMouseData.GetOrInsertNew(aEvent.pointerId);
MOZ_ASSERT(data);
if (data->CanCoalesce(aEvent, aGuid, aInputBlockId,
mCoalescedMouseEventFlusher->GetRefreshDriver())) {
// We don't need to dispatch aEvent immediately. However, we need to
// dispatch eMouseRawUpdate immediately if there is a `pointerrawupdate`
// event listener. Therefore, the cloned event in the queue shouldn't
// cause eMouseRawUpdate later when it'll be dispatched.
WidgetMouseEvent pendingMouseMoveEvent(aEvent);
pendingMouseMoveEvent.convertToPointerRawUpdate = false;
data->Coalesce(pendingMouseMoveEvent, aGuid, aInputBlockId);
mCoalescedMouseEventFlusher->StartObserver();
HandleMouseRawUpdateEvent(pendingMouseMoveEvent, aGuid, aInputBlockId);
return IPC_OK();
}
// Can't coalesce current mousemove event. Put the coalesced mousemove data
// with the same pointer id to mToBeDispatchedMouseData, coalesce the
// current one, and process all pending data in mToBeDispatchedMouseData.
UniquePtr<CoalescedMouseData> dispatchData =
MakeUnique<CoalescedMouseData>();
dispatchData->RetrieveDataFrom(*data);
mToBeDispatchedMouseData.Push(dispatchData.release());
// Put new data to replace the old one in the hash table.
CoalescedMouseData* newData =
mCoalescedMouseData
.InsertOrUpdate(aEvent.pointerId, MakeUnique<CoalescedMouseData>())
.get();
// We don't want to dispatch aEvent immediately. However, we need to
// dispatch eMouseRawUpdate immediately if there is a `pointerrawupdate`
// event listener. Therefore, the cloned event in the queue shouldn't
// cause eMouseRawUpdate later when it'll be dispatched.
WidgetMouseEvent pendingMouseMoveEvent(aEvent);
pendingMouseMoveEvent.convertToPointerRawUpdate = false;
newData->Coalesce(pendingMouseMoveEvent, aGuid, aInputBlockId);
// Dispatch all pending mouse events which does NOT include aEvent.
ProcessPendingCoalescedMouseDataAndDispatchEvents();
mCoalescedMouseEventFlusher->StartObserver();
// Finally, dispatch eMouseRawUpdate for aEvent right now.
HandleMouseRawUpdateEvent(pendingMouseMoveEvent, aGuid, aInputBlockId);
return IPC_OK();
}
if (!RecvRealMouseButtonEvent(aEvent, aGuid, aInputBlockId)) {
return IPC_FAIL_NO_REASON(this);
}
return IPC_OK();
}
void BrowserChild::HandleMouseRawUpdateEvent(
const WidgetMouseEvent& aPendingMouseEvent,
const ScrollableLayerGuid& aGuid, const uint64_t& aInputBlockId) {
// If there is no window containing pointerrawupdate event listeners or the
// event is a synthesized mousemove, we don't need to dispatch eMouseRawUpdate
// event.
if (!mPointerRawUpdateWindowCount || aPendingMouseEvent.IsSynthesized()) {
return;
}
WidgetMouseEvent mouseRawUpdateEvent(aPendingMouseEvent);
mouseRawUpdateEvent.mMessage = eMouseRawUpdate;
// PointerEvent.button should always be -1 if the source event is eMouseMove.
// PointerEventHandler cannot distinguish whether it's caused by
// eMouseDown/eMouseUp or eMouseMove. Therefore, we need to set -1
// (eNotPressed) here.
mouseRawUpdateEvent.mButton = MouseButton::eNotPressed;
mouseRawUpdateEvent.mCoalescedWidgetEvents = nullptr;
mouseRawUpdateEvent.convertToPointer = true;
// Nobody checks `convertToPointerRawUpdate` of eMouseRawUpdate event.
// However, the name indicates that it would cause ePointerRawUpdate.
// For avoiding to make the developers who watch the value with the debugger
// confused, here sets it to `true`.
mouseRawUpdateEvent.convertToPointerRawUpdate = true;
HandleRealMouseButtonEvent(mouseRawUpdateEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult BrowserChild::RecvRealMouseMoveEventForTests(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvRealMouseMoveEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityRealMouseMoveEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvRealMouseMoveEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult
BrowserChild::RecvNormalPriorityRealMouseMoveEventForTests(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvRealMouseMoveEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult BrowserChild::RecvSynthMouseMoveEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
if (!RecvRealMouseButtonEvent(aEvent, aGuid, aInputBlockId)) {
return IPC_FAIL_NO_REASON(this);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPrioritySynthMouseMoveEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvSynthMouseMoveEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult BrowserChild::RecvRealMouseButtonEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
if (mCoalesceMouseMoveEvents && mCoalescedMouseEventFlusher &&
aEvent.mMessage != eMouseMove) {
// When receiving a mouse event other than mousemove, we have to dispatch
// all coalesced events before it. However, we can't dispatch all pending
// coalesced events directly because we may reentry the event loop while
// dispatching. To make sure we won't dispatch disorder events, we move all
// coalesced mousemove events and current event to a deque to dispatch them.
// When reentrying the event loop and dispatching more events, we put new
// events in the end of the nsQueue and dispatch events from the beginning.
FlushAllCoalescedMouseData();
UniquePtr<CoalescedMouseData> dispatchData =
MakeUnique<CoalescedMouseData>();
// We'll dispatch aEvent immediately via
// ProcessPendingCoalescedMouseDataAndDispatchEvents().
// Therefore, PresShell should convert it to eMouseRawUpdate when it starts
// handling aEvent if and only if there is a `pointerrawupdate` event
// listener. Therefore, let's assert the allowing flag to convert it to
// eMouseRawUpdate here.
MOZ_ASSERT(aEvent.convertToPointerRawUpdate);
dispatchData->Coalesce(aEvent, aGuid, aInputBlockId);
mToBeDispatchedMouseData.Push(dispatchData.release());
ProcessPendingCoalescedMouseDataAndDispatchEvents();
return IPC_OK();
}
HandleRealMouseButtonEvent(aEvent, aGuid, aInputBlockId);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvRealPointerButtonEvent(
const WidgetPointerEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvRealMouseButtonEvent(aEvent, aGuid, aInputBlockId);
}
void BrowserChild::HandleRealMouseButtonEvent(const WidgetMouseEvent& aEvent,
const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
Maybe<WidgetPointerEvent> pointerEvent;
Maybe<WidgetMouseEvent> mouseEvent;
if (aEvent.mClass == ePointerEventClass) {
pointerEvent.emplace(aEvent);
} else {
mouseEvent.emplace(aEvent);
}
WidgetMouseEvent& localEvent =
pointerEvent.isSome() ? pointerEvent.ref() : mouseEvent.ref();
localEvent.mWidget = mPuppetWidget;
// We need one InputAPZContext here to propagate |aGuid| to places in
// SendSetTargetAPZCNotification() which apply the visual-to-layout transform,
// and another below to propagate the |postLayerization| flag (whose value
// we don't know until SendSetTargetAPZCNotification() returns) into
// the event dispatch code.
InputAPZContext context1(aGuid, aInputBlockId, nsEventStatus_eSentinel);
// Mouse events like eMouseEnterIntoWidget, that are created in the parent
// process EventStateManager code, have an input block id which they get from
// the InputAPZContext in the parent process stack. However, they did not
// actually go through the APZ code and so their mHandledByAPZ flag is false.
// Since thos events didn't go through APZ, we don't need to send
// notifications for them.
RefPtr<DisplayportSetListener> postLayerization;
if (aInputBlockId && localEvent.mFlags.mHandledByAPZ) {
nsCOMPtr<Document> document(GetTopLevelDocument());
postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
mPuppetWidget, document, localEvent, aGuid.mLayersId, aInputBlockId);
}
InputAPZContext context2(aGuid, aInputBlockId, nsEventStatus_eSentinel,
postLayerization != nullptr);
DispatchWidgetEventViaAPZ(localEvent);
if (aInputBlockId && localEvent.mFlags.mHandledByAPZ && mAPZEventState) {
mAPZEventState->ProcessMouseEvent(localEvent, aInputBlockId);
}
// Do this after the DispatchWidgetEventViaAPZ call above, so that if the
// mouse event triggered a post-refresh AsyncDragMetrics message to be sent
// to APZ (from scrollbar dragging in nsSliderFrame), then that will reach
// APZ before the SetTargetAPZC message. This ensures the drag input block
// gets the drag metrics before handling the input events.
if (postLayerization) {
postLayerization->Register();
}
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityRealMouseButtonEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvRealMouseButtonEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityRealPointerButtonEvent(
const WidgetPointerEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvNormalPriorityRealMouseButtonEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult BrowserChild::RecvRealMouseEnterExitWidgetEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvRealMouseButtonEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult
BrowserChild::RecvNormalPriorityRealMouseEnterExitWidgetEvent(
const WidgetMouseEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvRealMouseButtonEvent(aEvent, aGuid, aInputBlockId);
}
nsEventStatus BrowserChild::DispatchWidgetEventViaAPZ(WidgetGUIEvent& aEvent) {
aEvent.ResetWaitingReplyFromRemoteProcessState();
return APZCCallbackHelper::DispatchWidgetEvent(aEvent);
}
void BrowserChild::DispatchCoalescedWheelEvent() {
UniquePtr<WidgetWheelEvent> wheelEvent =
mCoalescedWheelData.TakeCoalescedEvent();
MOZ_ASSERT(wheelEvent);
DispatchWheelEvent(*wheelEvent, mCoalescedWheelData.GetScrollableLayerGuid(),
mCoalescedWheelData.GetInputBlockId());
}
void BrowserChild::DispatchWheelEvent(const WidgetWheelEvent& aEvent,
const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
WidgetWheelEvent localEvent(aEvent);
if (aInputBlockId && aEvent.mFlags.mHandledByAPZ) {
nsCOMPtr<Document> document(GetTopLevelDocument());
RefPtr<DisplayportSetListener> postLayerization =
APZCCallbackHelper::SendSetTargetAPZCNotification(
mPuppetWidget, document, aEvent, aGuid.mLayersId, aInputBlockId);
if (postLayerization) {
postLayerization->Register();
}
}
localEvent.mWidget = mPuppetWidget;
// Stash the guid in InputAPZContext so that when the visual-to-layout
// transform is applied to the event's coordinates, we use the right transform
// based on the scroll frame being targeted.
// The other values don't really matter.
InputAPZContext context(aGuid, aInputBlockId, nsEventStatus_eSentinel);
DispatchWidgetEventViaAPZ(localEvent);
if (localEvent.mCanTriggerSwipe) {
SendRespondStartSwipeEvent(aInputBlockId, localEvent.TriggersSwipe());
}
if (aInputBlockId && aEvent.mFlags.mHandledByAPZ && mAPZEventState) {
mAPZEventState->ProcessWheelEvent(localEvent, aInputBlockId);
}
}
namespace {
class SynthesizedEventChildCallback final : public nsISynthesizedEventCallback {
NS_DECL_ISUPPORTS
public:
SynthesizedEventChildCallback(BrowserChild* aBrowserChild,
const uint64_t& aCallbackId)
: mBrowserChild(aBrowserChild), mCallbackId(aCallbackId) {
MOZ_ASSERT(mBrowserChild);
MOZ_ASSERT(mCallbackId > 0, "Invalid callback ID");
}
NS_IMETHOD OnCompleteDispatch() override {
MOZ_ASSERT(mCallbackId > 0, "Invalid callback ID");
if (!mBrowserChild) {
// We already sent the notification, or we don't actually need to
// send any notification at all.
MOZ_ASSERT_UNREACHABLE("OnCompleteDispatch called multiple times");
return NS_OK;
}
if (mBrowserChild->IsDestroyed()) {
// If this happens it's probably a bug in the test that's triggering this.
NS_WARNING(
"BrowserChild was unexpectedly destroyed during event "
"synthesization response!");
} else if (!mBrowserChild->SendSynthesizedEventResponse(mCallbackId)) {
NS_WARNING("Unable to send event synthesization response!");
}
// Null out browserChild to indicate we already sent the response
mBrowserChild = nullptr;
return NS_OK;
}
private:
virtual ~SynthesizedEventChildCallback() = default;
RefPtr<BrowserChild> mBrowserChild;
uint64_t mCallbackId;
};
NS_IMPL_ISUPPORTS(SynthesizedEventChildCallback, nsISynthesizedEventCallback)
class MOZ_RAII AutoSynthesizedWheelEventResponder final {
public:
AutoSynthesizedWheelEventResponder(BrowserChild* aBrowserChild,
const WidgetWheelEvent& aEvent) {
if (aEvent.mCallbackId.isSome()) {
mCallback = MakeAndAddRef<SynthesizedEventChildCallback>(
aBrowserChild, aEvent.mCallbackId.ref());
}
}
~AutoSynthesizedWheelEventResponder() {
if (mCallback) {
mCallback->OnCompleteDispatch();
}
}
private:
nsCOMPtr<nsISynthesizedEventCallback> mCallback;
};
} // namespace
mozilla::ipc::IPCResult BrowserChild::RecvMouseWheelEvent(
const WidgetWheelEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
AutoSynthesizedWheelEventResponder responder(this, aEvent);
bool isNextWheelEvent = false;
// We only coalesce the current event when
// 1. It's eWheel (we don't coalesce eOperationStart and eWheelOperationEnd)
// 2. It has same attributes as the coalesced wheel event which is not yet
// fired.
if (aEvent.mMessage == eWheel) {
GetIPCChannel()->PeekMessages(
[&isNextWheelEvent](const IPC::Message& aMsg) -> bool {
if (aMsg.type() == mozilla::dom::PBrowser::Msg_MouseWheelEvent__ID) {
isNextWheelEvent = true;
}
return false; // Stop peeking.
});
if (!mCoalescedWheelData.IsEmpty() &&
!mCoalescedWheelData.CanCoalesce(aEvent, aGuid, aInputBlockId)) {
DispatchCoalescedWheelEvent();
MOZ_ASSERT(mCoalescedWheelData.IsEmpty());
}
mCoalescedWheelData.Coalesce(aEvent, aGuid, aInputBlockId);
MOZ_ASSERT(!mCoalescedWheelData.IsEmpty());
// If the next event isn't a wheel event, make sure we dispatch.
if (!isNextWheelEvent) {
DispatchCoalescedWheelEvent();
}
} else {
DispatchWheelEvent(aEvent, aGuid, aInputBlockId);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityMouseWheelEvent(
const WidgetWheelEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId) {
return RecvMouseWheelEvent(aEvent, aGuid, aInputBlockId);
}
mozilla::ipc::IPCResult BrowserChild::RecvRealTouchEvent(
const WidgetTouchEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId, const nsEventStatus& aApzResponse) {
MOZ_LOG(sApzChildLog, LogLevel::Debug,
("Receiving touch event of type %d\n", aEvent.mMessage));
if (StaticPrefs::dom_events_coalesce_touchmove()) {
if (aEvent.mMessage == eTouchEnd || aEvent.mMessage == eTouchStart) {
ProcessPendingCoalescedTouchData();
}
if (aEvent.mMessage != eTouchMove && aEvent.mMessage != eTouchRawUpdate) {
sConsecutiveTouchMoveCount = 0;
}
}
WidgetTouchEvent localEvent(aEvent);
localEvent.mWidget = mPuppetWidget;
// Stash the guid in InputAPZContext so that when the visual-to-layout
// transform is applied to the event's coordinates, we use the right transform
// based on the scroll frame being targeted.
// The other values don't really matter.
InputAPZContext context(aGuid, aInputBlockId, aApzResponse);
nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
if (localEvent.mMessage == eTouchStart && AsyncPanZoomEnabled()) {
nsCOMPtr<Document> document = GetTopLevelDocument();
allowedTouchBehaviors = TouchActionHelper::GetAllowedTouchBehavior(
mPuppetWidget, document, localEvent);
if (!allowedTouchBehaviors.IsEmpty() && mApzcTreeManager) {
mApzcTreeManager->SetAllowedTouchBehavior(aInputBlockId,
allowedTouchBehaviors);
}
RefPtr<DisplayportSetListener> postLayerization =
APZCCallbackHelper::SendSetTargetAPZCNotification(
mPuppetWidget, document, localEvent, aGuid.mLayersId,
aInputBlockId);
if (postLayerization) {
postLayerization->Register();
}
}
// Dispatch event to content (potentially a long-running operation)
nsEventStatus status = DispatchWidgetEventViaAPZ(localEvent);
if (!AsyncPanZoomEnabled()) {
// We shouldn't have any e10s platforms that have touch events enabled
// without APZ.
MOZ_ASSERT(false);
return IPC_OK();
}
if (mAPZEventState) {
mAPZEventState->ProcessTouchEvent(localEvent, aGuid, aInputBlockId,
aApzResponse, status,
std::move(allowedTouchBehaviors));
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityRealTouchEvent(
const WidgetTouchEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId, const nsEventStatus& aApzResponse) {
return RecvRealTouchEvent(aEvent, aGuid, aInputBlockId, aApzResponse);
}
mozilla::ipc::IPCResult BrowserChild::RecvRealTouchMoveEvent(
const WidgetTouchEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId, const nsEventStatus& aApzResponse) {
if (StaticPrefs::dom_events_coalesce_touchmove()) {
++sConsecutiveTouchMoveCount;
if (mCoalescedTouchMoveEventFlusher) {
MOZ_ASSERT(aEvent.mMessage == eTouchMove);
// NOTE: While dispatching eTouchMove or eTouchRawUpdate,
// sConsecutiveTouchMoveCount may be changed by the event loop spun,
// e.g., an event listener uses sync XHR or calling window.alert().
const auto PostponeDispatchingTouchMove = [&]() {
return sConsecutiveTouchMoveCount > 1;
};
if (mCoalescedTouchData.IsEmpty() ||
mCoalescedTouchData.CanCoalesce(aEvent, aGuid, aInputBlockId,
aApzResponse)) {
if (PostponeDispatchingTouchMove()) {
WidgetTouchEvent pendingTouchMoveEvent(
aEvent, WidgetTouchEvent::CloneTouches::Yes);
// We don't dispatch aEvent immediately here. However, we need to
// dispatch eTouchRawUpdate immediately if and only if there is a
// `pointerrawupdate` event listener. Therefore, the cloned event in
// the queue and it shouldn't cause eTouchRawUpdate again.
pendingTouchMoveEvent.SetConvertToPointerRawUpdate(false);
mCoalescedTouchData.Coalesce(pendingTouchMoveEvent, aGuid,
aInputBlockId, aApzResponse);
MOZ_ASSERT(PostponeDispatchingTouchMove());
mCoalescedTouchMoveEventFlusher->StartObserver();
// Let's notify the web app of `pointerrawupdate` immediately if and
// only if they listen to it.
HandleTouchRawUpdateEvent(pendingTouchMoveEvent, aGuid, aInputBlockId,
aApzResponse);
return IPC_OK();
}
// We'll dispatch aEvent via ProcessPendingCoalescedTouchData() below.
// Therefore, the touches should cause eTouchRawUpdate event.
MOZ_ASSERT(aEvent.CanConvertToPointerRawUpdate());
mCoalescedTouchData.Coalesce(aEvent, aGuid, aInputBlockId,
aApzResponse);
MOZ_ASSERT(!PostponeDispatchingTouchMove());
} else {
UniquePtr<WidgetTouchEvent> touchMoveEvent =
mCoalescedTouchData.TakeCoalescedEvent();
MOZ_ASSERT(touchMoveEvent->mMessage == eTouchMove);
// Before dispatching touchMoveEvent, we need to put aEvent into the
// queue for keeping the event order even if an event listener spins the
// event loop and we'll receive another touch event. So, aEvent may be
// dispatched while we're dispatching touchMoveEvent. Therefore, we need
// to make it convertible to eTouchRawUpdate.
MOZ_ASSERT(aEvent.CanConvertToPointerRawUpdate());
mCoalescedTouchData.Coalesce(aEvent, aGuid, aInputBlockId,
aApzResponse);
MOZ_ASSERT(!PostponeDispatchingTouchMove());
// touchMoveEvent was stored by mCoalescedTouchData before receiving
// aEvent. Therefore, the receiver should've already dispatched
// eTouchRawUpdate for dispatching `pointerrawupdate` and let web apps
// know the update immediately (with sacrificing the performance).
// Therefore, we don't need to dispatch eTouchRawUpdate here before
// dispatching the touchMoveEvent.
MOZ_ASSERT(!touchMoveEvent->CanConvertToPointerRawUpdate());
const uint32_t generation = mCoalescedTouchData.Generation();
if (!RecvRealTouchEvent(*touchMoveEvent,
mCoalescedTouchData.GetScrollableLayerGuid(),
mCoalescedTouchData.GetInputBlockId(),
mCoalescedTouchData.GetApzResponse())) {
return IPC_FAIL_NO_REASON(this);
}
// RecvRealTouchEvent() may have caused spinning the event loop and
// changed sConsecutiveTouchMoveCount. So, we need to check it now.
if (PostponeDispatchingTouchMove()) {
mCoalescedTouchMoveEventFlusher->StartObserver();
if (generation == mCoalescedTouchData.Generation()) {
// Let's notify the web app of `pointerrawupdate` immediately if and
// only if they listen to it. Additionally, we don't want to notify
// eTouchRawUpdate when ProcessPendingCoalescedTouchData() is called
// later.
mCoalescedTouchData.NotifyTouchRawUpdateOfHandled(aEvent);
HandleTouchRawUpdateEvent(aEvent, aGuid, aInputBlockId,
aApzResponse);
}
return IPC_OK();
}
}
// Flush the pending coalesced touch in order to avoid the first
// touchmove be overridden by the second one, this contains aEvent.
ProcessPendingCoalescedTouchData();
return IPC_OK();
}
}
if (!RecvRealTouchEvent(aEvent, aGuid, aInputBlockId, aApzResponse)) {
return IPC_FAIL_NO_REASON(this);
}
return IPC_OK();
}
void BrowserChild::HandleTouchRawUpdateEvent(
const WidgetTouchEvent& aPendingTouchEvent,
const ScrollableLayerGuid& aGuid, const uint64_t& aInputBlockId,
const nsEventStatus& aApzResponse) {
if (!mPointerRawUpdateWindowCount) {
return; // There is no window containing pointerrawupdate event listeners
}
WidgetTouchEvent touchRawUpdateEvent(aPendingTouchEvent,
WidgetTouchEvent::CloneTouches::Yes);
touchRawUpdateEvent.mMessage = eTouchRawUpdate;
for (Touch* const touch : touchRawUpdateEvent.mTouches) {
touch->mMessage = eTouchRawUpdate;
touch->mCoalescedWidgetEvents = nullptr;
touch->convertToPointer = true;
// Although nobody checks `convertToPointerRawUpdate` of eTouchRawUpdate.
// However, the name indicates it would cause ePointerRawUpdate or not, so,
// for avoiding to make developers confused when they watch the value with
// the debugger, we should set this to `true`.
touch->convertToPointerRawUpdate = true;
}
RecvRealTouchEvent(touchRawUpdateEvent, aGuid, aInputBlockId, aApzResponse);
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityRealTouchMoveEvent(
const WidgetTouchEvent& aEvent, const ScrollableLayerGuid& aGuid,
const uint64_t& aInputBlockId, const nsEventStatus& aApzResponse) {
return RecvRealTouchMoveEvent(aEvent, aGuid, aInputBlockId, aApzResponse);
}
mozilla::ipc::IPCResult BrowserChild::RecvRealDragEvent(
const WidgetDragEvent& aEvent, const uint32_t& aDragAction,
const uint32_t& aDropEffect, nsIPrincipal* aPrincipal,
nsIPolicyContainer* aPolicyContainer) {
WidgetDragEvent localEvent(aEvent);
localEvent.mWidget = mPuppetWidget;
nsCOMPtr<nsIDragSession> dragSession = GetDragSession();
DRAGSERVICE_LOGD(
"[%p] %s | aEvent.mMessage: %s | aDragAction: %u | aDropEffect: %u | "
"widgetRelativePt: (%d,%d) | dragSession: %p",
this, __FUNCTION__,
NS_ConvertUTF16toUTF8(dom::Event::GetEventName(aEvent.mMessage)).get(),
aDragAction, aDropEffect, static_cast<int>(localEvent.mRefPoint.x),
static_cast<int>(localEvent.mRefPoint.y), dragSession.get());
if (dragSession) {
dragSession->SetDragAction(aDragAction);
dragSession->SetTriggeringPrincipal(aPrincipal);
dragSession->SetPolicyContainer(aPolicyContainer);
RefPtr<DataTransfer> initialDataTransfer = dragSession->GetDataTransfer();
if (initialDataTransfer) {
initialDataTransfer->SetDropEffectInt(aDropEffect);
}
}
if (aEvent.mMessage == eDrop) {
bool canDrop = true;
if (!dragSession || NS_FAILED(dragSession->GetCanDrop(&canDrop)) ||
!canDrop) {
DRAGSERVICE_LOGD("[%p] %s | changed drop to dragexit", this,
__FUNCTION__);
localEvent.mMessage = eDragExit;
}
} else if (aEvent.mMessage == eDragOver) {
if (dragSession) {
// This will dispatch 'drag' event at the source if the
// drag transaction started in this process.
dragSession->FireDragEventAtSource(eDrag, aEvent.mModifiers);
}
}
DispatchWidgetEventViaAPZ(localEvent);
return IPC_OK();
}
already_AddRefed<DataTransfer> BrowserChild::ConvertToDataTransfer(
nsIPrincipal* aPrincipal, nsTArray<IPCTransferableData>&& aTransferables,
EventMessage aMessage) {
// The extension process should grant access to a protected DataTransfer if
// the principal permits it (and dom.events.datatransfer.protected.enabled is
// false). Otherwise, protected DataTransfer access should only be given to
// the system.
if (!aPrincipal || Manager()->GetRemoteType() != EXTENSION_REMOTE_TYPE) {
aPrincipal = nsContentUtils::GetSystemPrincipal();
}
// Check if we are receiving any file objects. If we are we will want
// to hide any of the other objects coming in from content.
bool hasFiles = false;
for (uint32_t i = 0; i < aTransferables.Length() && !hasFiles; ++i) {
auto& items = aTransferables[i].items();
for (uint32_t j = 0; j < items.Length() && !hasFiles; ++j) {
if (items[j].data().type() ==
IPCTransferableDataType::TIPCTransferableDataBlob) {
hasFiles = true;
}
}
}
// Add the entries from the IPC to the new DataTransfer
RefPtr<DataTransfer> dataTransfer =
new DataTransfer(nullptr, aMessage, false, Nothing());
for (uint32_t i = 0; i < aTransferables.Length(); ++i) {
auto& items = aTransferables[i].items();
for (uint32_t j = 0; j < items.Length(); ++j) {
const IPCTransferableDataItem& item = items[j];
RefPtr<nsVariantCC> variant = new nsVariantCC();
nsresult rv =
nsContentUtils::IPCTransferableDataItemToVariant(item, variant);
if (NS_FAILED(rv)) {
continue;
}
// We should hide this data from content if we have a file, and we
// aren't a file.
bool hidden =
hasFiles && item.data().type() !=
IPCTransferableDataType::TIPCTransferableDataBlob;
dataTransfer->SetDataWithPrincipalFromOtherProcess(
NS_ConvertUTF8toUTF16(item.flavor()), variant, i, aPrincipal, hidden);
}
}
return dataTransfer.forget();
}
mozilla::ipc::IPCResult BrowserChild::RecvInvokeChildDragSession(
const MaybeDiscarded<WindowContext>& aSourceWindowContext,
const MaybeDiscarded<WindowContext>& aSourceTopWindowContext,
nsIPrincipal* aPrincipal, nsTArray<IPCTransferableData>&& aTransferables,
const uint32_t& aAction) {
if (nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1")) {
nsIWidget* widget = WebWidget();
dragService->StartDragSession(widget);
if (RefPtr<nsIDragSession> session = GetDragSession()) {
session->SetSourceWindowContext(aSourceWindowContext.GetMaybeDiscarded());
session->SetSourceTopWindowContext(
aSourceTopWindowContext.GetMaybeDiscarded());
session->SetDragAction(aAction);
RefPtr<DataTransfer> dataTransfer = ConvertToDataTransfer(
aPrincipal, std::move(aTransferables), eDragStart);
session->SetDataTransfer(dataTransfer);
DRAGSERVICE_LOGD("[%p] %s | Successfully started dragSession: %p", this,
__FUNCTION__, session.get());
} else {
DRAGSERVICE_LOGE("[%p] %s | Failed to start dragSession", this,
__FUNCTION__);
}
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvUpdateDragSession(
nsIPrincipal* aPrincipal, nsTArray<IPCTransferableData>&& aTransferables,
EventMessage aEventMessage) {
if (RefPtr<nsIDragSession> session = GetDragSession()) {
nsCOMPtr<DataTransfer> dataTransfer = ConvertToDataTransfer(
aPrincipal, std::move(aTransferables), aEventMessage);
session->SetDataTransfer(dataTransfer);
DRAGSERVICE_LOGD(
"[%p] %s | session: %p | aEventMessage: %s | Updated dragSession "
"dataTransfer",
this, __FUNCTION__, session.get(),
NS_ConvertUTF16toUTF8(dom::Event::GetEventName(aEventMessage)).get());
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvEndDragSession(
const bool& aDoneDrag, const bool& aUserCancelled,
const LayoutDeviceIntPoint& aDragEndPoint, const uint32_t& aKeyModifiers,
const uint32_t& aDropEffect) {
RefPtr<nsIDragSession> dragSession = GetDragSession();
if (dragSession) {
DRAGSERVICE_LOGD(
"[%p] %s | dragSession: %p | aDoneDrag: %s | aUserCancelled: %s | "
"aDragEndPoint: (%d, %d) | aKeyModifiers: %u | aDropEffect: %u",
this, __FUNCTION__, dragSession.get(), GetBoolName(aDoneDrag),
GetBoolName(aUserCancelled), static_cast<int>(aDragEndPoint.x),
static_cast<int>(aDragEndPoint.y), aKeyModifiers, aDropEffect);
if (aUserCancelled) {
dragSession->UserCancelled();
}
RefPtr<DataTransfer> dataTransfer = dragSession->GetDataTransfer();
if (dataTransfer) {
dataTransfer->SetDropEffectInt(aDropEffect);
}
dragSession->SetDragEndPoint(aDragEndPoint.x, aDragEndPoint.y);
dragSession->EndDragSession(aDoneDrag, aKeyModifiers);
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvStoreDropTargetAndDelayEndDragSession(
const LayoutDeviceIntPoint& aPt, uint32_t aDropEffect, uint32_t aDragAction,
nsIPrincipal* aPrincipal, nsIPolicyContainer* aPolicyContainer) {
// cf. RecvRealDragEvent
nsCOMPtr<nsIDragSession> dragSession = GetDragSession();
MOZ_ASSERT(dragSession);
DRAGSERVICE_LOGD(
"[%p] %s | dragSession: %p aPt: (%d, %d) | aDropEffect: %u | "
"aDragAction: %u",
this, __FUNCTION__, dragSession.get(), static_cast<int>(aPt.x),
static_cast<int>(aPt.y), aDropEffect, aDragAction);
dragSession->SetDragAction(aDragAction);
dragSession->SetTriggeringPrincipal(aPrincipal);
dragSession->SetPolicyContainer(aPolicyContainer);
RefPtr<DataTransfer> initialDataTransfer = dragSession->GetDataTransfer();
if (initialDataTransfer) {
initialDataTransfer->SetDropEffectInt(aDropEffect);
}
bool canDrop = true;
if (!dragSession || NS_FAILED(dragSession->GetCanDrop(&canDrop)) ||
!canDrop) {
// Don't record the target or delay EDS calls.
return IPC_OK();
}
auto parentToChildTf = GetChildToParentConversionMatrix().MaybeInverse();
NS_ENSURE_TRUE(parentToChildTf, IPC_OK());
LayoutDevicePoint floatPt(aPt);
LayoutDevicePoint floatTf = parentToChildTf->TransformPoint(floatPt);
WidgetQueryContentEvent queryEvent(true, eQueryDropTargetHittest,
mPuppetWidget);
queryEvent.mRefPoint = RoundedToInt(floatTf);
DispatchWidgetEventViaAPZ(queryEvent);
if (queryEvent.mReply && queryEvent.mReply->mDropElement) {
mDelayedDropPoint = queryEvent.mRefPoint;
dragSession->StoreDropTargetAndDelayEndDragSession(
queryEvent.mReply->mDropElement, queryEvent.mReply->mDropFrame);
} else {
MOZ_ASSERT(false, "Didn't get reply from eQueryDropTargetHittest event!");
}
return IPC_OK();
}
mozilla::ipc::IPCResult
BrowserChild::RecvDispatchToDropTargetAndResumeEndDragSession(
bool aShouldDrop, nsTHashSet<nsString>&& aAllowedFilesPaths) {
DRAGSERVICE_LOGD("[%p] %s | aShouldDrop: %s", this, __FUNCTION__,
GetBoolName(aShouldDrop));
nsCOMPtr<nsIDragSession> dragSession = GetDragSession();
MOZ_ASSERT(dragSession);
RefPtr<nsIWidget> widget = mPuppetWidget;
nsTHashSet<nsString> allowedPaths =
aShouldDrop ? std::move(aAllowedFilesPaths) : nsTHashSet<nsString>();
dragSession->DispatchToDropTargetAndResumeEndDragSession(
widget, mDelayedDropPoint, aShouldDrop, allowedPaths);
mDelayedDropPoint = {};
return IPC_OK();
}
void BrowserChild::RequestEditCommands(NativeKeyBindingsType aType,
const WidgetKeyboardEvent& aEvent,
nsTArray<CommandInt>& aCommands) {
MOZ_ASSERT(aCommands.IsEmpty());
if (NS_WARN_IF(aEvent.IsEditCommandsInitialized(aType))) {
aCommands = aEvent.EditCommandsConstRef(aType).Clone();
return;
}
switch (aType) {
case NativeKeyBindingsType::SingleLineEditor:
case NativeKeyBindingsType::MultiLineEditor:
case NativeKeyBindingsType::RichTextEditor:
break;
default:
MOZ_ASSERT_UNREACHABLE("Invalid native key bindings type");
}
// Don't send aEvent to the parent process directly because it'll be marked
// as posted to remote process.
WidgetKeyboardEvent localEvent(aEvent);
SendRequestNativeKeyBindings(static_cast<uint32_t>(aType), localEvent,
&aCommands);
}
mozilla::ipc::IPCResult BrowserChild::RecvSynthesizedEventResponse(
const uint64_t& aCallbackId) {
NS_ENSURE_TRUE(xpc::IsInAutomation(), IPC_FAIL(this, "Unexpected event"));
mozilla::widget::AutoSynthesizedEventCallbackNotifier::NotifySavedCallback(
aCallbackId);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvUpdateSHistory() {
if (mSessionStoreChild) {
mSessionStoreChild->UpdateSHistoryChanges();
}
return IPC_OK();
}
// In case handling repeated keys takes much time, we skip firing new ones.
bool BrowserChild::SkipRepeatedKeyEvent(const WidgetKeyboardEvent& aEvent) {
if (mRepeatedKeyEventTime.IsNull() || !aEvent.CanSkipInRemoteProcess() ||
(aEvent.mMessage != eKeyDown && aEvent.mMessage != eKeyPress)) {
mRepeatedKeyEventTime = TimeStamp();
mSkipKeyPress = false;
return false;
}
if ((aEvent.mMessage == eKeyDown &&
(mRepeatedKeyEventTime > aEvent.mTimeStamp)) ||
(mSkipKeyPress && (aEvent.mMessage == eKeyPress))) {
// If we skip a keydown event, also the following keypress events should be
// skipped.
mSkipKeyPress |= aEvent.mMessage == eKeyDown;
return true;
}
if (aEvent.mMessage == eKeyDown) {
// If keydown wasn't skipped, nor should the possible following keypress.
mRepeatedKeyEventTime = TimeStamp();
mSkipKeyPress = false;
}
return false;
}
void BrowserChild::UpdateRepeatedKeyEventEndTime(
const WidgetKeyboardEvent& aEvent) {
if (aEvent.mIsRepeat &&
(aEvent.mMessage == eKeyDown || aEvent.mMessage == eKeyPress)) {
mRepeatedKeyEventTime = TimeStamp::Now();
}
}
mozilla::ipc::IPCResult BrowserChild::RecvRealKeyEvent(
const WidgetKeyboardEvent& aEvent, const nsID& aUUID) {
MOZ_ASSERT_IF(aEvent.mMessage == eKeyPress,
aEvent.AreAllEditCommandsInitialized());
// If content code called preventDefault() on a keydown event, then we don't
// want to process any following keypress events which is caused by the
// preceding keydown (i.e., default action of the preceding keydown).
// In other words, if the keypress is not a default action of the preceding
// keydown, we should not stop dispatching keypress event even if the
// immediate preceding keydown was consumed.
const bool isPrecedingKeyDownEventConsumed =
aEvent.mMessage == eKeyPress && mPreviousConsumedKeyDownCode.isSome() &&
mPreviousConsumedKeyDownCode.value() == aEvent.mCodeNameIndex;
WidgetKeyboardEvent localEvent(aEvent);
localEvent.mWidget = mPuppetWidget;
localEvent.mUniqueId = aEvent.mUniqueId;
if (!SkipRepeatedKeyEvent(aEvent) && !isPrecedingKeyDownEventConsumed) {
nsEventStatus status = DispatchWidgetEventViaAPZ(localEvent);
// Update the end time of the possible repeated event so that we can skip
// some incoming events in case event handling took long time.
UpdateRepeatedKeyEventEndTime(localEvent);
if (aEvent.mMessage == eKeyDown) {
// If eKeyDown is consumed, we should stop dispatching the following
// eKeyPress events since the events are default action of eKeyDown.
// FIXME: We should synthesize eKeyPress in this process (bug 1181501).
if (status == nsEventStatus_eConsumeNoDefault) {
MOZ_ASSERT_IF(!aEvent.mFlags.mIsSynthesizedForTests,
aEvent.mCodeNameIndex != CODE_NAME_INDEX_USE_STRING);
// If mPreviousConsumedKeyDownCode is not Nothing, 2 or more keys may be
// pressed at same time and their eKeyDown are consumed. However, we
// forget the previous eKeyDown event result here and that might cause
// dispatching eKeyPress events caused by the previous eKeyDown in
// theory. However, this should not occur because eKeyPress should be
// fired before another eKeyDown, although it's depend on how the native
// keyboard event handler is implemented.
mPreviousConsumedKeyDownCode = Some(aEvent.mCodeNameIndex);
}
// If eKeyDown is not consumed but we know preceding eKeyDown is consumed,
// we need to forget it since we should not stop dispatching following
// eKeyPress events which are default action of current eKeyDown.
else if (mPreviousConsumedKeyDownCode.isSome() &&
aEvent.mCodeNameIndex == mPreviousConsumedKeyDownCode.value()) {
mPreviousConsumedKeyDownCode.reset();
}
}
// eKeyPress is a default action of eKeyDown. Therefore, eKeyPress is fired
// between eKeyDown and eKeyUp. So, received an eKeyUp for eKeyDown which
// was consumed means that following eKeyPress events should be dispatched.
// Therefore, we need to forget the fact that the preceding eKeyDown was
// consumed right now.
// NOTE: On Windows, eKeyPress may be fired without preceding eKeyDown if
// IME or utility app sends WM_CHAR message. So, if we don't forget it,
// we'd consume unrelated eKeyPress events.
else if (aEvent.mMessage == eKeyUp &&
mPreviousConsumedKeyDownCode.isSome() &&
aEvent.mCodeNameIndex == mPreviousConsumedKeyDownCode.value()) {
mPreviousConsumedKeyDownCode.reset();
}
if (localEvent.mFlags.mIsSuppressedOrDelayed) {
localEvent.PreventDefault();
}
// If the event's default isn't prevented but the status is no default,
// That means that the event was consumed by EventStateManager or something
// which is not a usual event handler. In such case, prevent its default
// as a default handler. For example, when an eKeyPress event matches
// with a content accesskey, and it's executed, preventDefault() of the
// event won't be called but the status is set to "no default". Then,
// the event shouldn't be handled by nsMenuBarListener in the main process.
if (!localEvent.DefaultPrevented() &&
status == nsEventStatus_eConsumeNoDefault) {
localEvent.PreventDefault();
}
MOZ_DIAGNOSTIC_ASSERT(!localEvent.PropagationStopped());
}
// The keyboard event which we ignore should not be handled in the main
// process for shortcut key handling. For notifying if we skipped it, we can
// use "stop propagation" flag here because it must be cleared by
// `EventTargetChainItem` if we've dispatched it.
else {
localEvent.StopPropagation();
}
// If we don't need to send a rely for the given keyboard event, we do nothing
// anymore here.
if (!aEvent.WantReplyFromContentProcess()) {
return IPC_OK();
}
// This is an ugly hack, mNoRemoteProcessDispatch is set to true when the
// event's PreventDefault() or StopScrollProcessForwarding() is called.
// And then, it'll be checked by ParamTraits<mozilla::WidgetEvent>::Write()
// whether the event is being sent to remote process unexpectedly.
// However, unfortunately, it cannot check the destination. Therefore,
// we need to clear the flag explicitly here because ParamTraits should
// keep checking the flag for avoiding regression.
localEvent.mFlags.mNoRemoteProcessDispatch = false;
SendReplyKeyEvent(localEvent, aUUID);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityRealKeyEvent(
const WidgetKeyboardEvent& aEvent, const nsID& aUUID) {
return RecvRealKeyEvent(aEvent, aUUID);
}
mozilla::ipc::IPCResult BrowserChild::RecvCompositionEvent(
const WidgetCompositionEvent& aEvent) {
WidgetCompositionEvent localEvent(aEvent);
localEvent.mWidget = mPuppetWidget;
DispatchWidgetEventViaAPZ(localEvent);
Unused << SendOnEventNeedingAckHandled(aEvent.mMessage,
localEvent.mCompositionId);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityCompositionEvent(
const WidgetCompositionEvent& aEvent) {
return RecvCompositionEvent(aEvent);
}
mozilla::ipc::IPCResult BrowserChild::RecvSelectionEvent(
const WidgetSelectionEvent& aEvent) {
WidgetSelectionEvent localEvent(aEvent);
localEvent.mWidget = mPuppetWidget;
DispatchWidgetEventViaAPZ(localEvent);
Unused << SendOnEventNeedingAckHandled(aEvent.mMessage, 0u);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPrioritySelectionEvent(
const WidgetSelectionEvent& aEvent) {
return RecvSelectionEvent(aEvent);
}
mozilla::ipc::IPCResult BrowserChild::RecvSimpleContentCommandEvent(
const EventMessage& aMessage) {
WidgetContentCommandEvent localEvent(true, aMessage, mPuppetWidget);
DispatchWidgetEventViaAPZ(localEvent);
Unused << SendOnEventNeedingAckHandled(aMessage, 0u);
return IPC_OK();
}
mozilla::ipc::IPCResult
BrowserChild::RecvNormalPrioritySimpleContentCommandEvent(
const EventMessage& aMessage) {
return RecvSimpleContentCommandEvent(aMessage);
}
mozilla::ipc::IPCResult BrowserChild::RecvInsertText(
const nsAString& aStringToInsert) {
// Use normal event path to reach focused document.
WidgetContentCommandEvent localEvent(true, eContentCommandInsertText,
mPuppetWidget);
localEvent.mString = Some(nsString(aStringToInsert));
DispatchWidgetEventViaAPZ(localEvent);
Unused << SendOnEventNeedingAckHandled(eContentCommandInsertText, 0u);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityInsertText(
const nsAString& aStringToInsert) {
return RecvInsertText(aStringToInsert);
}
mozilla::ipc::IPCResult BrowserChild::RecvReplaceText(
const nsString& aReplaceSrcString, const nsString& aStringToInsert,
uint32_t aOffset, bool aPreventSetSelection) {
// Use normal event path to reach focused document.
WidgetContentCommandEvent localEvent(true, eContentCommandReplaceText,
mPuppetWidget);
localEvent.mString = Some(aStringToInsert);
localEvent.mSelection.mReplaceSrcString = aReplaceSrcString;
localEvent.mSelection.mOffset = aOffset;
localEvent.mSelection.mPreventSetSelection = aPreventSetSelection;
DispatchWidgetEventViaAPZ(localEvent);
Unused << SendOnEventNeedingAckHandled(eContentCommandReplaceText, 0u);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNormalPriorityReplaceText(
const nsString& aReplaceSrcString, const nsString& aStringToInsert,
uint32_t aOffset, bool aPreventSetSelection) {
return RecvReplaceText(aReplaceSrcString, aStringToInsert, aOffset,
aPreventSetSelection);
}
mozilla::ipc::IPCResult BrowserChild::RecvPasteTransferable(
const IPCTransferable& aTransferable) {
nsresult rv;
nsCOMPtr<nsITransferable> trans =
do_CreateInstance("@mozilla.org/widget/transferable;1", &rv);
NS_ENSURE_SUCCESS(rv, IPC_OK());
trans->Init(nullptr);
rv = nsContentUtils::IPCTransferableToTransferable(
aTransferable, true /* aAddDataFlavor */, trans,
false /* aFilterUnknownFlavors */);
NS_ENSURE_SUCCESS(rv, IPC_OK());
nsCOMPtr<nsIDocShell> ourDocShell = do_GetInterface(WebNavigation());
if (NS_WARN_IF(!ourDocShell)) {
return IPC_OK();
}
RefPtr<nsCommandParams> params = new nsCommandParams();
rv = params->SetISupports("transferable", trans);
NS_ENSURE_SUCCESS(rv, IPC_OK());
ourDocShell->DoCommandWithParams("cmd_pasteTransferable", params);
return IPC_OK();
}
#ifdef ACCESSIBILITY
a11y::PDocAccessibleChild* BrowserChild::AllocPDocAccessibleChild(
PDocAccessibleChild*, const uint64_t&,
const MaybeDiscardedBrowsingContext&) {
MOZ_ASSERT(false, "should never call this!");
return nullptr;
}
bool BrowserChild::DeallocPDocAccessibleChild(
a11y::PDocAccessibleChild* aChild) {
delete static_cast<mozilla::a11y::DocAccessibleChild*>(aChild);
return true;
}
#endif
RefPtr<VsyncMainChild> BrowserChild::GetVsyncChild() {
// Initializing VsyncMainChild here turns on per-BrowserChild Vsync for a
// given platform. Note: this only makes sense if nsWindow returns a
// window-specific VsyncSource.
#if defined(MOZ_WAYLAND)
if (IsWaylandEnabled()) {
if (auto* actor = static_cast<VsyncMainChild*>(
LoneManagedOrNullAsserts(ManagedPVsyncChild()))) {
return actor;
}
auto actor = MakeRefPtr<VsyncMainChild>();
if (!SendPVsyncConstructor(actor)) {
return nullptr;
}
return actor;
}
#endif
return nullptr;
}
mozilla::ipc::IPCResult BrowserChild::RecvLoadRemoteScript(
const nsAString& aURL, const bool& aRunInGlobalScope) {
if (!InitBrowserChildMessageManager())
// This can happen if we're half-destroyed. It's not a fatal
// error.
return IPC_OK();
JS::Rooted<JSObject*> mm(RootingCx(),
mBrowserChildMessageManager->GetOrCreateWrapper());
if (!mm) {
// This can happen if we're half-destroyed. It's not a fatal error.
return IPC_OK();
}
LoadScriptInternal(mm, aURL, !aRunInGlobalScope);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvAsyncMessage(
const nsAString& aMessage, const ClonedMessageData& aData) {
AUTO_PROFILER_LABEL_DYNAMIC_LOSSY_NSSTRING("BrowserChild::RecvAsyncMessage",
OTHER, aMessage);
MMPrinter::Print("BrowserChild::RecvAsyncMessage", aMessage, aData);
if (!mBrowserChildMessageManager) {
return IPC_OK();
}
RefPtr<nsFrameMessageManager> mm =
mBrowserChildMessageManager->GetMessageManager();
// We should have a message manager if the global is alive, but it
// seems sometimes we don't. Assert in aurora/nightly, but don't
// crash in release builds.
MOZ_DIAGNOSTIC_ASSERT(mm);
if (!mm) {
return IPC_OK();
}
JS::Rooted<JSObject*> kungFuDeathGrip(
dom::RootingCx(), mBrowserChildMessageManager->GetWrapper());
StructuredCloneData data;
UnpackClonedMessageData(aData, data);
mm->ReceiveMessage(static_cast<EventTarget*>(mBrowserChildMessageManager),
nullptr, aMessage, false, &data, nullptr, IgnoreErrors());
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvSwappedWithOtherRemoteLoader(
const IPCTabContext& aContext) {
nsCOMPtr<nsIDocShell> ourDocShell = do_GetInterface(WebNavigation());
if (NS_WARN_IF(!ourDocShell)) {
return IPC_OK();
}
nsCOMPtr<nsPIDOMWindowOuter> ourWindow = ourDocShell->GetWindow();
if (NS_WARN_IF(!ourWindow)) {
return IPC_OK();
}
RefPtr<nsDocShell> docShell = static_cast<nsDocShell*>(ourDocShell.get());
nsCOMPtr<EventTarget> ourEventTarget = nsGlobalWindowOuter::Cast(ourWindow);
docShell->SetInFrameSwap(true);
nsContentUtils::FirePageShowEventForFrameLoaderSwap(
ourDocShell, ourEventTarget, false, true);
nsContentUtils::FirePageHideEventForFrameLoaderSwap(ourDocShell,
ourEventTarget, true);
// Owner content type may have changed, so store the possibly updated context
// and notify others.
MaybeInvalidTabContext maybeContext(aContext);
if (!maybeContext.IsValid()) {
NS_ERROR(nsPrintfCString("Received an invalid TabContext from "
"the parent process. (%s)",
maybeContext.GetInvalidReason())
.get());
MOZ_CRASH("Invalid TabContext received from the parent process.");
}
if (!UpdateTabContextAfterSwap(maybeContext.GetTabContext())) {
MOZ_CRASH("Update to TabContext after swap was denied.");
}
// Ignore previous value of mTriedBrowserInit since owner content has changed.
mTriedBrowserInit = true;
nsContentUtils::FirePageShowEventForFrameLoaderSwap(
ourDocShell, ourEventTarget, true, true);
docShell->SetInFrameSwap(false);
// This is needed to get visibility state right in cases when we swapped a
// visible tab (foreground in visible window) with a non-visible tab.
if (RefPtr<Document> doc = docShell->GetDocument()) {
doc->UpdateVisibilityState();
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvHandleAccessKey(
const WidgetKeyboardEvent& aEvent, nsTArray<uint32_t>&& aCharCodes) {
nsCOMPtr<Document> document(GetTopLevelDocument());
RefPtr<nsPresContext> pc = document->GetPresContext();
if (pc) {
if (!pc->EventStateManager()->HandleAccessKey(
&(const_cast<WidgetKeyboardEvent&>(aEvent)), pc, aCharCodes)) {
// If no accesskey was found, inform the parent so that accesskeys on
// menus can be handled.
WidgetKeyboardEvent localEvent(aEvent);
localEvent.mWidget = mPuppetWidget;
SendAccessKeyNotHandled(localEvent);
}
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvPrintPreview(
const PrintData& aPrintData, const MaybeDiscardedBrowsingContext& aSourceBC,
PrintPreviewResolver&& aCallback) {
#ifdef NS_PRINTING
// If we didn't succeed in passing off ownership of aCallback, then something
// went wrong.
auto sendCallbackError = MakeScopeExit([&] {
if (aCallback) {
// signal error
aCallback(PrintPreviewResultInfo(0, 0, false, false, false, {}, {}, {}));
}
});
if (NS_WARN_IF(aSourceBC.IsDiscarded())) {
return IPC_OK();
}
RefPtr<nsGlobalWindowOuter> sourceWindow;
if (!aSourceBC.IsNull()) {
sourceWindow = nsGlobalWindowOuter::Cast(aSourceBC.get()->GetDOMWindow());
if (NS_WARN_IF(!sourceWindow)) {
return IPC_OK();
}
} else {
nsCOMPtr<nsPIDOMWindowOuter> ourWindow = do_GetInterface(WebNavigation());
if (NS_WARN_IF(!ourWindow)) {
return IPC_OK();
}
sourceWindow = nsGlobalWindowOuter::Cast(ourWindow);
}
RefPtr<nsIPrintSettings> printSettings;
nsCOMPtr<nsIPrintSettingsService> printSettingsSvc =
do_GetService("@mozilla.org/gfx/printsettings-service;1");
if (NS_WARN_IF(!printSettingsSvc)) {
return IPC_OK();
}
printSettingsSvc->CreateNewPrintSettings(getter_AddRefs(printSettings));
if (NS_WARN_IF(!printSettings)) {
return IPC_OK();
}
printSettingsSvc->DeserializeToPrintSettings(aPrintData, printSettings);
nsCOMPtr<nsIDocShell> docShellToCloneInto;
if (!aSourceBC.IsNull()) {
docShellToCloneInto = do_GetInterface(WebNavigation());
if (NS_WARN_IF(!docShellToCloneInto)) {
return IPC_OK();
}
}
sourceWindow->Print(printSettings,
/* aRemotePrintJob = */ nullptr,
/* aListener = */ nullptr, docShellToCloneInto,
nsGlobalWindowOuter::IsPreview::Yes,
nsGlobalWindowOuter::IsForWindowDotPrint::No,
std::move(aCallback), nullptr, IgnoreErrors());
#endif
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvExitPrintPreview() {
#ifdef NS_PRINTING
nsCOMPtr<nsIWebBrowserPrint> webBrowserPrint =
do_GetInterface(ToSupports(WebNavigation()));
if (NS_WARN_IF(!webBrowserPrint)) {
return IPC_OK();
}
webBrowserPrint->ExitPrintPreview();
#endif
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::CommonPrint(
const MaybeDiscardedBrowsingContext& aBc, const PrintData& aPrintData,
RefPtr<BrowsingContext>* aCachedBrowsingContext) {
#ifdef NS_PRINTING
if (NS_WARN_IF(aBc.IsNullOrDiscarded())) {
return IPC_OK();
}
RefPtr<nsGlobalWindowOuter> outerWindow =
nsGlobalWindowOuter::Cast(aBc.get()->GetDOMWindow());
if (NS_WARN_IF(!outerWindow)) {
return IPC_OK();
}
nsCOMPtr<nsIPrintSettingsService> printSettingsSvc =
do_GetService("@mozilla.org/gfx/printsettings-service;1");
if (NS_WARN_IF(!printSettingsSvc)) {
return IPC_OK();
}
nsCOMPtr<nsIPrintSettings> printSettings;
nsresult rv =
printSettingsSvc->CreateNewPrintSettings(getter_AddRefs(printSettings));
if (NS_WARN_IF(NS_FAILED(rv))) {
return IPC_OK();
}
printSettingsSvc->DeserializeToPrintSettings(aPrintData, printSettings);
{
IgnoredErrorResult rv;
RefPtr printJob = static_cast<RemotePrintJobChild*>(
aPrintData.remotePrintJob().AsChild());
outerWindow->Print(
printSettings, printJob,
/* aListener = */ nullptr,
/* aWindowToCloneInto = */ nullptr, nsGlobalWindowOuter::IsPreview::No,
nsGlobalWindowOuter::IsForWindowDotPrint::No,
/* aPrintPreviewCallback = */ nullptr, aCachedBrowsingContext, rv);
if (NS_WARN_IF(rv.Failed())) {
return IPC_OK();
}
}
#endif
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvPrint(
const MaybeDiscardedBrowsingContext& aBc, const PrintData& aPrintData,
bool aReturnStaticClone, PrintResolver&& aResolve) {
#ifdef NS_PRINTING
RefPtr<BrowsingContext> browsingContext;
auto result = CommonPrint(aBc, aPrintData,
aReturnStaticClone ? &browsingContext : nullptr);
aResolve(browsingContext);
return result;
#else
aResolve(nullptr);
return IPC_OK();
#endif
}
mozilla::ipc::IPCResult BrowserChild::RecvPrintClonedPage(
const MaybeDiscardedBrowsingContext& aBc, const PrintData& aPrintData,
const MaybeDiscardedBrowsingContext& aClonedBc) {
#ifdef NS_PRINTING
if (aClonedBc.IsNullOrDiscarded()) {
return IPC_OK();
}
RefPtr<BrowsingContext> clonedBc = aClonedBc.get();
return CommonPrint(aBc, aPrintData, &clonedBc);
#else
return IPC_OK();
#endif
}
mozilla::ipc::IPCResult BrowserChild::RecvDestroyPrintClone(
const MaybeDiscardedBrowsingContext& aCachedPage) {
#ifdef NS_PRINTING
if (aCachedPage) {
RefPtr<nsPIDOMWindowOuter> window = aCachedPage->GetDOMWindow();
if (NS_WARN_IF(!window)) {
return IPC_OK();
}
window->Close();
}
#endif
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvUpdateNativeWindowHandle(
const uintptr_t& aNewHandle) {
#if defined(XP_WIN) && defined(ACCESSIBILITY)
mNativeWindowHandle = aNewHandle;
return IPC_OK();
#else
return IPC_FAIL_NO_REASON(this);
#endif
}
mozilla::ipc::IPCResult BrowserChild::RecvDestroy() {
MOZ_ASSERT(!mDestroyed);
mDestroyed = true;
nsTArray<PContentPermissionRequestChild*> childArray =
nsContentPermissionUtils::GetContentPermissionRequestChildById(
GetTabId());
// Need to close undeleted ContentPermissionRequestChilds before tab is
// closed.
for (auto& permissionRequestChild : childArray) {
auto* child = static_cast<RemotePermissionRequest*>(permissionRequestChild);
child->Destroy();
}
if (mBrowserChildMessageManager) {
// Message handlers are called from the event loop, so it better be safe to
// run script.
MOZ_ASSERT(nsContentUtils::IsSafeToRunScript());
mBrowserChildMessageManager->DispatchTrustedEvent(u"unload"_ns);
}
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
observerService->RemoveObserver(this, BEFORE_FIRST_PAINT);
// XXX what other code in ~BrowserChild() should we be running here?
DestroyWindow();
// Bounce through the event loop once to allow any delayed teardown runnables
// that were just generated to have a chance to run.
nsCOMPtr<nsIRunnable> deleteRunnable = new DelayedDeleteRunnable(this);
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(deleteRunnable));
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvRenderLayers(const bool& aEnabled) {
auto clearPaintWhileInterruptingJS = MakeScopeExit([&] {
// We might force a paint, or we might already have painted and this is a
// no-op. In either case, once we exit this scope, we need to alert the
// ProcessHangMonitor that we've finished responding to what might have
// been a request to force paint. This is so that the BackgroundHangMonitor
// for force painting can be made to wait again.
if (aEnabled) {
ProcessHangMonitor::ClearPaintWhileInterruptingJS();
}
});
if (aEnabled) {
ProcessHangMonitor::MaybeStartPaintWhileInterruptingJS();
}
mRenderLayers = aEnabled;
const bool wasVisible = IsVisible();
UpdateVisibility();
// If we just became visible, try to trigger a paint as soon as possible.
const bool becameVisible = !wasVisible && IsVisible();
if (!becameVisible) {
return IPC_OK();
}
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
if (!docShell) {
return IPC_OK();
}
// We don't use BrowserChildBase::GetPresShell() here because that would
// create a content viewer if one doesn't exist yet. Creating a content
// viewer can cause JS to run, which we want to avoid.
// nsIDocShell::GetPresShell returns null if no content viewer exists yet.
RefPtr<PresShell> presShell = docShell->GetPresShell();
if (!presShell) {
return IPC_OK();
}
if (nsIFrame* root = presShell->GetRootFrame()) {
root->SchedulePaint();
}
// If we need to repaint, let's do that right away. No sense waiting until
// we get back to the event loop again. We suppress the display port so
// that we only paint what's visible. This ensures that the tab we're
// switching to paints as quickly as possible.
presShell->SuppressDisplayport(true);
if (nsContentUtils::IsSafeToRunScript()) {
WebWidget()->PaintNowIfNeeded();
} else {
RefPtr<nsViewManager> vm = presShell->GetViewManager();
if (nsView* view = vm->GetRootView()) {
presShell->PaintAndRequestComposite(view, PaintFlags::None);
}
}
presShell->SuppressDisplayport(false);
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvNavigateByKey(
const bool& aForward, const bool& aForDocumentNavigation) {
nsFocusManager* fm = nsFocusManager::GetFocusManager();
if (!fm) {
return IPC_OK();
}
RefPtr<Element> result;
nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(WebNavigation());
// Move to the first or last document.
{
uint32_t type =
aForward
? (aForDocumentNavigation
? static_cast<uint32_t>(nsIFocusManager::MOVEFOCUS_FIRSTDOC)
: static_cast<uint32_t>(nsIFocusManager::MOVEFOCUS_FIRST))
: (aForDocumentNavigation
? static_cast<uint32_t>(nsIFocusManager::MOVEFOCUS_LASTDOC)
: static_cast<uint32_t>(nsIFocusManager::MOVEFOCUS_LAST));
uint32_t flags = nsIFocusManager::FLAG_BYKEY;
if (aForward || aForDocumentNavigation) {
flags |= nsIFocusManager::FLAG_NOSCROLL;
}
fm->MoveFocus(window, nullptr, type, flags, getter_AddRefs(result));
}
// No valid root element was found, so move to the first focusable element.
if (!result && aForward && !aForDocumentNavigation) {
fm->MoveFocus(window, nullptr, nsIFocusManager::MOVEFOCUS_FIRST,
nsIFocusManager::FLAG_BYKEY, getter_AddRefs(result));
}
SendRequestFocus(false, CallerType::System);
return IPC_OK();
}
bool BrowserChild::InitBrowserChildMessageManager() {
mShouldSendWebProgressEventsToParent = true;
if (!mBrowserChildMessageManager) {
nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(WebNavigation());
NS_ENSURE_TRUE(window, false);
nsCOMPtr<EventTarget> chromeHandler = window->GetChromeEventHandler();
NS_ENSURE_TRUE(chromeHandler, false);
RefPtr<BrowserChildMessageManager> scope = mBrowserChildMessageManager =
new BrowserChildMessageManager(this);
MOZ_ALWAYS_TRUE(nsMessageManagerScriptExecutor::Init());
nsCOMPtr<nsPIWindowRoot> root = do_QueryInterface(chromeHandler);
if (NS_WARN_IF(!root)) {
mBrowserChildMessageManager = nullptr;
return false;
}
root->SetParentTarget(scope);
}
if (!mTriedBrowserInit) {
mTriedBrowserInit = true;
}
return true;
}
void BrowserChild::InitRenderingState(
const TextureFactoryIdentifier& aTextureFactoryIdentifier,
const layers::LayersId& aLayersId,
const CompositorOptions& aCompositorOptions) {
mPuppetWidget->InitIMEState();
MOZ_ASSERT(aLayersId.IsValid());
mTextureFactoryIdentifier = aTextureFactoryIdentifier;
// Pushing layers transactions directly to a separate
// compositor context.
PCompositorBridgeChild* compositorChild = CompositorBridgeChild::Get();
if (!compositorChild) {
mLayersConnected = Some(false);
NS_WARNING("failed to get CompositorBridgeChild instance");
return;
}
mCompositorOptions = Some(aCompositorOptions);
if (aLayersId.IsValid()) {
StaticMutexAutoLock lock(sBrowserChildrenMutex);
if (!sBrowserChildren) {
sBrowserChildren = new BrowserChildMap;
}
MOZ_ASSERT(!sBrowserChildren->Contains(uint64_t(aLayersId)));
sBrowserChildren->InsertOrUpdate(uint64_t(aLayersId), this);
mLayersId = aLayersId;
}
// Depending on timing, we might paint too early and fall back to basic
// layers. CreateRemoteLayerManager will destroy us if we manage to get a
// remote layer manager though, so that's fine.
MOZ_ASSERT(!mPuppetWidget->HasWindowRenderer() ||
mPuppetWidget->GetWindowRenderer()->GetBackendType() ==
layers::LayersBackend::LAYERS_NONE);
bool success = false;
if (mLayersConnected == Some(true)) {
success = CreateRemoteLayerManager(compositorChild);
}
if (success) {
MOZ_ASSERT(mLayersConnected == Some(true));
// Succeeded to create "remote" layer manager
ImageBridgeChild::IdentifyCompositorTextureHost(mTextureFactoryIdentifier);
gfx::VRManagerChild::IdentifyTextureHost(mTextureFactoryIdentifier);
InitAPZState();
} else {
mLayersConnected = Some(false);
}
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
observerService->AddObserver(this, BEFORE_FIRST_PAINT, false);
}
}
bool BrowserChild::CreateRemoteLayerManager(
mozilla::layers::PCompositorBridgeChild* aCompositorChild) {
MOZ_ASSERT(aCompositorChild);
return mPuppetWidget->CreateRemoteLayerManager(
[&](WebRenderLayerManager* aLayerManager) -> bool {
nsCString error;
return aLayerManager->Initialize(aCompositorChild,
wr::AsPipelineId(mLayersId),
&mTextureFactoryIdentifier, error);
});
}
void BrowserChild::InitAPZState() {
if (!mCompositorOptions->UseAPZ()) {
return;
}
auto* cbc = CompositorBridgeChild::Get();
// Initialize the ApzcTreeManager. This takes multiple casts because of ugly
// multiple inheritance.
PAPZCTreeManagerChild* baseProtocol =
cbc->SendPAPZCTreeManagerConstructor(mLayersId);
if (!baseProtocol) {
MOZ_ASSERT(false,
"Allocating a TreeManager should not fail with APZ enabled");
return;
}
APZCTreeManagerChild* derivedProtocol =
static_cast<APZCTreeManagerChild*>(baseProtocol);
mApzcTreeManager = RefPtr<IAPZCTreeManager>(derivedProtocol);
// Initialize the GeckoContentController for this tab. We don't hold a
// reference because we don't need it. The ContentProcessController will hold
// a reference to the tab, and will be destroyed by the compositor or ipdl
// during destruction.
RefPtr<GeckoContentController> contentController =
new ContentProcessController(this);
APZChild* apzChild = new APZChild(contentController);
cbc->SendPAPZConstructor(apzChild, mLayersId);
}
IPCResult BrowserChild::RecvUpdateEffects(const EffectsInfo& aEffects) {
bool needInvalidate = false;
if (mEffectsInfo.IsVisible() && aEffects.IsVisible() &&
mEffectsInfo != aEffects) {
// If we are staying visible and either the visrect or scale changed we need
// to invalidate
needInvalidate = true;
}
mEffectsInfo = aEffects;
UpdateVisibility();
if (needInvalidate) {
if (nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation())) {
// We don't use BrowserChildBase::GetPresShell() here because that would
// create a content viewer if one doesn't exist yet. Creating a content
// viewer can cause JS to run, which we want to avoid.
// nsIDocShell::GetPresShell returns null if no content viewer exists yet.
if (RefPtr<PresShell> presShell = docShell->GetPresShell()) {
if (nsIFrame* root = presShell->GetRootFrame()) {
root->InvalidateFrame();
}
}
}
}
return IPC_OK();
}
bool BrowserChild::IsVisible() {
return mPuppetWidget && mPuppetWidget->IsVisible();
}
void BrowserChild::UpdateVisibility() {
const bool shouldBeVisible = [&] {
// If we're known to be visibility: hidden / display: none, just return
// false here, we're pretty sure we don't want to be considered visible
// here.
if (mBrowsingContext && mBrowsingContext->IsUnderHiddenEmbedderElement()) {
return false;
}
// If we're explicitly told not to render layers, we're also invisible.
if (!mRenderLayers) {
return false;
}
if (!mIsTopLevel) {
// For OOP iframes, include viewport visibility.
if (!mEffectsInfo.IsVisible()) {
return false;
}
// Also include activeness, unless we're artificially preserving layers.
// An alternative to this would be to propagate mRenderLayers from the
// parent, perhaps, so that it applies to the whole tree...
if (!mIsPreservingLayers && mBrowsingContext &&
!mBrowsingContext->IsActive()) {
return false;
}
}
return true;
}();
const bool isVisible = IsVisible();
if (shouldBeVisible == isVisible) {
return;
}
if (shouldBeVisible) {
MakeVisible();
} else {
MakeHidden();
}
}
void BrowserChild::MakeVisible() {
if (IsVisible()) {
return;
}
if (mPuppetWidget) {
mPuppetWidget->Show(true);
}
PresShellActivenessMaybeChanged();
}
void BrowserChild::MakeHidden() {
if (!IsVisible()) {
return;
}
// Due to the nested event loop in ContentChild::ProvideWindowCommon,
// it's possible to be told to become hidden before we're finished
// setting up a layer manager. We should skip clearing cached layers
// in that case, since doing so might accidentally put is into
// BasicLayers mode.
if (mPuppetWidget) {
if (mPuppetWidget->HasWindowRenderer()) {
ClearCachedResources();
}
mPuppetWidget->Show(false);
}
PresShellActivenessMaybeChanged();
}
IPCResult BrowserChild::RecvPreserveLayers(bool aPreserve) {
mIsPreservingLayers = aPreserve;
UpdateVisibility();
PresShellActivenessMaybeChanged();
return IPC_OK();
}
void BrowserChild::PresShellActivenessMaybeChanged() {
// We don't use BrowserChildBase::GetPresShell() here because that would
// create a content viewer if one doesn't exist yet. Creating a content
// viewer can cause JS to run, which we want to avoid.
// nsIDocShell::GetPresShell returns null if no content viewer exists yet.
//
// When this method is called we don't want to go through the browsing context
// because we don't want to change the visibility state of the document, which
// has side effects like firing events to content, unblocking media playback,
// unthrottling timeouts... PresShell activeness has a lot less side effects.
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
if (!docShell) {
return;
}
RefPtr<PresShell> presShell = docShell->GetPresShell();
if (!presShell) {
return;
}
presShell->ActivenessMaybeChanged();
}
NS_IMETHODIMP
BrowserChild::GetMessageManager(ContentFrameMessageManager** aResult) {
RefPtr<ContentFrameMessageManager> mm(mBrowserChildMessageManager);
mm.forget(aResult);
return *aResult ? NS_OK : NS_ERROR_FAILURE;
}
void BrowserChild::SendRequestFocus(bool aCanFocus, CallerType aCallerType) {
nsFocusManager* fm = nsFocusManager::GetFocusManager();
if (!fm) {
return;
}
nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(WebNavigation());
if (!window) {
return;
}
BrowsingContext* focusedBC = fm->GetFocusedBrowsingContext();
if (focusedBC == window->GetBrowsingContext()) {
// BrowsingContext has the focus already, do not request again.
return;
}
PBrowserChild::SendRequestFocus(aCanFocus, aCallerType);
}
NS_IMETHODIMP
BrowserChild::GetTabId(uint64_t* aId) {
*aId = GetTabId();
return NS_OK;
}
NS_IMETHODIMP
BrowserChild::GetChromeOuterWindowID(uint64_t* aId) {
*aId = ChromeOuterWindowID();
return NS_OK;
}
bool BrowserChild::DoSendBlockingMessage(
const nsAString& aMessage, StructuredCloneData& aData,
nsTArray<StructuredCloneData>* aRetVal) {
ClonedMessageData data;
if (!BuildClonedMessageData(aData, data)) {
return false;
}
return SendSyncMessage(PromiseFlatString(aMessage), data, aRetVal);
}
nsresult BrowserChild::DoSendAsyncMessage(const nsAString& aMessage,
StructuredCloneData& aData) {
ClonedMessageData data;
if (!BuildClonedMessageData(aData, data)) {
return NS_ERROR_DOM_DATA_CLONE_ERR;
}
if (!SendAsyncMessage(PromiseFlatString(aMessage), data)) {
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
/* static */
nsTArray<RefPtr<BrowserChild>> BrowserChild::GetAll() {
StaticMutexAutoLock lock(sBrowserChildrenMutex);
if (!sBrowserChildren) {
return {};
}
return ToTArray<nsTArray<RefPtr<BrowserChild>>>(sBrowserChildren->Values());
}
BrowserChild* BrowserChild::GetFrom(PresShell* aPresShell) {
Document* doc = aPresShell->GetDocument();
if (!doc) {
return nullptr;
}
nsCOMPtr<nsIDocShell> docShell(doc->GetDocShell());
return GetFrom(docShell);
}
BrowserChild* BrowserChild::GetFrom(layers::LayersId aLayersId) {
StaticMutexAutoLock lock(sBrowserChildrenMutex);
if (!sBrowserChildren) {
return nullptr;
}
return sBrowserChildren->Get(uint64_t(aLayersId));
}
void BrowserChild::DidComposite(mozilla::layers::TransactionId aTransactionId,
const TimeStamp& aCompositeStart,
const TimeStamp& aCompositeEnd) {
MOZ_ASSERT(mPuppetWidget);
RefPtr<WebRenderLayerManager> lm =
mPuppetWidget->GetWindowRenderer()->AsWebRender();
MOZ_ASSERT(lm);
if (lm) {
lm->DidComposite(aTransactionId, aCompositeStart, aCompositeEnd);
}
}
void BrowserChild::ClearCachedResources() {
MOZ_ASSERT(mPuppetWidget);
RefPtr<WebRenderLayerManager> lm =
mPuppetWidget->GetWindowRenderer()->AsWebRender();
if (lm) {
lm->ClearCachedResources();
}
if (nsCOMPtr<Document> document = GetTopLevelDocument()) {
nsPresContext* presContext = document->GetPresContext();
if (presContext) {
presContext->NotifyPaintStatusReset();
}
}
}
void BrowserChild::SchedulePaint() {
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
if (!docShell) {
return;
}
// We don't use BrowserChildBase::GetPresShell() here because that would
// create a content viewer if one doesn't exist yet. Creating a content viewer
// can cause JS to run, which we want to avoid. nsIDocShell::GetPresShell
// returns null if no content viewer exists yet.
if (RefPtr<PresShell> presShell = docShell->GetPresShell()) {
if (nsIFrame* root = presShell->GetRootFrame()) {
root->SchedulePaint();
}
}
}
void SkipViewTransitionsAfterRenderingReset(Document& aDocument) {
if (RefPtr<ViewTransition> transition = aDocument.GetActiveViewTransition()) {
transition->SkipTransition(SkipTransitionReason::ResetRendering);
}
aDocument.EnumerateSubDocuments([&](Document& aSubDoc) {
SkipViewTransitionsAfterRenderingReset(aSubDoc);
return CallState::Continue;
});
}
void BrowserChild::ReinitRendering() {
MOZ_ASSERT(mLayersId.IsValid());
if (RefPtr<Document> doc = GetTopLevelDocument()) {
SkipViewTransitionsAfterRenderingReset(*doc);
}
// In some cases, like when we create a windowless browser,
// RemoteLayerTreeOwner/BrowserChild is not connected to a compositor.
if (mLayersConnectRequested.isNothing() ||
mLayersConnectRequested == Some(false)) {
return;
}
// Before we establish a new PLayerTransaction, we must connect our layer tree
// id, CompositorBridge, and the widget compositor all together again.
// Normally this happens in BrowserParent before BrowserChild is given
// rendering information.
//
// In this case, we will send a sync message to our BrowserParent, which in
// turn will send a sync message to the Compositor of the widget owning this
// tab. This guarantees the correct association is in place before our
// PLayerTransaction constructor message arrives on the cross-process
// compositor bridge.
CompositorOptions options;
SendEnsureLayersConnected(&options);
mCompositorOptions = Some(options);
bool success = false;
RefPtr<CompositorBridgeChild> cb = CompositorBridgeChild::Get();
if (cb) {
success = CreateRemoteLayerManager(cb);
}
if (!success) {
NS_WARNING("failed to recreate layer manager");
return;
}
mLayersConnected = Some(true);
ImageBridgeChild::IdentifyCompositorTextureHost(mTextureFactoryIdentifier);
gfx::VRManagerChild::IdentifyTextureHost(mTextureFactoryIdentifier);
InitAPZState();
if (nsCOMPtr<Document> doc = GetTopLevelDocument()) {
doc->NotifyLayerManagerRecreated();
}
if (mRenderLayers) {
SchedulePaint();
}
}
void BrowserChild::ReinitRenderingForDeviceReset() {
RefPtr<WebRenderLayerManager> lm =
mPuppetWidget->GetWindowRenderer()->AsWebRender();
if (lm) {
lm->DoDestroy(/* aIsSync */ true);
}
// Proceed with destroying and recreating the layer manager.
ReinitRendering();
}
NS_IMETHODIMP
BrowserChild::OnShowTooltip(int32_t aXCoords, int32_t aYCoords,
const nsAString& aTipText,
const nsAString& aTipDir) {
nsString str(aTipText);
nsString dir(aTipDir);
SendShowTooltip(aXCoords, aYCoords, str, dir);
return NS_OK;
}
NS_IMETHODIMP
BrowserChild::OnHideTooltip() {
SendHideTooltip();
return NS_OK;
}
void BrowserChild::NotifyJankedAnimations(
const nsTArray<uint64_t>& aJankedAnimations) {
MOZ_ASSERT(mPuppetWidget);
RefPtr<WebRenderLayerManager> lm =
mPuppetWidget->GetWindowRenderer()->AsWebRender();
if (lm) {
lm->UpdatePartialPrerenderedAnimations(aJankedAnimations);
}
}
mozilla::ipc::IPCResult BrowserChild::RecvUIResolutionChanged(
const float& aDpi, const int32_t& aRounding, const double& aScale) {
const LayoutDeviceIntSize oldInnerSize = GetInnerSize();
if (aDpi > 0) {
mPuppetWidget->UpdateBackingScaleCache(aDpi, aRounding, aScale);
}
const LayoutDeviceIntSize innerSize = GetInnerSize();
if (mHasValidInnerSize && oldInnerSize != innerSize) {
// See RecvUpdateDimensions for the order of these operations.
nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(WebNavigation());
baseWin->SetPositionAndSize(0, 0, innerSize.width, innerSize.height,
nsIBaseWindow::eRepaint);
const LayoutDeviceIntRect outerRect =
GetOuterRect() + mClientOffset + mChromeOffset;
mPuppetWidget->Resize(outerRect.x, outerRect.y, innerSize.width,
innerSize.height, true);
}
nsCOMPtr<Document> document(GetTopLevelDocument());
RefPtr<nsPresContext> presContext =
document ? document->GetPresContext() : nullptr;
if (presContext) {
presContext->UIResolutionChangedSync();
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvSafeAreaInsetsChanged(
const mozilla::LayoutDeviceIntMargin& aSafeAreaInsets) {
mPuppetWidget->UpdateSafeAreaInsets(aSafeAreaInsets);
LayoutDeviceIntMargin currentSafeAreaInsets;
// aSafeAreaInsets is for current screen. But we have to calculate safe insets
// for content window.
LayoutDeviceIntRect outerRect = GetOuterRect();
RefPtr<Screen> screen = widget::ScreenManager::GetSingleton().ScreenForRect(
RoundedToInt(outerRect / mPuppetWidget->GetDesktopToDeviceScale()));
if (screen) {
LayoutDeviceIntRect windowRect = outerRect + mClientOffset + mChromeOffset;
currentSafeAreaInsets = nsContentUtils::GetWindowSafeAreaInsets(
screen, aSafeAreaInsets, windowRect);
}
if (nsCOMPtr<Document> document = GetTopLevelDocument()) {
if (nsPresContext* presContext = document->GetPresContext()) {
presContext->SetSafeAreaInsets(currentSafeAreaInsets);
}
}
// https://github.com/w3c/csswg-drafts/issues/4670
// Actually we don't set this value on sub document. This behaviour is
// same as Blink that safe area insets isn't set on sub document.
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvAllowScriptsToClose() {
nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(WebNavigation());
if (window) {
nsGlobalWindowOuter::Cast(window)->AllowScriptsToClose();
}
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvReleaseAllPointerCapture() {
PointerEventHandler::ReleaseAllPointerCapture();
return IPC_OK();
}
mozilla::ipc::IPCResult BrowserChild::RecvReleasePointerLock() {
PointerLockManager::Unlock("BrowserChild::RecvReleasePointerLock");
return IPC_OK();
}
PPaymentRequestChild* BrowserChild::AllocPPaymentRequestChild() {
MOZ_CRASH(
"We should never be manually allocating PPaymentRequestChild actors");
return nullptr;
}
bool BrowserChild::DeallocPPaymentRequestChild(PPaymentRequestChild* actor) {
delete actor;
return true;
}
LayoutDeviceIntSize BrowserChild::GetInnerSize() {
return RoundedToInt(mUnscaledInnerSize * mPuppetWidget->GetDefaultScale());
};
Maybe<nsRect> BrowserChild::GetVisibleRect() const {
if (mIsTopLevel) {
// We are conservative about visible rects for top-level browsers to avoid
// artifacts when resizing
return Nothing();
}
return mEffectsInfo.mVisibleRect;
}
Maybe<LayoutDeviceRect>
BrowserChild::GetTopLevelViewportVisibleRectInSelfCoords() const {
if (mIsTopLevel) {
return Nothing();
}
if (!mChildToParentConversionMatrix) {
// We have no way to tell this remote document visible rect right now.
return Nothing();
}
Maybe<LayoutDeviceToLayoutDeviceMatrix4x4> inverse =
mChildToParentConversionMatrix->MaybeInverse();
if (!inverse) {
return Nothing();
}
// Convert the remote document visible rect to the coordinate system of the
// iframe document.
Maybe<LayoutDeviceRect> rect = UntransformBy(
*inverse,
ViewAs<LayoutDevicePixel>(
mTopLevelViewportVisibleRectInBrowserCoords,
PixelCastJustification::ContentProcessIsLayerInUiProcess),
LayoutDeviceRect::MaxIntRect());
if (!rect) {
return Nothing();
}
return rect;
}
LayoutDeviceIntRect BrowserChild::GetOuterRect() {
return RoundedToInt(mUnscaledOuterRect * mPuppetWidget->GetDefaultScale());
}
void BrowserChild::PaintWhileInterruptingJS() {
if (!IPCOpen() || !mPuppetWidget || !mPuppetWidget->HasWindowRenderer()) {
// Don't bother doing anything now. Better to wait until we receive the
// message on the PContent channel.
return;
}
MOZ_DIAGNOSTIC_ASSERT(nsContentUtils::IsSafeToRunScript());
nsAutoScriptBlocker scriptBlocker;
RecvRenderLayers(/* aEnabled = */ true);
}
void BrowserChild::UnloadLayersWhileInterruptingJS() {
if (!IPCOpen() || !mPuppetWidget || !mPuppetWidget->HasWindowRenderer()) {
// Don't bother doing anything now. Better to wait until we receive the
// message on the PContent channel.
return;
}
MOZ_DIAGNOSTIC_ASSERT(nsContentUtils::IsSafeToRunScript());
nsAutoScriptBlocker scriptBlocker;
RecvRenderLayers(/* aEnabled = */ false);
}
nsresult BrowserChild::CanCancelContentJS(
nsIRemoteTab::NavigationType aNavigationType, int32_t aNavigationIndex,
nsIURI* aNavigationURI, int32_t aEpoch, bool* aCanCancel) {
nsresult rv;
*aCanCancel = false;
if (aEpoch <= mCancelContentJSEpoch) {
// The next page loaded before we got here, so we shouldn't try to cancel
// the content JS.
return NS_OK;
}
// If we have session history in the parent we've already performed
// the checks following, so we can return early.
if (mozilla::SessionHistoryInParent()) {
*aCanCancel = true;
return NS_OK;
}
nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
nsCOMPtr<nsISHistory> history;
if (docShell) {
history = nsDocShell::Cast(docShell)->GetSessionHistory()->LegacySHistory();
}
if (!history) {
return NS_ERROR_FAILURE;
}
int32_t current;
rv = history->GetIndex(¤t);
NS_ENSURE_SUCCESS(rv, rv);
if (current == -1) {
// This tab has no history! Just return.
return NS_OK;
}
nsCOMPtr<nsISHEntry> entry;
rv = history->GetEntryAtIndex(current, getter_AddRefs(entry));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIURI> currentURI = entry->GetURI();
if (!net::SchemeIsHttpOrHttps(currentURI) && !currentURI->SchemeIs("file")) {
// Only cancel content JS for http(s) and file URIs. Other URIs are probably
// internal and we should just let them run to completion.
return NS_OK;
}
if (aNavigationType == nsIRemoteTab::NAVIGATE_BACK) {
aNavigationIndex = current - 1;
} else if (aNavigationType == nsIRemoteTab::NAVIGATE_FORWARD) {
aNavigationIndex = current + 1;
} else if (aNavigationType == nsIRemoteTab::NAVIGATE_URL) {
if (!aNavigationURI) {
return NS_ERROR_FAILURE;
}
if (aNavigationURI->SchemeIs("javascript")) {
// "javascript:" URIs don't (necessarily) trigger navigation to a
// different page, so don't allow the current page's JS to terminate.
return NS_OK;
}
// If navigating directly to a URL (e.g. via hitting Enter in the location
// bar), then we can cancel anytime the next URL is different from the
// current, *excluding* the ref ("#").
bool equals;
rv = currentURI->EqualsExceptRef(aNavigationURI, &equals);
NS_ENSURE_SUCCESS(rv, rv);
*aCanCancel = !equals;
return NS_OK;
}
// Note: aNavigationType may also be NAVIGATE_INDEX, in which case we don't
// need to do anything special.
int32_t delta = aNavigationIndex > current ? 1 : -1;
for (int32_t i = current + delta; i != aNavigationIndex + delta; i += delta) {
nsCOMPtr<nsISHEntry> nextEntry;
// If `i` happens to be negative, this call will fail (which is what we
// would want to happen).
rv = history->GetEntryAtIndex(i, getter_AddRefs(nextEntry));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsISHEntry> laterEntry = delta == 1 ? nextEntry : entry;
nsCOMPtr<nsIURI> thisURI = entry->GetURI();
nsCOMPtr<nsIURI> nextURI = nextEntry->GetURI();
// If we changed origin and the load wasn't in a subframe, we know it was
// a full document load, so we can cancel the content JS safely.
if (!laterEntry->GetIsSubFrame()) {
nsAutoCString thisHost;
rv = thisURI->GetPrePath(thisHost);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString nextHost;
rv = nextURI->GetPrePath(nextHost);
NS_ENSURE_SUCCESS(rv, rv);
if (!thisHost.Equals(nextHost)) {
*aCanCancel = true;
return NS_OK;
}
}
entry = nextEntry;
}
return NS_OK;
}
NS_IMETHODIMP BrowserChild::OnStateChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
uint32_t aStateFlags,
nsresult aStatus) {
if (!IPCOpen() || mDestroyed || !mShouldSendWebProgressEventsToParent) {
return NS_OK;
}
// We shouldn't need to notify the parent of redirect state changes, since
// with DocumentChannel that only happens when we switch to the real channel,
// and that's an implementation detail that we can hide.
if (aStateFlags & nsIWebProgressListener::STATE_IS_REDIRECTED_DOCUMENT) {
return NS_OK;
}
// Our OnStateChange call must have provided the nsIDocShell which the source
// comes from. We'll use this to locate the corresponding BrowsingContext in
// the parent process.
nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(aWebProgress);
if (!docShell) {
MOZ_ASSERT_UNREACHABLE("aWebProgress is null or not a nsIDocShell?");
return NS_ERROR_UNEXPECTED;
}
WebProgressData webProgressData;
Maybe<WebProgressStateChangeData> stateChangeData;
RequestData requestData;
MOZ_TRY(PrepareProgressListenerData(aWebProgress, aRequest, webProgressData,
requestData));
RefPtr<BrowsingContext> browsingContext = docShell->GetBrowsingContext();
if (browsingContext->IsTopContent()) {
stateChangeData.emplace();
stateChangeData->isNavigating() = docShell->GetIsNavigating();
stateChangeData->mayEnableCharacterEncodingMenu() =
docShell->GetMayEnableCharacterEncodingMenu();
RefPtr<Document> document = browsingContext->GetExtantDocument();
if (document && aStateFlags & nsIWebProgressListener::STATE_STOP) {
document->GetContentType(stateChangeData->contentType());
document->GetCharacterSet(stateChangeData->charset());
stateChangeData->documentURI() = document->GetDocumentURIObject();
} else {
stateChangeData->contentType().SetIsVoid(true);
stateChangeData->charset().SetIsVoid(true);
}
}
Unused << SendOnStateChange(webProgressData, requestData, aStateFlags,
aStatus, stateChangeData);
return NS_OK;
}
NS_IMETHODIMP BrowserChild::OnProgressChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
int32_t aCurSelfProgress,
int32_t aMaxSelfProgress,
int32_t aCurTotalProgress,
int32_t aMaxTotalProgress) {
if (!IPCOpen() || mDestroyed || !mShouldSendWebProgressEventsToParent) {
return NS_OK;
}
// FIXME: We currently ignore ProgressChange events from out-of-process
// subframes both here and in BrowserParent. We may want to change this
// behaviour in the future.
if (!GetBrowsingContext()->IsTopContent()) {
return NS_OK;
}
// NOTE: ProgressChange notifications delivered here are filtered by
// nsBrowserStatusFilter, which passes meaningless values for all other
// arguments, so they are ignored here.
Unused << SendOnProgressChange(aCurTotalProgress, aMaxTotalProgress);
return NS_OK;
}
NS_IMETHODIMP BrowserChild::OnLocationChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
nsIURI* aLocation,
uint32_t aFlags) {
if (!IPCOpen() || mDestroyed || !mShouldSendWebProgressEventsToParent) {
return NS_OK;
}
nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(aWebProgress);
if (!docShell) {
MOZ_ASSERT_UNREACHABLE("aWebProgress is null or not a nsIDocShell?");
return NS_ERROR_UNEXPECTED;
}
RefPtr<BrowsingContext> browsingContext = docShell->GetBrowsingContext();
RefPtr<Document> document = browsingContext->GetExtantDocument();
if (!document) {
return NS_OK;
}
WebProgressData webProgressData;
RequestData requestData;
MOZ_TRY(PrepareProgressListenerData(aWebProgress, aRequest, webProgressData,
requestData));
Maybe<WebProgressLocationChangeData> locationChangeData;
bool canGoBack = false;
bool canGoBackIgnoringUserInteraction = false;
bool canGoForward = false;
if (!mozilla::SessionHistoryInParent()) {
MOZ_TRY(WebNavigation()->GetCanGoBack(&canGoBack));
MOZ_TRY(WebNavigation()->GetCanGoBackIgnoringUserInteraction(
&canGoBackIgnoringUserInteraction));
MOZ_TRY(WebNavigation()->GetCanGoForward(&canGoForward));
}
if (browsingContext->IsTopContent()) {
MOZ_ASSERT(
browsingContext == GetBrowsingContext(),
"Toplevel content BrowsingContext which isn't GetBrowsingContext()?");
locationChangeData.emplace();
document->GetContentType(locationChangeData->contentType());
locationChangeData->isNavigating() = docShell->GetIsNavigating();
locationChangeData->documentURI() = document->GetDocumentURIObject();
document->GetTitle(locationChangeData->title());
document->GetCharacterSet(locationChangeData->charset());
locationChangeData->mayEnableCharacterEncodingMenu() =
docShell->GetMayEnableCharacterEncodingMenu();
locationChangeData->contentPrincipal() = document->NodePrincipal();
locationChangeData->contentPartitionedPrincipal() =
document->PartitionedPrincipal();
locationChangeData->policyContainer() = document->GetPolicyContainer();
locationChangeData->referrerInfo() = document->ReferrerInfo();
locationChangeData->isSyntheticDocument() = document->IsSyntheticDocument();
if (nsCOMPtr<nsILoadGroup> loadGroup = document->GetDocumentLoadGroup()) {
uint64_t requestContextID = 0;
MOZ_TRY(loadGroup->GetRequestContextID(&requestContextID));
locationChangeData->requestContextID() = Some(requestContextID);
}
#ifdef MOZ_CRASHREPORTER
if (CrashReporter::GetEnabled()) {
nsCOMPtr<nsIURI> annotationURI;
nsresult rv =
NS_MutateURI(aLocation).SetUserPass(""_ns).Finalize(annotationURI);
if (NS_FAILED(rv)) {
// Ignore failures on about: URIs.
annotationURI = aLocation;
}
CrashReporter::RecordAnnotationNSCString(
CrashReporter::Annotation::URL, annotationURI->GetSpecOrDefault());
}
#endif
}
Unused << SendOnLocationChange(
webProgressData, requestData, aLocation, aFlags, canGoBack,
canGoBackIgnoringUserInteraction, canGoForward, locationChangeData);
return NS_OK;
}
NS_IMETHODIMP BrowserChild::OnStatusChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
nsresult aStatus,
const char16_t* aMessage) {
if (!IPCOpen() || mDestroyed || !mShouldSendWebProgressEventsToParent) {
return NS_OK;
}
// NOTE: StatusChange notifications delivered here are filtered by
// nsBrowserStatusFilter, which passes meaningless values for all other
// arguments, so they are ignored here.
Unused << SendOnStatusChange(nsDependentString(aMessage));
return NS_OK;
}
NS_IMETHODIMP BrowserChild::OnSecurityChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
uint32_t aState) {
// Security changes are now handled entirely in the parent process
// so we don't need to worry about forwarding them (and we shouldn't
// be receiving any to forward).
return NS_OK;
}
NS_IMETHODIMP BrowserChild::OnContentBlockingEvent(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
uint32_t aEvent) {
// The OnContentBlockingEvent only happenes in the parent process. It should
// not be seen in the content process.
MOZ_DIAGNOSTIC_ASSERT(
false, "OnContentBlockingEvent should not be seen in content process.");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP BrowserChild::NotifyNavigationFinished() {
Unused << SendNavigationFinished();
return NS_OK;
}
nsresult BrowserChild::PrepareRequestData(nsIRequest* aRequest,
RequestData& aRequestData) {
nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
if (!channel) {
aRequestData.requestURI() = nullptr;
return NS_OK;
}
nsresult rv = channel->GetURI(getter_AddRefs(aRequestData.requestURI()));
NS_ENSURE_SUCCESS(rv, rv);
rv = channel->GetOriginalURI(
getter_AddRefs(aRequestData.originalRequestURI()));
NS_ENSURE_SUCCESS(rv, rv);
rv = channel->GetCanceledReason(aRequestData.canceledReason());
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIClassifiedChannel> classifiedChannel = do_QueryInterface(channel);
if (classifiedChannel) {
rv = classifiedChannel->GetMatchedList(aRequestData.matchedList());
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
nsresult BrowserChild::PrepareProgressListenerData(
nsIWebProgress* aWebProgress, nsIRequest* aRequest,
WebProgressData& aWebProgressData, RequestData& aRequestData) {
nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(aWebProgress);
if (!docShell) {
MOZ_ASSERT_UNREACHABLE("aWebProgress is null or not a nsIDocShell?");
return NS_ERROR_UNEXPECTED;
}
aWebProgressData.browsingContext() = docShell->GetBrowsingContext();
nsresult rv = aWebProgress->GetLoadType(&aWebProgressData.loadType());
NS_ENSURE_SUCCESS(rv, rv);
return PrepareRequestData(aRequest, aRequestData);
}
void BrowserChild::UpdateSessionStore() {
if (mSessionStoreChild) {
mSessionStoreChild->UpdateSessionStore();
}
}
#ifdef XP_WIN
RefPtr<PBrowserChild::IsWindowSupportingProtectedMediaPromise>
BrowserChild::DoesWindowSupportProtectedMedia() {
MOZ_ASSERT(
NS_IsMainThread(),
"Protected media support check should be done on main thread only.");
if (mWindowSupportsProtectedMedia) {
// If we've already checked and have a cached result, resolve with that.
return IsWindowSupportingProtectedMediaPromise::CreateAndResolve(
mWindowSupportsProtectedMedia.value(), __func__);
}
RefPtr<BrowserChild> self = this;
// We chain off the promise rather than passing it directly so we can cache
// the result and use that for future calls.
return SendIsWindowSupportingProtectedMedia(ChromeOuterWindowID())
->Then(
GetCurrentSerialEventTarget(), __func__,
[self](bool isSupported) {
// If a result was cached while this check was inflight, ensure the
// results match.
MOZ_ASSERT_IF(
self->mWindowSupportsProtectedMedia,
self->mWindowSupportsProtectedMedia.value() == isSupported);
// Cache the response as it will not change during the lifetime
// of this object.
self->mWindowSupportsProtectedMedia = Some(isSupported);
return IsWindowSupportingProtectedMediaPromise::CreateAndResolve(
self->mWindowSupportsProtectedMedia.value(), __func__);
},
[](ResponseRejectReason reason) {
return IsWindowSupportingProtectedMediaPromise::CreateAndReject(
reason, __func__);
});
}
#endif
void BrowserChild::NotifyContentBlockingEvent(
uint32_t aEvent, nsIChannel* aChannel, bool aBlocked,
const nsACString& aTrackingOrigin,
const nsTArray<nsCString>& aTrackingFullHashes,
const Maybe<
mozilla::ContentBlockingNotifier::StorageAccessPermissionGrantedReason>&
aReason,
const Maybe<ContentBlockingNotifier::CanvasFingerprinter>&
aCanvasFingerprinter,
const Maybe<bool> aCanvasFingerprinterKnownText) {
if (!IPCOpen()) {
return;
}
RequestData requestData;
if (NS_SUCCEEDED(PrepareRequestData(aChannel, requestData))) {
Unused << SendNotifyContentBlockingEvent(
aEvent, requestData, aBlocked, PromiseFlatCString(aTrackingOrigin),
aTrackingFullHashes, aReason, aCanvasFingerprinter,
aCanvasFingerprinterKnownText);
}
}
NS_IMETHODIMP
BrowserChild::ContentTransformsReceived(JSContext* aCx,
dom::Promise** aPromise) {
auto* globalObject = xpc::CurrentNativeGlobal(aCx);
ErrorResult rv;
if (mChildToParentConversionMatrix) {
// Already received content transforms
RefPtr<Promise> promise =
Promise::CreateResolvedWithUndefined(globalObject, rv);
promise.forget(aPromise);
return rv.StealNSResult();
}
if (!mContentTransformPromise) {
mContentTransformPromise = Promise::Create(globalObject, rv);
}
MOZ_ASSERT(globalObject == mContentTransformPromise->GetGlobalObject());
NS_IF_ADDREF(*aPromise = mContentTransformPromise);
return rv.StealNSResult();
}
already_AddRefed<nsIDragSession> BrowserChild::GetDragSession() {
return RefPtr(mDragSession).forget();
}
void BrowserChild::SetDragSession(nsIDragSession* aSession) {
mDragSession = aSession;
}
LazyLogModule gPointerRawUpdateEventListenersLog(
"PointerRawUpdateEventListeners");
void BrowserChild::OnPointerRawUpdateEventListenerAdded(
const nsPIDOMWindowInner* aWindow) {
mPointerRawUpdateWindowCount++;
MOZ_LOG(gPointerRawUpdateEventListenersLog, LogLevel::Info,
("Added for %p (total: %u)", aWindow, mPointerRawUpdateWindowCount));
}
void BrowserChild::OnPointerRawUpdateEventListenerRemoved(
const nsPIDOMWindowInner* aWindow) {
MOZ_ASSERT(mPointerRawUpdateWindowCount);
if (MOZ_LIKELY(mPointerRawUpdateWindowCount)) {
mPointerRawUpdateWindowCount--;
}
MOZ_LOG(gPointerRawUpdateEventListenersLog, LogLevel::Info,
("Removed for %p (remaining: %u)", aWindow,
mPointerRawUpdateWindowCount));
}
BrowserChildMessageManager::BrowserChildMessageManager(
BrowserChild* aBrowserChild)
: ContentFrameMessageManager(new nsFrameMessageManager(aBrowserChild)),
mBrowserChild(aBrowserChild) {}
BrowserChildMessageManager::~BrowserChildMessageManager() = default;
NS_IMPL_CYCLE_COLLECTION_CLASS(BrowserChildMessageManager)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(BrowserChildMessageManager,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mMessageManager);
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBrowserChild);
NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(BrowserChildMessageManager,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMessageManager)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBrowserChild)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(BrowserChildMessageManager)
NS_INTERFACE_MAP_ENTRY(nsIMessageSender)
NS_INTERFACE_MAP_ENTRY_CONCRETE(ContentFrameMessageManager)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
NS_IMPL_ADDREF_INHERITED(BrowserChildMessageManager, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(BrowserChildMessageManager, DOMEventTargetHelper)
JSObject* BrowserChildMessageManager::WrapObject(
JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
return ContentFrameMessageManager_Binding::Wrap(aCx, this, aGivenProto);
}
void BrowserChildMessageManager::MarkForCC() {
if (mBrowserChild) {
mBrowserChild->MarkScopesForCC();
}
EventListenerManager* elm = GetExistingListenerManager();
if (elm) {
elm->MarkForCC();
}
MessageManagerGlobal::MarkForCC();
}
Nullable<WindowProxyHolder> BrowserChildMessageManager::GetContent(
ErrorResult& aError) {
nsCOMPtr<nsIDocShell> docShell = GetDocShell(aError);
if (!docShell) {
return nullptr;
}
return WindowProxyHolder(docShell->GetBrowsingContext());
}
already_AddRefed<nsIDocShell> BrowserChildMessageManager::GetDocShell(
ErrorResult& aError) {
if (!mBrowserChild) {
aError.Throw(NS_ERROR_NULL_POINTER);
return nullptr;
}
nsCOMPtr<nsIDocShell> window =
do_GetInterface(mBrowserChild->WebNavigation());
return window.forget();
}
already_AddRefed<nsIEventTarget>
BrowserChildMessageManager::GetTabEventTarget() {
return do_AddRef(GetMainThreadSerialEventTarget());
}
nsresult BrowserChildMessageManager::Dispatch(
already_AddRefed<nsIRunnable>&& aRunnable) const {
return SchedulerGroup::Dispatch(std::move(aRunnable));
}
|