1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803
|
/* -*- 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 "nsGlobalWindowInner.h"
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdint>
#include <new>
#include <type_traits>
#include <utility>
#include "AudioChannelService.h"
#include "AutoplayPolicy.h"
#include "Crypto.h"
#include "MainThreadUtils.h"
#include "Navigator.h"
#include "PaintWorkletImpl.h"
#include "SessionStorageCache.h"
#include "Units.h"
#include "VRManagerChild.h"
#include "WindowDestroyedEvent.h"
#include "WindowNamedPropertiesHandler.h"
#include "js/ComparisonOperators.h"
#include "js/CompilationAndEvaluation.h"
#include "js/CompileOptions.h"
#include "js/Id.h"
#include "js/PropertyAndElement.h" // JS_DefineProperty, JS_GetProperty
#include "js/PropertyDescriptor.h"
#include "js/RealmOptions.h"
#include "js/RootingAPI.h"
#include "js/TypeDecls.h"
#include "js/Value.h"
#include "js/Warnings.h"
#include "js/friend/PerformanceHint.h"
#include "js/loader/LoadedScript.h"
#include "js/shadow/String.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "mozIDOMWindow.h"
#include "moz_external_vr.h"
#include "mozilla/AlreadyAddRefed.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/ArrayIterator.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/BaseProfilerMarkersPrerequisites.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/BounceTrackingStorageObserver.h"
#include "mozilla/CallState.h"
#include "mozilla/Components.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/DOMEventTargetHelper.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/EventQueue.h"
#include "mozilla/ExtensionPolicyService.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/FlushType.h"
#include "mozilla/Likely.h"
#include "mozilla/LinkedList.h"
#include "mozilla/Logging.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MacroForEach.h"
#include "mozilla/Maybe.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/PermissionDelegateHandler.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/ProcessHangMonitor.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Result.h"
#include "mozilla/ScrollContainerFrame.h"
#include "mozilla/ScrollTypes.h"
#include "mozilla/SizeOfState.h"
#include "mozilla/Span.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "mozilla/Sprintf.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_docshell.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_extensions.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/StorageAccess.h"
#include "mozilla/StoragePrincipalHelper.h"
#include "mozilla/TelemetryHistogramEnums.h"
#include "mozilla/ThrottledEventQueue.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/AudioContext.h"
#include "mozilla/dom/AutoEntryScript.h"
#include "mozilla/dom/BarProps.h"
#include "mozilla/dom/BindingDeclarations.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/CSPEvalChecker.h"
#include "mozilla/dom/CallbackDebuggerNotification.h"
#include "mozilla/dom/ChromeMessageBroadcaster.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/ClientManager.h"
#include "mozilla/dom/ClientSource.h"
#include "mozilla/dom/ClientState.h"
#include "mozilla/dom/ClientsBinding.h"
#include "mozilla/dom/CloseWatcher.h"
#include "mozilla/dom/CloseWatcherManager.h"
#include "mozilla/dom/Console.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentFrameMessageManager.h"
#include "mozilla/dom/ContentMediaController.h"
#include "mozilla/dom/CookieStore.h"
#include "mozilla/dom/Credential.h"
#include "mozilla/dom/CustomElementRegistry.h"
#include "mozilla/dom/DebuggerNotification.h"
#include "mozilla/dom/DebuggerNotificationBinding.h"
#include "mozilla/dom/DebuggerNotificationManager.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/EventTarget.h"
#include "mozilla/dom/External.h"
#include "mozilla/dom/Fetch.h"
#include "mozilla/dom/Gamepad.h"
#include "mozilla/dom/GamepadHandle.h"
#include "mozilla/dom/GamepadManager.h"
#include "mozilla/dom/HashChangeEvent.h"
#include "mozilla/dom/HashChangeEventBinding.h"
#include "mozilla/dom/IDBFactory.h"
#include "mozilla/dom/IdleRequest.h"
#include "mozilla/dom/ImageBitmap.h"
#include "mozilla/dom/ImageBitmapSource.h"
#include "mozilla/dom/InstallTriggerBinding.h"
#include "mozilla/dom/IntlUtils.h"
#include "mozilla/dom/JSExecutionUtils.h" // mozilla::dom::Compile, mozilla::dom::EvaluationExceptionToNSResult
#include "mozilla/dom/LSObject.h"
#include "mozilla/dom/LocalStorage.h"
#include "mozilla/dom/LocalStorageCommon.h"
#include "mozilla/dom/Location.h"
#include "mozilla/dom/MediaDevices.h"
#include "mozilla/dom/MediaKeys.h"
#include "mozilla/dom/Navigation.h"
#include "mozilla/dom/NavigatorBinding.h"
#include "mozilla/dom/Nullable.h"
#include "mozilla/dom/PartitionedLocalStorage.h"
#include "mozilla/dom/Performance.h"
#include "mozilla/dom/PerformanceMainThread.h"
#include "mozilla/dom/PolicyContainer.h"
#include "mozilla/dom/PopStateEvent.h"
#include "mozilla/dom/PopStateEventBinding.h"
#include "mozilla/dom/PopupBlocker.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/ScriptLoader.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/ServiceWorker.h"
#include "mozilla/dom/ServiceWorkerDescriptor.h"
#include "mozilla/dom/ServiceWorkerRegistration.h"
#include "mozilla/dom/SessionStorageManager.h"
#include "mozilla/dom/SharedWorker.h"
#include "mozilla/dom/Storage.h"
#include "mozilla/dom/StorageEvent.h"
#include "mozilla/dom/StorageEventBinding.h"
#include "mozilla/dom/StorageNotifierService.h"
#include "mozilla/dom/StorageUtils.h"
#include "mozilla/dom/TabMessageTypes.h"
#include "mozilla/dom/Timeout.h"
#include "mozilla/dom/TimeoutHandler.h"
#include "mozilla/dom/TimeoutManager.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/TrustedTypePolicyFactory.h"
#include "mozilla/dom/TrustedTypeUtils.h"
#include "mozilla/dom/TrustedTypesConstants.h"
#include "mozilla/dom/VRDisplay.h"
#include "mozilla/dom/VRDisplayEvent.h"
#include "mozilla/dom/VRDisplayEventBinding.h"
#include "mozilla/dom/VREventObserver.h"
#include "mozilla/dom/VisualViewport.h"
#include "mozilla/dom/WebIDLGlobalNameHash.h"
#include "mozilla/dom/WebIdentityHandler.h"
#include "mozilla/dom/WebTaskSchedulerMainThread.h"
#include "mozilla/dom/WindowBinding.h"
#include "mozilla/dom/WindowContext.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/WindowOrWorkerGlobalScopeBinding.h"
#include "mozilla/dom/WindowProxyHolder.h"
#include "mozilla/dom/WorkerCommon.h"
#include "mozilla/dom/Worklet.h"
#include "mozilla/dom/XRPermissionRequest.h"
#include "mozilla/dom/cache/CacheStorage.h"
#include "mozilla/dom/cache/Types.h"
#include "mozilla/extensions/WebExtensionPolicy.h"
#include "mozilla/fallible.h"
#include "mozilla/gfx/BasePoint.h"
#include "mozilla/gfx/BaseRect.h"
#include "mozilla/gfx/BaseSize.h"
#include "mozilla/gfx/Rect.h"
#include "mozilla/gfx/Types.h"
#include "mozilla/glean/DomMetrics.h"
#include "mozilla/glean/bindings/Glean.h"
#include "mozilla/glean/bindings/GleanPings.h"
#include "mozilla/intl/LocaleService.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/net/CookieJarSettings.h"
#include "nsAtom.h"
#include "nsBaseHashtable.h"
#include "nsCCUncollectableMarker.h"
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include "nsCRTGlue.h"
#include "nsCanvasFrame.h"
#include "nsCharTraits.h"
#include "nsCheapSets.h"
#include "nsContentUtils.h"
#include "nsCoord.h"
#include "nsCycleCollectionNoteChild.h"
#include "nsCycleCollectionTraversalCallback.h"
#include "nsDOMNavigationTiming.h"
#include "nsDebug.h"
#include "nsDeviceContext.h"
#include "nsDocShell.h"
#include "nsFocusManager.h"
#include "nsFrameMessageManager.h"
#include "nsGkAtoms.h"
#include "nsGlobalWindowOuter.h"
#include "nsHashKeys.h"
#include "nsHistory.h"
#include "nsIAddonPolicyService.h"
#include "nsIArray.h"
#include "nsIBaseWindow.h"
#include "nsIBrowserChild.h"
#include "nsICancelableRunnable.h"
#include "nsIChannel.h"
#include "nsIClipboard.h"
#include "nsIContentSecurityPolicy.h"
#include "nsIControllers.h"
#include "nsICookieJarSettings.h"
#include "nsICookieService.h"
#include "nsID.h"
#include "nsIDOMStorageManager.h"
#include "nsIDOMXULControlElement.h"
#include "nsIDeviceSensors.h"
#include "nsIDocShell.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocShellTreeOwner.h"
#include "nsIDocumentLoader.h"
#include "nsIDragService.h"
#include "nsIFocusManager.h"
#include "nsIFrame.h"
#include "nsIGlobalObject.h"
#include "nsIIOService.h"
#include "nsIIdleRunnable.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsILoadContext.h"
#include "nsILoadGroup.h"
#include "nsILoadInfo.h"
#include "nsINamed.h"
#include "nsINode.h"
#include "nsIObserver.h"
#include "nsIObserverService.h"
#include "nsIPermission.h"
#include "nsIPermissionManager.h"
#include "nsIPrefBranch.h"
#include "nsIPrincipal.h"
#include "nsIPrompt.h"
#include "nsIRunnable.h"
#include "nsIScreen.h"
#include "nsIScreenManager.h"
#include "nsIScriptContext.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsISerialEventTarget.h"
#include "nsISimpleEnumerator.h"
#include "nsISizeOfEventTarget.h"
#include "nsISlowScriptDebug.h"
#include "nsISupportsUtils.h"
#include "nsIThread.h"
#include "nsITimedChannel.h"
#include "nsIURI.h"
#include "nsIWeakReference.h"
#include "nsIWebBrowserChrome.h"
#include "nsIWebNavigation.h"
#include "nsIWebProgressListener.h"
#include "nsIWidget.h"
#include "nsIWidgetListener.h"
#include "nsIXULRuntime.h"
#include "nsJSPrincipals.h"
#include "nsJSUtils.h"
#include "nsLayoutStatics.h"
#include "nsLiteralString.h"
#include "nsNetUtil.h"
#include "nsPIDOMWindow.h"
#include "nsPIDOMWindowInlines.h"
#include "nsPIWindowRoot.h"
#include "nsPoint.h"
#include "nsPresContext.h"
#include "nsQueryObject.h"
#include "nsSandboxFlags.h"
#include "nsScreen.h"
#include "nsServiceManagerUtils.h"
#include "nsString.h"
#include "nsStringFlags.h"
#include "nsStringFwd.h"
#include "nsTArray.h"
#include "nsTLiteralString.h"
#include "nsTObserverArray.h"
#include "nsTStringRepr.h"
#include "nsThreadUtils.h"
#include "nsWeakReference.h"
#include "nsWindowMemoryReporter.h"
#include "nsWindowSizes.h"
#include "nsWrapperCache.h"
#include "nsWrapperCacheInlines.h"
#include "nsXULAppAPI.h"
#include "nsrootidl.h"
#include "prclist.h"
#include "prtypes.h"
#include "xpcprivate.h"
#include "xpcpublic.h"
#ifdef NS_PRINTING
# include "nsIPrintSettings.h"
#endif
#ifdef MOZ_WEBSPEECH
# include "mozilla/dom/SpeechSynthesis.h"
#endif
#ifdef ANDROID
# include <android/log.h>
#endif
#ifdef XP_WIN
# include <process.h>
# include "mozilla/Debug.h"
# define getpid _getpid
#else
# include <unistd.h> // for getpid()
#endif
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::dom::ipc;
using mozilla::TimeDuration;
using mozilla::TimeStamp;
using mozilla::dom::GamepadHandle;
using mozilla::dom::cache::CacheStorage;
#define FORWARD_TO_OUTER(method, args, err_rval) \
PR_BEGIN_MACRO \
RefPtr<nsGlobalWindowOuter> outer = GetOuterWindowInternal(); \
if (!HasActiveDocument()) { \
NS_WARNING(outer ? "Inner window does not have active document." \
: "No outer window available!"); \
return err_rval; \
} \
return outer->method args; \
PR_END_MACRO
static nsGlobalWindowOuter* GetOuterWindowForForwarding(
nsGlobalWindowInner* aInner, ErrorResult& aError) {
nsGlobalWindowOuter* outer = aInner->GetOuterWindowInternal();
if (MOZ_LIKELY(aInner->HasActiveDocument())) {
return outer;
}
if (!outer) {
NS_WARNING("No outer window available!");
aError.Throw(NS_ERROR_NOT_INITIALIZED);
} else {
aError.Throw(NS_ERROR_XPC_SECURITY_MANAGER_VETO);
}
return nullptr;
}
#define FORWARD_TO_OUTER_OR_THROW(method, args, rv, err_rval) \
PR_BEGIN_MACRO \
RefPtr<nsGlobalWindowOuter> outer = GetOuterWindowForForwarding(this, rv); \
if (MOZ_LIKELY(outer)) { \
return outer->method args; \
} \
return err_rval; \
PR_END_MACRO
#define FORWARD_TO_OUTER_VOID(method, args) \
PR_BEGIN_MACRO \
RefPtr<nsGlobalWindowOuter> outer = GetOuterWindowInternal(); \
if (!HasActiveDocument()) { \
NS_WARNING(outer ? "Inner window does not have active document." \
: "No outer window available!"); \
return; \
} \
outer->method args; \
return; \
PR_END_MACRO
#define ENSURE_ACTIVE_DOCUMENT(errorresult, err_rval) \
PR_BEGIN_MACRO \
if (MOZ_UNLIKELY(!HasActiveDocument())) { \
aError.Throw(NS_ERROR_XPC_SECURITY_MANAGER_VETO); \
return err_rval; \
} \
PR_END_MACRO
#define DOM_TOUCH_LISTENER_ADDED "dom-touch-listener-added"
#define MEMORY_PRESSURE_OBSERVER_TOPIC "memory-pressure"
#define PERMISSION_CHANGED_TOPIC "perm-changed"
static LazyLogModule gDOMLeakPRLogInner("DOMLeakInner");
extern mozilla::LazyLogModule gTimeoutLog;
#ifdef DEBUG
static LazyLogModule gDocShellAndDOMWindowLeakLogging(
"DocShellAndDOMWindowLeak");
#endif
static FILE* gDumpFile = nullptr;
nsGlobalWindowInner::InnerWindowByIdTable*
nsGlobalWindowInner::sInnerWindowsById = nullptr;
bool nsGlobalWindowInner::sDragServiceDisabled = false;
bool nsGlobalWindowInner::sMouseDown = false;
/**
* An indirect observer object that means we don't have to implement nsIObserver
* on nsGlobalWindow, where any script could see it.
*/
class nsGlobalWindowObserver final : public nsIObserver,
public nsIInterfaceRequestor,
public StorageNotificationObserver {
public:
explicit nsGlobalWindowObserver(nsGlobalWindowInner* aWindow)
: mWindow(aWindow) {}
NS_DECL_ISUPPORTS
NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) override {
if (!mWindow) return NS_OK;
return mWindow->Observe(aSubject, aTopic, aData);
}
void Forget() { mWindow = nullptr; }
NS_IMETHOD GetInterface(const nsIID& aIID, void** aResult) override {
if (mWindow && aIID.Equals(NS_GET_IID(nsIDOMWindow)) && mWindow) {
return mWindow->QueryInterface(aIID, aResult);
}
return NS_NOINTERFACE;
}
void ObserveStorageNotification(StorageEvent* aEvent,
const char16_t* aStorageType,
bool aPrivateBrowsing) override {
if (mWindow) {
mWindow->ObserveStorageNotification(aEvent, aStorageType,
aPrivateBrowsing);
}
}
nsIPrincipal* GetEffectiveCookiePrincipal() const override {
return mWindow ? mWindow->GetEffectiveCookiePrincipal() : nullptr;
}
nsIPrincipal* GetEffectiveStoragePrincipal() const override {
return mWindow ? mWindow->GetEffectiveStoragePrincipal() : nullptr;
}
bool IsPrivateBrowsing() const override {
return mWindow ? mWindow->IsPrivateBrowsing() : false;
}
nsIEventTarget* GetEventTarget() const override {
return mWindow ? mWindow->SerialEventTarget() : nullptr;
}
private:
~nsGlobalWindowObserver() = default;
// This reference is non-owning and safe because it's cleared by
// nsGlobalWindowInner::FreeInnerObjects().
nsGlobalWindowInner* MOZ_NON_OWNING_REF mWindow;
};
NS_IMPL_ISUPPORTS(nsGlobalWindowObserver, nsIObserver, nsIInterfaceRequestor)
class IdleRequestExecutor;
class IdleRequestExecutorTimeoutHandler final : public TimeoutHandler {
public:
explicit IdleRequestExecutorTimeoutHandler(IdleRequestExecutor* aExecutor)
: mExecutor(aExecutor) {}
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(IdleRequestExecutorTimeoutHandler)
bool Call(const char* /* unused */) override;
private:
~IdleRequestExecutorTimeoutHandler() override = default;
RefPtr<IdleRequestExecutor> mExecutor;
};
NS_IMPL_CYCLE_COLLECTION(IdleRequestExecutorTimeoutHandler, mExecutor)
NS_IMPL_CYCLE_COLLECTING_ADDREF(IdleRequestExecutorTimeoutHandler)
NS_IMPL_CYCLE_COLLECTING_RELEASE(IdleRequestExecutorTimeoutHandler)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IdleRequestExecutorTimeoutHandler)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
class IdleRequestExecutor final : public nsIRunnable,
public nsICancelableRunnable,
public nsINamed,
public nsIIdleRunnable {
public:
explicit IdleRequestExecutor(nsGlobalWindowInner* aWindow)
: mDispatched(false), mDeadline(TimeStamp::Now()), mWindow(aWindow) {
MOZ_DIAGNOSTIC_ASSERT(mWindow);
mIdlePeriodLimit = {mDeadline, mWindow->LastIdleRequestHandle()};
mDelayedExecutorDispatcher = new IdleRequestExecutorTimeoutHandler(this);
}
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(IdleRequestExecutor, nsIRunnable)
NS_DECL_NSIRUNNABLE
NS_DECL_NSINAMED
nsresult Cancel() override;
void SetDeadline(TimeStamp aDeadline) override;
bool IsCancelled() const { return !mWindow || mWindow->IsDying(); }
// Checks if aRequest shouldn't execute in the current idle period
// since it has been queued from a chained call to
// requestIdleCallback from within a running idle callback.
bool IneligibleForCurrentIdlePeriod(IdleRequest* aRequest) const {
return aRequest->Handle() >= mIdlePeriodLimit.mLastRequestIdInIdlePeriod &&
TimeStamp::Now() <= mIdlePeriodLimit.mEndOfIdlePeriod;
}
void MaybeUpdateIdlePeriodLimit();
// Maybe dispatch the IdleRequestExecutor. MabyeDispatch will
// schedule a delayed dispatch if the associated window is in the
// background or if given a time to wait until dispatching.
void MaybeDispatch(TimeStamp aDelayUntil = TimeStamp());
void ScheduleDispatch();
private:
struct IdlePeriodLimit {
TimeStamp mEndOfIdlePeriod;
uint32_t mLastRequestIdInIdlePeriod;
};
void DelayedDispatch(uint32_t aDelay);
~IdleRequestExecutor() override = default;
bool mDispatched;
TimeStamp mDeadline;
IdlePeriodLimit mIdlePeriodLimit;
RefPtr<nsGlobalWindowInner> mWindow;
// The timeout handler responsible for dispatching this executor in
// the case of immediate dispatch to the idle queue isn't
// desirable. This is used if we've dispatched all idle callbacks
// that are allowed to run in the current idle period, or if the
// associated window is currently in the background.
RefPtr<TimeoutHandler> mDelayedExecutorDispatcher;
// If not Nothing() then this value is the handle to the currently
// scheduled delayed executor dispatcher. This is needed to be able
// to cancel the timeout handler in case of the executor being
// cancelled.
Maybe<int32_t> mDelayedExecutorHandle;
};
NS_IMPL_CYCLE_COLLECTION(IdleRequestExecutor, mWindow,
mDelayedExecutorDispatcher)
NS_IMPL_CYCLE_COLLECTING_ADDREF(IdleRequestExecutor)
NS_IMPL_CYCLE_COLLECTING_RELEASE(IdleRequestExecutor)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IdleRequestExecutor)
NS_INTERFACE_MAP_ENTRY(nsIRunnable)
NS_INTERFACE_MAP_ENTRY(nsICancelableRunnable)
NS_INTERFACE_MAP_ENTRY(nsINamed)
NS_INTERFACE_MAP_ENTRY(nsIIdleRunnable)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRunnable)
NS_INTERFACE_MAP_END
NS_IMETHODIMP
IdleRequestExecutor::GetName(nsACString& aName) {
aName.AssignLiteral("IdleRequestExecutor");
return NS_OK;
}
// MOZ_CAN_RUN_SCRIPT_BOUNDARY until nsIRunnable::Run is MOZ_CAN_RUN_SCRIPT.
// See bug 1535398.
MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP IdleRequestExecutor::Run() {
MOZ_ASSERT(NS_IsMainThread());
mDispatched = false;
if (mWindow) {
RefPtr<nsGlobalWindowInner> window(mWindow);
window->ExecuteIdleRequest(mDeadline);
}
return NS_OK;
}
nsresult IdleRequestExecutor::Cancel() {
MOZ_ASSERT(NS_IsMainThread());
if (mDelayedExecutorHandle && mWindow) {
mWindow->GetTimeoutManager()->ClearTimeout(
mDelayedExecutorHandle.value(), Timeout::Reason::eIdleCallbackTimeout);
}
mWindow = nullptr;
return NS_OK;
}
void IdleRequestExecutor::SetDeadline(TimeStamp aDeadline) {
MOZ_ASSERT(NS_IsMainThread());
if (!mWindow) {
return;
}
mDeadline = aDeadline;
}
void IdleRequestExecutor::MaybeUpdateIdlePeriodLimit() {
if (TimeStamp::Now() > mIdlePeriodLimit.mEndOfIdlePeriod) {
mIdlePeriodLimit = {mDeadline, mWindow->LastIdleRequestHandle()};
}
}
void IdleRequestExecutor::MaybeDispatch(TimeStamp aDelayUntil) {
// If we've already dispatched the executor we don't want to do it
// again. Also, if we've called IdleRequestExecutor::Cancel mWindow
// will be null, which indicates that we shouldn't dispatch this
// executor either.
if (mDispatched || IsCancelled()) {
return;
}
mDispatched = true;
nsPIDOMWindowOuter* outer = mWindow->GetOuterWindow();
if (outer && outer->IsBackground()) {
// Set a timeout handler with a timeout of 0 ms to throttle idle
// callback requests coming from a backround window using
// background timeout throttling.
DelayedDispatch(0);
return;
}
TimeStamp now = TimeStamp::Now();
if (!aDelayUntil || aDelayUntil < now) {
ScheduleDispatch();
return;
}
TimeDuration delay = aDelayUntil - now;
DelayedDispatch(static_cast<uint32_t>(delay.ToMilliseconds()));
}
void IdleRequestExecutor::ScheduleDispatch() {
MOZ_ASSERT(mWindow);
mDelayedExecutorHandle = Nothing();
RefPtr<IdleRequestExecutor> request = this;
NS_DispatchToCurrentThreadQueue(request.forget(), EventQueuePriority::Idle);
}
void IdleRequestExecutor::DelayedDispatch(uint32_t aDelay) {
MOZ_ASSERT(mWindow);
MOZ_ASSERT(mDelayedExecutorHandle.isNothing());
int32_t handle;
mWindow->GetTimeoutManager()->SetTimeout(
mDelayedExecutorDispatcher, aDelay, false,
Timeout::Reason::eIdleCallbackTimeout, &handle);
mDelayedExecutorHandle = Some(handle);
}
bool IdleRequestExecutorTimeoutHandler::Call(const char* /* unused */) {
if (!mExecutor->IsCancelled()) {
mExecutor->ScheduleDispatch();
}
return true;
}
void nsGlobalWindowInner::ScheduleIdleRequestDispatch() {
AssertIsOnMainThread();
if (!mIdleRequestExecutor) {
mIdleRequestExecutor = new IdleRequestExecutor(this);
}
mIdleRequestExecutor->MaybeDispatch();
}
void nsGlobalWindowInner::SuspendIdleRequests() {
if (mIdleRequestExecutor) {
mIdleRequestExecutor->Cancel();
mIdleRequestExecutor = nullptr;
}
}
void nsGlobalWindowInner::ResumeIdleRequests() {
MOZ_ASSERT(!mIdleRequestExecutor);
ScheduleIdleRequestDispatch();
}
void nsGlobalWindowInner::RemoveIdleCallback(
mozilla::dom::IdleRequest* aRequest) {
AssertIsOnMainThread();
if (aRequest->HasTimeout()) {
mTimeoutManager->ClearTimeout(aRequest->GetTimeoutHandle(),
Timeout::Reason::eIdleCallbackTimeout);
}
aRequest->removeFrom(mIdleRequestCallbacks);
}
void nsGlobalWindowInner::RunIdleRequest(IdleRequest* aRequest,
DOMHighResTimeStamp aDeadline,
bool aDidTimeout) {
AssertIsOnMainThread();
// XXXbz Do we still need this RefPtr? MOZ_CAN_RUN_SCRIPT should
// guarantee that caller is holding a strong ref on the stack.
RefPtr<IdleRequest> request(aRequest);
RemoveIdleCallback(request);
request->IdleRun(this, aDeadline, aDidTimeout);
}
void nsGlobalWindowInner::ExecuteIdleRequest(TimeStamp aDeadline) {
AssertIsOnMainThread();
RefPtr<IdleRequest> request = mIdleRequestCallbacks.getFirst();
if (!request) {
// There are no more idle requests, so stop scheduling idle
// request callbacks.
return;
}
// If the request that we're trying to execute has been queued
// during the current idle period, then dispatch it again at the end
// of the idle period.
if (mIdleRequestExecutor->IneligibleForCurrentIdlePeriod(request)) {
mIdleRequestExecutor->MaybeDispatch(aDeadline);
return;
}
DOMHighResTimeStamp deadline = 0.0;
if (Performance* perf = GetPerformance()) {
deadline = perf->GetDOMTiming()->TimeStampToDOMHighRes(aDeadline);
}
mIdleRequestExecutor->MaybeUpdateIdlePeriodLimit();
RunIdleRequest(request, deadline, false);
// Running the idle callback could've suspended the window, in which
// case mIdleRequestExecutor will be null.
if (mIdleRequestExecutor) {
mIdleRequestExecutor->MaybeDispatch();
}
}
class IdleRequestTimeoutHandler final : public TimeoutHandler {
public:
IdleRequestTimeoutHandler(JSContext* aCx, IdleRequest* aIdleRequest,
nsPIDOMWindowInner* aWindow)
: TimeoutHandler(aCx), mIdleRequest(aIdleRequest), mWindow(aWindow) {}
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(IdleRequestTimeoutHandler)
MOZ_CAN_RUN_SCRIPT bool Call(const char* /* unused */) override {
RefPtr<nsGlobalWindowInner> window(nsGlobalWindowInner::Cast(mWindow));
RefPtr<IdleRequest> request(mIdleRequest);
window->RunIdleRequest(request, 0.0, true);
return true;
}
private:
~IdleRequestTimeoutHandler() override = default;
RefPtr<IdleRequest> mIdleRequest;
nsCOMPtr<nsPIDOMWindowInner> mWindow;
};
NS_IMPL_CYCLE_COLLECTION(IdleRequestTimeoutHandler, mIdleRequest, mWindow)
NS_IMPL_CYCLE_COLLECTING_ADDREF(IdleRequestTimeoutHandler)
NS_IMPL_CYCLE_COLLECTING_RELEASE(IdleRequestTimeoutHandler)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IdleRequestTimeoutHandler)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
uint32_t nsGlobalWindowInner::RequestIdleCallback(
JSContext* aCx, IdleRequestCallback& aCallback,
const IdleRequestOptions& aOptions, ErrorResult& aError) {
AssertIsOnMainThread();
if (IsDying()) {
return 0;
}
uint32_t handle = mIdleRequestCallbackCounter++;
RefPtr<IdleRequest> request = new IdleRequest(&aCallback, handle);
if (aOptions.mTimeout.WasPassed()) {
int32_t timeoutHandle;
RefPtr<TimeoutHandler> handler(
new IdleRequestTimeoutHandler(aCx, request, this));
nsresult rv = mTimeoutManager->SetTimeout(
handler, aOptions.mTimeout.Value(), false,
Timeout::Reason::eIdleCallbackTimeout, &timeoutHandle);
if (NS_WARN_IF(NS_FAILED(rv))) {
return 0;
}
request->SetTimeoutHandle(timeoutHandle);
}
mIdleRequestCallbacks.insertBack(request);
if (!IsSuspended()) {
ScheduleIdleRequestDispatch();
}
return handle;
}
void nsGlobalWindowInner::CancelIdleCallback(uint32_t aHandle) {
for (IdleRequest* r : mIdleRequestCallbacks) {
if (r->Handle() == aHandle) {
RemoveIdleCallback(r);
break;
}
}
}
void nsGlobalWindowInner::DisableIdleCallbackRequests() {
if (mIdleRequestExecutor) {
mIdleRequestExecutor->Cancel();
mIdleRequestExecutor = nullptr;
}
while (!mIdleRequestCallbacks.isEmpty()) {
RefPtr<IdleRequest> request = mIdleRequestCallbacks.getFirst();
RemoveIdleCallback(request);
}
}
bool nsGlobalWindowInner::IsBackgroundInternal() const {
return !mOuterWindow || mOuterWindow->IsBackground();
}
class PromiseDocumentFlushedResolver final {
public:
PromiseDocumentFlushedResolver(Promise* aPromise,
PromiseDocumentFlushedCallback& aCallback)
: mPromise(aPromise), mCallback(&aCallback) {}
virtual ~PromiseDocumentFlushedResolver() = default;
void Call() {
nsMutationGuard guard;
ErrorResult error;
JS::Rooted<JS::Value> returnVal(RootingCx());
mCallback->Call(&returnVal, error);
if (error.Failed()) {
mPromise->MaybeReject(std::move(error));
} else if (guard.Mutated(0)) {
// Something within the callback mutated the DOM.
mPromise->MaybeRejectWithNoModificationAllowedError(
"DOM mutated from promiseDocumentFlushed callbacks");
} else {
mPromise->MaybeResolve(returnVal);
}
}
RefPtr<Promise> mPromise;
RefPtr<PromiseDocumentFlushedCallback> mCallback;
};
//*****************************************************************************
//*** nsGlobalWindowInner: Object Management
//*****************************************************************************
nsGlobalWindowInner::nsGlobalWindowInner(nsGlobalWindowOuter* aOuterWindow,
WindowGlobalChild* aActor)
: nsPIDOMWindowInner(aOuterWindow, aActor),
mHasOrientationChangeListeners(false),
mWasOffline(false),
mHasHadSlowScript(false),
mIsChrome(false),
mCleanMessageManager(false),
mNeedsFocus(true),
mFocusByKeyOccurred(false),
mDidFireDocElemInserted(false),
mHasGamepad(false),
mHasXRSession(false),
mHasVRDisplayActivateEvents(false),
mXRRuntimeDetectionInFlight(false),
mXRPermissionRequestInFlight(false),
mXRPermissionGranted(false),
mWasCurrentInnerWindow(false),
mHasSeenGamepadInput(false),
mHintedWasLoading(false),
mHasOpenedExternalProtocolFrame(false),
mScrollMarksOnHScrollbar(false),
mStorageAllowedReasonCache(0),
mSuspendDepth(0),
mFreezeDepth(0),
#ifdef DEBUG
mSerial(0),
#endif
mFocusMethod(0),
mIdleRequestCallbackCounter(1),
mIdleRequestExecutor(nullptr),
mObservingRefresh(false),
mIteratingDocumentFlushedResolvers(false),
mCanSkipCCGeneration(0) {
mIsInnerWindow = true;
AssertIsOnMainThread();
SetIsOnMainThread();
nsLayoutStatics::AddRef();
// Initialize the PRCList (this).
PR_INIT_CLIST(this);
// add this inner window to the outer window list of inners.
PR_INSERT_AFTER(this, aOuterWindow);
mTimeoutManager = MakeUnique<dom::TimeoutManager>(
*this, StaticPrefs::dom_timeout_max_idle_defer_ms(),
static_cast<nsISerialEventTarget*>(nsPIDOMWindowInner::From(this)
->GetBrowsingContextGroup()
->GetTimerEventQueue()));
mObserver = new nsGlobalWindowObserver(this);
if (nsCOMPtr<nsIObserverService> os = services::GetObserverService()) {
// Watch for online/offline status changes so we can fire events. Use
// a strong reference.
os->AddObserver(mObserver, NS_IOSERVICE_OFFLINE_STATUS_TOPIC, false);
os->AddObserver(mObserver, MEMORY_PRESSURE_OBSERVER_TOPIC, false);
os->AddObserver(mObserver, PERMISSION_CHANGED_TOPIC, false);
os->AddObserver(mObserver, "screen-information-changed", false);
os->AddObserver(mObserver, "audio-playback", false);
}
Preferences::AddStrongObserver(mObserver, "intl.accept_languages");
// Watch for storage notifications so we can fire storage events.
RefPtr<StorageNotifierService> sns = StorageNotifierService::GetOrCreate();
if (sns) {
sns->Register(mObserver);
}
if (XRE_IsContentProcess()) {
nsCOMPtr<nsIDocShell> docShell = GetDocShell();
if (docShell) {
mBrowserChild = docShell->GetBrowserChild();
}
}
if (gDumpFile == nullptr) {
nsAutoCString fname;
Preferences::GetCString("browser.dom.window.dump.file", fname);
if (!fname.IsEmpty()) {
// If this fails to open, Dump() knows to just go to stdout on null.
gDumpFile = fopen(fname.get(), "wb+");
} else {
gDumpFile = stdout;
}
}
#ifdef DEBUG
mSerial = nsContentUtils::InnerOrOuterWindowCreated();
MOZ_LOG(gDocShellAndDOMWindowLeakLogging, LogLevel::Info,
("++DOMWINDOW == %d (%p) [pid = %d] [serial = %d] [outer = %p]\n",
nsContentUtils::GetCurrentInnerOrOuterWindowCount(),
static_cast<void*>(ToCanonicalSupports(this)), getpid(), mSerial,
static_cast<void*>(ToCanonicalSupports(aOuterWindow))));
#endif
MOZ_LOG(gDOMLeakPRLogInner, LogLevel::Debug,
("DOMWINDOW %p created outer=%p", this, aOuterWindow));
// Add ourselves to the inner windows list.
MOZ_ASSERT(sInnerWindowsById, "Inner Windows hash table must be created!");
MOZ_ASSERT(!sInnerWindowsById->Contains(mWindowID),
"This window shouldn't be in the hash table yet!");
// We seem to see crashes in release builds because of null
// |sInnerWindowsById|.
if (sInnerWindowsById) {
sInnerWindowsById->InsertOrUpdate(mWindowID, this);
}
}
#ifdef DEBUG
/* static */
void nsGlobalWindowInner::AssertIsOnMainThread() {
MOZ_ASSERT(NS_IsMainThread());
}
#endif // DEBUG
/* static */
void nsGlobalWindowInner::Init() {
AssertIsOnMainThread();
NS_ASSERTION(gDOMLeakPRLogInner,
"gDOMLeakPRLogInner should have been initialized!");
sInnerWindowsById = new InnerWindowByIdTable();
}
nsGlobalWindowInner::~nsGlobalWindowInner() {
AssertIsOnMainThread();
MOZ_ASSERT(!mHintedWasLoading);
if (IsChromeWindow()) {
MOZ_ASSERT(mCleanMessageManager,
"chrome windows may always disconnect the msg manager");
DisconnectAndClearGroupMessageManagers();
if (mChromeFields.mMessageManager) {
static_cast<nsFrameMessageManager*>(mChromeFields.mMessageManager.get())
->Disconnect();
}
mCleanMessageManager = false;
}
// In most cases this should already have been called, but call it again
// here to catch any corner cases.
FreeInnerObjects();
if (sInnerWindowsById) {
sInnerWindowsById->Remove(mWindowID);
}
nsContentUtils::InnerOrOuterWindowDestroyed();
#ifdef DEBUG
if (MOZ_LOG_TEST(gDocShellAndDOMWindowLeakLogging, LogLevel::Info)) {
nsAutoCString url;
if (mLastOpenedURI) {
url = mLastOpenedURI->GetSpecOrDefault();
// Data URLs can be very long, so truncate to avoid flooding the log.
const uint32_t maxURLLength = 1000;
if (url.Length() > maxURLLength) {
url.Truncate(maxURLLength);
}
}
nsGlobalWindowOuter* outer = nsGlobalWindowOuter::Cast(mOuterWindow);
MOZ_LOG(
gDocShellAndDOMWindowLeakLogging, LogLevel::Info,
("--DOMWINDOW == %d (%p) [pid = %d] [serial = %d] [outer = %p] [url = "
"%s]\n",
nsContentUtils::GetCurrentInnerOrOuterWindowCount(),
static_cast<void*>(ToCanonicalSupports(this)), getpid(), mSerial,
static_cast<void*>(ToCanonicalSupports(outer)), url.get()));
}
#endif
MOZ_LOG(gDOMLeakPRLogInner, LogLevel::Debug,
("DOMWINDOW %p destroyed", this));
glean::dom::innerwindows_with_mutation_listeners
.EnumGet(static_cast<glean::dom::InnerwindowsWithMutationListenersLabel>(
mMutationBits ? 1 : 0))
.Add();
// An inner window is destroyed, pull it out of the outer window's
// list if inner windows.
PR_REMOVE_LINK(this);
// If our outer window's inner window is this window, null out the
// outer window's reference to this window that's being deleted.
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
if (outer) {
outer->MaybeClearInnerWindow(this);
}
// We don't have to leave the tab group if we are an inner window.
nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
if (ac) ac->RemoveWindowAsListener(this);
nsLayoutStatics::Release();
}
// static
void nsGlobalWindowInner::ShutDown() {
AssertIsOnMainThread();
if (gDumpFile && gDumpFile != stdout) {
fclose(gDumpFile);
}
gDumpFile = nullptr;
delete sInnerWindowsById;
sInnerWindowsById = nullptr;
}
void nsGlobalWindowInner::FreeInnerObjects() {
if (IsDying()) {
return;
}
StartDying();
ClearHasPointerRawUpdateEventListeners();
if (mDoc && mDoc->GetWindowContext()) {
// The document is about to lose its window, so this is a good time to send
// our page use counters.
//
// (We also do this in Document::SetScriptGlobalObject(nullptr), which
// catches most cases of documents losing their window, but not all.)
mDoc->SendPageUseCounters();
}
// Make sure that this is called before we null out the document and
// other members that the window destroyed observers could
// re-create.
if (auto* reporter = nsWindowMemoryReporter::Get()) {
reporter->ObserveDOMWindowDetached(this);
}
// Kill all of the workers for this window.
CancelWorkersForWindow(*this);
for (RefPtr<mozilla::dom::SharedWorker> pinnedWorker :
mSharedWorkers.ForwardRange()) {
pinnedWorker->Close();
}
if (mTimeoutManager) {
mTimeoutManager->ClearAllTimeouts();
}
DisableIdleCallbackRequests();
mChromeEventHandler = nullptr;
if (mListenerManager) {
mListenerManager->RemoveAllListeners();
mListenerManager->Disconnect();
mListenerManager = nullptr;
}
mHistory = nullptr;
mNavigation = nullptr;
if (mNavigator) {
mNavigator->OnNavigation();
mNavigator->Invalidate();
mNavigator = nullptr;
}
mScreen = nullptr;
if (mDoc) {
// Remember the document's principal, URI, and policyContainer.
mDocumentPrincipal = mDoc->NodePrincipal();
mDocumentCookiePrincipal = mDoc->EffectiveCookiePrincipal();
mDocumentStoragePrincipal = mDoc->EffectiveStoragePrincipal();
mDocumentPartitionedPrincipal = mDoc->PartitionedPrincipal();
mDocumentURI = mDoc->GetDocumentURI();
mDocBaseURI = mDoc->GetDocBaseURI();
mDocumentPolicyContainer = mDoc->GetPolicyContainer();
while (mDoc->EventHandlingSuppressed()) {
mDoc->UnsuppressEventHandlingAndFireEvents(false);
}
}
// Remove our reference to the document and the document principal.
mFocusedElement = nullptr;
nsIGlobalObject::UnlinkObjectsInGlobal();
NotifyWindowIDDestroyed("inner-window-destroyed");
for (uint32_t i = 0; i < mAudioContexts.Length(); ++i) {
mAudioContexts[i]->OnWindowDestroy();
}
mAudioContexts.Clear();
for (MediaKeys* mediaKeys : mMediaKeysInstances) {
mediaKeys->OnInnerWindowDestroy();
}
mMediaKeysInstances.Clear();
DisableGamepadUpdates();
mHasGamepad = false;
mGamepads.Clear();
DisableVRUpdates();
mHasXRSession = false;
mHasVRDisplayActivateEvents = false;
mXRRuntimeDetectionInFlight = false;
mXRPermissionRequestInFlight = false;
mXRPermissionGranted = false;
mVRDisplays.Clear();
// This breaks a cycle between the window and the ClientSource object.
mClientSource.reset();
if (mWindowGlobalChild) {
// Remove any remaining listeners.
int64_t nListeners = mWindowGlobalChild->BeforeUnloadListeners();
for (int64_t i = 0; i < nListeners; ++i) {
mWindowGlobalChild->BeforeUnloadRemoved();
}
MOZ_ASSERT(mWindowGlobalChild->BeforeUnloadListeners() == 0);
}
// If we have any promiseDocumentFlushed callbacks, fire them now so
// that the Promises can resolve.
CallDocumentFlushedResolvers(/* aUntilExhaustion = */ true);
DisconnectGlobalTeardownObservers();
#ifdef MOZ_WIDGET_ANDROID
DisableOrientationChangeListener();
#endif
if (mObserver) {
if (nsCOMPtr<nsIObserverService> os = services::GetObserverService()) {
os->RemoveObserver(mObserver, NS_IOSERVICE_OFFLINE_STATUS_TOPIC);
os->RemoveObserver(mObserver, MEMORY_PRESSURE_OBSERVER_TOPIC);
os->RemoveObserver(mObserver, PERMISSION_CHANGED_TOPIC);
os->RemoveObserver(mObserver, "screen-information-changed");
os->RemoveObserver(mObserver, "audio-playback");
}
RefPtr<StorageNotifierService> sns = StorageNotifierService::GetOrCreate();
if (sns) {
sns->Unregister(mObserver);
}
Preferences::RemoveObserver(mObserver, "intl.accept_languages");
// Drop its reference to this dying window, in case for some bogus reason
// the object stays around.
mObserver->Forget();
}
mMenubar = nullptr;
mToolbar = nullptr;
mLocationbar = nullptr;
mPersonalbar = nullptr;
mStatusbar = nullptr;
mScrollbars = nullptr;
mConsole = nullptr;
mCookieStore = nullptr;
mPaintWorklet = nullptr;
mExternal = nullptr;
mInstallTrigger = nullptr;
if (mLocalStorage) {
mLocalStorage->Disconnect();
mLocalStorage = nullptr;
}
mSessionStorage = nullptr;
if (mPerformance) {
// Since window is dying, nothing is going to be painted
// with meaningful sizes, so these temp data for LCP is
// no longer needed.
static_cast<PerformanceMainThread*>(mPerformance.get())
->ClearGeneratedTempDataForLCP();
}
mPerformance = nullptr;
mContentMediaController = nullptr;
if (mWebTaskScheduler) {
mWebTaskScheduler->Disconnect();
mWebTaskScheduler = nullptr;
}
mTrustedTypePolicyFactory = nullptr;
mSharedWorkers.Clear();
#ifdef MOZ_WEBSPEECH
mSpeechSynthesis = nullptr;
#endif
mGlean = nullptr;
mGleanPings = nullptr;
mParentTarget = nullptr;
if (mCleanMessageManager) {
MOZ_ASSERT(mIsChrome, "only chrome should have msg manager cleaned");
if (mChromeFields.mMessageManager) {
mChromeFields.mMessageManager->Disconnect();
}
}
if (mWindowGlobalChild && !mWindowGlobalChild->IsClosed()) {
mWindowGlobalChild->Destroy();
}
mIntlUtils = nullptr;
HintIsLoading(false);
}
//*****************************************************************************
// nsGlobalWindowInner::nsISupports
//*****************************************************************************
// QueryInterface implementation for nsGlobalWindowInner
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsGlobalWindowInner)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, EventTarget)
NS_INTERFACE_MAP_ENTRY(nsIDOMWindow)
NS_INTERFACE_MAP_ENTRY(nsIGlobalObject)
NS_INTERFACE_MAP_ENTRY(nsIScriptGlobalObject)
NS_INTERFACE_MAP_ENTRY(nsIScriptObjectPrincipal)
NS_INTERFACE_MAP_ENTRY(mozilla::dom::EventTarget)
NS_INTERFACE_MAP_ENTRY(nsPIDOMWindowInner)
NS_INTERFACE_MAP_ENTRY(mozIDOMWindow)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsGlobalWindowInner)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsGlobalWindowInner)
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(nsGlobalWindowInner)
if (tmp->IsBlackForCC(false)) {
if (nsCCUncollectableMarker::InGeneration(tmp->mCanSkipCCGeneration)) {
return true;
}
tmp->mCanSkipCCGeneration = nsCCUncollectableMarker::sGeneration;
if (EventListenerManager* elm = tmp->GetExistingListenerManager()) {
elm->MarkForCC();
}
if (tmp->mTimeoutManager) {
tmp->mTimeoutManager->UnmarkGrayTimers();
}
return true;
}
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(nsGlobalWindowInner)
return tmp->IsBlackForCC(true);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(nsGlobalWindowInner)
return tmp->IsBlackForCC(false);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
NS_IMPL_CYCLE_COLLECTION_CLASS(nsGlobalWindowInner)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsGlobalWindowInner)
if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
char name[512];
nsAutoCString uri;
if (tmp->mDoc && tmp->mDoc->GetDocumentURI()) {
uri = tmp->mDoc->GetDocumentURI()->GetSpecOrDefault();
}
SprintfLiteral(name, "nsGlobalWindowInner # %" PRIu64 " inner %s",
tmp->mWindowID, uri.get());
cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name);
} else {
NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsGlobalWindowInner, tmp->mRefCnt.get())
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNavigation)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNavigator)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPerformance)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWebTaskScheduler)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWebTaskSchedulingState)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTrustedTypePolicyFactory)
#ifdef MOZ_WEBSPEECH
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSpeechSynthesis)
#endif
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGlean)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGleanPings)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOuterWindow)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopInnerWindow)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mListenerManager)
if (tmp->mTimeoutManager) {
tmp->mTimeoutManager->ForEachUnorderedTimeout([&cb](Timeout* timeout) {
cb.NoteNativeChild(timeout, NS_CYCLE_COLLECTION_PARTICIPANT(Timeout));
});
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLocation)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mHistory)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCustomElements)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSharedWorkers)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLocalStorage)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSessionStorage)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIndexedDB)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentPrincipal)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentCookiePrincipal)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentStoragePrincipal)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentPartitionedPrincipal)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentPolicyContainer)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBrowserChild)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDoc)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWebIdentityHandler)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIdleRequestExecutor)
for (IdleRequest* request : tmp->mIdleRequestCallbacks) {
cb.NoteNativeChild(request, NS_CYCLE_COLLECTION_PARTICIPANT(IdleRequest));
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mClientSource)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGamepads)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCacheStorage)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mVRDisplays)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDebuggerNotificationManager)
// Traverse stuff from nsPIDOMWindow
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChromeEventHandler)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mParentTarget)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFocusedElement)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBrowsingContext)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindowGlobalChild)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCloseWatcherManager)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMenubar)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mToolbar)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLocationbar)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPersonalbar)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStatusbar)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mScrollbars)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCrypto)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mConsole)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCookieStore)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPaintWorklet)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mExternal)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInstallTrigger)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIntlUtils)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mVisualViewport)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCurrentPasteDataTransfer)
tmp->TraverseObjectsInGlobal(cb);
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChromeFields.mMessageManager)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChromeFields.mGroupMessageManagers)
for (size_t i = 0; i < tmp->mDocumentFlushedResolvers.Length(); i++) {
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentFlushedResolvers[i]->mPromise);
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentFlushedResolvers[i]->mCallback);
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGlobalWindowInner)
NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
if (sInnerWindowsById) {
sInnerWindowsById->Remove(tmp->mWindowID);
}
JSObject* wrapper = tmp->GetWrapperPreserveColor();
if (wrapper) {
// Mark our realm as dead, so the JS engine won't hand out our
// global after this point.
JS::SetRealmNonLive(js::GetNonCCWObjectRealm(wrapper));
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mNavigation)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mNavigator)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPerformance)
if (tmp->mWebTaskScheduler) {
tmp->mWebTaskScheduler->Disconnect();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mWebTaskScheduler)
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mWebTaskSchedulingState)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTrustedTypePolicyFactory)
#ifdef MOZ_WEBSPEECH
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSpeechSynthesis)
#endif
NS_IMPL_CYCLE_COLLECTION_UNLINK(mGlean)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mGleanPings)
if (tmp->mOuterWindow) {
nsGlobalWindowOuter::Cast(tmp->mOuterWindow)->MaybeClearInnerWindow(tmp);
NS_IMPL_CYCLE_COLLECTION_UNLINK(mOuterWindow)
}
if (tmp->mListenerManager) {
tmp->mListenerManager->Disconnect();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mListenerManager)
}
// Here the Timeouts list would've been unlinked, but we rely on
// that Timeout objects have been traced and will remove themselves
// while unlinking.
tmp->UpdateTopInnerWindow();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTopInnerWindow)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mLocation)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mHistory)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mNavigation)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCustomElements)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSharedWorkers)
if (tmp->mLocalStorage) {
tmp->mLocalStorage->Disconnect();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mLocalStorage)
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSessionStorage)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mIndexedDB)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentPrincipal)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentCookiePrincipal)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentStoragePrincipal)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentPartitionedPrincipal)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentPolicyContainer)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBrowserChild)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDoc)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mGamepads)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCacheStorage)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mVRDisplays)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDebuggerNotificationManager)
// Unlink stuff from nsPIDOMWindow
NS_IMPL_CYCLE_COLLECTION_UNLINK(mChromeEventHandler)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mParentTarget)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mFocusedElement)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBrowsingContext)
MOZ_DIAGNOSTIC_ASSERT(
!tmp->mWindowGlobalChild || tmp->mWindowGlobalChild->IsClosed(),
"How are we unlinking a window before its actor has been destroyed?");
NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindowGlobalChild)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mMenubar)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mToolbar)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mLocationbar)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPersonalbar)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mStatusbar)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mScrollbars)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCrypto)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mConsole)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCookieStore)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPaintWorklet)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mExternal)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mInstallTrigger)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mIntlUtils)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mVisualViewport)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCurrentPasteDataTransfer)
tmp->UnlinkObjectsInGlobal();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mIdleRequestExecutor)
// Here the IdleRequest list would've been unlinked, but we rely on
// that IdleRequest objects have been traced and will remove
// themselves while unlinking.
NS_IMPL_CYCLE_COLLECTION_UNLINK(mClientSource)
if (tmp->IsChromeWindow()) {
if (tmp->mChromeFields.mMessageManager) {
static_cast<nsFrameMessageManager*>(
tmp->mChromeFields.mMessageManager.get())
->Disconnect();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mChromeFields.mMessageManager)
}
tmp->DisconnectAndClearGroupMessageManagers();
NS_IMPL_CYCLE_COLLECTION_UNLINK(mChromeFields.mGroupMessageManagers)
}
for (size_t i = 0; i < tmp->mDocumentFlushedResolvers.Length(); i++) {
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentFlushedResolvers[i]->mPromise);
NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentFlushedResolvers[i]->mCallback);
}
tmp->mDocumentFlushedResolvers.Clear();
NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
#ifdef DEBUG
void nsGlobalWindowInner::RiskyUnlink() {
NS_CYCLE_COLLECTION_INNERNAME.Unlink(this);
}
#endif
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsGlobalWindowInner)
NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_TRACE_END
bool nsGlobalWindowInner::IsBlackForCC(bool aTracingNeeded) {
if (!nsCCUncollectableMarker::sGeneration) {
return false;
}
return (nsCCUncollectableMarker::InGeneration(GetMarkedCCGeneration()) ||
HasKnownLiveWrapper()) &&
(!aTracingNeeded || HasNothingToTrace(ToSupports(this)));
}
//*****************************************************************************
// nsGlobalWindowInner::nsIScriptGlobalObject
//*****************************************************************************
bool nsGlobalWindowInner::ShouldResistFingerprinting(RFPTarget aTarget) const {
if (mDoc) {
return mDoc->ShouldResistFingerprinting(aTarget);
}
return nsContentUtils::ShouldResistFingerprinting(
"If we do not have a document then we do not have any context"
"to make an informed RFP choice, so we fall back to the global pref",
aTarget);
}
OriginTrials nsGlobalWindowInner::Trials() const {
return OriginTrials::FromWindow(this);
}
FontFaceSet* nsGlobalWindowInner::GetFonts() {
if (mDoc) {
return mDoc->Fonts();
}
return nullptr;
}
mozilla::Result<mozilla::ipc::PrincipalInfo, nsresult>
nsGlobalWindowInner::GetStorageKey() {
MOZ_ASSERT(NS_IsMainThread());
nsIPrincipal* principal = GetEffectiveStoragePrincipal();
if (!principal) {
return mozilla::Err(NS_ERROR_FAILURE);
}
mozilla::ipc::PrincipalInfo principalInfo;
nsresult rv = PrincipalToPrincipalInfo(principal, &principalInfo);
if (NS_FAILED(rv)) {
return mozilla::Err(rv);
}
// Block expanded and null principals, let content and system through.
if (principalInfo.type() !=
mozilla::ipc::PrincipalInfo::TContentPrincipalInfo &&
principalInfo.type() !=
mozilla::ipc::PrincipalInfo::TSystemPrincipalInfo) {
return Err(NS_ERROR_DOM_SECURITY_ERR);
}
return std::move(principalInfo);
}
mozilla::dom::StorageManager* nsGlobalWindowInner::GetStorageManager() {
return Navigator()->Storage();
}
// https://html.spec.whatwg.org/multipage/web-messaging.html#eligible-for-messaging
// * a Window object whose associated Document is fully active
bool nsGlobalWindowInner::IsEligibleForMessaging() { return IsFullyActive(); }
void nsGlobalWindowInner::ReportToConsole(
uint32_t aErrorFlags, const nsCString& aCategory,
nsContentUtils::PropertiesFile aFile, const nsCString& aMessageName,
const nsTArray<nsString>& aParams,
const mozilla::SourceLocation& aLocation) {
nsContentUtils::ReportToConsole(aErrorFlags, aCategory, mDoc, aFile,
aMessageName.get(), aParams, aLocation);
}
nsresult nsGlobalWindowInner::EnsureScriptEnvironment() {
// NOTE: We can't use FORWARD_TO_OUTER here because we don't want to fail if
// we're called on an inactive inner window.
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
if (!outer) {
NS_WARNING("No outer window available!");
return NS_ERROR_FAILURE;
}
return outer->EnsureScriptEnvironment();
}
nsIScriptContext* nsGlobalWindowInner::GetScriptContext() {
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
if (!outer) {
return nullptr;
}
return outer->GetScriptContext();
}
void nsGlobalWindowInner::TraceGlobalJSObject(JSTracer* aTrc) {
TraceWrapper(aTrc, "active window global");
}
void nsGlobalWindowInner::UpdateAutoplayPermission() {
if (!GetWindowContext()) {
return;
}
uint32_t perm =
media::AutoplayPolicy::GetSiteAutoplayPermission(GetPrincipal());
if (GetWindowContext()->GetAutoplayPermission() == perm) {
return;
}
// Setting autoplay permission on a discarded context has no effect.
Unused << GetWindowContext()->SetAutoplayPermission(perm);
}
void nsGlobalWindowInner::UpdateShortcutsPermission() {
if (!GetWindowContext() ||
!GetWindowContext()->GetBrowsingContext()->IsTop()) {
// We only cache the shortcuts permission on top-level WindowContexts
// since we always check the top-level principal for the permission.
return;
}
uint32_t perm = GetShortcutsPermission(GetPrincipal());
if (GetWindowContext()->GetShortcutsPermission() == perm) {
return;
}
// If the WindowContext is discarded this has no effect.
Unused << GetWindowContext()->SetShortcutsPermission(perm);
}
/* static */
uint32_t nsGlobalWindowInner::GetShortcutsPermission(nsIPrincipal* aPrincipal) {
uint32_t perm = nsIPermissionManager::DENY_ACTION;
nsCOMPtr<nsIPermissionManager> permMgr =
mozilla::components::PermissionManager::Service();
if (aPrincipal && permMgr) {
permMgr->TestExactPermissionFromPrincipal(aPrincipal, "shortcuts"_ns,
&perm);
}
return perm;
}
void nsGlobalWindowInner::UpdatePopupPermission() {
if (!GetWindowContext()) {
return;
}
uint32_t perm = PopupBlocker::GetPopupPermission(GetPrincipal());
if (GetWindowContext()->GetPopupPermission() == perm) {
return;
}
// If the WindowContext is discarded this has no effect.
Unused << GetWindowContext()->SetPopupPermission(perm);
}
void nsGlobalWindowInner::UpdatePermissions() {
if (!GetWindowContext()) {
return;
}
nsCOMPtr<nsIPrincipal> principal = GetPrincipal();
RefPtr<WindowContext> windowContext = GetWindowContext();
WindowContext::Transaction txn;
txn.SetAutoplayPermission(
media::AutoplayPolicy::GetSiteAutoplayPermission(principal));
txn.SetPopupPermission(PopupBlocker::GetPopupPermission(principal));
if (windowContext->IsTop()) {
txn.SetShortcutsPermission(GetShortcutsPermission(principal));
}
// Setting permissions on a discarded WindowContext has no effect
Unused << txn.Commit(windowContext);
}
void nsGlobalWindowInner::InitDocumentDependentState(JSContext* aCx) {
MOZ_ASSERT(mDoc);
if (MOZ_LOG_TEST(gDOMLeakPRLogInner, LogLevel::Debug)) {
nsIURI* uri = mDoc->GetDocumentURI();
MOZ_LOG(gDOMLeakPRLogInner, LogLevel::Debug,
("DOMWINDOW %p SetNewDocument %s", this,
uri ? uri->GetSpecOrDefault().get() : ""));
}
mFocusedElement = nullptr;
mLocalStorage = nullptr;
mSessionStorage = nullptr;
mPerformance = nullptr;
if (mWebTaskScheduler) {
mWebTaskScheduler->Disconnect();
mWebTaskScheduler = nullptr;
mWebTaskSchedulingState = nullptr;
}
// This must be called after nullifying the internal objects because here we
// could recreate them, calling the getter methods, and store them into the JS
// slots. If we nullify them after, the slot values and the objects will be
// out of sync.
ClearDocumentDependentSlots(aCx);
if (!mWindowGlobalChild) {
mWindowGlobalChild = WindowGlobalChild::Create(this);
}
MOZ_ASSERT(!GetWindowContext()->HasBeenUserGestureActivated(),
"WindowContext should always not have user gesture activation at "
"this point.");
UpdatePermissions();
RefPtr<PermissionDelegateHandler> permDelegateHandler =
mDoc->GetPermissionDelegateHandler();
if (permDelegateHandler) {
permDelegateHandler->PopulateAllDelegatedPermissions();
}
#if defined(MOZ_WIDGET_ANDROID)
// When we insert the new document to the window in the top-level browsing
// context, we should reset the status of the request which is used for the
// previous document.
if (mWindowGlobalChild && GetBrowsingContext() &&
!GetBrowsingContext()->GetParent()) {
// Return value of setting synced field should be checked. See bug 1656492.
Unused << GetBrowsingContext()->ResetGVAutoplayRequestStatus();
}
#endif
#ifdef DEBUG
mLastOpenedURI = mDoc->GetDocumentURI();
#endif
glean::dom::innerwindows_with_mutation_listeners
.EnumGet(static_cast<glean::dom::InnerwindowsWithMutationListenersLabel>(
mMutationBits ? 1 : 0))
.Add();
// Clear our mutation bitfield.
mMutationBits = 0;
}
nsresult nsGlobalWindowInner::EnsureClientSource() {
MOZ_DIAGNOSTIC_ASSERT(mDoc);
bool newClientSource = false;
// Get the load info for the document if we performed a load. Be careful not
// to look at local URLs, though. Local URLs are those that have a scheme of:
// * about:
// * data:
// * blob:
// We also do an additional check here so that we only treat about:blank
// and about:srcdoc as local URLs. Other internal firefox about: URLs should
// not be treated this way.
nsCOMPtr<nsILoadInfo> loadInfo;
nsCOMPtr<nsIChannel> channel = mDoc->GetChannel();
if (channel) {
nsCOMPtr<nsIURI> uri;
Unused << channel->GetURI(getter_AddRefs(uri));
bool ignoreLoadInfo = false;
if (uri->SchemeIs("about")) {
ignoreLoadInfo =
NS_IsAboutBlankAllowQueryAndFragment(uri) || NS_IsAboutSrcdoc(uri);
} else {
// Its not an about: URL, so now check for our other URL types.
ignoreLoadInfo = uri->SchemeIs("data") || uri->SchemeIs("blob");
}
if (!ignoreLoadInfo) {
loadInfo = channel->LoadInfo();
}
}
// Take the initial client source from the docshell immediately. Even if we
// don't end up using it here we should consume it.
UniquePtr<ClientSource> initialClientSource;
nsIDocShell* docshell = GetDocShell();
if (docshell) {
initialClientSource = docshell->TakeInitialClientSource();
}
// Try to get the reserved client from the LoadInfo. A Client is
// reserved at the start of the channel load if there is not an
// initial about:blank document that will be reused. It is also
// created if the channel load encounters a cross-origin redirect.
if (loadInfo) {
UniquePtr<ClientSource> reservedClient =
loadInfo->TakeReservedClientSource();
if (reservedClient) {
mClientSource.reset();
mClientSource = std::move(reservedClient);
newClientSource = true;
}
}
// We don't have a LoadInfo reserved client, but maybe we should
// be inheriting an initial one from the docshell. This means
// that the docshell started the channel load before creating the
// initial about:blank document. This is an optimization, though,
// and it created an initial Client as a placeholder for the document.
// In this case we want to inherit this placeholder Client here.
if (!mClientSource) {
mClientSource = std::move(initialClientSource);
if (mClientSource) {
newClientSource = true;
}
}
nsCOMPtr<nsIPrincipal> foreignPartitionedPrincipal;
nsresult rv = StoragePrincipalHelper::GetPrincipal(
this,
StaticPrefs::privacy_partition_serviceWorkers()
? StoragePrincipalHelper::eForeignPartitionedPrincipal
: StoragePrincipalHelper::eRegularPrincipal,
getter_AddRefs(foreignPartitionedPrincipal));
NS_ENSURE_SUCCESS(rv, rv);
// Verify the final ClientSource principal matches the final document
// principal. The ClientChannelHelper handles things like network
// redirects, but there are other ways the document principal can change.
// For example, if something sets the nsIChannel.owner property, then
// the final channel principal can be anything. Unfortunately there is
// no good way to detect this until after the channel completes loading.
//
// For now we handle this just by reseting the ClientSource. This will
// result in a new ClientSource with the correct principal being created.
// To APIs like ServiceWorker and Clients API it will look like there was
// an initial content page created that was then immediately replaced.
// This is pretty close to what we are actually doing.
if (mClientSource) {
auto principalOrErr = mClientSource->Info().GetPrincipal();
nsCOMPtr<nsIPrincipal> clientPrincipal =
principalOrErr.isOk() ? principalOrErr.unwrap() : nullptr;
if (!clientPrincipal ||
!clientPrincipal->Equals(foreignPartitionedPrincipal)) {
mClientSource.reset();
}
}
// If we don't have a reserved client or an initial client, then create
// one now. This can happen in certain cases where we avoid preallocating
// the client in the docshell. This mainly occurs in situations where
// the principal is not clearly inherited from the parent; e.g. sandboxed
// iframes, window.open(), etc.
//
// We also do this late ClientSource creation if the final document ended
// up with a different principal.
//
// TODO: We may not be marking initial about:blank documents created
// this way as controlled by a service worker properly. The
// controller should be coming from the same place as the inheritted
// principal. We do this in docshell, but as mentioned we aren't
// smart enough to handle all cases yet. For example, a
// window.open() with new URL should inherit the controller from
// the opener, but we probably don't handle that yet.
if (!mClientSource) {
mClientSource = ClientManager::CreateSource(
ClientType::Window, SerialEventTarget(), foreignPartitionedPrincipal);
MOZ_DIAGNOSTIC_ASSERT(mClientSource);
newClientSource = true;
// Note, we don't apply the loadinfo controller below if we create
// the ClientSource here.
}
// The load may have started controlling the Client as well. If
// so, mark it as controlled immediately here. The actor may
// or may not have been notified by the parent side about being
// controlled yet.
//
// Note: We should be careful not to control a client that was created late.
// These clients were not seen by the ServiceWorkerManager when it
// marked the LoadInfo controlled and it won't know about them. Its
// also possible we are creating the client late due to the final
// principal changing and these clients should definitely not be
// controlled by a service worker with a different principal.
else if (loadInfo) {
const Maybe<ServiceWorkerDescriptor> controller = loadInfo->GetController();
if (controller.isSome()) {
mClientSource->SetController(controller.ref());
}
// We also have to handle the case where te initial about:blank is
// controlled due to inheritting the service worker from its parent,
// but the actual nsIChannel load is not covered by any service worker.
// In this case we want the final page to be uncontrolled. There is
// an open spec issue about how exactly this should be handled, but for
// now we just force creation of a new ClientSource to clear the
// controller.
//
// https://github.com/w3c/ServiceWorker/issues/1232
//
else if (mClientSource->GetController().isSome()) {
mClientSource.reset();
mClientSource = ClientManager::CreateSource(
ClientType::Window, SerialEventTarget(), foreignPartitionedPrincipal);
MOZ_DIAGNOSTIC_ASSERT(mClientSource);
newClientSource = true;
}
}
if (mClientSource) {
// Generally the policyContainer is stored within the Client and cached on
// the document. At the time of policyContainer parsing however, the Client
// has not been created yet, hence we store the policyContainer on the
// document and propagate/sync the policyContainer with Client here when we
// create the Client.
mClientSource->SetPolicyContainer(mDoc->GetPolicyContainer());
DocGroup* docGroup = GetDocGroup();
MOZ_DIAGNOSTIC_ASSERT(docGroup);
mClientSource->SetAgentClusterId(docGroup->AgentClusterId());
if (mWindowGlobalChild) {
mWindowGlobalChild->SendSetClientInfo(mClientSource->Info().ToIPC());
}
}
// Its possible that we got a client just after being frozen in
// the bfcache. In that case freeze the client immediately.
if (newClientSource && IsFrozen()) {
mClientSource->Freeze();
}
return NS_OK;
}
nsresult nsGlobalWindowInner::ExecutionReady() {
nsresult rv = EnsureClientSource();
NS_ENSURE_SUCCESS(rv, rv);
rv = mClientSource->WindowExecutionReady(this);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
void nsGlobalWindowInner::UpdateParentTarget() {
// NOTE: This method is identical to
// nsGlobalWindowOuter::UpdateParentTarget(). IF YOU UPDATE THIS METHOD,
// UPDATE THE OTHER ONE TOO!
// Try to get our frame element's tab child global (its in-process message
// manager). If that fails, fall back to the chrome event handler's tab
// child global, and if it doesn't have one, just use the chrome event
// handler itself.
nsPIDOMWindowOuter* outer = GetOuterWindow();
if (!outer) {
return;
}
nsCOMPtr<Element> frameElement = outer->GetFrameElementInternal();
nsCOMPtr<EventTarget> eventTarget =
nsContentUtils::TryGetBrowserChildGlobal(frameElement);
if (!eventTarget) {
nsGlobalWindowOuter* topWin = GetInProcessScriptableTopInternal();
if (topWin) {
frameElement = topWin->GetFrameElementInternal();
eventTarget = nsContentUtils::TryGetBrowserChildGlobal(frameElement);
}
}
if (!eventTarget) {
eventTarget = nsContentUtils::TryGetBrowserChildGlobal(mChromeEventHandler);
}
if (!eventTarget) {
eventTarget = mChromeEventHandler;
}
mParentTarget = eventTarget;
}
EventTarget* nsGlobalWindowInner::GetTargetForDOMEvent() {
return GetOuterWindowInternal();
}
void nsGlobalWindowInner::GetEventTargetParent(EventChainPreVisitor& aVisitor) {
EventMessage msg = aVisitor.mEvent->mMessage;
aVisitor.mCanHandle = true;
aVisitor.mForceContentDispatch = true; // FIXME! Bug 329119
if (msg == eResize && aVisitor.mEvent->IsTrusted()) {
// Checking whether the event target is an inner window or not, so we can
// keep the old behavior also in case a child window is handling resize.
if (aVisitor.mEvent->mOriginalTarget &&
aVisitor.mEvent->mOriginalTarget->IsInnerWindow()) {
mIsHandlingResizeEvent = true;
}
} else if (msg == eMouseDown && aVisitor.mEvent->IsTrusted()) {
sMouseDown = true;
} else if ((msg == eMouseUp || msg == eDragEnd) &&
aVisitor.mEvent->IsTrusted()) {
sMouseDown = false;
if (sDragServiceDisabled) {
nsCOMPtr<nsIDragService> ds =
do_GetService("@mozilla.org/widget/dragservice;1");
if (ds) {
sDragServiceDisabled = false;
ds->Unsuppress();
}
}
}
aVisitor.SetParentTarget(GetParentTarget(), true);
}
void nsGlobalWindowInner::FireFrameLoadEvent() {
// If we're not in a content frame, or are at a BrowsingContext tree boundary,
// such as the content-chrome boundary, don't fire the "load" event.
if (GetBrowsingContext()->IsTopContent() ||
GetBrowsingContext()->IsChrome()) {
return;
}
// If embedder is same-process, fire the event on our embedder element.
//
// XXX: Bug 1440212 is looking into potentially changing this behaviour to act
// more like the remote case when in-process.
RefPtr<Element> element = GetBrowsingContext()->GetEmbedderElement();
if (element) {
nsEventStatus status = nsEventStatus_eIgnore;
WidgetEvent event(/* aIsTrusted = */ true, eLoad);
event.mFlags.mBubbles = false;
event.mFlags.mCancelable = false;
// Most of the time we could get a pres context to pass in here, but not
// always (i.e. if this window is not shown there won't be a pres context
// available). Since we're not firing a GUI event we don't need a pres
// context anyway so we just pass null as the pres context all the time.
EventDispatcher::Dispatch(element, nullptr, &event, nullptr, &status);
return;
}
// We don't have an in-process embedder. Try to get our `BrowserChild` actor
// to send a message to that embedder. We want to double-check that our outer
// window is actually the one at the root of this browserChild though, just in
// case.
RefPtr<BrowserChild> browserChild =
BrowserChild::GetFrom(static_cast<nsPIDOMWindowInner*>(this));
if (browserChild &&
!GetBrowsingContext()->GetParentWindowContext()->IsInProcess()) {
// Double-check that our outer window is actually at the root of this
// `BrowserChild`, in case we're in an odd maybe-unhosted situation like a
// print preview dialog.
nsCOMPtr<nsPIDOMWindowOuter> rootOuter =
do_GetInterface(browserChild->WebNavigation());
if (!rootOuter || rootOuter != GetOuterWindow()) {
return;
}
mozilla::Unused << browserChild->SendMaybeFireEmbedderLoadEvents(
EmbedderElementEventType::LoadEvent);
}
}
nsresult nsGlobalWindowInner::PostHandleEvent(EventChainPostVisitor& aVisitor) {
// Return early if there is nothing to do.
switch (aVisitor.mEvent->mMessage) {
case eResize:
case eUnload:
case eLoad:
break;
default:
return NS_OK;
}
/* mChromeEventHandler and mContext go dangling in the middle of this
function under some circumstances (events that destroy the window)
without this addref. */
RefPtr<EventTarget> kungFuDeathGrip1(mChromeEventHandler);
mozilla::Unused
<< kungFuDeathGrip1; // These aren't referred to through the function
nsCOMPtr<nsIScriptContext> kungFuDeathGrip2(GetContextInternal());
mozilla::Unused
<< kungFuDeathGrip2; // These aren't referred to through the function
if (aVisitor.mEvent->mMessage == eResize) {
mIsHandlingResizeEvent = false;
} else if (aVisitor.mEvent->mMessage == eUnload &&
aVisitor.mEvent->IsTrusted()) {
// If any VR display presentation is active at unload, the next page
// will receive a vrdisplayactive event to indicate that it should
// immediately begin vr presentation. This should occur when navigating
// forwards, navigating backwards, and on page reload.
for (const auto& display : mVRDisplays) {
if (display->IsPresenting()) {
display->StartVRNavigation();
// Save this VR display ID to trigger vrdisplayactivate event
// after the next load event.
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
if (outer) {
outer->SetAutoActivateVRDisplayID(display->DisplayId());
}
// XXX The WebVR 1.1 spec does not define which of multiple VR
// presenting VR displays will be chosen during navigation.
// As the underlying platform VR API's currently only allow a single
// VR display, it is safe to choose the first VR display for now.
break;
}
}
mIsDocumentLoaded = false;
// Tell the parent process that the document is not loaded.
if (mWindowGlobalChild) {
mWindowGlobalChild->SendUpdateDocumentHasLoaded(mIsDocumentLoaded);
}
} else if (aVisitor.mEvent->mMessage == eLoad &&
aVisitor.mEvent->IsTrusted()) {
// This is page load event since load events don't propagate to |window|.
// @see Document::GetEventTargetParent.
mIsDocumentLoaded = true;
// Tell the parent process that the document is loaded.
if (mWindowGlobalChild) {
mWindowGlobalChild->SendUpdateDocumentHasLoaded(mIsDocumentLoaded);
}
mTimeoutManager->OnDocumentLoaded();
MOZ_ASSERT(aVisitor.mEvent->IsTrusted());
FireFrameLoadEvent();
if (mVREventObserver) {
mVREventObserver->NotifyAfterLoad();
}
uint32_t autoActivateVRDisplayID = 0;
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
if (outer) {
autoActivateVRDisplayID = outer->GetAutoActivateVRDisplayID();
}
if (autoActivateVRDisplayID) {
DispatchVRDisplayActivate(autoActivateVRDisplayID,
VRDisplayEventReason::Navigation);
}
}
return NS_OK;
}
nsresult nsGlobalWindowInner::DefineArgumentsProperty(nsIArray* aArguments) {
nsIScriptContext* ctx = GetOuterWindowInternal()->mContext;
NS_ENSURE_TRUE(aArguments && ctx, NS_ERROR_NOT_INITIALIZED);
JS::Rooted<JSObject*> obj(RootingCx(), GetWrapperPreserveColor());
return ctx->SetProperty(obj, "arguments", aArguments);
}
//*****************************************************************************
// nsGlobalWindowInner::nsIScriptObjectPrincipal
//*****************************************************************************
nsIPrincipal* nsGlobalWindowInner::GetPrincipal() {
if (mDoc) {
// If we have a document, get the principal from the document
return mDoc->NodePrincipal();
}
if (mDocumentPrincipal) {
return mDocumentPrincipal;
}
// If we don't have a principal and we don't have a document we
// ask the parent window for the principal. This can happen when
// loading a frameset that has a <frame src="javascript:xxx">, in
// that case the global window is used in JS before we've loaded
// a document into the window.
nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
do_QueryInterface(GetInProcessParentInternal());
if (objPrincipal) {
return objPrincipal->GetPrincipal();
}
return nullptr;
}
nsIPrincipal* nsGlobalWindowInner::GetEffectiveCookiePrincipal() {
if (mDoc) {
// If we have a document, get the principal from the document
return mDoc->EffectiveCookiePrincipal();
}
if (mDocumentCookiePrincipal) {
return mDocumentCookiePrincipal;
}
// If we don't have a cookie principal and we don't have a document we ask
// the parent window for the cookie principal.
nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
do_QueryInterface(GetInProcessParentInternal());
if (objPrincipal) {
return objPrincipal->GetEffectiveCookiePrincipal();
}
return nullptr;
}
nsIPrincipal* nsGlobalWindowInner::GetEffectiveStoragePrincipal() {
if (mDoc) {
// If we have a document, get the principal from the document
return mDoc->EffectiveStoragePrincipal();
}
if (mDocumentStoragePrincipal) {
return mDocumentStoragePrincipal;
}
// If we don't have a cookie principal and we don't have a document we ask
// the parent window for the cookie principal.
nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
do_QueryInterface(GetInProcessParentInternal());
if (objPrincipal) {
return objPrincipal->GetEffectiveStoragePrincipal();
}
return nullptr;
}
nsIPrincipal* nsGlobalWindowInner::PartitionedPrincipal() {
if (mDoc) {
// If we have a document, get the principal from the document
return mDoc->PartitionedPrincipal();
}
if (mDocumentPartitionedPrincipal) {
return mDocumentPartitionedPrincipal;
}
// If we don't have a partitioned principal and we don't have a document we
// ask the parent window for the partitioned principal.
nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
do_QueryInterface(GetInProcessParentInternal());
if (objPrincipal) {
return objPrincipal->PartitionedPrincipal();
}
return nullptr;
}
//*****************************************************************************
// nsGlobalWindowInner::nsIDOMWindow
//*****************************************************************************
bool nsPIDOMWindowInner::AddAudioContext(AudioContext* aAudioContext) {
mAudioContexts.AppendElement(aAudioContext);
// Return true if the context should be muted and false if not.
nsIDocShell* docShell = GetDocShell();
return docShell && !docShell->GetAllowMedia() && !aAudioContext->IsOffline();
}
void nsPIDOMWindowInner::RemoveAudioContext(AudioContext* aAudioContext) {
mAudioContexts.RemoveElement(aAudioContext);
}
void nsPIDOMWindowInner::MuteAudioContexts() {
for (uint32_t i = 0; i < mAudioContexts.Length(); ++i) {
if (!mAudioContexts[i]->IsOffline()) {
mAudioContexts[i]->Mute();
}
}
}
void nsPIDOMWindowInner::UnmuteAudioContexts() {
for (uint32_t i = 0; i < mAudioContexts.Length(); ++i) {
if (!mAudioContexts[i]->IsOffline()) {
mAudioContexts[i]->Unmute();
}
}
}
WindowProxyHolder nsGlobalWindowInner::Window() {
return WindowProxyHolder(GetBrowsingContext());
}
Navigation* nsPIDOMWindowInner::Navigation() {
if (!mNavigation && Navigation::IsAPIEnabled()) {
mNavigation = new mozilla::dom::Navigation(this);
}
return mNavigation;
}
Navigator* nsPIDOMWindowInner::Navigator() {
if (!mNavigator) {
mNavigator = new mozilla::dom::Navigator(this);
}
return mNavigator;
}
MediaDevices* nsPIDOMWindowInner::GetExtantMediaDevices() const {
return mNavigator ? mNavigator->GetExtantMediaDevices() : nullptr;
}
VisualViewport* nsGlobalWindowInner::VisualViewport() {
if (!mVisualViewport) {
mVisualViewport = new mozilla::dom::VisualViewport(this);
}
return mVisualViewport;
}
nsScreen* nsGlobalWindowInner::Screen() {
if (!mScreen) {
mScreen = new nsScreen(this);
}
return mScreen;
}
nsHistory* nsGlobalWindowInner::GetHistory(ErrorResult& aError) {
if (!mHistory) {
mHistory = new nsHistory(this);
}
return mHistory;
}
CustomElementRegistry* nsGlobalWindowInner::CustomElements() {
if (!mCustomElements) {
mCustomElements = new CustomElementRegistry(this);
}
return mCustomElements;
}
CustomElementRegistry* nsGlobalWindowInner::GetExistingCustomElements() {
return mCustomElements;
}
Performance* nsPIDOMWindowInner::GetPerformance() {
CreatePerformanceObjectIfNeeded();
return mPerformance;
}
void nsPIDOMWindowInner::QueuePerformanceNavigationTiming() {
CreatePerformanceObjectIfNeeded();
if (mPerformance) {
mPerformance->QueueNavigationTimingEntry();
}
}
void nsPIDOMWindowInner::CreatePerformanceObjectIfNeeded() {
if (mPerformance || !mDoc) {
return;
}
RefPtr<nsDOMNavigationTiming> timing = mDoc->GetNavigationTiming();
nsCOMPtr<nsITimedChannel> timedChannel(do_QueryInterface(mDoc->GetChannel()));
if (timing) {
mPerformance = Performance::CreateForMainThread(this, mDoc->NodePrincipal(),
timing, timedChannel);
}
}
bool nsPIDOMWindowInner::IsSecureContext() const {
return nsGlobalWindowInner::Cast(this)->IsSecureContext();
}
void nsPIDOMWindowInner::Suspend(bool aIncludeSubWindows) {
nsGlobalWindowInner::Cast(this)->Suspend(aIncludeSubWindows);
}
void nsPIDOMWindowInner::Resume(bool aIncludeSubWindows) {
nsGlobalWindowInner::Cast(this)->Resume(aIncludeSubWindows);
}
void nsPIDOMWindowInner::SyncStateFromParentWindow() {
nsGlobalWindowInner::Cast(this)->SyncStateFromParentWindow();
}
Maybe<ClientInfo> nsPIDOMWindowInner::GetClientInfo() const {
return nsGlobalWindowInner::Cast(this)->GetClientInfo();
}
Maybe<ClientState> nsPIDOMWindowInner::GetClientState() const {
return nsGlobalWindowInner::Cast(this)->GetClientState();
}
Maybe<ServiceWorkerDescriptor> nsPIDOMWindowInner::GetController() const {
return nsGlobalWindowInner::Cast(this)->GetController();
}
void nsPIDOMWindowInner::SetPolicyContainer(
nsIPolicyContainer* aPolicyContainer) {
return nsGlobalWindowInner::Cast(this)->SetPolicyContainer(aPolicyContainer);
}
void nsPIDOMWindowInner::SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCsp) {
return nsGlobalWindowInner::Cast(this)->SetPreloadCsp(aPreloadCsp);
}
nsIPolicyContainer* nsPIDOMWindowInner::GetPolicyContainer() {
return nsGlobalWindowInner::Cast(this)->GetPolicyContainer();
}
void nsPIDOMWindowInner::NoteCalledRegisterForServiceWorkerScope(
const nsACString& aScope) {
nsGlobalWindowInner::Cast(this)->NoteCalledRegisterForServiceWorkerScope(
aScope);
}
void nsPIDOMWindowInner::NoteDOMContentLoaded() {
nsGlobalWindowInner::Cast(this)->NoteDOMContentLoaded();
}
bool nsGlobalWindowInner::ShouldReportForServiceWorkerScope(
const nsAString& aScope) {
bool result = false;
nsPIDOMWindowOuter* topOuter = GetInProcessScriptableTop();
NS_ENSURE_TRUE(topOuter, false);
nsGlobalWindowInner* topInner =
nsGlobalWindowInner::Cast(topOuter->GetCurrentInnerWindow());
NS_ENSURE_TRUE(topInner, false);
topInner->ShouldReportForServiceWorkerScopeInternal(
NS_ConvertUTF16toUTF8(aScope), &result);
return result;
}
InstallTriggerImpl* nsGlobalWindowInner::GetInstallTrigger() {
if (!mInstallTrigger &&
!StaticPrefs::extensions_InstallTriggerImpl_enabled()) {
// Return nullptr when InstallTriggerImpl is disabled by pref,
// which does not yet break the "typeof InstallTrigger !== 'undefined"
// "UA detection" use case, but prevents access to the InstallTriggerImpl
// methods and properties.
//
// NOTE: a separate pref ("extensions.InstallTrigger.enabled"), associated
// to this property using the [Pref] extended attribute in Window.webidl,
// does instead hide the entire InstallTrigger property.
//
// See Bug 1754441 for more details about this deprecation.
return nullptr;
}
if (!mInstallTrigger) {
ErrorResult rv;
mInstallTrigger = ConstructJSImplementation<InstallTriggerImpl>(
"@mozilla.org/addons/installtrigger;1", this, rv);
if (rv.Failed()) {
rv.SuppressException();
return nullptr;
}
}
return mInstallTrigger;
}
nsIDOMWindowUtils* nsGlobalWindowInner::GetWindowUtils(ErrorResult& aRv) {
FORWARD_TO_OUTER_OR_THROW(WindowUtils, (), aRv, nullptr);
}
CallState nsGlobalWindowInner::ShouldReportForServiceWorkerScopeInternal(
const nsACString& aScope, bool* aResultOut) {
MOZ_DIAGNOSTIC_ASSERT(aResultOut);
// First check to see if this window is controlled. If so, then we have
// found a match and are done.
const Maybe<ServiceWorkerDescriptor> swd = GetController();
if (swd.isSome() && swd.ref().Scope() == aScope) {
*aResultOut = true;
return CallState::Stop;
}
// Next, check to see if this window has called
// navigator.serviceWorker.register() for this scope. If so, then treat this
// as a match so console reports appear in the devtools console.
if (mClientSource &&
mClientSource->CalledRegisterForServiceWorkerScope(aScope)) {
*aResultOut = true;
return CallState::Stop;
}
// Finally check the current docshell nsILoadGroup to see if there are any
// outstanding navigation requests. If so, match the scope against the
// channel's URL. We want to show console reports during the FetchEvent
// intercepting the navigation itself.
nsCOMPtr<nsIDocumentLoader> loader(do_QueryInterface(GetDocShell()));
if (loader) {
nsCOMPtr<nsILoadGroup> loadgroup;
Unused << loader->GetLoadGroup(getter_AddRefs(loadgroup));
if (loadgroup) {
nsCOMPtr<nsISimpleEnumerator> iter;
Unused << loadgroup->GetRequests(getter_AddRefs(iter));
if (iter) {
nsCOMPtr<nsISupports> tmp;
bool hasMore = true;
// Check each network request in the load group.
while (NS_SUCCEEDED(iter->HasMoreElements(&hasMore)) && hasMore) {
iter->GetNext(getter_AddRefs(tmp));
nsCOMPtr<nsIChannel> loadingChannel(do_QueryInterface(tmp));
// Ignore subresource requests. Logging for a subresource
// FetchEvent should be handled above since the client is
// already controlled.
if (!loadingChannel ||
!nsContentUtils::IsNonSubresourceRequest(loadingChannel)) {
continue;
}
nsCOMPtr<nsIURI> loadingURL;
Unused << loadingChannel->GetURI(getter_AddRefs(loadingURL));
if (!loadingURL) {
continue;
}
nsAutoCString loadingSpec;
Unused << loadingURL->GetSpec(loadingSpec);
// Perform a simple substring comparison to match the scope
// against the channel URL.
if (StringBeginsWith(loadingSpec, aScope)) {
*aResultOut = true;
return CallState::Stop;
}
}
}
}
}
// The current window doesn't care about this service worker, but maybe
// one of our child frames does.
return CallOnInProcessChildren(
&nsGlobalWindowInner::ShouldReportForServiceWorkerScopeInternal, aScope,
aResultOut);
}
void nsGlobalWindowInner::NoteCalledRegisterForServiceWorkerScope(
const nsACString& aScope) {
if (!mClientSource) {
return;
}
mClientSource->NoteCalledRegisterForServiceWorkerScope(aScope);
}
void nsGlobalWindowInner::NoteDOMContentLoaded() {
if (!mClientSource) {
return;
}
mClientSource->NoteDOMContentLoaded();
}
void nsGlobalWindowInner::UpdateTopInnerWindow() {
if (IsTopInnerWindow() || !mTopInnerWindow) {
return;
}
nsGlobalWindowInner::Cast(mTopInnerWindow)
->UpdateWebSocketCount(-(int32_t)mNumOfOpenWebSockets);
}
bool nsGlobalWindowInner::IsInSyncOperation() {
return GetExtantDoc() && GetExtantDoc()->IsInSyncOperation();
}
bool nsGlobalWindowInner::IsSharedMemoryAllowedInternal(
nsIPrincipal* aPrincipal) const {
MOZ_ASSERT(NS_IsMainThread());
if (StaticPrefs::
dom_postMessage_sharedArrayBuffer_bypassCOOP_COEP_insecure_enabled()) {
return true;
}
if (ExtensionPolicyService::GetSingleton().IsExtensionProcess()) {
if (auto* basePrincipal = BasePrincipal::Cast(aPrincipal)) {
if (auto* policy = basePrincipal->AddonPolicy()) {
return policy->IsPrivileged();
}
}
}
return CrossOriginIsolated();
}
bool nsGlobalWindowInner::CrossOriginIsolated() const {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<BrowsingContext> bc = GetBrowsingContext();
MOZ_DIAGNOSTIC_ASSERT(bc);
return bc->CrossOriginIsolated();
}
bool nsGlobalWindowInner::OriginAgentCluster() const {
if (DocGroup* docGroup = GetDocGroup()) {
return docGroup->IsOriginKeyed();
}
return false;
}
WindowContext* TopWindowContext(nsPIDOMWindowInner& aWindow) {
WindowContext* wc = aWindow.GetWindowContext();
if (!wc) {
return nullptr;
}
return wc->TopWindowContext();
}
void nsPIDOMWindowInner::AddPeerConnection() {
MOZ_ASSERT(NS_IsMainThread());
++mActivePeerConnections;
if (mActivePeerConnections == 1 && mWindowGlobalChild) {
mWindowGlobalChild->SendUpdateActivePeerConnectionStatus(
/*aIsAdded*/ true);
// We need to present having active peer connections immediately. If we need
// to wait for the parent process to come back with this information we
// might start throttling.
if (WindowContext* top = TopWindowContext(*this)) {
top->TransientSetHasActivePeerConnections();
}
}
}
void nsPIDOMWindowInner::RemovePeerConnection() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mActivePeerConnections > 0);
--mActivePeerConnections;
if (mActivePeerConnections == 0 && mWindowGlobalChild) {
mWindowGlobalChild->SendUpdateActivePeerConnectionStatus(
/*aIsAdded*/ false);
}
}
bool nsGlobalWindowInner::HasActivePeerConnections() {
MOZ_ASSERT(NS_IsMainThread());
WindowContext* topWindowContext = TopWindowContext(*this);
return topWindowContext && topWindowContext->GetHasActivePeerConnections();
}
void nsPIDOMWindowInner::AddMediaKeysInstance(MediaKeys* aMediaKeys) {
MOZ_ASSERT(NS_IsMainThread());
mMediaKeysInstances.AppendElement(aMediaKeys);
if (mWindowGlobalChild && mMediaKeysInstances.Length() == 1) {
mWindowGlobalChild->BlockBFCacheFor(BFCacheStatus::CONTAINS_EME_CONTENT);
}
}
void nsPIDOMWindowInner::RemoveMediaKeysInstance(MediaKeys* aMediaKeys) {
MOZ_ASSERT(NS_IsMainThread());
mMediaKeysInstances.RemoveElement(aMediaKeys);
if (mWindowGlobalChild && mMediaKeysInstances.IsEmpty()) {
mWindowGlobalChild->UnblockBFCacheFor(BFCacheStatus::CONTAINS_EME_CONTENT);
}
}
bool nsPIDOMWindowInner::HasActiveMediaKeysInstance() {
MOZ_ASSERT(NS_IsMainThread());
return !mMediaKeysInstances.IsEmpty();
}
bool nsGlobalWindowInner::IsPlayingAudio() {
for (uint32_t i = 0; i < mAudioContexts.Length(); i++) {
if (mAudioContexts[i]->IsRunning()) {
return true;
}
}
RefPtr<AudioChannelService> acs = AudioChannelService::Get();
if (!acs) {
return false;
}
auto outer = GetOuterWindow();
if (!outer) {
// We've been unlinked and are about to die. Not a good time to pretend to
// be playing audio.
return false;
}
return acs->IsWindowActive(outer);
}
bool nsPIDOMWindowInner::IsDocumentLoaded() const { return mIsDocumentLoaded; }
mozilla::dom::TimeoutManager* nsGlobalWindowInner::GetTimeoutManager() {
return mTimeoutManager.get();
}
bool nsGlobalWindowInner::IsRunningTimeout() {
return GetTimeoutManager()->IsRunningTimeout();
}
void nsPIDOMWindowInner::TryToCacheTopInnerWindow() {
if (mHasTriedToCacheTopInnerWindow) {
return;
}
nsGlobalWindowInner* window = nsGlobalWindowInner::Cast(this);
MOZ_ASSERT(!window->IsDying());
mHasTriedToCacheTopInnerWindow = true;
MOZ_ASSERT(window);
if (nsCOMPtr<nsPIDOMWindowOuter> topOutter =
window->GetInProcessScriptableTop()) {
mTopInnerWindow = topOutter->GetCurrentInnerWindow();
}
}
void nsGlobalWindowInner::UpdateActiveIndexedDBDatabaseCount(int32_t aDelta) {
MOZ_ASSERT(NS_IsMainThread());
if (aDelta == 0) {
return;
}
// We count databases but not transactions because only active databases
// could block throttling.
uint32_t& counter = mTopInnerWindow
? mTopInnerWindow->mNumOfIndexedDBDatabases
: mNumOfIndexedDBDatabases;
counter += aDelta;
}
bool nsGlobalWindowInner::HasActiveIndexedDBDatabases() const {
MOZ_ASSERT(NS_IsMainThread());
return mTopInnerWindow ? mTopInnerWindow->mNumOfIndexedDBDatabases > 0
: mNumOfIndexedDBDatabases > 0;
}
void nsGlobalWindowInner::UpdateWebSocketCount(int32_t aDelta) {
MOZ_ASSERT(NS_IsMainThread());
if (aDelta == 0) {
return;
}
if (mTopInnerWindow && !IsTopInnerWindow()) {
nsGlobalWindowInner::Cast(mTopInnerWindow)->UpdateWebSocketCount(aDelta);
}
MOZ_DIAGNOSTIC_ASSERT(
aDelta > 0 || ((aDelta + mNumOfOpenWebSockets) < mNumOfOpenWebSockets));
mNumOfOpenWebSockets += aDelta;
}
bool nsGlobalWindowInner::HasOpenWebSockets() const {
MOZ_ASSERT(NS_IsMainThread());
return mNumOfOpenWebSockets ||
(mTopInnerWindow && mTopInnerWindow->mNumOfOpenWebSockets);
}
void nsGlobalWindowInner::AudioPlaybackChanged(bool aIsPlayingAudio) {
AUTO_PROFILER_MARKER_UNTYPED("AudioPlaybackChanged", DOM, {});
UpdateWorkersPlaybackState(*this, aIsPlayingAudio);
}
bool nsPIDOMWindowInner::IsCurrentInnerWindow() const {
if (mozilla::SessionHistoryInParent() && mBrowsingContext &&
mBrowsingContext->IsInBFCache()) {
return false;
}
if (!mBrowsingContext || mBrowsingContext->IsDiscarded()) {
// If our BrowsingContext has been discarded, we consider ourselves
// still-current if we were current at the time it was discarded.
return mOuterWindow && WasCurrentInnerWindow();
}
nsPIDOMWindowOuter* outer = mBrowsingContext->GetDOMWindow();
return outer && outer->GetCurrentInnerWindow() == this;
}
bool nsGlobalWindowInner::HasScheduledNormalOrHighPriorityWebTasks() const {
return gNumNormalOrHighPriorityQueuesHaveTaskScheduledMainThread > 0;
}
bool nsPIDOMWindowInner::IsFullyActive() const {
WindowContext* wc = GetWindowContext();
if (!wc || wc->IsDiscarded() || !wc->IsCurrent()) {
return false;
}
return GetBrowsingContext()->AncestorsAreCurrent();
}
void nsPIDOMWindowInner::SetAudioCapture(bool aCapture) {
RefPtr<AudioChannelService> service = AudioChannelService::GetOrCreate();
if (service) {
service->SetWindowAudioCaptured(GetOuterWindow(), mWindowID, aCapture);
}
}
void nsGlobalWindowInner::SetActiveLoadingState(bool aIsLoading) {
MOZ_LOG(
gTimeoutLog, mozilla::LogLevel::Debug,
("SetActiveLoadingState innerwindow %p: %d", (void*)this, aIsLoading));
if (GetBrowsingContext()) {
// Setting loading on a discarded context has no effect.
Unused << GetBrowsingContext()->SetLoading(aIsLoading);
}
if (!nsGlobalWindowInner::Cast(this)->IsChromeWindow()) {
mTimeoutManager->SetLoading(aIsLoading);
}
HintIsLoading(aIsLoading);
}
void nsGlobalWindowInner::HintIsLoading(bool aIsLoading) {
// Hint to tell the JS GC to use modified triggers during pageload.
if (mHintedWasLoading != aIsLoading) {
using namespace js::gc;
SetPerformanceHint(danger::GetJSContext(), aIsLoading
? PerformanceHint::InPageLoad
: PerformanceHint::Normal);
mHintedWasLoading = aIsLoading;
}
}
// nsISpeechSynthesisGetter
#ifdef MOZ_WEBSPEECH
SpeechSynthesis* nsGlobalWindowInner::GetSpeechSynthesis(ErrorResult& aError) {
if (!mSpeechSynthesis) {
mSpeechSynthesis = new SpeechSynthesis(this);
}
return mSpeechSynthesis;
}
bool nsGlobalWindowInner::HasActiveSpeechSynthesis() {
if (mSpeechSynthesis) {
return !mSpeechSynthesis->HasEmptyQueue();
}
return false;
}
#endif
mozilla::glean::Glean* nsGlobalWindowInner::Glean() {
if (!mGlean) {
mGlean = new mozilla::glean::Glean(this);
}
return mGlean;
}
mozilla::glean::GleanPings* nsGlobalWindowInner::GleanPings() {
if (!mGleanPings) {
mGleanPings = new mozilla::glean::GleanPings();
}
return mGleanPings;
}
Nullable<WindowProxyHolder> nsGlobalWindowInner::GetParent(
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetParentOuter, (), aError, nullptr);
}
/**
* GetInProcessScriptableParent used to be called when a script read
* window.parent. Under Fission, that is now handled by
* BrowsingContext::GetParent, and the result is a WindowProxyHolder rather than
* an actual global window. This method still exists for legacy callers which
* relied on the old logic, and require in-process windows. However, it only
* works correctly when no out-of-process frames exist between this window and
* the top-level window, so it should not be used in new code.
*
* In contrast to GetRealParent, GetInProcessScriptableParent respects <iframe
* mozbrowser> boundaries, so if |this| is contained by an <iframe
* mozbrowser>, we will return |this| as its own parent.
*/
nsPIDOMWindowOuter* nsGlobalWindowInner::GetInProcessScriptableParent() {
FORWARD_TO_OUTER(GetInProcessScriptableParent, (), nullptr);
}
/**
* GetInProcessScriptableTop used to be called when a script read window.top.
* Under Fission, that is now handled by BrowsingContext::Top, and the result is
* a WindowProxyHolder rather than an actual global window. This method still
* exists for legacy callers which relied on the old logic, and require
* in-process windows. However, it only works correctly when no out-of-process
* frames exist between this window and the top-level window, so it should not
* be used in new code.
*
* In contrast to GetRealTop, GetInProcessScriptableTop respects <iframe
* mozbrowser> boundaries. If we encounter a window owned by an <iframe
* mozbrowser> while walking up the window hierarchy, we'll stop and return that
* window.
*/
nsPIDOMWindowOuter* nsGlobalWindowInner::GetInProcessScriptableTop() {
FORWARD_TO_OUTER(GetInProcessScriptableTop, (), nullptr);
}
void nsGlobalWindowInner::GetContent(JSContext* aCx,
JS::MutableHandle<JSObject*> aRetval,
CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetContentOuter,
(aCx, aRetval, aCallerType, aError), aError, );
}
BarProp* nsGlobalWindowInner::GetMenubar(ErrorResult& aError) {
if (!mMenubar) {
mMenubar = new MenubarProp(this);
}
return mMenubar;
}
BarProp* nsGlobalWindowInner::GetToolbar(ErrorResult& aError) {
if (!mToolbar) {
mToolbar = new ToolbarProp(this);
}
return mToolbar;
}
BarProp* nsGlobalWindowInner::GetLocationbar(ErrorResult& aError) {
if (!mLocationbar) {
mLocationbar = new LocationbarProp(this);
}
return mLocationbar;
}
BarProp* nsGlobalWindowInner::GetPersonalbar(ErrorResult& aError) {
if (!mPersonalbar) {
mPersonalbar = new PersonalbarProp(this);
}
return mPersonalbar;
}
BarProp* nsGlobalWindowInner::GetStatusbar(ErrorResult& aError) {
if (!mStatusbar) {
mStatusbar = new StatusbarProp(this);
}
return mStatusbar;
}
BarProp* nsGlobalWindowInner::GetScrollbars(ErrorResult& aError) {
if (!mScrollbars) {
mScrollbars = new ScrollbarsProp(this);
}
return mScrollbars;
}
bool nsGlobalWindowInner::GetClosed(ErrorResult& aError) {
// If we're called from JS (which is the only way we should be getting called
// here) and we reach this point, that means our JS global is the current
// target of the WindowProxy, which means that we are the "current inner"
// of our outer. So if FORWARD_TO_OUTER fails to forward, that means the
// outer is already torn down, which corresponds to the closed state.
FORWARD_TO_OUTER(GetClosedOuter, (), true);
}
Nullable<WindowProxyHolder> nsGlobalWindowInner::IndexedGetter(
uint32_t aIndex) {
FORWARD_TO_OUTER(IndexedGetterOuter, (aIndex), nullptr);
}
namespace {
struct InterfaceShimEntry {
const char* geckoName;
const char* domName;
};
} // anonymous namespace
// We add shims from Components.interfaces.nsIDOMFoo to window.Foo for each
// interface that has interface constants that sites might be getting off
// of Ci.
const InterfaceShimEntry kInterfaceShimMap[] = {
{"nsIXMLHttpRequest", "XMLHttpRequest"},
{"nsIDOMDOMException", "DOMException"},
{"nsIDOMNode", "Node"},
{"nsIDOMCSSRule", "CSSRule"},
{"nsIDOMEvent", "Event"},
{"nsIDOMNSEvent", "Event"},
{"nsIDOMKeyEvent", "KeyEvent"},
{"nsIDOMMouseEvent", "MouseEvent"},
{"nsIDOMMouseScrollEvent", "MouseScrollEvent"},
{"nsIDOMMutationEvent", "MutationEvent"},
{"nsIDOMUIEvent", "UIEvent"},
{"nsIDOMHTMLMediaElement", "HTMLMediaElement"},
{"nsIDOMRange", "Range"},
// Think about whether Ci.nsINodeFilter can just go away for websites!
{"nsIDOMNodeFilter", "NodeFilter"},
{"nsIDOMXPathResult", "XPathResult"}};
bool nsGlobalWindowInner::ResolveComponentsShim(
JSContext* aCx, JS::Handle<JSObject*> aGlobal,
JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> aDesc) {
// Warn once.
nsCOMPtr<Document> doc = GetExtantDoc();
if (doc) {
doc->WarnOnceAbout(DeprecatedOperations::eComponents, /* asError = */ true);
// Keep track of how often this happens.
doc->SetUseCounter(eUseCounter_custom_ComponentsShimResolved);
}
// Create a fake Components object.
AssertSameCompartment(aCx, aGlobal);
JS::Rooted<JSObject*> components(aCx, JS_NewPlainObject(aCx));
if (NS_WARN_IF(!components)) {
return false;
}
// Create a fake interfaces object.
JS::Rooted<JSObject*> interfaces(aCx, JS_NewPlainObject(aCx));
if (NS_WARN_IF(!interfaces)) {
return false;
}
bool ok =
JS_DefineProperty(aCx, components, "interfaces", interfaces,
JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY);
if (NS_WARN_IF(!ok)) {
return false;
}
// Define a bunch of shims from the Ci.nsIDOMFoo to window.Foo for DOM
// interfaces with constants.
for (uint32_t i = 0; i < std::size(kInterfaceShimMap); ++i) {
// Grab the names from the table.
const char* geckoName = kInterfaceShimMap[i].geckoName;
const char* domName = kInterfaceShimMap[i].domName;
// Look up the appopriate interface object on the global.
JS::Rooted<JS::Value> v(aCx, JS::UndefinedValue());
ok = JS_GetProperty(aCx, aGlobal, domName, &v);
if (NS_WARN_IF(!ok)) {
return false;
}
if (!v.isObject()) {
NS_WARNING("Unable to find interface object on global");
continue;
}
// Define the shim on the interfaces object.
ok = JS_DefineProperty(
aCx, interfaces, geckoName, v,
JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY);
if (NS_WARN_IF(!ok)) {
return false;
}
}
aDesc.set(mozilla::Some(JS::PropertyDescriptor::Data(
JS::ObjectValue(*components),
{JS::PropertyAttribute::Configurable, JS::PropertyAttribute::Enumerable,
JS::PropertyAttribute::Writable})));
return true;
}
#ifdef RELEASE_OR_BETA
# define USE_CONTROLLERS_SHIM
#endif
#ifdef USE_CONTROLLERS_SHIM
static const JSClass ControllersShimClass = {"Controllers", 0};
static const JSClass XULControllersShimClass = {"XULControllers", 0};
#endif
bool nsGlobalWindowInner::DoResolve(
JSContext* aCx, JS::Handle<JSObject*> aObj, JS::Handle<jsid> aId,
JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> aDesc) {
// Note: Keep this in sync with MayResolve.
// Note: The infallibleInit call in GlobalResolve depends on this check.
if (!aId.isString()) {
return true;
}
bool found;
if (!WebIDLGlobalNameHash::DefineIfEnabled(aCx, aObj, aId, aDesc, &found)) {
return false;
}
if (found) {
return true;
}
// We support a cut-down Components.interfaces in case websites are
// using Components.interfaces.nsIFoo.CONSTANT_NAME for the ones
// that have constants.
if (StaticPrefs::dom_use_components_shim() &&
aId == XPCJSRuntime::Get()->GetStringID(XPCJSContext::IDX_COMPONENTS)) {
return ResolveComponentsShim(aCx, aObj, aDesc);
}
// We also support a "window.controllers" thing; apparently some
// sites use it for browser-sniffing. See bug 1010577.
#ifdef USE_CONTROLLERS_SHIM
// Note: We use |aObj| rather than |this| to get the principal here, because
// this is called during Window setup when the Document isn't necessarily
// hooked up yet.
if ((aId == XPCJSRuntime::Get()->GetStringID(XPCJSContext::IDX_CONTROLLERS) ||
aId == XPCJSRuntime::Get()->GetStringID(
XPCJSContext::IDX_CONTROLLERS_CLASS)) &&
!xpc::IsXrayWrapper(aObj) &&
!nsContentUtils::ObjectPrincipal(aObj)->IsSystemPrincipal()) {
if (GetExtantDoc()) {
GetExtantDoc()->WarnOnceAbout(
DeprecatedOperations::eWindow_Cc_ontrollers);
}
const JSClass* clazz;
if (aId ==
XPCJSRuntime::Get()->GetStringID(XPCJSContext::IDX_CONTROLLERS)) {
clazz = &XULControllersShimClass;
} else {
clazz = &ControllersShimClass;
}
MOZ_ASSERT(JS_IsGlobalObject(aObj));
JS::Rooted<JSObject*> shim(aCx, JS_NewObject(aCx, clazz));
if (NS_WARN_IF(!shim)) {
return false;
}
aDesc.set(mozilla::Some(JS::PropertyDescriptor::Data(
JS::ObjectValue(*shim),
{JS::PropertyAttribute::Configurable, JS::PropertyAttribute::Enumerable,
JS::PropertyAttribute::Writable})));
return true;
}
#endif
return true;
}
/* static */
bool nsGlobalWindowInner::MayResolve(jsid aId) {
// Note: This function does not fail and may not have any side-effects.
// Note: Keep this in sync with DoResolve.
if (!aId.isString()) {
return false;
}
if (aId == XPCJSRuntime::Get()->GetStringID(XPCJSContext::IDX_COMPONENTS)) {
return true;
}
if (aId == XPCJSRuntime::Get()->GetStringID(XPCJSContext::IDX_CONTROLLERS) ||
aId == XPCJSRuntime::Get()->GetStringID(
XPCJSContext::IDX_CONTROLLERS_CLASS)) {
// We only resolve .controllers/.Controllers in release builds and on
// non-chrome windows, but let's not worry about any of that stuff.
return true;
}
return WebIDLGlobalNameHash::MayResolve(aId);
}
void nsGlobalWindowInner::GetOwnPropertyNames(
JSContext* aCx, JS::MutableHandleVector<jsid> aNames, bool aEnumerableOnly,
ErrorResult& aRv) {
if (aEnumerableOnly) {
// The names we would return from here get defined on the window via one of
// two codepaths. The ones coming from the WebIDLGlobalNameHash will end up
// in the DefineConstructor function in BindingUtils, which always defines
// things as non-enumerable. The ones coming from the script namespace
// manager get defined by our resolve hook using FillPropertyDescriptor with
// 0 for the property attributes, so non-enumerable as well.
//
// So in the aEnumerableOnly case we have nothing to do.
return;
}
// "Components" is marked as enumerable but only resolved on demand :-/.
// aNames.AppendElement(u"Components"_ns);
JS::Rooted<JSObject*> wrapper(aCx, GetWrapper());
// There are actually two ways we can get called here: For normal
// enumeration or for Xray enumeration. In the latter case, we want to
// return all possible WebIDL names, because we don't really support
// deleting these names off our Xray; trying to resolve them will just make
// them come back. In the former case, we want to avoid returning deleted
// names. But the JS engine already knows about the non-deleted
// already-resolved names, so we can just return the so-far-unresolved ones.
//
// We can tell which case we're in by whether aCx is in our wrapper's
// compartment. If not, we're in the Xray case.
WebIDLGlobalNameHash::NameType nameType =
js::IsObjectInContextCompartment(wrapper, aCx)
? WebIDLGlobalNameHash::UnresolvedNamesOnly
: WebIDLGlobalNameHash::AllNames;
if (!WebIDLGlobalNameHash::GetNames(aCx, wrapper, nameType, aNames)) {
aRv.NoteJSContextException(aCx);
}
}
/* static */
bool nsGlobalWindowInner::IsPrivilegedChromeWindow(JSContext*, JSObject* aObj) {
// For now, have to deal with XPConnect objects here.
nsGlobalWindowInner* win = xpc::WindowOrNull(aObj);
return win && win->IsChromeWindow() &&
nsContentUtils::ObjectPrincipal(aObj) ==
nsContentUtils::GetSystemPrincipal();
}
/* static */
bool nsGlobalWindowInner::DeviceSensorsEnabled(JSContext*, JSObject*) {
return Preferences::GetBool("device.sensors.enabled");
}
Crypto* nsGlobalWindowInner::GetCrypto(ErrorResult& aError) {
if (!mCrypto) {
mCrypto = new Crypto(this);
}
return mCrypto;
}
nsIControllers* nsGlobalWindowInner::GetControllers(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetControllersOuter, (aError), aError, nullptr);
}
nsresult nsGlobalWindowInner::GetControllers(nsIControllers** aResult) {
ErrorResult rv;
nsCOMPtr<nsIControllers> controllers = GetControllers(rv);
controllers.forget(aResult);
return rv.StealNSResult();
}
Nullable<WindowProxyHolder> nsGlobalWindowInner::GetOpenerWindow(
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetOpenerWindowOuter, (), aError, nullptr);
}
void nsGlobalWindowInner::GetOpener(JSContext* aCx,
JS::MutableHandle<JS::Value> aRetval,
ErrorResult& aError) {
Nullable<WindowProxyHolder> opener = GetOpenerWindow(aError);
if (aError.Failed() || opener.IsNull()) {
aRetval.setNull();
return;
}
if (!ToJSValue(aCx, opener.Value(), aRetval)) {
aError.NoteJSContextException(aCx);
}
}
void nsGlobalWindowInner::SetOpener(JSContext* aCx,
JS::Handle<JS::Value> aOpener,
ErrorResult& aError) {
if (aOpener.isNull()) {
RefPtr<BrowsingContext> bc(GetBrowsingContext());
if (!bc->IsDiscarded()) {
bc->SetOpener(nullptr);
}
return;
}
// If something other than null is passed, just define aOpener on our inner
// window's JS object, wrapped into the current compartment so that for Xrays
// we define on the Xray expando object, but don't set it on the outer window,
// so that it'll get reset on navigation. This is just like replaceable
// properties, but we're not quite readonly.
RedefineProperty(aCx, "opener", aOpener, aError);
}
void nsGlobalWindowInner::GetEvent(OwningEventOrUndefined& aRetval) {
if (mEvent) {
aRetval.SetAsEvent() = mEvent;
} else {
aRetval.SetUndefined();
}
}
void nsGlobalWindowInner::GetStatus(nsAString& aStatus, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetStatusOuter, (aStatus), aError, );
}
void nsGlobalWindowInner::SetStatus(const nsAString& aStatus,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(SetStatusOuter, (aStatus), aError, );
}
void nsGlobalWindowInner::GetName(nsAString& aName, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetNameOuter, (aName), aError, );
}
void nsGlobalWindowInner::SetName(const nsAString& aName,
mozilla::ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(SetNameOuter, (aName, aError), aError, );
}
double nsGlobalWindowInner::GetInnerWidth(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetInnerWidthOuter, (aError), aError, 0);
}
nsresult nsGlobalWindowInner::GetInnerWidth(double* aWidth) {
ErrorResult rv;
// Callee doesn't care about the caller type, but play it safe.
*aWidth = GetInnerWidth(rv);
return rv.StealNSResult();
}
double nsGlobalWindowInner::GetInnerHeight(ErrorResult& aError) {
// We ignore aCallerType; we only have that argument because some other things
// called by GetReplaceableWindowCoord need it. If this ever changes, fix
// nsresult nsGlobalWindowInner::GetInnerHeight(double* aInnerWidth)
// to actually take a useful CallerType and pass it in here.
FORWARD_TO_OUTER_OR_THROW(GetInnerHeightOuter, (aError), aError, 0);
}
nsresult nsGlobalWindowInner::GetInnerHeight(double* aHeight) {
ErrorResult rv;
// Callee doesn't care about the caller type, but play it safe.
*aHeight = GetInnerHeight(rv);
return rv.StealNSResult();
}
int32_t nsGlobalWindowInner::GetOuterWidth(CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetOuterWidthOuter, (aCallerType, aError), aError,
0);
}
int32_t nsGlobalWindowInner::GetOuterHeight(CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetOuterHeightOuter, (aCallerType, aError), aError,
0);
}
double nsGlobalWindowInner::ScreenEdgeSlopX() const {
FORWARD_TO_OUTER(ScreenEdgeSlopX, (), 0);
}
double nsGlobalWindowInner::ScreenEdgeSlopY() const {
FORWARD_TO_OUTER(ScreenEdgeSlopY, (), 0);
}
int32_t nsGlobalWindowInner::GetScreenX(CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScreenXOuter, (aCallerType, aError), aError, 0);
}
int32_t nsGlobalWindowInner::GetScreenY(CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScreenYOuter, (aCallerType, aError), aError, 0);
}
float nsGlobalWindowInner::GetMozInnerScreenX(CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetMozInnerScreenXOuter, (aCallerType), aError, 0);
}
float nsGlobalWindowInner::GetMozInnerScreenY(CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetMozInnerScreenYOuter, (aCallerType), aError, 0);
}
static nsPresContext* GetPresContextForRatio(Document* aDoc) {
if (nsPresContext* presContext = aDoc->GetPresContext()) {
return presContext;
}
// We're in an undisplayed subdocument... There's not really an awesome way
// to tell what the right DPI is from here, so we try to walk up our parent
// document chain to the extent that the docs can observe each other.
Document* doc = aDoc;
while (doc->StyleOrLayoutObservablyDependsOnParentDocumentLayout()) {
doc = doc->GetInProcessParentDocument();
if (nsPresContext* presContext = doc->GetPresContext()) {
return presContext;
}
}
return nullptr;
}
double nsGlobalWindowInner::GetDevicePixelRatio(CallerType aCallerType,
ErrorResult& aError) {
ENSURE_ACTIVE_DOCUMENT(aError, 0.0);
RefPtr<nsPresContext> presContext = GetPresContextForRatio(mDoc);
if (NS_WARN_IF(!presContext)) {
// Still nothing, oh well.
return 1.0;
}
if (nsIGlobalObject::ShouldResistFingerprinting(
aCallerType, RFPTarget::WindowDevicePixelRatio)) {
return nsRFPService::GetDevicePixelRatioAtZoom(presContext->GetFullZoom());
}
if (aCallerType == CallerType::NonSystem) {
float overrideDPPX = presContext->GetOverrideDPPX();
if (overrideDPPX > 0.0f) {
return overrideDPPX;
}
}
return double(AppUnitsPerCSSPixel()) /
double(presContext->AppUnitsPerDevPixel());
}
double nsGlobalWindowInner::GetDesktopToDeviceScale(ErrorResult& aError) {
ENSURE_ACTIVE_DOCUMENT(aError, 0.0);
nsPresContext* presContext = GetPresContextForRatio(mDoc);
if (!presContext) {
return 1.0;
}
return presContext->DeviceContext()->GetDesktopToDeviceScale().scale;
}
uint32_t nsGlobalWindowInner::RequestAnimationFrame(
FrameRequestCallback& aCallback, ErrorResult& aError) {
if (!mDoc) {
return 0;
}
if (GetWrapperPreserveColor()) {
js::NotifyAnimationActivity(GetWrapperPreserveColor());
}
DebuggerNotificationDispatch(this,
DebuggerNotificationType::RequestAnimationFrame);
uint32_t handle;
aError = mDoc->ScheduleFrameRequestCallback(aCallback, &handle);
return handle;
}
void nsGlobalWindowInner::CancelAnimationFrame(uint32_t aHandle,
ErrorResult& aError) {
if (!mDoc) {
return;
}
DebuggerNotificationDispatch(this,
DebuggerNotificationType::CancelAnimationFrame);
mDoc->CancelFrameRequestCallback(aHandle);
}
already_AddRefed<MediaQueryList> nsGlobalWindowInner::MatchMedia(
const nsACString& aMediaQueryList, CallerType aCallerType,
ErrorResult& aError) {
ENSURE_ACTIVE_DOCUMENT(aError, nullptr);
return mDoc->MatchMedia(aMediaQueryList, aCallerType);
}
int32_t nsGlobalWindowInner::GetScrollMinX(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScrollBoundaryOuter, (eSideLeft), aError, 0);
}
int32_t nsGlobalWindowInner::GetScrollMinY(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScrollBoundaryOuter, (eSideTop), aError, 0);
}
int32_t nsGlobalWindowInner::GetScrollMaxX(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScrollBoundaryOuter, (eSideRight), aError, 0);
}
int32_t nsGlobalWindowInner::GetScrollMaxY(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScrollBoundaryOuter, (eSideBottom), aError, 0);
}
double nsGlobalWindowInner::GetScrollX(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScrollXOuter, (), aError, 0);
}
double nsGlobalWindowInner::GetScrollY(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetScrollYOuter, (), aError, 0);
}
uint32_t nsGlobalWindowInner::Length() { FORWARD_TO_OUTER(Length, (), 0); }
Nullable<WindowProxyHolder> nsGlobalWindowInner::GetTop(
mozilla::ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetTopOuter, (), aError, nullptr);
}
already_AddRefed<BrowsingContext> nsGlobalWindowInner::GetChildWindow(
const nsAString& aName) {
if (GetOuterWindowInternal()) {
return GetOuterWindowInternal()->GetChildWindow(aName);
}
return nullptr;
}
void nsGlobalWindowInner::RefreshRealmPrincipal() {
JS::SetRealmPrincipals(js::GetNonCCWObjectRealm(GetWrapperPreserveColor()),
nsJSPrincipals::get(mDoc->NodePrincipal()));
}
void nsGlobalWindowInner::RefreshReduceTimerPrecisionCallerType() {
JS::SetRealmReduceTimerPrecisionCallerType(
js::GetNonCCWObjectRealm(GetWrapperPreserveColor()),
RTPCallerTypeToToken(GetRTPCallerType()));
}
already_AddRefed<nsIWidget> nsGlobalWindowInner::GetMainWidget() {
FORWARD_TO_OUTER(GetMainWidget, (), nullptr);
}
nsIWidget* nsGlobalWindowInner::GetNearestWidget() const {
if (GetOuterWindowInternal()) {
return GetOuterWindowInternal()->GetNearestWidget();
}
return nullptr;
}
void nsGlobalWindowInner::SetFullScreen(bool aFullscreen,
mozilla::ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(SetFullscreenOuter, (aFullscreen, aError), aError,
/* void */);
}
bool nsGlobalWindowInner::GetFullScreen(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetFullscreenOuter, (), aError, false);
}
bool nsGlobalWindowInner::GetFullScreen() {
ErrorResult dummy;
bool fullscreen = GetFullScreen(dummy);
dummy.SuppressException();
return fullscreen;
}
void nsGlobalWindowInner::Dump(const nsAString& aStr) {
if (!nsJSUtils::DumpEnabled()) {
return;
}
char* cstr = ToNewUTF8String(aStr);
#if defined(XP_MACOSX)
// have to convert \r to \n so that printing to the console works
char *c = cstr, *cEnd = cstr + strlen(cstr);
while (c < cEnd) {
if (*c == '\r') *c = '\n';
c++;
}
#endif
if (cstr) {
MOZ_LOG(nsContentUtils::DOMDumpLog(), LogLevel::Debug,
("[Window.Dump] %s", cstr));
#ifdef XP_WIN
PrintToDebugger(cstr);
#endif
#ifdef ANDROID
__android_log_write(ANDROID_LOG_INFO, "GeckoDump", cstr);
#endif
FILE* fp = gDumpFile ? gDumpFile : stdout;
fputs(cstr, fp);
fflush(fp);
free(cstr);
}
}
void nsGlobalWindowInner::Alert(nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
Alert(u""_ns, aSubjectPrincipal, aError);
}
void nsGlobalWindowInner::Alert(const nsAString& aMessage,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(AlertOuter, (aMessage, aSubjectPrincipal, aError),
aError, );
}
bool nsGlobalWindowInner::Confirm(const nsAString& aMessage,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(ConfirmOuter, (aMessage, aSubjectPrincipal, aError),
aError, false);
}
already_AddRefed<Promise> nsGlobalWindowInner::Fetch(
const RequestOrUTF8String& aInput, const RequestInit& aInit,
CallerType aCallerType, ErrorResult& aRv) {
return FetchRequest(this, aInput, aInit, aCallerType, aRv);
}
void nsGlobalWindowInner::Prompt(const nsAString& aMessage,
const nsAString& aInitial, nsAString& aReturn,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(
PromptOuter, (aMessage, aInitial, aReturn, aSubjectPrincipal, aError),
aError, );
}
void nsGlobalWindowInner::Focus(CallerType aCallerType, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(FocusOuter,
(aCallerType, /* aFromOtherProcess */ false,
nsFocusManager::GenerateFocusActionId()),
aError, );
}
nsresult nsGlobalWindowInner::Focus(CallerType aCallerType) {
ErrorResult rv;
Focus(aCallerType, rv);
return rv.StealNSResult();
}
void nsGlobalWindowInner::Blur(CallerType aCallerType, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(BlurOuter, (aCallerType), aError, );
}
void nsGlobalWindowInner::Stop(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(StopOuter, (aError), aError, );
}
void nsGlobalWindowInner::Print(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(PrintOuter, (aError), aError, );
}
Nullable<WindowProxyHolder> nsGlobalWindowInner::PrintPreview(
nsIPrintSettings* aSettings, nsIWebProgressListener* aListener,
nsIDocShell* aDocShellToCloneInto, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(
Print,
(aSettings,
/* aRemotePrintJob = */ nullptr, aListener, aDocShellToCloneInto,
nsGlobalWindowOuter::IsPreview::Yes,
nsGlobalWindowOuter::IsForWindowDotPrint::No,
/* aPrintPreviewCallback = */ nullptr, nullptr, aError),
aError, nullptr);
}
void nsGlobalWindowInner::MoveTo(int32_t aXPos, int32_t aYPos,
CallerType aCallerType, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(MoveToOuter, (aXPos, aYPos, aCallerType, aError),
aError, );
}
void nsGlobalWindowInner::MoveBy(int32_t aXDif, int32_t aYDif,
CallerType aCallerType, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(MoveByOuter, (aXDif, aYDif, aCallerType, aError),
aError, );
}
void nsGlobalWindowInner::ResizeTo(int32_t aWidth, int32_t aHeight,
CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(ResizeToOuter,
(aWidth, aHeight, aCallerType, aError), aError, );
}
void nsGlobalWindowInner::ResizeBy(int32_t aWidthDif, int32_t aHeightDif,
CallerType aCallerType,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(
ResizeByOuter, (aWidthDif, aHeightDif, aCallerType, aError), aError, );
}
void nsGlobalWindowInner::SizeToContent(
const SizeToContentConstraints& aConstraints, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(SizeToContentOuter, (aConstraints, aError),
aError, );
}
already_AddRefed<nsPIWindowRoot> nsGlobalWindowInner::GetTopWindowRoot() {
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
if (!outer) {
return nullptr;
}
return outer->GetTopWindowRoot();
}
void nsGlobalWindowInner::ScrollTo(double aXScroll, double aYScroll) {
ScrollToOptions options;
options.mLeft.Construct(aXScroll);
options.mTop.Construct(aYScroll);
ScrollTo(options);
}
void nsGlobalWindowInner::ScrollTo(const ScrollToOptions& aOptions) {
Maybe<double> left;
Maybe<double> top;
if (aOptions.mLeft.WasPassed()) {
left.emplace(ToZeroIfNonfinite(aOptions.mLeft.Value()));
}
if (aOptions.mTop.WasPassed()) {
top.emplace(ToZeroIfNonfinite(aOptions.mTop.Value()));
}
// When scrolling to a non-zero offset, we need to determine whether that
// position is within our scrollable range, so we need updated layout
// information.
if ((top && *top != 0) || (left && *left != 0)) {
FlushPendingNotifications(FlushType::Layout);
}
ScrollContainerFrame* sf = GetScrollContainerFrame();
if (!sf) {
return;
}
CSSPoint scrollPos = sf->GetScrollPositionCSSPixels();
if (left) {
scrollPos.x = *left;
}
if (top) {
scrollPos.y = *top;
}
// Here we calculate what the max pixel value is that we can
// scroll to, we do this by dividing maxint with the pixel to
// twips conversion factor, and subtracting 4, the 4 comes from
// experimenting with this value, anything less makes the view
// code not scroll correctly, I have no idea why. -- jst
//
// FIXME(emilio): This seems like if needed it should be done by the
// scrolling code itself...
const double maxpx = CSSPixel::FromAppUnits(0x7fffffff) - 4;
if (scrollPos.x > maxpx) {
scrollPos.x = maxpx;
}
if (scrollPos.y > maxpx) {
scrollPos.y = maxpx;
}
auto scrollMode = sf->IsSmoothScroll(aOptions.mBehavior)
? ScrollMode::SmoothMsd
: ScrollMode::Instant;
sf->ScrollToCSSPixels(scrollPos, scrollMode);
}
void nsGlobalWindowInner::ScrollBy(double aXScrollDif, double aYScrollDif) {
ScrollToOptions options;
options.mLeft.Construct(aXScrollDif);
options.mTop.Construct(aYScrollDif);
// It seems like it would make more sense for ScrollBy to use
// SMOOTH mode, but tests seem to depend on the synchronous behaviour.
// Perhaps Web content does too.
ScrollBy(options);
}
void nsGlobalWindowInner::ScrollBy(const ScrollToOptions& aOptions) {
CSSPoint scrollDelta;
if (aOptions.mLeft.WasPassed()) {
scrollDelta.x = ToZeroIfNonfinite(aOptions.mLeft.Value());
}
if (aOptions.mTop.WasPassed()) {
scrollDelta.y = ToZeroIfNonfinite(aOptions.mTop.Value());
}
if (!scrollDelta.x && !scrollDelta.y) {
return;
}
FlushPendingNotifications(FlushType::Layout);
ScrollContainerFrame* sf = GetScrollContainerFrame();
if (!sf) {
return;
}
auto scrollMode = sf->IsSmoothScroll(aOptions.mBehavior)
? ScrollMode::SmoothMsd
: ScrollMode::Instant;
sf->ScrollByCSSPixels(scrollDelta, scrollMode);
}
void nsGlobalWindowInner::ScrollByLines(int32_t numLines,
const ScrollOptions& aOptions) {
if (!numLines) {
return;
}
FlushPendingNotifications(FlushType::Layout);
ScrollContainerFrame* sf = GetScrollContainerFrame();
if (!sf) {
return;
}
// It seems like it would make more sense for ScrollByLines to use
// SMOOTH mode, but tests seem to depend on the synchronous behaviour.
// Perhaps Web content does too.
ScrollMode scrollMode = sf->IsSmoothScroll(aOptions.mBehavior)
? ScrollMode::SmoothMsd
: ScrollMode::Instant;
sf->ScrollBy(nsIntPoint(0, numLines), ScrollUnit::LINES, scrollMode);
}
void nsGlobalWindowInner::ScrollByPages(int32_t numPages,
const ScrollOptions& aOptions) {
if (!numPages) {
return;
}
FlushPendingNotifications(FlushType::Layout);
ScrollContainerFrame* sf = GetScrollContainerFrame();
if (!sf) {
return;
}
// It seems like it would make more sense for ScrollByPages to use
// SMOOTH mode, but tests seem to depend on the synchronous behaviour.
// Perhaps Web content does too.
ScrollMode scrollMode = sf->IsSmoothScroll(aOptions.mBehavior)
? ScrollMode::SmoothMsd
: ScrollMode::Instant;
sf->ScrollBy(nsIntPoint(0, numPages), ScrollUnit::PAGES, scrollMode);
}
void nsGlobalWindowInner::MozScrollSnap() {
FlushPendingNotifications(FlushType::Layout);
if (ScrollContainerFrame* sf = GetScrollContainerFrame()) {
sf->ScrollSnap();
}
}
void nsGlobalWindowInner::ClearTimeout(int32_t aHandle) {
DebuggerNotificationDispatch(this, DebuggerNotificationType::ClearTimeout);
if (aHandle > 0) {
mTimeoutManager->ClearTimeout(aHandle, Timeout::Reason::eTimeoutOrInterval);
}
}
void nsGlobalWindowInner::ClearInterval(int32_t aHandle) {
DebuggerNotificationDispatch(this, DebuggerNotificationType::ClearInterval);
if (aHandle > 0) {
mTimeoutManager->ClearTimeout(aHandle, Timeout::Reason::eTimeoutOrInterval);
}
}
void nsGlobalWindowInner::SetResizable(bool aResizable) const {
// nop
}
void nsGlobalWindowInner::CaptureEvents() {
if (mDoc) {
mDoc->WarnOnceAbout(DeprecatedOperations::eUseOfCaptureEvents);
}
}
void nsGlobalWindowInner::ReleaseEvents() {
if (mDoc) {
mDoc->WarnOnceAbout(DeprecatedOperations::eUseOfReleaseEvents);
}
}
Nullable<WindowProxyHolder> nsGlobalWindowInner::Open(const nsAString& aUrl,
const nsAString& aName,
const nsAString& aOptions,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(OpenOuter, (aUrl, aName, aOptions, aError), aError,
nullptr);
}
Nullable<WindowProxyHolder> nsGlobalWindowInner::OpenDialog(
JSContext* aCx, const nsAString& aUrl, const nsAString& aName,
const nsAString& aOptions, const Sequence<JS::Value>& aExtraArgument,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(
OpenDialogOuter, (aCx, aUrl, aName, aOptions, aExtraArgument, aError),
aError, nullptr);
}
WindowProxyHolder nsGlobalWindowInner::GetFrames(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetFramesOuter, (), aError, Window());
}
void nsGlobalWindowInner::PostMessageMoz(JSContext* aCx,
JS::Handle<JS::Value> aMessage,
const nsAString& aTargetOrigin,
JS::Handle<JS::Value> aTransfer,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(
PostMessageMozOuter,
(aCx, aMessage, aTargetOrigin, aTransfer, aSubjectPrincipal, aError),
aError, );
}
void nsGlobalWindowInner::PostMessageMoz(JSContext* aCx,
JS::Handle<JS::Value> aMessage,
const nsAString& aTargetOrigin,
const Sequence<JSObject*>& aTransfer,
nsIPrincipal& aSubjectPrincipal,
ErrorResult& aRv) {
JS::Rooted<JS::Value> transferArray(aCx, JS::UndefinedValue());
aRv = nsContentUtils::CreateJSValueFromSequenceOfObject(aCx, aTransfer,
&transferArray);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
PostMessageMoz(aCx, aMessage, aTargetOrigin, transferArray, aSubjectPrincipal,
aRv);
}
void nsGlobalWindowInner::PostMessageMoz(
JSContext* aCx, JS::Handle<JS::Value> aMessage,
const WindowPostMessageOptions& aOptions, nsIPrincipal& aSubjectPrincipal,
ErrorResult& aRv) {
JS::Rooted<JS::Value> transferArray(aCx, JS::UndefinedValue());
aRv = nsContentUtils::CreateJSValueFromSequenceOfObject(
aCx, aOptions.mTransfer, &transferArray);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
PostMessageMoz(aCx, aMessage, aOptions.mTargetOrigin, transferArray,
aSubjectPrincipal, aRv);
}
void nsGlobalWindowInner::Close(CallerType aCallerType, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(CloseOuter, (aCallerType == CallerType::System),
aError, );
}
nsresult nsGlobalWindowInner::Close() {
FORWARD_TO_OUTER(Close, (), NS_ERROR_UNEXPECTED);
}
bool nsGlobalWindowInner::IsInModalState() {
FORWARD_TO_OUTER(IsInModalState, (), false);
}
void nsGlobalWindowInner::NotifyWindowIDDestroyed(const char* aTopic) {
nsCOMPtr<nsIRunnable> runnable =
new WindowDestroyedEvent(this, mWindowID, aTopic);
Dispatch(runnable.forget());
}
Element* nsGlobalWindowInner::GetFrameElement(nsIPrincipal& aSubjectPrincipal,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetFrameElement, (aSubjectPrincipal), aError,
nullptr);
}
Element* nsGlobalWindowInner::GetRealFrameElement(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetFrameElement, (), aError, nullptr);
}
void nsGlobalWindowInner::UpdateCommands(const nsAString& anAction) {
if (GetOuterWindowInternal()) {
GetOuterWindowInternal()->UpdateCommands(anAction);
}
}
Selection* nsGlobalWindowInner::GetSelection(ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetSelectionOuter, (), aError, nullptr);
}
WebTaskScheduler* nsGlobalWindowInner::Scheduler() {
if (!mWebTaskScheduler) {
mWebTaskScheduler = WebTaskScheduler::CreateForMainThread(this);
}
MOZ_ASSERT(mWebTaskScheduler);
return mWebTaskScheduler;
}
inline void nsGlobalWindowInner::SetWebTaskSchedulingState(
WebTaskSchedulingState* aState) {
mWebTaskSchedulingState = aState;
}
bool nsGlobalWindowInner::Find(const nsAString& aString, bool aCaseSensitive,
bool aBackwards, bool aWrapAround,
bool aWholeWord, bool aSearchInFrames,
bool aShowDialog, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(FindOuter,
(aString, aCaseSensitive, aBackwards, aWrapAround,
aWholeWord, aSearchInFrames, aShowDialog, aError),
aError, false);
}
void nsGlobalWindowInner::GetOrigin(nsAString& aOrigin) {
nsContentUtils::GetWebExposedOriginSerialization(GetPrincipal(), aOrigin);
}
// See also AutoJSAPI::ReportException
void nsGlobalWindowInner::ReportError(JSContext* aCx,
JS::Handle<JS::Value> aError,
CallerType aCallerType,
ErrorResult& aRv) {
if (MOZ_UNLIKELY(!HasActiveDocument())) {
return aRv.Throw(NS_ERROR_XPC_SECURITY_MANAGER_VETO);
}
JS::ErrorReportBuilder jsReport(aCx);
JS::ExceptionStack exnStack(aCx, aError, nullptr);
if (!jsReport.init(aCx, exnStack, JS::ErrorReportBuilder::NoSideEffects)) {
return aRv.NoteJSContextException(aCx);
}
RefPtr<xpc::ErrorReport> xpcReport = new xpc::ErrorReport();
bool isChrome = aCallerType == CallerType::System;
xpcReport->Init(jsReport.report(), jsReport.toStringResult().c_str(),
isChrome, WindowID());
JS::RootingContext* rcx = JS::RootingContext::get(aCx);
DispatchScriptErrorEvent(this, rcx, xpcReport, exnStack.exception(),
exnStack.stack());
}
void nsGlobalWindowInner::Atob(const nsAString& aAsciiBase64String,
nsAString& aBinaryData, ErrorResult& aError) {
aError = nsContentUtils::Atob(aAsciiBase64String, aBinaryData);
}
void nsGlobalWindowInner::Btoa(const nsAString& aBinaryData,
nsAString& aAsciiBase64String,
ErrorResult& aError) {
aError = nsContentUtils::Btoa(aBinaryData, aAsciiBase64String);
}
//*****************************************************************************
// EventTarget
//*****************************************************************************
nsPIDOMWindowOuter* nsGlobalWindowInner::GetOwnerGlobalForBindingsInternal() {
return nsPIDOMWindowOuter::GetFromCurrentInner(this);
}
bool nsGlobalWindowInner::DispatchEvent(Event& aEvent, CallerType aCallerType,
ErrorResult& aRv) {
if (!IsCurrentInnerWindow()) {
NS_WARNING(
"DispatchEvent called on non-current inner window, dropping. "
"Please check the window in the caller instead.");
aRv.Throw(NS_ERROR_FAILURE);
return false;
}
if (!mDoc) {
aRv.Throw(NS_ERROR_FAILURE);
return false;
}
// Obtain a presentation shell
RefPtr<nsPresContext> presContext = mDoc->GetPresContext();
nsEventStatus status = nsEventStatus_eIgnore;
nsresult rv = EventDispatcher::DispatchDOMEvent(this, nullptr, &aEvent,
presContext, &status);
bool retval = !aEvent.DefaultPrevented(aCallerType);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
}
return retval;
}
mozilla::Maybe<mozilla::dom::EventCallbackDebuggerNotificationType>
nsGlobalWindowInner::GetDebuggerNotificationType() const {
return mozilla::Some(
mozilla::dom::EventCallbackDebuggerNotificationType::Global);
}
bool nsGlobalWindowInner::ComputeDefaultWantsUntrusted(ErrorResult& aRv) {
return !nsContentUtils::IsChromeDoc(mDoc);
}
EventListenerManager* nsGlobalWindowInner::GetOrCreateListenerManager() {
if (!mListenerManager) {
mListenerManager =
new EventListenerManager(static_cast<EventTarget*>(this));
}
return mListenerManager;
}
EventListenerManager* nsGlobalWindowInner::GetExistingListenerManager() const {
return mListenerManager;
}
mozilla::dom::DebuggerNotificationManager*
nsGlobalWindowInner::GetOrCreateDebuggerNotificationManager() {
if (!mDebuggerNotificationManager) {
mDebuggerNotificationManager = new DebuggerNotificationManager(this);
}
return mDebuggerNotificationManager;
}
mozilla::dom::DebuggerNotificationManager*
nsGlobalWindowInner::GetExistingDebuggerNotificationManager() {
return mDebuggerNotificationManager;
}
//*****************************************************************************
// nsGlobalWindowInner::nsPIDOMWindow
//*****************************************************************************
Location* nsGlobalWindowInner::Location() {
if (!mLocation) {
mLocation = new dom::Location(this);
}
return mLocation;
}
void nsGlobalWindowInner::MaybeUpdateTouchState() {
if (mMayHaveTouchEventListener) {
nsCOMPtr<nsIObserverService> observerService =
services::GetObserverService();
if (observerService) {
observerService->NotifyObservers(static_cast<nsIDOMWindow*>(this),
DOM_TOUCH_LISTENER_ADDED, nullptr);
}
}
}
void nsGlobalWindowInner::EnableGamepadUpdates() {
if (mHasGamepad) {
RefPtr<GamepadManager> gamepadManager(GamepadManager::GetService());
if (gamepadManager) {
gamepadManager->AddListener(this);
}
}
}
void nsGlobalWindowInner::DisableGamepadUpdates() {
if (mHasGamepad) {
RefPtr<GamepadManager> gamepadManager(GamepadManager::GetService());
if (gamepadManager) {
gamepadManager->RemoveListener(this);
}
}
}
void nsGlobalWindowInner::EnableVRUpdates() {
// We need to create a VREventObserver before we can either detect XR runtimes
// or start an XR session
if (!mVREventObserver && (mHasXRSession || mXRRuntimeDetectionInFlight)) {
// Assert that we are not creating the observer while IsDying() as
// that would result in a leak. VREventObserver holds a RefPtr to
// this nsGlobalWindowInner and would prevent it from being deallocated.
MOZ_ASSERT(!IsDying(),
"Creating a VREventObserver for an nsGlobalWindow that is "
"dying would cause it to leak.");
mVREventObserver = new VREventObserver(this);
}
// If the content has an XR session, then we need to tell
// VREventObserver that there is VR activity.
if (mHasXRSession) {
nsPIDOMWindowOuter* outer = GetOuterWindow();
if (outer && !outer->IsBackground()) {
StartVRActivity();
}
}
}
void nsGlobalWindowInner::DisableVRUpdates() {
if (mVREventObserver) {
mVREventObserver->DisconnectFromOwner();
mVREventObserver = nullptr;
}
}
void nsGlobalWindowInner::StartVRActivity() {
/**
* If the content has an XR session, tell
* the VREventObserver that the window is accessing
* VR devices.
*
* It's possible to have a VREventObserver without
* and XR session, if we are using it to get updates
* about XR runtime enumeration. In this case,
* we would not tell the VREventObserver that
* we are accessing VR devices.
*/
if (mVREventObserver && mHasXRSession) {
mVREventObserver->StartActivity();
}
}
void nsGlobalWindowInner::StopVRActivity() {
/**
* If the content has an XR session, tell
* the VReventObserver that the window is no longer
* accessing VR devices. This does not stop the
* XR session itself, which may be resumed with
* EnableVRUpdates.
* It's possible to have a VREventObserver without
* and XR session, if we are using it to get updates
* about XR runtime enumeration. In this case,
* we would not tell the VREventObserver that
* we ending an activity that accesses VR devices.
*/
if (mVREventObserver && mHasXRSession) {
mVREventObserver->StopActivity();
}
}
void nsGlobalWindowInner::SetFocusedElement(Element* aElement,
uint32_t aFocusMethod,
bool aNeedsFocus) {
if (aElement && aElement->GetComposedDoc() != mDoc) {
NS_WARNING("Trying to set focus to a node from a wrong document");
return;
}
if (IsDying()) {
NS_ASSERTION(!aElement, "Trying to focus cleaned up window!");
aElement = nullptr;
aNeedsFocus = false;
}
if (mFocusedElement != aElement) {
mFocusedElement = aElement;
// TODO: Maybe this should be set on refocus too?
mFocusMethod = aFocusMethod & nsIFocusManager::METHOD_MASK;
}
if (mFocusedElement) {
// if a node was focused by a keypress, turn on focus rings for the
// window.
if (mFocusMethod & nsIFocusManager::FLAG_BYKEY) {
mUnknownFocusMethodShouldShowOutline = true;
mFocusByKeyOccurred = true;
} else if (nsFocusManager::GetFocusMoveActionCause(mFocusMethod) !=
widget::InputContextAction::CAUSE_UNKNOWN) {
mUnknownFocusMethodShouldShowOutline = false;
} else if (aFocusMethod & nsIFocusManager::FLAG_NOSHOWRING) {
// If we get focused via script, and script has explicitly opted out of
// outlines via FLAG_NOSHOWRING, we don't want to make a refocus start
// showing outlines.
mUnknownFocusMethodShouldShowOutline = false;
}
}
if (aNeedsFocus) {
mNeedsFocus = aNeedsFocus;
}
}
uint32_t nsGlobalWindowInner::GetFocusMethod() { return mFocusMethod; }
bool nsGlobalWindowInner::ShouldShowFocusRing() {
if (mFocusByKeyOccurred &&
StaticPrefs::browser_display_always_show_rings_after_key_focus()) {
return true;
}
return StaticPrefs::browser_display_show_focus_rings();
}
bool nsGlobalWindowInner::TakeFocus(bool aFocus, uint32_t aFocusMethod) {
if (IsDying()) {
return false;
}
if (aFocus) {
mFocusMethod = aFocusMethod & nsIFocusManager::METHOD_MASK;
}
// if mNeedsFocus is true, then the document has not yet received a
// document-level focus event. If there is a root content node, then return
// true to tell the calling focus manager that a focus event is expected. If
// there is no root content node, the document hasn't loaded enough yet, or
// there isn't one and there is no point in firing a focus event.
if (aFocus && mNeedsFocus && mDoc && mDoc->GetRootElement()) {
mNeedsFocus = false;
return true;
}
mNeedsFocus = false;
return false;
}
void nsGlobalWindowInner::SetReadyForFocus() {
bool oldNeedsFocus = mNeedsFocus;
mNeedsFocus = false;
if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
nsCOMPtr<nsPIDOMWindowOuter> outerWindow = GetOuterWindow();
fm->WindowShown(outerWindow, oldNeedsFocus);
}
}
void nsGlobalWindowInner::PageHidden(bool aIsEnteringBFCacheInParent) {
// the window is being hidden, so tell the focus manager that the frame is
// no longer valid. Use the persisted field to determine if the document
// is being destroyed.
if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
nsCOMPtr<nsPIDOMWindowOuter> outerWindow = GetOuterWindow();
fm->WindowHidden(outerWindow, nsFocusManager::GenerateFocusActionId(),
aIsEnteringBFCacheInParent);
}
mNeedsFocus = true;
}
class HashchangeCallback : public Runnable {
public:
HashchangeCallback(const nsAString& aOldURL, const nsAString& aNewURL,
nsGlobalWindowInner* aWindow)
: mozilla::Runnable("HashchangeCallback"), mWindow(aWindow) {
MOZ_ASSERT(mWindow);
mOldURL.Assign(aOldURL);
mNewURL.Assign(aNewURL);
}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread(), "Should be called on the main thread.");
return mWindow->FireHashchange(mOldURL, mNewURL);
}
private:
nsString mOldURL;
nsString mNewURL;
RefPtr<nsGlobalWindowInner> mWindow;
};
nsresult nsGlobalWindowInner::DispatchAsyncHashchange(nsIURI* aOldURI,
nsIURI* aNewURI) {
// Make sure that aOldURI and aNewURI are identical up to the '#', and that
// their hashes are different.
bool equal = false;
NS_ENSURE_STATE(NS_SUCCEEDED(aOldURI->EqualsExceptRef(aNewURI, &equal)) &&
equal);
nsAutoCString oldHash, newHash;
bool oldHasHash, newHasHash;
NS_ENSURE_STATE(NS_SUCCEEDED(aOldURI->GetRef(oldHash)) &&
NS_SUCCEEDED(aNewURI->GetRef(newHash)) &&
NS_SUCCEEDED(aOldURI->GetHasRef(&oldHasHash)) &&
NS_SUCCEEDED(aNewURI->GetHasRef(&newHasHash)) &&
(oldHasHash != newHasHash || !oldHash.Equals(newHash)));
nsAutoCString oldSpec, newSpec;
nsresult rv = aOldURI->GetSpec(oldSpec);
NS_ENSURE_SUCCESS(rv, rv);
rv = aNewURI->GetSpec(newSpec);
NS_ENSURE_SUCCESS(rv, rv);
NS_ConvertUTF8toUTF16 oldWideSpec(oldSpec);
NS_ConvertUTF8toUTF16 newWideSpec(newSpec);
nsCOMPtr<nsIRunnable> callback =
new HashchangeCallback(oldWideSpec, newWideSpec, this);
return Dispatch(callback.forget());
}
nsresult nsGlobalWindowInner::FireHashchange(const nsAString& aOldURL,
const nsAString& aNewURL) {
// Don't do anything if the window is frozen.
if (IsFrozen()) {
return NS_OK;
}
// Get a presentation shell for use in creating the hashchange event.
NS_ENSURE_STATE(IsCurrentInnerWindow());
HashChangeEventInit init;
init.mNewURL = aNewURL;
init.mOldURL = aOldURL;
RefPtr<HashChangeEvent> event =
HashChangeEvent::Constructor(this, u"hashchange"_ns, init);
event->SetTrusted(true);
ErrorResult rv;
DispatchEvent(*event, rv);
return rv.StealNSResult();
}
nsresult nsGlobalWindowInner::DispatchSyncPopState() {
NS_ASSERTION(nsContentUtils::IsSafeToRunScript(),
"Must be safe to run script here.");
// Bail if the window is frozen.
if (IsFrozen()) {
return NS_OK;
}
AutoJSAPI jsapi;
bool result = jsapi.Init(this);
NS_ENSURE_TRUE(result, NS_ERROR_FAILURE);
JSContext* cx = jsapi.cx();
// Get the document's pending state object -- it contains the data we're
// going to send along with the popstate event. The object is serialized
// using structured clone.
JS::Rooted<JS::Value> stateJSValue(cx);
nsresult rv = mDoc->GetStateObject(&stateJSValue);
NS_ENSURE_SUCCESS(rv, rv);
if (!JS_WrapValue(cx, &stateJSValue)) {
return NS_ERROR_OUT_OF_MEMORY;
}
RootedDictionary<PopStateEventInit> init(cx);
init.mState = stateJSValue;
RefPtr<PopStateEvent> event =
PopStateEvent::Constructor(this, u"popstate"_ns, init);
event->SetTrusted(true);
event->SetTarget(this);
ErrorResult err;
DispatchEvent(*event, err);
return err.StealNSResult();
}
already_AddRefed<nsICSSDeclaration> nsGlobalWindowInner::GetComputedStyle(
Element& aElt, const nsAString& aPseudoElt, ErrorResult& aError) {
return GetComputedStyleHelper(aElt, aPseudoElt, false, aError);
}
already_AddRefed<nsICSSDeclaration>
nsGlobalWindowInner::GetDefaultComputedStyle(Element& aElt,
const nsAString& aPseudoElt,
ErrorResult& aError) {
return GetComputedStyleHelper(aElt, aPseudoElt, true, aError);
}
already_AddRefed<nsICSSDeclaration> nsGlobalWindowInner::GetComputedStyleHelper(
Element& aElt, const nsAString& aPseudoElt, bool aDefaultStylesOnly,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetComputedStyleHelperOuter,
(aElt, aPseudoElt, aDefaultStylesOnly, aError),
aError, nullptr);
}
void nsGlobalWindowInner::MaybeNotifyStorageKeyUsed() {
// Only notify once per window lifetime.
if (hasNotifiedStorageKeyUsed) {
return;
}
nsresult rv =
BounceTrackingStorageObserver::OnInitialStorageAccess(GetWindowContext());
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
hasNotifiedStorageKeyUsed = true;
}
Storage* nsGlobalWindowInner::GetSessionStorage(ErrorResult& aError) {
nsIPrincipal* principal = GetPrincipal();
nsIPrincipal* storagePrincipal;
if (StaticPrefs::
privacy_partition_always_partition_third_party_non_cookie_storage_exempt_sessionstorage()) {
storagePrincipal = GetEffectiveCookiePrincipal();
} else {
storagePrincipal = GetEffectiveStoragePrincipal();
}
BrowsingContext* browsingContext = GetBrowsingContext();
if (!principal || !storagePrincipal || !browsingContext ||
!Storage::StoragePrefIsEnabled()) {
return nullptr;
}
if (mSessionStorage) {
MOZ_LOG(gDOMLeakPRLogInner, LogLevel::Debug,
("nsGlobalWindowInner %p has %p sessionStorage", this,
mSessionStorage.get()));
bool canAccess =
principal->Subsumes(mSessionStorage->Principal()) &&
storagePrincipal->Subsumes(mSessionStorage->StoragePrincipal());
if (!canAccess) {
mSessionStorage = nullptr;
}
}
if (!mSessionStorage) {
nsString documentURI;
if (mDoc) {
aError = mDoc->GetDocumentURI(documentURI);
if (NS_WARN_IF(aError.Failed())) {
return nullptr;
}
}
if (!mDoc) {
aError.Throw(NS_ERROR_FAILURE);
return nullptr;
}
// If the document's sandboxed origin flag is set, then accessing
// sessionStorage is prohibited.
if (mDoc->GetSandboxFlags() & SANDBOXED_ORIGIN) {
aError.ThrowSecurityError(
"Forbidden in a sandboxed document without the 'allow-same-origin' "
"flag.");
return nullptr;
}
uint32_t rejectedReason = 0;
StorageAccess access = StorageAllowedForWindow(this, &rejectedReason);
// SessionStorage is an ephemeral per-tab per-origin storage that only lives
// as long as the tab is open, although it may survive browser restarts
// thanks to the session store. So we interpret storage access differently
// than we would for persistent per-origin storage like LocalStorage and so
// it may be okay to provide SessionStorage even when we receive a value of
// eDeny.
//
// ContentBlocking::ShouldAllowAccessFor will return false for 3 main
// reasons.
//
// 1. Cookies are entirely blocked due to a per-origin permission
// (nsICookiePermission::ACCESS_DENY for the top-level principal or this
// window's principal) or the very broad BEHAVIOR_REJECT. This will return
// eDeny with a reason of STATE_COOKIES_BLOCKED_BY_PERMISSION or
// STATE_COOKIES_BLOCKED_ALL.
//
// 2. Third-party cookies are limited via BEHAVIOR_REJECT_FOREIGN and
// BEHAVIOR_LIMIT_FOREIGN and this is a third-party window. This will return
// eDeny with a reason of STATE_COOKIES_BLOCKED_FOREIGN.
//
// 3. Tracking protection (BEHAVIOR_REJECT_TRACKER and
// BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN) is in effect and
// IsThirdPartyTrackingResourceWindow() returned true and there wasn't a
// permission that allows it. This will return ePartitionTrackersOrDeny with
// a reason of STATE_COOKIES_BLOCKED_TRACKER or
// STATE_COOKIES_BLOCKED_SOCIALTRACKER.
//
// In the 1st case, the user has explicitly indicated that they don't want
// to allow any storage to the origin or all origins and so we throw an
// error and deny access to SessionStorage. In the 2nd case, a legacy
// decision reasoned that there's no harm in providing SessionStorage
// because the information is not durable and cannot escape the current tab.
// The rationale is similar for the 3rd case.
if (access == StorageAccess::eDeny &&
rejectedReason !=
nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN) {
aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
const RefPtr<SessionStorageManager> storageManager =
browsingContext->GetSessionStorageManager();
if (!storageManager) {
aError.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
RefPtr<Storage> storage;
aError = storageManager->CreateStorage(this, principal, storagePrincipal,
documentURI, IsPrivateBrowsing(),
getter_AddRefs(storage));
if (aError.Failed()) {
return nullptr;
}
mSessionStorage = storage;
MOZ_ASSERT(mSessionStorage);
MOZ_LOG(gDOMLeakPRLogInner, LogLevel::Debug,
("nsGlobalWindowInner %p tried to get a new sessionStorage %p",
this, mSessionStorage.get()));
if (!mSessionStorage) {
aError.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
}
MaybeNotifyStorageKeyUsed();
MOZ_LOG(gDOMLeakPRLogInner, LogLevel::Debug,
("nsGlobalWindowInner %p returns %p sessionStorage", this,
mSessionStorage.get()));
return mSessionStorage;
}
Storage* nsGlobalWindowInner::GetLocalStorage(ErrorResult& aError) {
if (!Storage::StoragePrefIsEnabled()) {
return nullptr;
}
// If the document's sandboxed origin flag is set, then accessing localStorage
// is prohibited.
if (mDoc && mDoc->GetSandboxFlags() & SANDBOXED_ORIGIN) {
aError.ThrowSecurityError(
"Forbidden in a sandboxed document without the 'allow-same-origin' "
"flag.");
return nullptr;
}
// LocalStorage needs to be exposed in every context except for sandboxes and
// NullPrincipals (data: URLs, for instance). But we need to keep data
// separate in some scenarios: private-browsing and partitioned trackers.
// In private-browsing, LocalStorage keeps data in memory, and it shares
// StorageEvents just with other origins in the same private-browsing
// environment.
// For Partitioned Trackers, we expose a partitioned LocalStorage, which
// doesn't share data with other contexts, and it's just in memory.
// Partitioned localStorage is available only for trackers listed in the
// privacy.restrict3rdpartystorage.partitionedHosts pref. See
// nsContentUtils::IsURIInPrefList to know the syntax for the pref value.
// This is a temporary web-compatibility hack.
StorageAccess access = StorageAllowedForWindow(this);
// We allow partitioned localStorage only to some hosts.
bool isolated = false;
if (ShouldPartitionStorage(access)) {
if (!mDoc) {
access = StorageAccess::eDeny;
} else if (!StoragePartitioningEnabled(access, mDoc->CookieJarSettings())) {
static const char* kPrefName =
"privacy.restrict3rdpartystorage.partitionedHosts";
bool isInList = false;
mDoc->NodePrincipal()->IsURIInPrefList(kPrefName, &isInList);
if (!isInList) {
access = StorageAccess::eDeny;
} else {
isolated = true;
}
}
}
if (access == StorageAccess::eDeny) {
aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
if (mDoc) {
cookieJarSettings = mDoc->CookieJarSettings();
} else {
cookieJarSettings = net::CookieJarSettings::GetBlockingAll(
ShouldResistFingerprinting(RFPTarget::IsAlwaysEnabledForPrecompute));
}
// Note that this behavior is observable: if we grant storage permission to a
// tracker, we pass from the partitioned LocalStorage (or a partitioned cookie
// jar) to the 'normal' one. The previous data is lost and the 2
// window.localStorage objects, before and after the permission granted, will
// be different.
if (mLocalStorage) {
if ((mLocalStorage->Type() == (isolated ? Storage::ePartitionedLocalStorage
: Storage::eLocalStorage)) &&
(mLocalStorage->StoragePrincipal() == GetEffectiveStoragePrincipal())) {
return mLocalStorage;
}
// storage needs change
mLocalStorage = nullptr;
}
MOZ_ASSERT(!mLocalStorage);
if (!isolated) {
RefPtr<Storage> storage;
if (NextGenLocalStorageEnabled()) {
aError = LSObject::CreateForWindow(this, getter_AddRefs(storage));
} else {
nsresult rv;
nsCOMPtr<nsIDOMStorageManager> storageManager =
do_GetService("@mozilla.org/dom/localStorage-manager;1", &rv);
if (NS_FAILED(rv)) {
aError.Throw(rv);
return nullptr;
}
nsString documentURI;
if (mDoc) {
aError = mDoc->GetDocumentURI(documentURI);
if (NS_WARN_IF(aError.Failed())) {
return nullptr;
}
}
nsIPrincipal* principal = GetPrincipal();
if (!principal) {
aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
nsIPrincipal* storagePrincipal = GetEffectiveStoragePrincipal();
if (!storagePrincipal) {
aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
aError = storageManager->CreateStorage(this, principal, storagePrincipal,
documentURI, IsPrivateBrowsing(),
getter_AddRefs(storage));
}
if (aError.Failed()) {
return nullptr;
}
mLocalStorage = storage;
} else {
nsresult rv;
nsCOMPtr<nsIDOMSessionStorageManager> storageManager =
do_GetService("@mozilla.org/dom/sessionStorage-manager;1", &rv);
if (NS_FAILED(rv)) {
aError.Throw(rv);
return nullptr;
}
nsIPrincipal* principal = GetPrincipal();
if (!principal) {
aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
nsIPrincipal* storagePrincipal = GetEffectiveStoragePrincipal();
if (!storagePrincipal) {
aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
RefPtr<SessionStorageCache> cache;
if (isolated) {
cache = new SessionStorageCache();
} else {
// This will clone the session storage if it exists.
rv = storageManager->GetSessionStorageCache(principal, storagePrincipal,
&cache);
if (NS_FAILED(rv)) {
aError.Throw(rv);
return nullptr;
}
}
mLocalStorage =
new PartitionedLocalStorage(this, principal, storagePrincipal, cache);
}
MaybeNotifyStorageKeyUsed();
MOZ_ASSERT(mLocalStorage);
MOZ_ASSERT(
mLocalStorage->Type() ==
(isolated ? Storage::ePartitionedLocalStorage : Storage::eLocalStorage));
return mLocalStorage;
}
IDBFactory* nsGlobalWindowInner::GetIndexedDB(JSContext* aCx,
ErrorResult& aError) {
if (!mIndexedDB) {
// This may keep mIndexedDB null without setting an error.
auto res = IDBFactory::CreateForWindow(this);
if (res.isErr()) {
aError = res.unwrapErr();
} else {
mIndexedDB = res.unwrap();
}
}
MaybeNotifyStorageKeyUsed();
return mIndexedDB;
}
//*****************************************************************************
// nsGlobalWindowInner::nsIInterfaceRequestor
//*****************************************************************************
NS_IMETHODIMP
nsGlobalWindowInner::GetInterface(const nsIID& aIID, void** aSink) {
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
NS_ENSURE_TRUE(outer, NS_ERROR_NOT_INITIALIZED);
nsresult rv = outer->GetInterfaceInternal(aIID, aSink);
if (rv == NS_ERROR_NO_INTERFACE) {
return QueryInterface(aIID, aSink);
}
return rv;
}
void nsGlobalWindowInner::GetInterface(JSContext* aCx,
JS::Handle<JS::Value> aIID,
JS::MutableHandle<JS::Value> aRetval,
ErrorResult& aError) {
dom::GetInterface(aCx, this, aIID, aRetval, aError);
}
already_AddRefed<CacheStorage> nsGlobalWindowInner::GetCaches(
ErrorResult& aRv) {
if (!mCacheStorage) {
bool forceTrustedOrigin =
GetBrowsingContext() &&
GetBrowsingContext()->Top()->GetServiceWorkersTestingEnabled();
mCacheStorage = CacheStorage::CreateOnMainThread(
cache::DEFAULT_NAMESPACE, this, GetEffectiveStoragePrincipal(),
forceTrustedOrigin, aRv);
}
RefPtr<CacheStorage> ref = mCacheStorage;
return ref.forget();
}
void nsGlobalWindowInner::FireOfflineStatusEventIfChanged() {
if (!IsCurrentInnerWindow()) return;
// Don't fire an event if the status hasn't changed
if (mWasOffline == NS_IsOffline()) {
return;
}
if (ShouldResistFingerprinting(RFPTarget::NetworkConnection)) {
// We always report online=true when resistFingerprinting is enabled.
return;
}
mWasOffline = !mWasOffline;
nsAutoString name;
if (mWasOffline) {
name.AssignLiteral("offline");
} else {
name.AssignLiteral("online");
}
nsContentUtils::DispatchTrustedEvent(mDoc, this, name, CanBubble::eNo,
Cancelable::eNo);
}
nsGlobalWindowInner::SlowScriptResponse
nsGlobalWindowInner::ShowSlowScriptDialog(JSContext* aCx,
const nsString& aAddonId,
const double aDuration) {
nsresult rv;
if (Preferences::GetBool("dom.always_stop_slow_scripts")) {
return KillSlowScript;
}
// If it isn't safe to run script, then it isn't safe to bring up the prompt
// (since that spins the event loop). In that (rare) case, we just kill the
// script and report a warning.
if (!nsContentUtils::IsSafeToRunScript()) {
JS::WarnASCII(aCx, "A long running script was terminated");
return KillSlowScript;
}
// If our document is not active, just kill the script: we've been unloaded
if (!HasActiveDocument()) {
return KillSlowScript;
}
// Check if we should offer the option to debug
JS::AutoFilename filename;
uint32_t lineno;
// Computing the line number can be very expensive (see bug 1330231 for
// example), and we don't use the line number anywhere except than in the
// parent process, so we avoid computing it elsewhere. This gives us most of
// the wins we are interested in, since the source of the slowness here is
// minified scripts which is more common in Web content that is loaded in the
// content process.
uint32_t* linenop = XRE_IsParentProcess() ? &lineno : nullptr;
bool hasFrame = JS::DescribeScriptedCaller(&filename, aCx, linenop);
// Record the slow script event if we haven't done so already for this inner
// window (which represents a particular page to the user).
if (!mHasHadSlowScript) {
glean::dom::slow_script_page_count.Add(1);
}
mHasHadSlowScript = true;
// Override the cursor to something that we're sure the user can see.
SetCursor("auto"_ns, IgnoreErrors());
if (XRE_IsContentProcess() && ProcessHangMonitor::Get()) {
ProcessHangMonitor::SlowScriptAction action;
RefPtr<ProcessHangMonitor> monitor = ProcessHangMonitor::Get();
nsIDocShell* docShell = GetDocShell();
nsCOMPtr<nsIBrowserChild> child =
docShell ? docShell->GetBrowserChild() : nullptr;
action =
monitor->NotifySlowScript(child, filename.get(), aAddonId, aDuration);
if (action == ProcessHangMonitor::Terminate) {
return KillSlowScript;
}
if (action == ProcessHangMonitor::StartDebugger) {
// Spin a nested event loop so that the debugger in the parent can fetch
// any information it needs. Once the debugger has started, return to the
// script.
RefPtr<nsGlobalWindowOuter> outer = GetOuterWindowInternal();
outer->EnterModalState();
SpinEventLoopUntil("nsGlobalWindowInner::ShowSlowScriptDialog"_ns, [&]() {
return monitor->IsDebuggerStartupComplete() ||
AppShutdown::IsShutdownImpending();
});
outer->LeaveModalState();
return (AppShutdown::IsShutdownImpending()) ? KillSlowScript
: ContinueSlowScript;
}
return ContinueSlowScriptAndKeepNotifying;
}
// Reached only on non-e10s - once per slow script dialog.
// On e10s - we probe once at ProcessHangsMonitor.sys.mjs
glean::dom::slow_script_notice_count.Add(1);
// Get the nsIPrompt interface from the docshell
nsCOMPtr<nsIDocShell> ds = GetDocShell();
NS_ENSURE_TRUE(ds, KillSlowScript);
nsCOMPtr<nsIPrompt> prompt = do_GetInterface(ds);
NS_ENSURE_TRUE(prompt, KillSlowScript);
// Prioritize the SlowScriptDebug interface over JSD1.
nsCOMPtr<nsISlowScriptDebugCallback> debugCallback;
if (hasFrame) {
const char* debugCID = "@mozilla.org/dom/slow-script-debug;1";
nsCOMPtr<nsISlowScriptDebug> debugService = do_GetService(debugCID, &rv);
if (NS_SUCCEEDED(rv)) {
debugService->GetActivationHandler(getter_AddRefs(debugCallback));
}
}
bool failed = false;
auto getString = [&](const char* name,
nsContentUtils::PropertiesFile propFile =
nsContentUtils::eDOM_PROPERTIES) {
nsAutoString result;
nsresult rv = nsContentUtils::GetLocalizedString(propFile, name, result);
// GetStringFromName can return NS_OK and still give nullptr string
failed = failed || NS_FAILED(rv) || result.IsEmpty();
return result;
};
bool isAddonScript = !aAddonId.IsEmpty();
bool showDebugButton = debugCallback && !isAddonScript;
// Get localizable strings
nsAutoString title, checkboxMsg, debugButton, msg;
if (isAddonScript) {
title = getString("KillAddonScriptTitle");
checkboxMsg = getString("KillAddonScriptGlobalMessage");
auto appName =
getString("brandShortName", nsContentUtils::eBRAND_PROPERTIES);
nsCOMPtr<nsIAddonPolicyService> aps =
do_GetService("@mozilla.org/addons/policy-service;1");
nsString addonName;
if (!aps || NS_FAILED(aps->GetExtensionName(aAddonId, addonName))) {
addonName = aAddonId;
}
rv = nsContentUtils::FormatLocalizedString(
msg, nsContentUtils::eDOM_PROPERTIES, "KillAddonScriptMessage",
addonName, appName);
failed = failed || NS_FAILED(rv);
} else {
title = getString("KillScriptTitle");
checkboxMsg = getString("DontAskAgain");
if (showDebugButton) {
debugButton = getString("DebugScriptButton");
msg = getString("KillScriptWithDebugMessage");
} else {
msg = getString("KillScriptMessage");
}
}
auto stopButton = getString("StopScriptButton");
auto waitButton = getString("WaitForScriptButton");
if (failed) {
NS_ERROR("Failed to get localized strings.");
return ContinueSlowScript;
}
// Append file and line number information, if available
if (filename.get()) {
nsAutoString scriptLocation;
// We want to drop the middle part of too-long locations. We'll
// define "too-long" as longer than 60 UTF-16 code units. Just
// have to be a bit careful about unpaired surrogates.
NS_ConvertUTF8toUTF16 filenameUTF16(filename.get());
if (filenameUTF16.Length() > 60) {
// XXXbz Do we need to insert any bidi overrides here?
size_t cutStart = 30;
size_t cutLength = filenameUTF16.Length() - 60;
MOZ_ASSERT(cutLength > 0);
if (NS_IS_LOW_SURROGATE(filenameUTF16[cutStart])) {
// Don't truncate before the low surrogate, in case it's preceded by a
// high surrogate and forms a single Unicode character. Instead, just
// include the low surrogate.
++cutStart;
--cutLength;
}
if (NS_IS_LOW_SURROGATE(filenameUTF16[cutStart + cutLength])) {
// Likewise, don't drop a trailing low surrogate here. We want to
// increase cutLength, since it might be 0 already so we can't very well
// decrease it.
++cutLength;
}
// Insert U+2026 HORIZONTAL ELLIPSIS
filenameUTF16.ReplaceLiteral(cutStart, cutLength, u"\x2026");
}
rv = nsContentUtils::FormatLocalizedString(
scriptLocation, nsContentUtils::eDOM_PROPERTIES, "KillScriptLocation",
filenameUTF16);
if (NS_SUCCEEDED(rv)) {
msg.AppendLiteral("\n\n");
msg.Append(scriptLocation);
msg.Append(':');
msg.AppendInt(lineno);
}
}
uint32_t buttonFlags = nsIPrompt::BUTTON_POS_1_DEFAULT +
(nsIPrompt::BUTTON_TITLE_IS_STRING *
(nsIPrompt::BUTTON_POS_0 + nsIPrompt::BUTTON_POS_1));
// Add a third button if necessary.
if (showDebugButton)
buttonFlags += nsIPrompt::BUTTON_TITLE_IS_STRING * nsIPrompt::BUTTON_POS_2;
bool checkboxValue = false;
int32_t buttonPressed = 0; // In case the user exits dialog by clicking X.
{
// Null out the operation callback while we're re-entering JS here.
AutoDisableJSInterruptCallback disabler(aCx);
// Open the dialog.
rv = prompt->ConfirmEx(
title.get(), msg.get(), buttonFlags, waitButton.get(), stopButton.get(),
debugButton.get(), checkboxMsg.get(), &checkboxValue, &buttonPressed);
}
if (buttonPressed == 0) {
if (checkboxValue && !isAddonScript && NS_SUCCEEDED(rv))
return AlwaysContinueSlowScript;
return ContinueSlowScript;
}
if (buttonPressed == 2) {
MOZ_RELEASE_ASSERT(debugCallback);
rv = debugCallback->HandleSlowScriptDebug(this);
return NS_SUCCEEDED(rv) ? ContinueSlowScript : KillSlowScript;
}
JS_ClearPendingException(aCx);
return KillSlowScript;
}
nsresult nsGlobalWindowInner::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
if (!nsCRT::strcmp(aTopic, "audio-playback") &&
ToSupports(GetOuterWindow()) == aSubject) {
AUTO_PROFILER_MARKER_UNTYPED("audio-playback", DOM, {});
nsGlobalWindowOuter* outer =
nsGlobalWindowOuter::Cast(nsPIDOMWindowOuter::From(GetOuterWindow())
->GetInProcessScriptableTop());
nsGlobalWindowInner* topInnerWindow =
outer ? nsGlobalWindowInner::Cast(outer->GetCurrentInnerWindow())
: nullptr;
if (topInnerWindow) {
const bool isPlayingAudio{IsPlayingAudio()};
topInnerWindow->AudioPlaybackChanged(isPlayingAudio);
topInnerWindow->CallOnInProcessDescendants(
&nsGlobalWindowInner::AudioPlaybackChanged, isPlayingAudio);
}
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, NS_IOSERVICE_OFFLINE_STATUS_TOPIC)) {
if (!IsFrozen()) {
// Fires an offline status event if the offline status has changed
FireOfflineStatusEventIfChanged();
}
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, MEMORY_PRESSURE_OBSERVER_TOPIC)) {
if (mPerformance) {
mPerformance->MemoryPressure();
}
RemoveReportRecords();
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, PERMISSION_CHANGED_TOPIC)) {
nsCOMPtr<nsIPermission> perm(do_QueryInterface(aSubject));
if (!perm) {
// A null permission indicates that the entire permission list
// was cleared.
MOZ_ASSERT(!nsCRT::strcmp(aData, u"cleared"));
UpdatePermissions();
return NS_OK;
}
nsAutoCString type;
perm->GetType(type);
if (type == "autoplay-media"_ns) {
UpdateAutoplayPermission();
} else if (type == "shortcuts"_ns) {
UpdateShortcutsPermission();
} else if (type == "popup"_ns) {
UpdatePopupPermission();
}
if (!mDoc) {
return NS_OK;
}
RefPtr<PermissionDelegateHandler> permDelegateHandler =
mDoc->GetPermissionDelegateHandler();
if (permDelegateHandler) {
permDelegateHandler->UpdateDelegatedPermission(type);
}
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, "screen-information-changed")) {
if (mScreen) {
if (RefPtr<ScreenOrientation> orientation =
mScreen->GetOrientationIfExists()) {
orientation->MaybeChanged();
}
}
if (mHasOrientationChangeListeners) {
int32_t oldAngle = mOrientationAngle;
mOrientationAngle = Orientation(CallerType::System);
if (mOrientationAngle != oldAngle && IsCurrentInnerWindow()) {
nsCOMPtr<nsPIDOMWindowOuter> outer = GetOuterWindow();
outer->DispatchCustomEvent(u"orientationchange"_ns);
}
}
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
MOZ_ASSERT(!NS_strcmp(aData, u"intl.accept_languages"));
// The user preferred languages have changed, we need to fire an event on
// Window object and invalidate the cache for navigator.languages. It is
// done for every change which can be a waste of cycles but those should be
// fairly rare.
// We MUST invalidate navigator.languages before sending the event in the
// very likely situation where an event handler will try to read its value.
if (mNavigator) {
Navigator_Binding::ClearCachedLanguageValue(mNavigator);
Navigator_Binding::ClearCachedLanguagesValue(mNavigator);
}
// The event has to be dispatched only to the current inner window.
if (!IsCurrentInnerWindow()) {
return NS_OK;
}
RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
event->InitEvent(u"languagechange"_ns, false, false);
event->SetTrusted(true);
ErrorResult rv;
DispatchEvent(*event, rv);
return rv.StealNSResult();
}
NS_WARNING("unrecognized topic in nsGlobalWindowInner::Observe");
return NS_ERROR_FAILURE;
}
void nsGlobalWindowInner::ObserveStorageNotification(
StorageEvent* aEvent, const char16_t* aStorageType, bool aPrivateBrowsing) {
MOZ_ASSERT(aEvent);
// The private browsing check must be done here again because this window
// could have changed its state before the notification check and now. This
// happens in case this window did have a docShell at that time.
if (aPrivateBrowsing != IsPrivateBrowsing()) {
return;
}
// LocalStorage can only exist on an inner window, and we don't want to
// generate events on frozen or otherwise-navigated-away from windows.
// (Actually, this code used to try and buffer events for frozen windows,
// but it never worked, so we've removed it. See bug 1285898.)
if (!IsCurrentInnerWindow() || IsFrozen()) {
return;
}
nsIPrincipal* principal = GetPrincipal();
if (!principal) {
return;
}
bool fireMozStorageChanged = false;
nsAutoString eventType;
eventType.AssignLiteral("storage");
if (!NS_strcmp(aStorageType, u"sessionStorage")) {
RefPtr<Storage> changingStorage = aEvent->GetStorageArea();
MOZ_ASSERT(changingStorage);
bool check = false;
if (const RefPtr<SessionStorageManager> storageManager =
GetBrowsingContext()->GetSessionStorageManager()) {
nsresult rv = storageManager->CheckStorage(GetEffectiveStoragePrincipal(),
changingStorage, &check);
if (NS_FAILED(rv)) {
return;
}
}
if (!check) {
// This storage event is not coming from our storage or is coming
// from a different docshell, i.e. it is a clone, ignore this event.
return;
}
MOZ_LOG(
gDOMLeakPRLogInner, LogLevel::Debug,
("nsGlobalWindowInner %p with sessionStorage %p passing event from %p",
this, mSessionStorage.get(), changingStorage.get()));
fireMozStorageChanged = mSessionStorage == changingStorage;
if (fireMozStorageChanged) {
eventType.AssignLiteral("MozSessionStorageChanged");
}
}
else {
MOZ_ASSERT(!NS_strcmp(aStorageType, u"localStorage"));
nsIPrincipal* storagePrincipal = GetEffectiveStoragePrincipal();
if (!storagePrincipal) {
return;
}
MOZ_DIAGNOSTIC_ASSERT(StorageUtils::PrincipalsEqual(aEvent->GetPrincipal(),
storagePrincipal));
fireMozStorageChanged =
mLocalStorage && mLocalStorage == aEvent->GetStorageArea();
if (fireMozStorageChanged) {
eventType.AssignLiteral("MozLocalStorageChanged");
}
}
// Clone the storage event included in the observer notification. We want
// to dispatch clones rather than the original event.
IgnoredErrorResult error;
RefPtr<StorageEvent> clonedEvent =
CloneStorageEvent(eventType, aEvent, error);
if (error.Failed() || !clonedEvent) {
return;
}
clonedEvent->SetTrusted(true);
if (fireMozStorageChanged) {
WidgetEvent* internalEvent = clonedEvent->WidgetEventPtr();
internalEvent->mFlags.mOnlyChromeDispatch = true;
}
DispatchEvent(*clonedEvent);
}
already_AddRefed<StorageEvent> nsGlobalWindowInner::CloneStorageEvent(
const nsAString& aType, const RefPtr<StorageEvent>& aEvent,
ErrorResult& aRv) {
StorageEventInit dict;
dict.mBubbles = aEvent->Bubbles();
dict.mCancelable = aEvent->Cancelable();
aEvent->GetKey(dict.mKey);
aEvent->GetOldValue(dict.mOldValue);
aEvent->GetNewValue(dict.mNewValue);
aEvent->GetUrl(dict.mUrl);
RefPtr<Storage> storageArea = aEvent->GetStorageArea();
RefPtr<Storage> storage;
// If null, this is a localStorage event received by IPC.
if (!storageArea) {
storage = GetLocalStorage(aRv);
if (!NextGenLocalStorageEnabled()) {
if (aRv.Failed() || !storage) {
return nullptr;
}
if (storage->Type() == Storage::eLocalStorage) {
RefPtr<LocalStorage> localStorage =
static_cast<LocalStorage*>(storage.get());
// We must apply the current change to the 'local' localStorage.
localStorage->ApplyEvent(aEvent);
}
}
} else if (storageArea->Type() == Storage::eSessionStorage) {
storage = GetSessionStorage(aRv);
} else {
MOZ_ASSERT(storageArea->Type() == Storage::eLocalStorage);
storage = GetLocalStorage(aRv);
}
if (aRv.Failed() || !storage) {
return nullptr;
}
if (storage->Type() == Storage::ePartitionedLocalStorage) {
// This error message is not exposed.
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
MOZ_ASSERT(storage);
MOZ_ASSERT_IF(storageArea, storage->IsForkOf(storageArea));
dict.mStorageArea = storage;
RefPtr<StorageEvent> event = StorageEvent::Constructor(this, aType, dict);
return event.forget();
}
void nsGlobalWindowInner::Suspend(bool aIncludeSubWindows) {
MOZ_ASSERT(NS_IsMainThread());
// We can only safely suspend windows that are the current inner window. If
// its not the current inner, then we are in one of two different cases.
// Either we are in the bfcache or we are doomed window that is going away.
// When a window becomes inactive we purposely avoid placing already suspended
// windows into the bfcache. It only expects windows suspended due to the
// Freeze() method which occurs while the window is still the current inner.
// So we must not call Suspend() on bfcache windows at this point or this
// invariant will be broken. If the window is doomed there is no point in
// suspending it since it will soon be gone.
if (!IsCurrentInnerWindow()) {
return;
}
// All in-process descendants are also suspended. This ensure mSuspendDepth
// is set properly and the timers are properly canceled for each in-process
// descendant.
if (aIncludeSubWindows) {
CallOnInProcessDescendants(&nsGlobalWindowInner::Suspend, false);
}
mSuspendDepth += 1;
if (mSuspendDepth != 1) {
return;
}
if (mWindowGlobalChild) {
mWindowGlobalChild->BlockBFCacheFor(BFCacheStatus::SUSPENDED);
}
nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
if (ac) {
for (uint32_t i = 0; i < mEnabledSensors.Length(); i++)
ac->RemoveWindowListener(mEnabledSensors[i], this);
}
DisableGamepadUpdates();
DisableVRUpdates();
SuspendWorkersForWindow(*this);
for (RefPtr<mozilla::dom::SharedWorker> pinnedWorker :
mSharedWorkers.ForwardRange()) {
pinnedWorker->Suspend();
}
SuspendIdleRequests();
mTimeoutManager->Suspend();
// Suspend all of the AudioContexts for this window
for (uint32_t i = 0; i < mAudioContexts.Length(); ++i) {
mAudioContexts[i]->SuspendFromChrome();
}
}
void nsGlobalWindowInner::Resume(bool aIncludeSubWindows) {
MOZ_ASSERT(NS_IsMainThread());
// We can only safely resume a window if its the current inner window. If
// its not the current inner, then we are in one of two different cases.
// Either we are in the bfcache or we are doomed window that is going away.
// If a window is suspended when it becomes inactive we purposely do not
// put it in the bfcache, so Resume should never be needed in that case.
// If the window is doomed then there is no point in resuming it.
if (!IsCurrentInnerWindow()) {
return;
}
// Resume all in-process descendants. This restores timers recursively
// canceled in Suspend() and ensures all in-process descendants have the
// correct mSuspendDepth.
if (aIncludeSubWindows) {
CallOnInProcessDescendants(&nsGlobalWindowInner::Resume, false);
}
if (mSuspendDepth == 0) {
// Ignore if the window is not suspended.
return;
}
mSuspendDepth -= 1;
if (mSuspendDepth != 0) {
return;
}
// We should not be able to resume a frozen window. It must be Thaw()'d
// first.
MOZ_ASSERT(mFreezeDepth == 0);
nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
if (ac) {
for (uint32_t i = 0; i < mEnabledSensors.Length(); i++)
ac->AddWindowListener(mEnabledSensors[i], this);
}
EnableGamepadUpdates();
EnableVRUpdates();
// Resume all of the AudioContexts for this window
for (uint32_t i = 0; i < mAudioContexts.Length(); ++i) {
mAudioContexts[i]->ResumeFromChrome();
}
if (RefPtr<MediaDevices> devices = GetExtantMediaDevices()) {
devices->WindowResumed();
}
mTimeoutManager->Resume();
ResumeIdleRequests();
// Resume all of the workers for this window. We must do this
// after timeouts since workers may have queued events that can trigger
// a setTimeout().
ResumeWorkersForWindow(*this);
for (RefPtr<mozilla::dom::SharedWorker> pinnedWorker :
mSharedWorkers.ForwardRange()) {
pinnedWorker->Resume();
}
if (mWindowGlobalChild) {
mWindowGlobalChild->UnblockBFCacheFor(BFCacheStatus::SUSPENDED);
}
}
bool nsGlobalWindowInner::IsSuspended() const {
MOZ_ASSERT(NS_IsMainThread());
return mSuspendDepth != 0;
}
void nsGlobalWindowInner::Freeze(bool aIncludeSubWindows) {
MOZ_ASSERT(NS_IsMainThread());
Suspend(aIncludeSubWindows);
FreezeInternal(aIncludeSubWindows);
}
void nsGlobalWindowInner::FreezeInternal(bool aIncludeSubWindows) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(IsCurrentInnerWindow());
MOZ_DIAGNOSTIC_ASSERT(IsSuspended());
HintIsLoading(false);
if (aIncludeSubWindows) {
CallOnInProcessChildren(&nsGlobalWindowInner::FreezeInternal,
aIncludeSubWindows);
}
mFreezeDepth += 1;
MOZ_ASSERT(mSuspendDepth >= mFreezeDepth);
if (mFreezeDepth != 1) {
return;
}
FreezeWorkersForWindow(*this);
for (RefPtr<mozilla::dom::SharedWorker> pinnedWorker :
mSharedWorkers.ForwardRange()) {
pinnedWorker->Freeze();
}
mTimeoutManager->Freeze();
if (mClientSource) {
mClientSource->Freeze();
}
NotifyGlobalFrozen();
}
void nsGlobalWindowInner::Thaw(bool aIncludeSubWindows) {
MOZ_ASSERT(NS_IsMainThread());
ThawInternal(aIncludeSubWindows);
Resume(aIncludeSubWindows);
}
void nsGlobalWindowInner::ThawInternal(bool aIncludeSubWindows) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(IsCurrentInnerWindow());
MOZ_DIAGNOSTIC_ASSERT(IsSuspended());
if (aIncludeSubWindows) {
CallOnInProcessChildren(&nsGlobalWindowInner::ThawInternal,
aIncludeSubWindows);
}
MOZ_ASSERT(mFreezeDepth != 0);
mFreezeDepth -= 1;
MOZ_ASSERT(mSuspendDepth >= mFreezeDepth);
if (mFreezeDepth != 0) {
return;
}
if (mClientSource) {
mClientSource->Thaw();
}
mTimeoutManager->Thaw();
ThawWorkersForWindow(*this);
for (RefPtr<mozilla::dom::SharedWorker> pinnedWorker :
mSharedWorkers.ForwardRange()) {
pinnedWorker->Thaw();
}
NotifyGlobalThawed();
}
bool nsGlobalWindowInner::IsFrozen() const {
MOZ_ASSERT(NS_IsMainThread());
bool frozen = mFreezeDepth != 0;
MOZ_ASSERT_IF(frozen, IsSuspended());
return frozen;
}
void nsGlobalWindowInner::SyncStateFromParentWindow() {
// This method should only be called on an inner window that has been
// assigned to an outer window already.
MOZ_ASSERT(IsCurrentInnerWindow());
nsPIDOMWindowOuter* outer = GetOuterWindow();
MOZ_ASSERT(outer);
// Attempt to find our parent windows.
nsCOMPtr<Element> frame = outer->GetFrameElementInternal();
nsPIDOMWindowOuter* parentOuter =
frame ? frame->OwnerDoc()->GetWindow() : nullptr;
nsGlobalWindowInner* parentInner =
parentOuter
? nsGlobalWindowInner::Cast(parentOuter->GetCurrentInnerWindow())
: nullptr;
// If our outer is in a modal state, but our parent is not in a modal
// state, then we must apply the suspend directly. If our parent is
// in a modal state then we should get the suspend automatically
// via the parentSuspendDepth application below.
if ((!parentInner || !parentInner->IsInModalState()) && IsInModalState()) {
Suspend();
}
uint32_t parentFreezeDepth = parentInner ? parentInner->mFreezeDepth : 0;
uint32_t parentSuspendDepth = parentInner ? parentInner->mSuspendDepth : 0;
// Since every Freeze() calls Suspend(), the suspend count must
// be equal or greater to the freeze count.
MOZ_ASSERT(parentFreezeDepth <= parentSuspendDepth);
// First apply the Freeze() calls.
for (uint32_t i = 0; i < parentFreezeDepth; ++i) {
Freeze();
}
// Now apply only the number of Suspend() calls to reach the target
// suspend count after applying the Freeze() calls.
for (uint32_t i = 0; i < (parentSuspendDepth - parentFreezeDepth); ++i) {
Suspend();
}
}
void nsGlobalWindowInner::UpdateBackgroundState() {
if (RefPtr<MediaDevices> devices = GetExtantMediaDevices()) {
devices->BackgroundStateChanged();
}
mTimeoutManager->UpdateBackgroundState();
UpdateWorkersBackgroundState(*this, IsBackgroundInternal());
}
template <typename Method, typename... Args>
CallState nsGlobalWindowInner::CallOnInProcessDescendantsInternal(
BrowsingContext* aBrowsingContext, bool aChildOnly, Method aMethod,
Args&&... aArgs) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aBrowsingContext);
CallState state = CallState::Continue;
for (const RefPtr<BrowsingContext>& bc : aBrowsingContext->Children()) {
if (nsCOMPtr<nsPIDOMWindowOuter> pWin = bc->GetDOMWindow()) {
auto* win = nsGlobalWindowOuter::Cast(pWin);
if (nsGlobalWindowInner* inner =
nsGlobalWindowInner::Cast(win->GetCurrentInnerWindow())) {
// Call the descendant method using our helper CallDescendant() template
// method. This allows us to handle both void returning methods and
// methods that return CallState explicitly. For void returning methods
// we assume CallState::Continue.
using returnType = decltype((inner->*aMethod)(aArgs...));
state = CallDescendant<returnType>(inner, aMethod, aArgs...);
if (state == CallState::Stop) {
return state;
}
}
}
if (!aChildOnly) {
state = CallOnInProcessDescendantsInternal(bc.get(), aChildOnly, aMethod,
aArgs...);
if (state == CallState::Stop) {
return state;
}
}
}
return state;
}
nsIURI* nsGlobalWindowInner::GetBaseURI() const { return GetDocBaseURI(); }
Maybe<ClientInfo> nsGlobalWindowInner::GetClientInfo() const {
MOZ_ASSERT(NS_IsMainThread());
if (mDoc && mDoc->IsStaticDocument()) {
if (Maybe<ClientInfo> info = mDoc->GetOriginalDocument()->GetClientInfo()) {
return info;
}
}
Maybe<ClientInfo> clientInfo;
if (mClientSource) {
clientInfo.emplace(mClientSource->Info());
}
return clientInfo;
}
Maybe<ClientState> nsGlobalWindowInner::GetClientState() const {
MOZ_ASSERT(NS_IsMainThread());
if (mDoc && mDoc->IsStaticDocument()) {
if (Maybe<ClientState> state =
mDoc->GetOriginalDocument()->GetClientState()) {
return state;
}
}
Maybe<ClientState> clientState;
if (mClientSource) {
Result<ClientState, ErrorResult> res = mClientSource->SnapshotState();
if (res.isOk()) {
clientState.emplace(res.unwrap());
} else {
res.unwrapErr().SuppressException();
}
}
return clientState;
}
Maybe<ServiceWorkerDescriptor> nsGlobalWindowInner::GetController() const {
MOZ_ASSERT(NS_IsMainThread());
if (mDoc && mDoc->IsStaticDocument()) {
if (Maybe<ServiceWorkerDescriptor> controller =
mDoc->GetOriginalDocument()->GetController()) {
return controller;
}
}
Maybe<ServiceWorkerDescriptor> controller;
if (mClientSource) {
controller = mClientSource->GetController();
}
return controller;
}
void nsGlobalWindowInner::SetPolicyContainer(
nsIPolicyContainer* aPolicyContainer) {
if (!mClientSource) {
return;
}
mClientSource->SetPolicyContainer(aPolicyContainer);
// Also cache the PolicyContainer within the document
mDoc->SetPolicyContainer(aPolicyContainer);
if (mWindowGlobalChild) {
mWindowGlobalChild->SendSetClientInfo(mClientSource->Info().ToIPC());
}
}
nsIPolicyContainer* nsGlobalWindowInner::GetPolicyContainer() {
if (mDoc) {
return mDoc->GetPolicyContainer();
}
// If the window is partially torn down and has its document nulled out,
// we query the policy container we snapshot in FreeInnerObjects.
if (mDocumentPolicyContainer) {
return mDocumentPolicyContainer;
}
return nullptr;
}
void nsGlobalWindowInner::SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCsp) {
if (!mClientSource) {
return;
}
mClientSource->SetPreloadCsp(aPreloadCsp);
// Also cache the preload CSP within the document
mDoc->SetPreloadCsp(aPreloadCsp);
if (mWindowGlobalChild) {
mWindowGlobalChild->SendSetClientInfo(mClientSource->Info().ToIPC());
}
}
already_AddRefed<ServiceWorkerContainer>
nsGlobalWindowInner::GetServiceWorkerContainer() {
return Navigator()->ServiceWorker();
}
RefPtr<ServiceWorker> nsGlobalWindowInner::GetOrCreateServiceWorker(
const ServiceWorkerDescriptor& aDescriptor) {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<ServiceWorker> ref;
ForEachGlobalTeardownObserver(
[&](GlobalTeardownObserver* aObserver, bool* aDoneOut) {
RefPtr<ServiceWorker> sw = do_QueryObject(aObserver);
if (!sw || !sw->Descriptor().Matches(aDescriptor)) {
return;
}
ref = std::move(sw);
*aDoneOut = true;
});
if (!ref) {
ref = ServiceWorker::Create(this, aDescriptor);
}
return ref;
}
RefPtr<mozilla::dom::ServiceWorkerRegistration>
nsGlobalWindowInner::GetServiceWorkerRegistration(
const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
const {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<ServiceWorkerRegistration> ref;
ForEachGlobalTeardownObserver(
[&](GlobalTeardownObserver* aObserver, bool* aDoneOut) {
RefPtr<ServiceWorkerRegistration> swr = do_QueryObject(aObserver);
if (!swr || !swr->MatchesDescriptor(aDescriptor)) {
return;
}
ref = std::move(swr);
*aDoneOut = true;
});
return ref;
}
RefPtr<ServiceWorkerRegistration>
nsGlobalWindowInner::GetOrCreateServiceWorkerRegistration(
const ServiceWorkerRegistrationDescriptor& aDescriptor) {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<ServiceWorkerRegistration> ref =
GetServiceWorkerRegistration(aDescriptor);
if (!ref) {
ref = ServiceWorkerRegistration::CreateForMainThread(this, aDescriptor);
}
return ref;
}
StorageAccess nsGlobalWindowInner::GetStorageAccess() {
return StorageAllowedForWindow(this);
}
nsICookieJarSettings* nsGlobalWindowInner::GetCookieJarSettings() {
MOZ_ASSERT(NS_IsMainThread());
if (mDoc) {
return mDoc->CookieJarSettings();
}
return nullptr;
}
nsresult nsGlobalWindowInner::FireDelayedDOMEvents(bool aIncludeSubWindows) {
// Fires an offline status event if the offline status has changed
FireOfflineStatusEventIfChanged();
if (mCookieStore) {
mCookieStore->FireDelayedDOMEvents();
}
if (!aIncludeSubWindows) {
return NS_OK;
}
nsCOMPtr<nsIDocShell> docShell = GetDocShell();
if (docShell) {
int32_t childCount = 0;
docShell->GetInProcessChildCount(&childCount);
// Take a copy of the current children so that modifications to
// the child list don't affect to the iteration.
AutoTArray<nsCOMPtr<nsIDocShellTreeItem>, 8> children;
for (int32_t i = 0; i < childCount; ++i) {
nsCOMPtr<nsIDocShellTreeItem> childShell;
docShell->GetInProcessChildAt(i, getter_AddRefs(childShell));
if (childShell) {
children.AppendElement(childShell);
}
}
for (nsCOMPtr<nsIDocShellTreeItem> childShell : children) {
if (nsCOMPtr<nsPIDOMWindowOuter> pWin = childShell->GetWindow()) {
auto* win = nsGlobalWindowOuter::Cast(pWin);
win->FireDelayedDOMEvents(true);
}
}
}
return NS_OK;
}
//*****************************************************************************
// nsGlobalWindowInner: Window Control Functions
//*****************************************************************************
nsPIDOMWindowOuter* nsGlobalWindowInner::GetInProcessParentInternal() {
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
if (!outer) {
// No outer window available!
return nullptr;
}
return outer->GetInProcessParentInternal();
}
nsIPrincipal* nsGlobalWindowInner::GetTopLevelAntiTrackingPrincipal() {
nsPIDOMWindowOuter* outerWindow = GetOuterWindowInternal();
if (!outerWindow) {
return nullptr;
}
nsPIDOMWindowOuter* topLevelOuterWindow =
GetBrowsingContext()->Top()->GetDOMWindow();
if (!topLevelOuterWindow) {
return nullptr;
}
bool stopAtOurLevel =
mDoc && mDoc->CookieJarSettings()->GetCookieBehavior() ==
nsICookieService::BEHAVIOR_REJECT_TRACKER;
if (stopAtOurLevel && topLevelOuterWindow == outerWindow) {
return nullptr;
}
nsPIDOMWindowInner* topLevelInnerWindow =
topLevelOuterWindow->GetCurrentInnerWindow();
if (NS_WARN_IF(!topLevelInnerWindow)) {
return nullptr;
}
nsIPrincipal* topLevelPrincipal =
nsGlobalWindowInner::Cast(topLevelInnerWindow)->GetPrincipal();
if (NS_WARN_IF(!topLevelPrincipal)) {
return nullptr;
}
return topLevelPrincipal;
}
nsIPrincipal* nsGlobalWindowInner::GetClientPrincipal() {
return mClientSource ? mClientSource->GetPrincipal() : nullptr;
}
bool nsGlobalWindowInner::IsInFullScreenTransition() {
if (!mIsChrome) {
return false;
}
nsGlobalWindowOuter* outerWindow = GetOuterWindowInternal();
if (!outerWindow) {
return false;
}
return outerWindow->mIsInFullScreenTransition;
}
//*****************************************************************************
// nsGlobalWindowInner: Timeout Functions
//*****************************************************************************
class WindowScriptTimeoutHandler final : public ScriptTimeoutHandler {
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(WindowScriptTimeoutHandler,
ScriptTimeoutHandler)
WindowScriptTimeoutHandler(JSContext* aCx, nsIGlobalObject* aGlobal,
const nsAString& aExpression)
: ScriptTimeoutHandler(aCx, aGlobal, aExpression),
mInitiatingScript(ScriptLoader::GetActiveScript(aCx)) {}
MOZ_CAN_RUN_SCRIPT virtual bool Call(const char* aExecutionReason) override;
private:
virtual ~WindowScriptTimeoutHandler() = default;
// Initiating script for use when evaluating mExpr on the main thread.
RefPtr<JS::loader::LoadedScript> mInitiatingScript;
};
NS_IMPL_CYCLE_COLLECTION_INHERITED(WindowScriptTimeoutHandler,
ScriptTimeoutHandler, mInitiatingScript)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(WindowScriptTimeoutHandler)
NS_INTERFACE_MAP_END_INHERITING(ScriptTimeoutHandler)
NS_IMPL_ADDREF_INHERITED(WindowScriptTimeoutHandler, ScriptTimeoutHandler)
NS_IMPL_RELEASE_INHERITED(WindowScriptTimeoutHandler, ScriptTimeoutHandler)
bool WindowScriptTimeoutHandler::Call(const char* aExecutionReason) {
// New script entry point required, due to the "Create a script" sub-step
// of
// http://www.whatwg.org/specs/web-apps/current-work/#timer-initialisation-steps
nsAutoMicroTask mt;
AutoEntryScript aes(mGlobal, aExecutionReason, true);
JS::CompileOptions options(aes.cx());
options.setFileAndLine(mCaller.FileName().get(), mCaller.mLine);
options.setNoScriptRval(true);
options.setIntroductionType("domTimer");
JS::Rooted<JSObject*> global(aes.cx(), mGlobal->GetGlobalJSObject());
{
if (MOZ_UNLIKELY(!xpc::Scriptability::Get(global).Allowed())) {
return true;
}
IgnoredErrorResult erv;
mozilla::AutoProfilerLabel autoProfilerLabel("JSExecutionContext",
/* dynamicStr */ nullptr,
JS::ProfilingCategoryPair::JS);
JSAutoRealm autoRealm(aes.cx(), global);
RefPtr<JS::Stencil> stencil;
JS::Rooted<JSScript*> script(aes.cx());
Compile(aes.cx(), options, mExpr, stencil, erv);
if (stencil) {
JS::InstantiateOptions instantiateOptions(options);
MOZ_ASSERT(!instantiateOptions.deferDebugMetadata);
script.set(JS::InstantiateGlobalStencil(aes.cx(), instantiateOptions,
stencil, /* storage */ nullptr));
if (!script) {
erv.NoteJSContextException(aes.cx());
}
}
if (script) {
MOZ_ASSERT(!erv.Failed());
if (mInitiatingScript) {
mInitiatingScript->AssociateWithScript(script);
}
if (!JS_ExecuteScript(aes.cx(), script)) {
erv.NoteJSContextException(aes.cx());
}
}
if (erv.IsUncatchableException()) {
return false;
}
}
return true;
};
nsGlobalWindowInner* nsGlobalWindowInner::InnerForSetTimeoutOrInterval(
ErrorResult& aError) {
nsGlobalWindowOuter* outer = GetOuterWindowInternal();
nsPIDOMWindowInner* currentInner =
outer ? outer->GetCurrentInnerWindow() : this;
// If forwardTo is not the window with an active document then we want the
// call to setTimeout/Interval to be a noop, so return null but don't set an
// error.
return HasActiveDocument() ? nsGlobalWindowInner::Cast(currentInner)
: nullptr;
}
int32_t nsGlobalWindowInner::SetTimeout(
JSContext* aCx, const FunctionOrTrustedScriptOrString& aHandler,
int32_t aTimeout, const Sequence<JS::Value>& aArguments,
nsIPrincipal* aSubjectPrincipal, ErrorResult& aError) {
return SetTimeoutOrInterval(aCx, aHandler, aTimeout, aArguments, false,
aSubjectPrincipal, aError);
}
int32_t nsGlobalWindowInner::SetInterval(
JSContext* aCx, const FunctionOrTrustedScriptOrString& aHandler,
const int32_t aTimeout, const Sequence<JS::Value>& aArguments,
nsIPrincipal* aSubjectPrincipal, ErrorResult& aError) {
return SetTimeoutOrInterval(aCx, aHandler, aTimeout, aArguments, true,
aSubjectPrincipal, aError);
}
int32_t nsGlobalWindowInner::SetTimeoutOrInterval(
JSContext* aCx, const FunctionOrTrustedScriptOrString& aHandler,
int32_t aTimeout, const Sequence<JS::Value>& aArguments, bool aIsInterval,
nsIPrincipal* aSubjectPrincipal, ErrorResult& aError) {
nsGlobalWindowInner* inner = InnerForSetTimeoutOrInterval(aError);
if (!inner) {
return -1;
}
if (inner != this) {
RefPtr<nsGlobalWindowInner> innerRef(inner);
return innerRef->SetTimeoutOrInterval(aCx, aHandler, aTimeout, aArguments,
aIsInterval, aSubjectPrincipal,
aError);
}
DebuggerNotificationDispatch(
this, aIsInterval ? DebuggerNotificationType::SetInterval
: DebuggerNotificationType::SetTimeout);
if (!GetContextInternal() || !HasJSGlobal()) {
// This window was already closed, or never properly initialized,
// don't let a timer be scheduled on such a window.
aError.Throw(NS_ERROR_NOT_INITIALIZED);
return 0;
}
if (aHandler.IsFunction()) {
nsTArray<JS::Heap<JS::Value>> args;
if (!args.AppendElements(aArguments, fallible)) {
aError.Throw(NS_ERROR_OUT_OF_MEMORY);
return 0;
}
RefPtr<TimeoutHandler> handler = new CallbackTimeoutHandler(
aCx, this, &aHandler.GetAsFunction(), std::move(args));
int32_t result;
aError = mTimeoutManager->SetTimeout(handler, aTimeout, aIsInterval,
Timeout::Reason::eTimeoutOrInterval,
&result);
return result;
}
constexpr nsLiteralString sinkSetTimeout = u"Window setTimeout"_ns;
constexpr nsLiteralString sinkSetInterval = u"Window setInterval"_ns;
Maybe<nsAutoString> compliantStringHolder;
nsCOMPtr<nsIGlobalObject> pinnedGlobal = this;
const nsAString* compliantString =
TrustedTypeUtils::GetTrustedTypesCompliantString(
aHandler, aIsInterval ? sinkSetInterval : sinkSetTimeout,
kTrustedTypesOnlySinkGroup, *pinnedGlobal, aSubjectPrincipal,
compliantStringHolder, aError);
if (aError.Failed()) {
return 0;
}
bool allowEval = false;
aError =
CSPEvalChecker::CheckForWindow(aCx, this, *compliantString, &allowEval);
if (NS_WARN_IF(aError.Failed()) || !allowEval) {
return 0;
}
RefPtr<TimeoutHandler> handler =
new WindowScriptTimeoutHandler(aCx, this, *compliantString);
int32_t result;
aError =
mTimeoutManager->SetTimeout(handler, aTimeout, aIsInterval,
Timeout::Reason::eTimeoutOrInterval, &result);
return result;
}
static const char* GetTimeoutReasonString(Timeout* aTimeout) {
switch (aTimeout->mReason) {
case Timeout::Reason::eTimeoutOrInterval:
if (aTimeout->mIsInterval) {
return "setInterval handler";
}
return "setTimeout handler";
case Timeout::Reason::eIdleCallbackTimeout:
return "setIdleCallback handler (timed out)";
case Timeout::Reason::eAbortSignalTimeout:
return "AbortSignal timeout";
case Timeout::Reason::eDelayedWebTaskTimeout:
return "delayedWebTaskCallback handler (timed out)";
case Timeout::Reason::eJSTimeout:
return "JavaScript TimeoutJob (timed out)";
default:
MOZ_CRASH("Unexpected enum value");
return "";
}
MOZ_CRASH("Unexpected enum value");
return "";
}
bool nsGlobalWindowInner::RunTimeoutHandler(Timeout* aTimeout) {
// Hold on to the timeout in case mExpr or mFunObj releases its
// doc.
// XXXbz Our caller guarantees it'll hold on to the timeout (because
// we're MOZ_CAN_RUN_SCRIPT), so we can probably stop doing that...
RefPtr<Timeout> timeout = aTimeout;
Timeout* last_running_timeout = mTimeoutManager->BeginRunningTimeout(timeout);
timeout->mRunning = true;
// Push this timeout's popup control state, which should only be
// enabled the first time a timeout fires that was created while
// popups were enabled and with a delay less than
// "dom.disable_open_click_delay".
AutoPopupStatePusher popupStatePusher(timeout->mPopupState);
// Clear the timeout's popup state, if any, to prevent interval
// timeouts from repeatedly opening poups.
timeout->mPopupState = PopupBlocker::openAbused;
uint32_t nestingLevel = mTimeoutManager->GetNestingLevelForWindow();
mTimeoutManager->SetNestingLevelForWindow(timeout->mNestingLevel);
const char* reason = GetTimeoutReasonString(timeout);
nsCString str;
if (profiler_thread_is_being_profiled_for_markers()) {
TimeDuration originalInterval = timeout->When() - timeout->SubmitTime();
str.Append(reason);
str.Append(" with interval ");
str.AppendInt(int(originalInterval.ToMilliseconds()));
str.Append("ms: ");
nsCString handlerDescription;
timeout->mScriptHandler->GetDescription(handlerDescription);
str.Append(handlerDescription);
}
AUTO_PROFILER_MARKER_TEXT("setTimeout callback", DOM,
MarkerOptions(MarkerStack::TakeBacktrace(
timeout->TakeProfilerBacktrace()),
MarkerInnerWindowId(mWindowID)),
str);
bool abortIntervalHandler;
{
RefPtr<TimeoutHandler> handler(timeout->mScriptHandler);
CallbackDebuggerNotificationGuard guard(
this, timeout->mIsInterval
? DebuggerNotificationType::SetIntervalCallback
: DebuggerNotificationType::SetTimeoutCallback);
abortIntervalHandler = !handler->Call(reason);
}
// If we received an uncatchable exception, do not schedule the timeout again.
// This allows the slow script dialog to break easy DoS attacks like
// setInterval(function() { while(1); }, 100);
if (abortIntervalHandler) {
// If it wasn't an interval timer to begin with, this does nothing. If it
// was, we'll treat it as a timeout that we just ran and discard it when
// we return.
timeout->mIsInterval = false;
}
// We ignore any failures from calling EvaluateString() on the context or
// Call() on a Function here since we're in a loop
// where we're likely to be running timeouts whose OS timers
// didn't fire in time and we don't want to not fire those timers
// now just because execution of one timer failed. We can't
// propagate the error to anyone who cares about it from this
// point anyway, and the script context should have already reported
// the script error in the usual way - so we just drop it.
mTimeoutManager->SetNestingLevelForWindow(nestingLevel);
mTimeoutManager->EndRunningTimeout(last_running_timeout);
timeout->mRunning = false;
return timeout->mCleared;
}
//*****************************************************************************
// nsGlobalWindowInner: Helper Functions
//*****************************************************************************
already_AddRefed<nsIDocShellTreeOwner> nsGlobalWindowInner::GetTreeOwner() {
FORWARD_TO_OUTER(GetTreeOwner, (), nullptr);
}
already_AddRefed<nsIWebBrowserChrome>
nsGlobalWindowInner::GetWebBrowserChrome() {
nsCOMPtr<nsIDocShellTreeOwner> treeOwner = GetTreeOwner();
nsCOMPtr<nsIWebBrowserChrome> browserChrome = do_GetInterface(treeOwner);
return browserChrome.forget();
}
ScrollContainerFrame* nsGlobalWindowInner::GetScrollContainerFrame() {
FORWARD_TO_OUTER(GetScrollContainerFrame, (), nullptr);
}
bool nsGlobalWindowInner::IsPrivateBrowsing() {
nsCOMPtr<nsILoadContext> loadContext = do_QueryInterface(GetDocShell());
return loadContext && loadContext->UsePrivateBrowsing();
}
void nsGlobalWindowInner::FlushPendingNotifications(FlushType aType) {
if (mDoc) {
mDoc->FlushPendingNotifications(aType);
}
}
void nsGlobalWindowInner::EnableDeviceSensor(uint32_t aType) {
bool alreadyEnabled = false;
for (uint32_t i = 0; i < mEnabledSensors.Length(); i++) {
if (mEnabledSensors[i] == aType) {
alreadyEnabled = true;
break;
}
}
mEnabledSensors.AppendElement(aType);
if (alreadyEnabled) {
return;
}
nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
if (ac) {
ac->AddWindowListener(aType, this);
}
}
void nsGlobalWindowInner::DisableDeviceSensor(uint32_t aType) {
int32_t doomedElement = -1;
int32_t listenerCount = 0;
for (uint32_t i = 0; i < mEnabledSensors.Length(); i++) {
if (mEnabledSensors[i] == aType) {
doomedElement = i;
listenerCount++;
}
}
if (doomedElement == -1) {
return;
}
mEnabledSensors.RemoveElementAt(doomedElement);
if (listenerCount > 1) {
return;
}
nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
if (ac) {
ac->RemoveWindowListener(aType, this);
}
}
#if defined(MOZ_WIDGET_ANDROID)
void nsGlobalWindowInner::EnableOrientationChangeListener() {
if (!ShouldResistFingerprinting(RFPTarget::ScreenOrientation)) {
mHasOrientationChangeListeners = true;
mOrientationAngle = Orientation(CallerType::System);
}
}
void nsGlobalWindowInner::DisableOrientationChangeListener() {
mHasOrientationChangeListeners = false;
}
#endif
void nsGlobalWindowInner::SetHasGamepadEventListener(
bool aHasGamepad /* = true*/) {
mHasGamepad = aHasGamepad;
if (aHasGamepad) {
EnableGamepadUpdates();
}
}
void nsGlobalWindowInner::NotifyDetectXRRuntimesCompleted() {
if (!mXRRuntimeDetectionInFlight) {
return;
}
mXRRuntimeDetectionInFlight = false;
if (mXRPermissionRequestInFlight) {
return;
}
gfx::VRManagerChild* vm = gfx::VRManagerChild::Get();
bool supported = vm->RuntimeSupportsVR();
if (!supported) {
// A VR runtime was not installed; we can suppress
// the permission prompt
OnXRPermissionRequestCancel();
return;
}
// A VR runtime was found. Display a permission prompt before
// allowing it to be accessed.
// Connect to the VRManager in order to receive the runtime
// detection results.
mXRPermissionRequestInFlight = true;
RefPtr<XRPermissionRequest> request =
new XRPermissionRequest(this, WindowID());
Unused << NS_WARN_IF(NS_FAILED(request->Start()));
}
void nsGlobalWindowInner::RequestXRPermission() {
if (IsDying()) {
// Do not proceed if the window is dying, as that will result
// in leaks of objects that get re-allocated after FreeInnerObjects
// has been called, including mVREventObserver.
return;
}
if (mXRPermissionGranted) {
// Don't prompt redundantly once permission to
// access XR devices has been granted.
OnXRPermissionRequestAllow();
return;
}
if (mXRRuntimeDetectionInFlight || mXRPermissionRequestInFlight) {
// Don't allow multiple simultaneous permissions requests;
return;
}
// Before displaying a permission prompt, detect
// if there is any VR runtime installed.
gfx::VRManagerChild* vm = gfx::VRManagerChild::Get();
mXRRuntimeDetectionInFlight = true;
EnableVRUpdates();
vm->DetectRuntimes();
}
void nsGlobalWindowInner::OnXRPermissionRequestAllow() {
mXRPermissionRequestInFlight = false;
if (IsDying()) {
// The window may have started dying while the permission request
// is in flight.
// Do not proceed if the window is dying, as that will result
// in leaks of objects that get re-allocated after FreeInnerObjects
// has been called, including mNavigator.
return;
}
mXRPermissionGranted = true;
NotifyHasXRSession();
dom::Navigator* nav = Navigator();
MOZ_ASSERT(nav != nullptr);
nav->OnXRPermissionRequestAllow();
}
void nsGlobalWindowInner::OnXRPermissionRequestCancel() {
mXRPermissionRequestInFlight = false;
if (IsDying()) {
// The window may have started dying while the permission request
// is in flight.
// Do not proceed if the window is dying, as that will result
// in leaks of objects that get re-allocated after FreeInnerObjects
// has been called, including mNavigator.
return;
}
dom::Navigator* nav = Navigator();
MOZ_ASSERT(nav != nullptr);
nav->OnXRPermissionRequestCancel();
}
void nsGlobalWindowInner::EventListenerAdded(nsAtom* aType) {
if (aType == nsGkAtoms::onvrdisplayactivate ||
aType == nsGkAtoms::onvrdisplayconnect ||
aType == nsGkAtoms::onvrdisplaydeactivate ||
aType == nsGkAtoms::onvrdisplaydisconnect ||
aType == nsGkAtoms::onvrdisplaypresentchange) {
RequestXRPermission();
}
if (aType == nsGkAtoms::onvrdisplayactivate) {
mHasVRDisplayActivateEvents = true;
}
if (aType == nsGkAtoms::onunload && mWindowGlobalChild) {
if (++mUnloadOrBeforeUnloadListenerCount == 1) {
mWindowGlobalChild->BlockBFCacheFor(BFCacheStatus::UNLOAD_LISTENER);
}
}
if (aType == nsGkAtoms::onbeforeunload && mWindowGlobalChild) {
if (!mozilla::SessionHistoryInParent() ||
!StaticPrefs::
docshell_shistory_bfcache_ship_allow_beforeunload_listeners()) {
if (++mUnloadOrBeforeUnloadListenerCount == 1) {
mWindowGlobalChild->BlockBFCacheFor(
BFCacheStatus::BEFOREUNLOAD_LISTENER);
}
}
if (!mDoc || !(mDoc->GetSandboxFlags() & SANDBOXED_MODALS)) {
mWindowGlobalChild->BeforeUnloadAdded();
MOZ_ASSERT(mWindowGlobalChild->BeforeUnloadListeners() > 0);
}
}
// We need to initialize localStorage in order to receive notifications.
if (aType == nsGkAtoms::onstorage) {
ErrorResult rv;
GetLocalStorage(rv);
rv.SuppressException();
if (NextGenLocalStorageEnabled() && mLocalStorage &&
mLocalStorage->Type() == Storage::eLocalStorage) {
auto object = static_cast<LSObject*>(mLocalStorage.get());
Unused << NS_WARN_IF(NS_FAILED(object->EnsureObserver()));
}
}
}
void nsGlobalWindowInner::EventListenerRemoved(nsAtom* aType) {
if (aType == nsGkAtoms::onunload && mWindowGlobalChild) {
MOZ_ASSERT(mUnloadOrBeforeUnloadListenerCount > 0);
if (--mUnloadOrBeforeUnloadListenerCount == 0) {
mWindowGlobalChild->UnblockBFCacheFor(BFCacheStatus::UNLOAD_LISTENER);
}
}
if (aType == nsGkAtoms::onbeforeunload && mWindowGlobalChild) {
if (!mozilla::SessionHistoryInParent() ||
!StaticPrefs::
docshell_shistory_bfcache_ship_allow_beforeunload_listeners()) {
if (--mUnloadOrBeforeUnloadListenerCount == 0) {
mWindowGlobalChild->UnblockBFCacheFor(
BFCacheStatus::BEFOREUNLOAD_LISTENER);
}
}
if (!mDoc || !(mDoc->GetSandboxFlags() & SANDBOXED_MODALS)) {
mWindowGlobalChild->BeforeUnloadRemoved();
MOZ_ASSERT(mWindowGlobalChild->BeforeUnloadListeners() >= 0);
}
}
if (aType == nsGkAtoms::onstorage) {
if (NextGenLocalStorageEnabled() && mLocalStorage &&
mLocalStorage->Type() == Storage::eLocalStorage &&
// The remove event is fired even if this isn't the last listener, so
// only remove if there are no other listeners left.
mListenerManager &&
!mListenerManager->HasListenersFor(nsGkAtoms::onstorage)) {
auto object = static_cast<LSObject*>(mLocalStorage.get());
object->DropObserver();
}
}
}
void nsGlobalWindowInner::NotifyHasXRSession() {
if (IsDying()) {
// Do not proceed if the window is dying, as that will result
// in leaks of objects that get re-allocated after FreeInnerObjects
// has been called, including mVREventObserver.
return;
}
if (mWindowGlobalChild && !mHasXRSession) {
mWindowGlobalChild->BlockBFCacheFor(BFCacheStatus::HAS_USED_VR);
}
mHasXRSession = true;
EnableVRUpdates();
}
bool nsGlobalWindowInner::HasUsedVR() const {
// Returns true only if content has enumerated and activated
// XR devices. Detection of XR runtimes without activation
// will not cause true to be returned.
return mHasXRSession;
}
bool nsGlobalWindowInner::IsVRContentDetected() const {
// Returns true only if the content will respond to
// the VRDisplayActivate event.
return mHasVRDisplayActivateEvents;
}
bool nsGlobalWindowInner::IsVRContentPresenting() const {
for (const auto& display : mVRDisplays) {
if (display->IsAnyPresenting(gfx::kVRGroupAll)) {
return true;
}
}
return false;
}
void nsGlobalWindowInner::AddSizeOfIncludingThis(
nsWindowSizes& aWindowSizes) const {
aWindowSizes.mDOMSizes.mDOMOtherSize +=
aWindowSizes.mState.mMallocSizeOf(this);
aWindowSizes.mDOMSizes.mDOMOtherSize +=
nsIGlobalObject::ShallowSizeOfExcludingThis(
aWindowSizes.mState.mMallocSizeOf);
EventListenerManager* elm = GetExistingListenerManager();
if (elm) {
aWindowSizes.mDOMSizes.mDOMOtherSize +=
elm->SizeOfIncludingThis(aWindowSizes.mState.mMallocSizeOf);
aWindowSizes.mDOMEventListenersCount += elm->ListenerCount();
}
if (mDoc) {
// Multiple global windows can share a document. So only measure the
// document if it (a) doesn't have a global window, or (b) it's the
// primary document for the window.
if (!mDoc->GetInnerWindow() || mDoc->GetInnerWindow() == this) {
mDoc->DocAddSizeOfIncludingThis(aWindowSizes);
}
}
if (mNavigation) {
aWindowSizes.mDOMSizes.mDOMOtherSize +=
aWindowSizes.mState.mMallocSizeOf(mNavigation.get());
}
if (mNavigator) {
aWindowSizes.mDOMSizes.mDOMOtherSize +=
mNavigator->SizeOfIncludingThis(aWindowSizes.mState.mMallocSizeOf);
}
ForEachGlobalTeardownObserver([&](GlobalTeardownObserver* et,
bool* aDoneOut) {
if (nsCOMPtr<nsISizeOfEventTarget> iSizeOf = do_QueryObject(et)) {
aWindowSizes.mDOMSizes.mDOMEventTargetsSize +=
iSizeOf->SizeOfEventTargetIncludingThis(
aWindowSizes.mState.mMallocSizeOf);
}
if (nsCOMPtr<DOMEventTargetHelper> helper = do_QueryObject(et)) {
if (EventListenerManager* elm = helper->GetExistingListenerManager()) {
aWindowSizes.mDOMEventListenersCount += elm->ListenerCount();
}
}
++aWindowSizes.mDOMEventTargetsCount;
});
if (mPerformance) {
aWindowSizes.mDOMSizes.mDOMPerformanceUserEntries =
mPerformance->SizeOfUserEntries(aWindowSizes.mState.mMallocSizeOf);
aWindowSizes.mDOMSizes.mDOMPerformanceResourceEntries =
mPerformance->SizeOfResourceEntries(aWindowSizes.mState.mMallocSizeOf);
aWindowSizes.mDOMSizes.mDOMPerformanceEventEntries =
mPerformance->SizeOfEventEntries(aWindowSizes.mState.mMallocSizeOf);
}
}
void nsGlobalWindowInner::RegisterDataDocumentForMemoryReporting(
Document* aDocument) {
aDocument->SetAddedToMemoryReportAsDataDocument();
mDataDocumentsForMemoryReporting.AppendElement(aDocument);
}
void nsGlobalWindowInner::UnregisterDataDocumentForMemoryReporting(
Document* aDocument) {
DebugOnly<bool> found =
mDataDocumentsForMemoryReporting.RemoveElement(aDocument);
MOZ_ASSERT(found);
}
void nsGlobalWindowInner::CollectDOMSizesForDataDocuments(
nsWindowSizes& aSize) const {
for (Document* doc : mDataDocumentsForMemoryReporting) {
if (doc) {
doc->DocAddSizeOfIncludingThis(aSize);
}
}
}
void nsGlobalWindowInner::AddGamepad(GamepadHandle aHandle, Gamepad* aGamepad) {
// Create the index we will present to content based on which indices are
// already taken, as required by the spec.
// https://w3c.github.io/gamepad/gamepad.html#widl-Gamepad-index
int index = 0;
while (mGamepadIndexSet.Contains(index)) {
++index;
}
mGamepadIndexSet.Put(index);
aGamepad->SetIndex(index);
mGamepads.InsertOrUpdate(aHandle, RefPtr{aGamepad});
}
void nsGlobalWindowInner::RemoveGamepad(GamepadHandle aHandle) {
RefPtr<Gamepad> gamepad;
if (!mGamepads.Get(aHandle, getter_AddRefs(gamepad))) {
return;
}
// Free up the index we were using so it can be reused
mGamepadIndexSet.Remove(gamepad->Index());
mGamepads.Remove(aHandle);
}
void nsGlobalWindowInner::GetGamepads(nsTArray<RefPtr<Gamepad>>& aGamepads) {
aGamepads.Clear();
// navigator.getGamepads() always returns an empty array when
// privacy.resistFingerprinting is true.
if (ShouldResistFingerprinting(RFPTarget::Gamepad)) {
return;
}
// mGamepads.Count() may not be sufficient, but it's not harmful.
aGamepads.SetCapacity(mGamepads.Count());
for (const auto& entry : mGamepads) {
Gamepad* gamepad = entry.GetWeak();
aGamepads.EnsureLengthAtLeast(gamepad->Index() + 1);
aGamepads[gamepad->Index()] = gamepad;
}
}
already_AddRefed<mozilla::dom::Promise> nsGlobalWindowInner::RequestAllGamepads(
ErrorResult& aRv) {
RefPtr<GamepadManager> gamepadManager(GamepadManager::GetService());
if (!gamepadManager) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
return gamepadManager->RequestAllGamepads(this, aRv);
}
already_AddRefed<Gamepad> nsGlobalWindowInner::GetGamepad(
GamepadHandle aHandle) {
RefPtr<Gamepad> gamepad;
if (mGamepads.Get(aHandle, getter_AddRefs(gamepad))) {
return gamepad.forget();
}
return nullptr;
}
void nsGlobalWindowInner::SetHasSeenGamepadInput(bool aHasSeen) {
mHasSeenGamepadInput = aHasSeen;
}
bool nsGlobalWindowInner::HasSeenGamepadInput() { return mHasSeenGamepadInput; }
void nsGlobalWindowInner::SyncGamepadState() {
if (mHasSeenGamepadInput) {
RefPtr<GamepadManager> gamepadManager(GamepadManager::GetService());
for (const auto& entry : mGamepads) {
gamepadManager->SyncGamepadState(entry.GetKey(), this, entry.GetWeak());
}
}
}
void nsGlobalWindowInner::StopGamepadHaptics() {
if (mHasSeenGamepadInput) {
RefPtr<GamepadManager> gamepadManager(GamepadManager::GetService());
gamepadManager->StopHaptics();
}
}
bool nsGlobalWindowInner::UpdateVRDisplays(
nsTArray<RefPtr<mozilla::dom::VRDisplay>>& aDevices) {
VRDisplay::UpdateVRDisplays(mVRDisplays, this);
aDevices = mVRDisplays.Clone();
return true;
}
void nsGlobalWindowInner::NotifyActiveVRDisplaysChanged() {
if (mNavigator) {
mNavigator->NotifyActiveVRDisplaysChanged();
}
}
void nsGlobalWindowInner::NotifyPresentationGenerationChanged(
uint32_t aDisplayID) {
for (const auto& display : mVRDisplays) {
if (display->DisplayId() == aDisplayID) {
display->OnPresentationGenerationChanged();
}
}
}
void nsGlobalWindowInner::DispatchVRDisplayActivate(
uint32_t aDisplayID, mozilla::dom::VRDisplayEventReason aReason) {
// Ensure that our list of displays is up to date
VRDisplay::UpdateVRDisplays(mVRDisplays, this);
// Search for the display identified with aDisplayID and fire the
// event if found.
for (const auto& display : mVRDisplays) {
if (display->DisplayId() == aDisplayID) {
if (aReason != VRDisplayEventReason::Navigation &&
display->IsAnyPresenting(gfx::kVRGroupContent)) {
// We only want to trigger this event if nobody is presenting to the
// display already or when a page is loaded by navigating away
// from a page with an active VR Presentation.
continue;
}
VRDisplayEventInit init;
init.mBubbles = false;
init.mCancelable = false;
init.mDisplay = display;
init.mReason.Construct(aReason);
RefPtr<VRDisplayEvent> event =
VRDisplayEvent::Constructor(this, u"vrdisplayactivate"_ns, init);
// vrdisplayactivate is a trusted event, allowing VRDisplay.requestPresent
// to be used in response to link traversal, user request (chrome UX), and
// HMD mounting detection sensors.
event->SetTrusted(true);
// VRDisplay.requestPresent normally requires a user gesture; however, an
// exception is made to allow it to be called in response to
// vrdisplayactivate during VR link traversal.
display->StartHandlingVRNavigationEvent();
DispatchEvent(*event);
display->StopHandlingVRNavigationEvent();
// Once we dispatch the event, we must not access any members as an event
// listener can do anything, including closing windows.
return;
}
}
}
void nsGlobalWindowInner::DispatchVRDisplayDeactivate(
uint32_t aDisplayID, mozilla::dom::VRDisplayEventReason aReason) {
// Ensure that our list of displays is up to date
VRDisplay::UpdateVRDisplays(mVRDisplays, this);
// Search for the display identified with aDisplayID and fire the
// event if found.
for (const auto& display : mVRDisplays) {
if (display->DisplayId() == aDisplayID && display->IsPresenting()) {
// We only want to trigger this event to content that is presenting to
// the display already.
VRDisplayEventInit init;
init.mBubbles = false;
init.mCancelable = false;
init.mDisplay = display;
init.mReason.Construct(aReason);
RefPtr<VRDisplayEvent> event =
VRDisplayEvent::Constructor(this, u"vrdisplaydeactivate"_ns, init);
event->SetTrusted(true);
DispatchEvent(*event);
// Once we dispatch the event, we must not access any members as an event
// listener can do anything, including closing windows.
return;
}
}
}
void nsGlobalWindowInner::DispatchVRDisplayConnect(uint32_t aDisplayID) {
// Ensure that our list of displays is up to date
VRDisplay::UpdateVRDisplays(mVRDisplays, this);
// Search for the display identified with aDisplayID and fire the
// event if found.
for (const auto& display : mVRDisplays) {
if (display->DisplayId() == aDisplayID) {
// Fire event even if not presenting to the display.
VRDisplayEventInit init;
init.mBubbles = false;
init.mCancelable = false;
init.mDisplay = display;
// VRDisplayEvent.reason is not set for vrdisplayconnect
RefPtr<VRDisplayEvent> event =
VRDisplayEvent::Constructor(this, u"vrdisplayconnect"_ns, init);
event->SetTrusted(true);
DispatchEvent(*event);
// Once we dispatch the event, we must not access any members as an event
// listener can do anything, including closing windows.
return;
}
}
}
void nsGlobalWindowInner::DispatchVRDisplayDisconnect(uint32_t aDisplayID) {
// Ensure that our list of displays is up to date
VRDisplay::UpdateVRDisplays(mVRDisplays, this);
// Search for the display identified with aDisplayID and fire the
// event if found.
for (const auto& display : mVRDisplays) {
if (display->DisplayId() == aDisplayID) {
// Fire event even if not presenting to the display.
VRDisplayEventInit init;
init.mBubbles = false;
init.mCancelable = false;
init.mDisplay = display;
// VRDisplayEvent.reason is not set for vrdisplaydisconnect
RefPtr<VRDisplayEvent> event =
VRDisplayEvent::Constructor(this, u"vrdisplaydisconnect"_ns, init);
event->SetTrusted(true);
DispatchEvent(*event);
// Once we dispatch the event, we must not access any members as an event
// listener can do anything, including closing windows.
return;
}
}
}
void nsGlobalWindowInner::DispatchVRDisplayPresentChange(uint32_t aDisplayID) {
// Ensure that our list of displays is up to date
VRDisplay::UpdateVRDisplays(mVRDisplays, this);
// Search for the display identified with aDisplayID and fire the
// event if found.
for (const auto& display : mVRDisplays) {
if (display->DisplayId() == aDisplayID) {
// Fire event even if not presenting to the display.
VRDisplayEventInit init;
init.mBubbles = false;
init.mCancelable = false;
init.mDisplay = display;
// VRDisplayEvent.reason is not set for vrdisplaypresentchange
RefPtr<VRDisplayEvent> event =
VRDisplayEvent::Constructor(this, u"vrdisplaypresentchange"_ns, init);
event->SetTrusted(true);
DispatchEvent(*event);
// Once we dispatch the event, we must not access any members as an event
// listener can do anything, including closing windows.
return;
}
}
}
enum WindowState {
// These constants need to match the constants in Window.webidl
STATE_MAXIMIZED = 1,
STATE_MINIMIZED = 2,
STATE_NORMAL = 3,
STATE_FULLSCREEN = 4
};
uint16_t nsGlobalWindowInner::WindowState() {
nsCOMPtr<nsIWidget> widget = GetMainWidget();
int32_t mode = widget ? widget->SizeMode() : 0;
switch (mode) {
case nsSizeMode_Minimized:
return STATE_MINIMIZED;
case nsSizeMode_Maximized:
return STATE_MAXIMIZED;
case nsSizeMode_Fullscreen:
return STATE_FULLSCREEN;
case nsSizeMode_Normal:
return STATE_NORMAL;
default:
NS_WARNING("Illegal window state for this chrome window");
break;
}
return STATE_NORMAL;
}
bool nsGlobalWindowInner::IsFullyOccluded() {
nsCOMPtr<nsIWidget> widget = GetMainWidget();
return widget && widget->IsFullyOccluded();
}
void nsGlobalWindowInner::Maximize() {
if (nsCOMPtr<nsIWidget> widget = GetMainWidget()) {
widget->SetSizeMode(nsSizeMode_Maximized);
}
}
void nsGlobalWindowInner::Minimize() {
if (nsCOMPtr<nsIWidget> widget = GetMainWidget()) {
widget->SetSizeMode(nsSizeMode_Minimized);
}
}
void nsGlobalWindowInner::Restore() {
if (nsCOMPtr<nsIWidget> widget = GetMainWidget()) {
widget->SetSizeMode(nsSizeMode_Normal);
}
}
void nsGlobalWindowInner::GetWorkspaceID(nsAString& workspaceID) {
workspaceID.Truncate();
if (nsCOMPtr<nsIWidget> widget = GetMainWidget()) {
return widget->GetWorkspaceID(workspaceID);
}
}
void nsGlobalWindowInner::MoveToWorkspace(const nsAString& workspaceID) {
if (nsCOMPtr<nsIWidget> widget = GetMainWidget()) {
widget->MoveToWorkspace(workspaceID);
}
}
void nsGlobalWindowInner::GetAttention(ErrorResult& aResult) {
return GetAttentionWithCycleCount(-1, aResult);
}
void nsGlobalWindowInner::GetAttentionWithCycleCount(int32_t aCycleCount,
ErrorResult& aError) {
nsCOMPtr<nsIWidget> widget = GetMainWidget();
if (widget) {
aError = widget->GetAttention(aCycleCount);
}
}
already_AddRefed<Promise> nsGlobalWindowInner::PromiseDocumentFlushed(
PromiseDocumentFlushedCallback& aCallback, ErrorResult& aError) {
MOZ_RELEASE_ASSERT(IsChromeWindow());
if (!IsCurrentInnerWindow()) {
aError.ThrowInvalidStateError("Not the current inner window");
return nullptr;
}
if (!mDoc) {
aError.ThrowInvalidStateError("No document");
return nullptr;
}
if (mIteratingDocumentFlushedResolvers) {
aError.ThrowInvalidStateError("Already iterating through resolvers");
return nullptr;
}
PresShell* presShell = mDoc->GetPresShell();
if (!presShell) {
aError.ThrowInvalidStateError("No pres shell");
return nullptr;
}
// We need to associate the lifetime of the Promise to the lifetime
// of the caller's global. That way, if the window we're observing
// refresh driver ticks on goes away before our observer is fired,
// we can still resolve the Promise.
nsIGlobalObject* global = GetIncumbentGlobal();
if (!global) {
aError.ThrowInvalidStateError("No incumbent global");
return nullptr;
}
RefPtr<Promise> resultPromise = Promise::Create(global, aError);
if (aError.Failed()) {
return nullptr;
}
UniquePtr<PromiseDocumentFlushedResolver> flushResolver(
new PromiseDocumentFlushedResolver(resultPromise, aCallback));
if (!presShell->NeedStyleFlush() && !presShell->NeedLayoutFlush()) {
flushResolver->Call();
return resultPromise.forget();
}
if (!TryToObserveRefresh()) {
aError.ThrowInvalidStateError("Couldn't observe refresh");
return nullptr;
}
mDocumentFlushedResolvers.AppendElement(std::move(flushResolver));
return resultPromise.forget();
}
bool nsGlobalWindowInner::TryToObserveRefresh() {
if (mObservingRefresh) {
return true;
}
if (!mDoc) {
return false;
}
nsPresContext* pc = mDoc->GetPresContext();
if (!pc) {
return false;
}
mObservingRefresh = true;
auto observer = MakeRefPtr<ManagedPostRefreshObserver>(
pc, [win = RefPtr{this}](bool aWasCanceled) {
if (win->MaybeCallDocumentFlushedResolvers(
/* aUntilExhaustion = */ aWasCanceled)) {
return ManagedPostRefreshObserver::Unregister::No;
}
win->mObservingRefresh = false;
return ManagedPostRefreshObserver::Unregister::Yes;
});
pc->RegisterManagedPostRefreshObserver(observer.get());
return mObservingRefresh;
}
void nsGlobalWindowInner::CallDocumentFlushedResolvers(bool aUntilExhaustion) {
while (true) {
{
// To coalesce MicroTask checkpoints inside callback call, enclose the
// inner loop with nsAutoMicroTask, and perform a MicroTask checkpoint
// after the loop.
nsAutoMicroTask mt;
mIteratingDocumentFlushedResolvers = true;
auto resolvers = std::move(mDocumentFlushedResolvers);
for (const auto& resolver : resolvers) {
resolver->Call();
}
mIteratingDocumentFlushedResolvers = false;
}
// Leaving nsAutoMicroTask above will perform MicroTask checkpoint, and
// Promise callbacks there may create mDocumentFlushedResolvers items.
// If there's no new resolvers, or we're not exhausting the queue, there's
// nothing to do (we'll keep observing if there's any new observer).
//
// Otherwise, keep looping to call all promises. This case can happen while
// destroying the window. This violates the constraint that the
// promiseDocumentFlushed callback only ever run when no flush is needed,
// but it's necessary to resolve the Promise returned by that.
if (!aUntilExhaustion || mDocumentFlushedResolvers.IsEmpty()) {
break;
}
}
}
bool nsGlobalWindowInner::MaybeCallDocumentFlushedResolvers(
bool aUntilExhaustion) {
MOZ_ASSERT(mDoc);
PresShell* presShell = mDoc->GetPresShell();
if (!presShell || aUntilExhaustion) {
CallDocumentFlushedResolvers(/* aUntilExhaustion = */ true);
return false;
}
if (presShell->NeedStyleFlush() || presShell->NeedLayoutFlush()) {
// By the time our observer fired, something has already invalidated
// style or layout - or perhaps we're still in the middle of a flush that
// was interrupted. In either case, we'll wait until the next refresh driver
// tick instead and try again.
return true;
}
CallDocumentFlushedResolvers(/* aUntilExhaustion = */ false);
return !mDocumentFlushedResolvers.IsEmpty();
}
already_AddRefed<nsWindowRoot> nsGlobalWindowInner::GetWindowRoot(
mozilla::ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetWindowRootOuter, (), aError, nullptr);
}
void nsGlobalWindowInner::SetCursor(const nsACString& aCursor,
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(SetCursorOuter, (aCursor, aError), aError, );
}
nsIBrowserDOMWindow* nsGlobalWindowInner::GetBrowserDOMWindow(
ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(GetBrowserDOMWindow, (), aError, nullptr);
}
void nsGlobalWindowInner::SetBrowserDOMWindow(
nsIBrowserDOMWindow* aBrowserWindow, ErrorResult& aError) {
FORWARD_TO_OUTER_OR_THROW(SetBrowserDOMWindowOuter, (aBrowserWindow),
aError, );
}
void nsGlobalWindowInner::NotifyDefaultButtonLoaded(Element& aDefaultButton,
ErrorResult& aError) {
// Don't snap to a disabled button.
nsCOMPtr<nsIDOMXULControlElement> xulControl = aDefaultButton.AsXULControl();
if (!xulControl) {
aError.Throw(NS_ERROR_FAILURE);
return;
}
bool disabled;
aError = xulControl->GetDisabled(&disabled);
if (aError.Failed() || disabled) {
return;
}
// Get the button rect in screen coordinates.
nsIFrame* frame = aDefaultButton.GetPrimaryFrame();
if (!frame) {
aError.Throw(NS_ERROR_FAILURE);
return;
}
LayoutDeviceIntRect buttonRect = LayoutDeviceIntRect::FromAppUnitsToNearest(
frame->GetScreenRectInAppUnits(),
frame->PresContext()->AppUnitsPerDevPixel());
// Get the widget rect in screen coordinates.
nsIWidget* widget = GetNearestWidget();
if (!widget) {
aError.Throw(NS_ERROR_FAILURE);
return;
}
LayoutDeviceIntRect widgetRect = widget->GetScreenBounds();
// Convert the buttonRect coordinates from screen to the widget.
buttonRect -= widgetRect.TopLeft();
nsresult rv = widget->OnDefaultButtonLoaded(buttonRect);
if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
aError.Throw(rv);
}
}
ChromeMessageBroadcaster* nsGlobalWindowInner::MessageManager() {
MOZ_ASSERT(IsChromeWindow());
if (!mChromeFields.mMessageManager) {
RefPtr<ChromeMessageBroadcaster> globalMM =
nsFrameMessageManager::GetGlobalMessageManager();
mChromeFields.mMessageManager = new ChromeMessageBroadcaster(globalMM);
}
return mChromeFields.mMessageManager;
}
ChromeMessageBroadcaster* nsGlobalWindowInner::GetGroupMessageManager(
const nsAString& aGroup) {
MOZ_ASSERT(IsChromeWindow());
return mChromeFields.mGroupMessageManagers
.LookupOrInsertWith(
aGroup,
[&] {
return MakeAndAddRef<ChromeMessageBroadcaster>(MessageManager());
})
.get();
}
void nsGlobalWindowInner::InitWasOffline() { mWasOffline = NS_IsOffline(); }
int16_t nsGlobalWindowInner::Orientation(CallerType aCallerType) {
// GetOrientationAngle() returns 0, 90, 180 or 270.
// window.orientation returns -90, 0, 90 or 180.
uint16_t screenAngle = Screen()->GetOrientationAngle();
if (nsIGlobalObject::ShouldResistFingerprinting(
aCallerType, RFPTarget::ScreenOrientation)) {
CSSIntSize size = mBrowsingContext->GetTopInnerSizeForRFP();
screenAngle = nsRFPService::ViewportSizeToAngle(size.width, size.height);
}
int16_t angle = AssertedCast<int16_t>(screenAngle);
return angle <= 180 ? angle : angle - 360;
}
already_AddRefed<Console> nsGlobalWindowInner::GetConsole(JSContext* aCx,
ErrorResult& aRv) {
if (!mConsole) {
mConsole = Console::Create(aCx, this, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
}
RefPtr<Console> console = mConsole;
return console.forget();
}
already_AddRefed<CookieStore> nsGlobalWindowInner::CookieStore() {
if (!mCookieStore) {
mCookieStore = CookieStore::Create(this);
}
return do_AddRef(mCookieStore);
}
bool nsGlobalWindowInner::IsSecureContext() const {
JS::Realm* realm = js::GetNonCCWObjectRealm(GetWrapperPreserveColor());
return JS::GetIsSecureContext(realm);
}
External* nsGlobalWindowInner::External() {
if (!mExternal) {
mExternal = new dom::External(ToSupports(this));
}
return mExternal;
}
void nsGlobalWindowInner::ClearDocumentDependentSlots(JSContext* aCx) {
// If JSAPI OOMs here, there is basically nothing we can do to recover safely.
if (!Window_Binding::ClearCachedDocumentValue(aCx, this) ||
!Window_Binding::ClearCachedPerformanceValue(aCx, this)) {
MOZ_CRASH("Unhandlable OOM while clearing document dependent slots.");
}
}
/* static */
JSObject* nsGlobalWindowInner::CreateNamedPropertiesObject(
JSContext* aCx, JS::Handle<JSObject*> aProto) {
return WindowNamedPropertiesHandler::Create(aCx, aProto);
}
void nsGlobalWindowInner::RedefineProperty(JSContext* aCx,
const char* aPropName,
JS::Handle<JS::Value> aValue,
ErrorResult& aError) {
JS::Rooted<JSObject*> thisObj(aCx, GetWrapperPreserveColor());
if (!thisObj) {
aError.Throw(NS_ERROR_UNEXPECTED);
return;
}
if (!JS_WrapObject(aCx, &thisObj) ||
!JS_DefineProperty(aCx, thisObj, aPropName, aValue, JSPROP_ENUMERATE)) {
aError.Throw(NS_ERROR_FAILURE);
}
}
void nsGlobalWindowInner::FireOnNewGlobalObject() {
// AutoEntryScript required to invoke debugger hook, which is a
// Gecko-specific concept at present.
AutoEntryScript aes(this, "nsGlobalWindowInner report new global");
JS::Rooted<JSObject*> global(aes.cx(), GetWrapper());
JS_FireOnNewGlobalObject(aes.cx(), global);
}
#if defined(_WINDOWS_) && !defined(MOZ_WRAPPED_WINDOWS_H)
# pragma message( \
"wrapper failure reason: " MOZ_WINDOWS_WRAPPER_DISABLED_REASON)
# error "Never include unwrapped windows.h in this file!"
#endif
already_AddRefed<Promise> nsGlobalWindowInner::CreateImageBitmap(
const ImageBitmapSource& aImage, const ImageBitmapOptions& aOptions,
ErrorResult& aRv) {
return ImageBitmap::Create(this, aImage, Nothing(), aOptions, aRv);
}
already_AddRefed<Promise> nsGlobalWindowInner::CreateImageBitmap(
const ImageBitmapSource& aImage, int32_t aSx, int32_t aSy, int32_t aSw,
int32_t aSh, const ImageBitmapOptions& aOptions, ErrorResult& aRv) {
return ImageBitmap::Create(
this, aImage, Some(gfx::IntRect(aSx, aSy, aSw, aSh)), aOptions, aRv);
}
// https://html.spec.whatwg.org/#structured-cloning
void nsGlobalWindowInner::StructuredClone(
JSContext* aCx, JS::Handle<JS::Value> aValue,
const StructuredSerializeOptions& aOptions,
JS::MutableHandle<JS::Value> aRetval, ErrorResult& aError) {
nsContentUtils::StructuredClone(aCx, this, aValue, aOptions, aRetval, aError);
}
nsresult nsGlobalWindowInner::Dispatch(
already_AddRefed<nsIRunnable>&& aRunnable) const {
MOZ_RELEASE_ASSERT(NS_IsMainThread());
return NS_DispatchToCurrentThread(std::move(aRunnable));
}
nsISerialEventTarget* nsGlobalWindowInner::SerialEventTarget() const {
MOZ_RELEASE_ASSERT(NS_IsMainThread());
return GetMainThreadSerialEventTarget();
}
Worklet* nsGlobalWindowInner::GetPaintWorklet(ErrorResult& aRv) {
if (!mPaintWorklet) {
nsIPrincipal* principal = GetPrincipal();
if (!principal) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
mPaintWorklet = PaintWorkletImpl::CreateWorklet(this, principal);
}
return mPaintWorklet;
}
void nsGlobalWindowInner::GetRegionalPrefsLocales(
nsTArray<nsString>& aLocales) {
MOZ_ASSERT(mozilla::intl::LocaleService::GetInstance());
AutoTArray<nsCString, 10> rpLocales;
mozilla::intl::LocaleService::GetInstance()->GetRegionalPrefsLocales(
rpLocales);
for (const auto& loc : rpLocales) {
aLocales.AppendElement(NS_ConvertUTF8toUTF16(loc));
}
}
void nsGlobalWindowInner::GetWebExposedLocales(nsTArray<nsString>& aLocales) {
MOZ_ASSERT(mozilla::intl::LocaleService::GetInstance());
AutoTArray<nsCString, 10> rpLocales;
mozilla::intl::LocaleService::GetInstance()->GetWebExposedLocales(rpLocales);
for (const auto& loc : rpLocales) {
aLocales.AppendElement(NS_ConvertUTF8toUTF16(loc));
}
}
IntlUtils* nsGlobalWindowInner::GetIntlUtils(ErrorResult& aError) {
if (!mIntlUtils) {
mIntlUtils = new IntlUtils(this);
}
return mIntlUtils;
}
void nsGlobalWindowInner::StoreSharedWorker(SharedWorker* aSharedWorker) {
MOZ_ASSERT(aSharedWorker);
MOZ_ASSERT(!mSharedWorkers.Contains(aSharedWorker));
mSharedWorkers.AppendElement(aSharedWorker);
}
void nsGlobalWindowInner::ForgetSharedWorker(SharedWorker* aSharedWorker) {
MOZ_ASSERT(aSharedWorker);
MOZ_ASSERT(mSharedWorkers.Contains(aSharedWorker));
mSharedWorkers.RemoveElement(aSharedWorker);
}
RefPtr<GenericPromise> nsGlobalWindowInner::StorageAccessPermissionChanged(
bool aGranted) {
// Invalidate cached StorageAllowed field so that calls to GetLocalStorage
// give us the updated localStorage object.
ClearStorageAllowedCache();
// If we're always partitioning non-cookie third party storage then
// there is no need to clear it when the user accepts requestStorageAccess.
if (StaticPrefs::
privacy_partition_always_partition_third_party_non_cookie_storage()) {
// Just reset the active cookie and storage principals
nsCOMPtr<nsICookieJarSettings> cjs;
if (mDoc) {
cjs = mDoc->CookieJarSettings();
}
StorageAccess storageAccess = StorageAllowedForWindow(this);
if (ShouldPartitionStorage(storageAccess) &&
StoragePartitioningEnabled(storageAccess, cjs)) {
if (mDoc) {
mDoc->ClearActiveCookieAndStoragePrincipals();
}
// When storage access is granted the content process needs to request the
// updated cookie list from the parent process. Otherwise the site won't
// have access to unpartitioned cookies via document.cookie without a
// reload.
if (aGranted) {
nsIChannel* channel = mDoc->GetChannel();
if (channel) {
// The promise resolves when the updated cookie list has been received
// from the parent.
return ContentChild::UpdateCookieStatus(channel);
}
}
}
}
PropagateStorageAccessPermissionGrantedToWorkers(*this);
// If we have a partitioned localStorage, it's time to replace it with a real
// one in order to receive notifications.
if (mLocalStorage) {
IgnoredErrorResult error;
GetLocalStorage(error);
if (NS_WARN_IF(error.Failed())) {
return MozPromise<bool, nsresult, true>::CreateAndReject(
error.StealNSResult(), __func__);
}
MOZ_ASSERT(mLocalStorage &&
mLocalStorage->Type() == Storage::eLocalStorage);
if (NextGenLocalStorageEnabled() && mListenerManager &&
mListenerManager->HasListenersFor(nsGkAtoms::onstorage)) {
auto object = static_cast<LSObject*>(mLocalStorage.get());
object->EnsureObserver();
}
}
// Reset the IndexedDB factory.
mIndexedDB = nullptr;
// Reset DOM Cache
mCacheStorage = nullptr;
// Reset the active cookie and storage principals
if (mDoc) {
mDoc->ClearActiveCookieAndStoragePrincipals();
if (mWindowGlobalChild) {
// XXX(farre): This is a bit backwards, but clearing the cookie
// principal might make us end up with a new effective storage
// principal on the child side than on the parent side, which
// means that we need to sync it. See bug 1705359.
mWindowGlobalChild->SetDocumentPrincipal(
mDoc->NodePrincipal(), mDoc->EffectiveStoragePrincipal());
}
}
// When storage access is granted the content process needs to request the
// updated cookie list from the parent process. Otherwise the site won't have
// access to unpartitioned cookies via document.cookie without a reload.
if (aGranted) {
nsIChannel* channel = mDoc->GetChannel();
if (channel) {
// The promise resolves when the updated cookie list has been received
// from the parent.
return ContentChild::UpdateCookieStatus(channel);
}
}
return MozPromise<bool, nsresult, true>::CreateAndResolve(true, __func__);
}
ContentMediaController* nsGlobalWindowInner::GetContentMediaController() {
if (mContentMediaController) {
return mContentMediaController;
}
if (!mBrowsingContext) {
return nullptr;
}
mContentMediaController = new ContentMediaController(mBrowsingContext->Id());
return mContentMediaController;
}
void nsGlobalWindowInner::SetScrollMarks(const nsTArray<uint32_t>& aScrollMarks,
bool aOnHScrollbar) {
mScrollMarks.Assign(aScrollMarks);
mScrollMarksOnHScrollbar = aOnHScrollbar;
// Mark the scrollbar for repainting.
if (mDoc) {
PresShell* presShell = mDoc->GetPresShell();
if (presShell) {
ScrollContainerFrame* sf = presShell->GetRootScrollContainerFrame();
if (sf) {
sf->InvalidateScrollbars();
}
}
}
}
/* static */
already_AddRefed<nsGlobalWindowInner> nsGlobalWindowInner::Create(
nsGlobalWindowOuter* aOuterWindow, bool aIsChrome,
WindowGlobalChild* aActor) {
RefPtr<nsGlobalWindowInner> window =
new nsGlobalWindowInner(aOuterWindow, aActor);
if (aIsChrome) {
window->mIsChrome = true;
window->mCleanMessageManager = true;
}
if (aActor) {
aActor->InitWindowGlobal(window);
}
window->InitWasOffline();
return window.forget();
}
JS::loader::ModuleLoaderBase* nsGlobalWindowInner::GetModuleLoader(
JSContext* aCx) {
Document* document = GetDocument();
if (!document) {
return nullptr;
}
ScriptLoader* loader = document->ScriptLoader();
if (!loader) {
return nullptr;
}
return loader->GetModuleLoader();
}
void nsGlobalWindowInner::SetCurrentPasteDataTransfer(
DataTransfer* aDataTransfer) {
MOZ_ASSERT_IF(aDataTransfer, aDataTransfer->GetEventMessage() == ePaste);
MOZ_ASSERT_IF(aDataTransfer, aDataTransfer->ClipboardType() ==
Some(nsIClipboard::kGlobalClipboard));
MOZ_ASSERT_IF(aDataTransfer, aDataTransfer->GetClipboardDataSnapshot());
mCurrentPasteDataTransfer = aDataTransfer;
}
DataTransfer* nsGlobalWindowInner::GetCurrentPasteDataTransfer() const {
return mCurrentPasteDataTransfer;
}
TrustedTypePolicyFactory* nsGlobalWindowInner::TrustedTypes() {
if (!mTrustedTypePolicyFactory) {
mTrustedTypePolicyFactory = MakeRefPtr<TrustedTypePolicyFactory>(this);
}
return mTrustedTypePolicyFactory;
}
void nsPIDOMWindowInner::MaybeSetHasPointerRawUpdateEventListeners() {
if (HasPointerRawUpdateEventListeners() || !IsSecureContext()) {
return;
}
mMayHavePointerRawUpdateEventListener = true;
if (BrowserChild* const browserChild = BrowserChild::GetFrom(this)) {
browserChild->OnPointerRawUpdateEventListenerAdded(this);
}
}
void nsPIDOMWindowInner::ClearHasPointerRawUpdateEventListeners() {
if (!HasPointerRawUpdateEventListeners()) {
return;
}
mMayHavePointerRawUpdateEventListener = false;
if (BrowserChild* const browserChild = BrowserChild::GetFrom(this)) {
browserChild->OnPointerRawUpdateEventListenerRemoved(this);
}
}
nsIURI* nsPIDOMWindowInner::GetDocumentURI() const {
return mDoc ? mDoc->GetDocumentURI() : mDocumentURI.get();
}
nsIURI* nsPIDOMWindowInner::GetDocBaseURI() const {
return mDoc ? mDoc->GetDocBaseURI() : mDocBaseURI.get();
}
mozilla::dom::WindowContext* nsPIDOMWindowInner::GetWindowContext() const {
return mWindowGlobalChild ? mWindowGlobalChild->WindowContext() : nullptr;
}
bool nsPIDOMWindowInner::RemoveFromBFCacheSync() {
if (Document* doc = GetExtantDoc()) {
return doc->RemoveFromBFCacheSync();
}
return false;
}
void nsPIDOMWindowInner::MaybeCreateDoc() {
// XXX: Forward to outer?
MOZ_ASSERT(!mDoc);
if (nsIDocShell* docShell = GetDocShell()) {
// Note that |document| here is the same thing as our mDoc, but we
// don't have to explicitly set the member variable because the docshell
// has already called SetNewDocument().
nsCOMPtr<Document> document = docShell->GetDocument();
Unused << document;
}
}
mozilla::dom::DocGroup* nsPIDOMWindowInner::GetDocGroup() const {
Document* doc = GetExtantDoc();
if (doc) {
return doc->GetDocGroup();
}
return nullptr;
}
mozilla::dom::BrowsingContextGroup*
nsPIDOMWindowInner::GetBrowsingContextGroup() const {
return mBrowsingContext ? mBrowsingContext->Group() : nullptr;
}
nsIGlobalObject* nsPIDOMWindowInner::AsGlobal() {
return nsGlobalWindowInner::Cast(this);
}
const nsIGlobalObject* nsPIDOMWindowInner::AsGlobal() const {
return nsGlobalWindowInner::Cast(this);
}
RefPtr<GenericPromise>
nsPIDOMWindowInner::SaveStorageAccessPermissionGranted() {
WindowContext* wc = GetWindowContext();
if (wc) {
Unused << wc->SetUsingStorageAccess(true);
}
return nsGlobalWindowInner::Cast(this)->StorageAccessPermissionChanged(true);
}
RefPtr<GenericPromise>
nsPIDOMWindowInner::SaveStorageAccessPermissionRevoked() {
WindowContext* wc = GetWindowContext();
if (wc) {
Unused << wc->SetUsingStorageAccess(false);
}
return nsGlobalWindowInner::Cast(this)->StorageAccessPermissionChanged(false);
}
bool nsPIDOMWindowInner::UsingStorageAccess() {
WindowContext* wc = GetWindowContext();
if (!wc) {
return false;
}
return wc->GetUsingStorageAccess();
}
WebIdentityHandler* nsPIDOMWindowInner::GetOrCreateWebIdentityHandler() {
if (mWebIdentityHandler) {
return mWebIdentityHandler;
}
mWebIdentityHandler = new WebIdentityHandler(this);
bool success = mWebIdentityHandler->MaybeCreateActor();
if (!success) {
mWebIdentityHandler = nullptr;
}
return mWebIdentityHandler;
}
CloseWatcherManager* nsPIDOMWindowInner::EnsureCloseWatcherManager() {
if (!mCloseWatcherManager) {
mCloseWatcherManager = new CloseWatcherManager();
}
return mCloseWatcherManager;
}
void nsPIDOMWindowInner::NotifyCloseWatcherAdded() {
MOZ_ASSERT(mCloseWatcherManager && !mCloseWatcherManager->IsEmpty());
if (WindowContext* top = TopWindowContext(*this)) {
Unused << top->SetHasActiveCloseWatcher(true);
}
}
void nsPIDOMWindowInner::NotifyCloseWatcherRemoved() {
MOZ_ASSERT(mCloseWatcherManager);
if (WindowContext* top = TopWindowContext(*this)) {
Unused << top->SetHasActiveCloseWatcher(!mCloseWatcherManager->IsEmpty());
}
}
nsPIDOMWindowInner::nsPIDOMWindowInner(nsPIDOMWindowOuter* aOuterWindow,
WindowGlobalChild* aActor)
: mOuterWindow(aOuterWindow), mWindowGlobalChild(aActor) {
MOZ_ASSERT(aOuterWindow);
mBrowsingContext = aOuterWindow->GetBrowsingContext();
if (mWindowGlobalChild) {
mWindowID = aActor->InnerWindowId();
MOZ_ASSERT(mWindowGlobalChild->BrowsingContext() == mBrowsingContext);
} else {
mWindowID = nsContentUtils::GenerateWindowId();
}
}
nsPIDOMWindowInner::~nsPIDOMWindowInner() = default;
#undef FORWARD_TO_OUTER
#undef FORWARD_TO_OUTER_OR_THROW
#undef FORWARD_TO_OUTER_VOID
|