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 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183
|
/* -*- 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/. */
/* a presentation of a document, part 2 */
#include "PresShell.h"
#include <algorithm>
#include "AnchorPositioningUtils.h"
#include "AutoProfilerStyleMarker.h"
#include "ChildIterator.h"
#include "gfxContext.h"
#include "gfxPlatform.h"
#include "gfxUserFontSet.h"
#include "gfxUtils.h"
#include "js/GCAPI.h"
#include "MobileViewportManager.h"
#include "mozilla/AccessibleCaretEventHub.h"
#include "mozilla/AnimationEventDispatcher.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/CaretAssociationHint.h"
#include "mozilla/ContentIterator.h"
#include "mozilla/css/ImageLoader.h"
#include "mozilla/DisplayPortUtils.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/BrowserBridgeChild.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/DocumentTimeline.h"
#include "mozilla/dom/DOMIntersectionObserver.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ElementBinding.h"
#include "mozilla/dom/ElementInlines.h"
#include "mozilla/dom/FontFaceSet.h"
#include "mozilla/dom/FragmentDirective.h"
#include "mozilla/dom/HTMLAreaElement.h"
#include "mozilla/dom/ImageTracker.h"
#include "mozilla/dom/LargestContentfulPaint.h"
#include "mozilla/dom/MouseEventBinding.h"
#include "mozilla/dom/Performance.h"
#include "mozilla/dom/PerformanceMainThread.h"
#include "mozilla/dom/PointerEventBinding.h"
#include "mozilla/dom/PointerEventHandler.h"
#include "mozilla/dom/PopupBlocker.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/ShadowIncludingTreeIterator.h"
#include "mozilla/dom/SVGAnimationElement.h"
#include "mozilla/dom/Touch.h"
#include "mozilla/dom/TouchEvent.h"
#include "mozilla/dom/UserActivation.h"
#include "mozilla/EditorBase.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventForwards.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/GeckoMVMContext.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/Types.h"
#include "mozilla/GlobalStyleSheetCache.h"
#include "mozilla/IMEStateManager.h"
#include "mozilla/InputTaskManager.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/layers/APZPublicUtils.h"
#include "mozilla/layers/CompositorBridgeChild.h"
#include "mozilla/layers/FocusTarget.h"
#include "mozilla/layers/InputAPZContext.h"
#include "mozilla/layers/ScrollingInteractionContext.h"
#include "mozilla/layers/WebRenderLayerManager.h"
#include "mozilla/layers/WebRenderUserData.h"
#include "mozilla/layout/ScrollAnchorContainer.h"
#include "mozilla/Likely.h"
#include "mozilla/Logging.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/PerfStats.h"
#include "mozilla/PointerLockManager.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShellInlines.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/ProfilerMarkers.h"
#include "mozilla/RangeUtils.h"
#include "mozilla/RefPtr.h"
#include "mozilla/RestyleManager.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/ScrollContainerFrame.h"
#include "mozilla/ScrollTimelineAnimationTracker.h"
#include "mozilla/ScrollTypes.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/ServoStyleSet.h"
#include "mozilla/SMILAnimationController.h"
#include "mozilla/Sprintf.h"
#include "mozilla/StaticAnalysisFunctions.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_font.h"
#include "mozilla/StaticPrefs_image.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_test.h"
#include "mozilla/StaticPrefs_toolkit.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
#include "mozilla/SVGFragmentIdentifier.h"
#include "mozilla/SVGObserverUtils.h"
#include "mozilla/glean/GfxMetrics.h"
#include "mozilla/glean/LayoutMetrics.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TextComposition.h"
#include "mozilla/TextEvents.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/TouchEvents.h"
#include "mozilla/Try.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/ViewportFrame.h"
#include "mozilla/ViewportUtils.h"
#include "nsAnimationManager.h"
#include "nsAutoLayoutPhase.h"
#include "nsCanvasFrame.h"
#include "nsCaret.h"
#include "nsClassHashtable.h"
#include "nsCOMArray.h"
#include "nsCOMPtr.h"
#include "nsContainerFrame.h"
#include "nsContentList.h"
#include "nsCRTGlue.h"
#include "nsCSSFrameConstructor.h"
#include "nsCSSRendering.h"
#include "nsDisplayList.h"
#include "nsDocShell.h" // for reflow observation
#include "nsDOMNavigationTiming.h"
#include "nsError.h"
#include "nsFlexContainerFrame.h"
#include "nsFocusManager.h"
#include "nsFrameSelection.h"
#include "nsGkAtoms.h"
#include "nsGlobalWindowOuter.h"
#include "nsHashKeys.h"
#include "nsIBaseWindow.h"
#include "nsIContent.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocShellTreeOwner.h"
#include "nsIDOMXULMenuListElement.h"
#include "nsIDOMXULMultSelectCntrlEl.h"
#include "nsIDOMXULSelectCntrlItemEl.h"
#include "nsIDragSession.h"
#include "nsIFrame.h"
#include "nsIFrameInlines.h"
#include "nsILayoutHistoryState.h"
#include "nsILineIterator.h" // for ScrollContentIntoView
#include "nsImageFrame.h"
#include "nsIObserverService.h"
#include "nsIReflowCallback.h"
#include "nsIScreen.h"
#include "nsIScreenManager.h"
#include "nsITimer.h"
#include "nsIURI.h"
#include "nsLayoutUtils.h"
#include "nsMenuPopupFrame.h"
#include "nsNameSpaceManager.h" // for Pref-related rule management (bugs 22963,20760,31816)
#include "nsNetUtil.h"
#include "nsNetUtil.h"
#include "nsPageSequenceFrame.h"
#include "nsPIDOMWindow.h"
#include "nsPlaceholderFrame.h"
#include "nsPresContext.h"
#include "nsQueryObject.h"
#include "nsRange.h"
#include "nsReadableUtils.h"
#include "nsRefreshDriver.h"
#include "nsRegion.h"
#include "nsStyleChangeList.h"
#include "nsStyleSheetService.h"
#include "nsSubDocumentFrame.h"
#include "nsTArray.h"
#include "nsThreadUtils.h"
#include "nsTransitionManager.h"
#include "nsTreeBodyFrame.h"
#include "nsTreeColumns.h"
#include "nsView.h"
#include "nsViewManager.h"
#include "nsViewportInfo.h"
#include "nsWindowSizes.h"
#include "nsXPCOM.h"
#include "nsXULElement.h"
#include "OverflowChangedTracker.h"
#include "PLDHashTable.h"
#include "PositionedEventTargeting.h"
#include "prenv.h"
#include "prinrval.h"
#include "ScrollSnap.h"
#include "StickyScrollContainer.h"
#include "Units.h"
#include "VisualViewport.h"
#include "XULTreeElement.h"
#include "ZoomConstraintsClient.h"
#ifdef XP_WIN
# include "winuser.h"
#endif
#ifdef MOZ_REFLOW_PERF
# include "nsFontMetrics.h"
#endif
#ifdef ACCESSIBILITY
# include "mozilla/a11y/DocAccessible.h"
# ifdef DEBUG
# include "mozilla/a11y/Logging.h"
# endif
#endif
// define the scalfactor of drag and drop images
// relative to the max screen height/width
#define RELATIVE_SCALEFACTOR 0.0925f
using namespace mozilla;
using namespace mozilla::css;
using namespace mozilla::dom;
using namespace mozilla::gfx;
using namespace mozilla::layers;
using namespace mozilla::gfx;
using namespace mozilla::layout;
using PaintFrameFlags = nsLayoutUtils::PaintFrameFlags;
typedef ScrollableLayerGuid::ViewID ViewID;
MOZ_RUNINIT PresShell::CapturingContentInfo PresShell::sCapturingContentInfo;
// RangePaintInfo is used to paint ranges to offscreen buffers
struct RangePaintInfo {
nsDisplayListBuilder mBuilder;
nsDisplayList mList;
// offset of builder's reference frame to the root frame
nsPoint mRootOffset;
// Resolution at which the items are normally painted. So if we're painting
// these items in a range separately from the "full display list", we may want
// to paint them at this resolution.
float mResolution = 1.0;
explicit RangePaintInfo(nsIFrame* aFrame)
: mBuilder(aFrame, nsDisplayListBuilderMode::Painting, false),
mList(&mBuilder) {
MOZ_COUNT_CTOR(RangePaintInfo);
mBuilder.BeginFrame();
}
~RangePaintInfo() {
mList.DeleteAll(&mBuilder);
mBuilder.EndFrame();
MOZ_COUNT_DTOR(RangePaintInfo);
}
};
#undef NOISY
// ----------------------------------------------------------------------
#ifdef DEBUG
// Set the environment variable GECKO_VERIFY_REFLOW_FLAGS to one or
// more of the following flags (comma separated) for handy debug
// output.
static VerifyReflowFlags gVerifyReflowFlags;
struct VerifyReflowFlagData {
const char* name;
VerifyReflowFlags bit;
};
static const VerifyReflowFlagData gFlags[] = {
// clang-format off
{ "verify", VerifyReflowFlags::On },
{ "reflow", VerifyReflowFlags::Noisy },
{ "all", VerifyReflowFlags::All },
{ "list-commands", VerifyReflowFlags::DumpCommands },
{ "noisy-commands", VerifyReflowFlags::NoisyCommands },
{ "really-noisy-commands", VerifyReflowFlags::ReallyNoisyCommands },
{ "resize", VerifyReflowFlags::DuringResizeReflow },
// clang-format on
};
# define NUM_VERIFY_REFLOW_FLAGS (sizeof(gFlags) / sizeof(gFlags[0]))
static void ShowVerifyReflowFlags() {
printf("Here are the available GECKO_VERIFY_REFLOW_FLAGS:\n");
const VerifyReflowFlagData* flag = gFlags;
const VerifyReflowFlagData* limit = gFlags + NUM_VERIFY_REFLOW_FLAGS;
while (flag < limit) {
printf(" %s\n", flag->name);
++flag;
}
printf("Note: GECKO_VERIFY_REFLOW_FLAGS is a comma separated list of flag\n");
printf("names (no whitespace)\n");
}
#endif
//========================================================================
//========================================================================
//========================================================================
#ifdef MOZ_REFLOW_PERF
class ReflowCountMgr;
static const char kGrandTotalsStr[] = "Grand Totals";
// Counting Class
class ReflowCounter {
public:
explicit ReflowCounter(ReflowCountMgr* aMgr = nullptr);
~ReflowCounter();
void ClearTotals();
void DisplayTotals(const char* aStr);
void DisplayDiffTotals(const char* aStr);
void DisplayHTMLTotals(const char* aStr);
void Add() { mTotal++; }
void Add(uint32_t aTotal) { mTotal += aTotal; }
void CalcDiffInTotals();
void SetTotalsCache();
void SetMgr(ReflowCountMgr* aMgr) { mMgr = aMgr; }
uint32_t GetTotal() { return mTotal; }
protected:
void DisplayTotals(uint32_t aTotal, const char* aTitle);
void DisplayHTMLTotals(uint32_t aTotal, const char* aTitle);
uint32_t mTotal;
uint32_t mCacheTotal;
ReflowCountMgr* mMgr; // weak reference (don't delete)
};
// Counting Class
class IndiReflowCounter {
public:
explicit IndiReflowCounter(ReflowCountMgr* aMgr = nullptr)
: mFrame(nullptr),
mCount(0),
mMgr(aMgr),
mCounter(aMgr),
mHasBeenOutput(false) {}
virtual ~IndiReflowCounter() = default;
nsAutoString mName;
nsIFrame* mFrame; // weak reference (don't delete)
int32_t mCount;
ReflowCountMgr* mMgr; // weak reference (don't delete)
ReflowCounter mCounter;
bool mHasBeenOutput;
};
//--------------------
// Manager Class
//--------------------
class ReflowCountMgr {
public:
ReflowCountMgr();
virtual ~ReflowCountMgr();
void ClearTotals();
void ClearGrandTotals();
void DisplayTotals(const char* aStr);
void DisplayHTMLTotals(const char* aStr);
void DisplayDiffsInTotals();
void Add(const char* aName, nsIFrame* aFrame);
ReflowCounter* LookUp(const char* aName);
void PaintCount(const char* aName, gfxContext* aRenderingContext,
nsPresContext* aPresContext, nsIFrame* aFrame,
const nsPoint& aOffset, uint32_t aColor);
FILE* GetOutFile() { return mFD; }
void SetPresContext(nsPresContext* aPresContext) {
mPresContext = aPresContext; // weak reference
}
void SetPresShell(PresShell* aPresShell) {
mPresShell = aPresShell; // weak reference
}
void SetDumpFrameCounts(bool aVal) { mDumpFrameCounts = aVal; }
void SetDumpFrameByFrameCounts(bool aVal) { mDumpFrameByFrameCounts = aVal; }
void SetPaintFrameCounts(bool aVal) { mPaintFrameByFrameCounts = aVal; }
bool IsPaintingFrameCounts() { return mPaintFrameByFrameCounts; }
protected:
void DisplayTotals(uint32_t aTotal, uint32_t* aDupArray, char* aTitle);
void DisplayHTMLTotals(uint32_t aTotal, uint32_t* aDupArray, char* aTitle);
void DoGrandTotals();
void DoIndiTotalsTree();
// HTML Output Methods
void DoGrandHTMLTotals();
nsClassHashtable<nsCharPtrHashKey, ReflowCounter> mCounts;
nsClassHashtable<nsCharPtrHashKey, IndiReflowCounter> mIndiFrameCounts;
FILE* mFD;
bool mDumpFrameCounts;
bool mDumpFrameByFrameCounts;
bool mPaintFrameByFrameCounts;
bool mCycledOnce;
// Root Frame for Individual Tracking
nsPresContext* mPresContext;
PresShell* mPresShell;
// ReflowCountMgr gReflowCountMgr;
};
#endif
//========================================================================
// comment out to hide caret
#define SHOW_CARET
// The upper bound on the amount of time to spend reflowing, in
// microseconds. When this bound is exceeded and reflow commands are
// still queued up, a reflow event is posted. The idea is for reflow
// to not hog the processor beyond the time specifed in
// gMaxRCProcessingTime. This data member is initialized from the
// layout.reflow.timeslice pref.
#define NS_MAX_REFLOW_TIME 1000000
static int32_t gMaxRCProcessingTime = -1;
struct nsCallbackEventRequest {
nsIReflowCallback* callback;
nsCallbackEventRequest* next;
};
// ----------------------------------------------------------------------------
class nsAutoCauseReflowNotifier {
public:
MOZ_CAN_RUN_SCRIPT explicit nsAutoCauseReflowNotifier(PresShell* aPresShell)
: mPresShell(aPresShell) {
mPresShell->WillCauseReflow();
}
MOZ_CAN_RUN_SCRIPT ~nsAutoCauseReflowNotifier() {
// This check should not be needed. Currently the only place that seem
// to need it is the code that deals with bug 337586.
if (!mPresShell->mHaveShutDown) {
RefPtr<PresShell> presShell(mPresShell);
presShell->DidCauseReflow();
} else {
nsContentUtils::RemoveScriptBlocker();
}
}
PresShell* mPresShell;
};
class MOZ_STACK_CLASS nsPresShellEventCB : public EventDispatchingCallback {
public:
explicit nsPresShellEventCB(PresShell* aPresShell) : mPresShell(aPresShell) {}
MOZ_CAN_RUN_SCRIPT
virtual void HandleEvent(EventChainPostVisitor& aVisitor) override {
if (aVisitor.mPresContext && aVisitor.mEvent->mClass != eBasicEventClass) {
if (aVisitor.mEvent->mMessage == eMouseDown ||
aVisitor.mEvent->mMessage == eMouseUp) {
// Mouse-up and mouse-down events call nsIFrame::HandlePress/Release
// which call GetContentOffsetsFromPoint which requires up-to-date
// layout. Bring layout up-to-date now so that GetCurrentEventFrame()
// below will return a real frame and we don't have to worry about
// destroying it by flushing later.
MOZ_KnownLive(mPresShell)->FlushPendingNotifications(FlushType::Layout);
} else if (aVisitor.mEvent->mMessage == eWheel &&
aVisitor.mEventStatus != nsEventStatus_eConsumeNoDefault) {
nsIFrame* frame = mPresShell->GetCurrentEventFrame();
if (frame) {
// chrome (including addons) should be able to know if content
// handles both D3E "wheel" event and legacy mouse scroll events.
// We should dispatch legacy mouse events before dispatching the
// "wheel" event into system group.
RefPtr<EventStateManager> esm =
aVisitor.mPresContext->EventStateManager();
esm->DispatchLegacyMouseScrollEvents(
frame, aVisitor.mEvent->AsWheelEvent(), &aVisitor.mEventStatus);
}
}
nsIFrame* frame = mPresShell->GetCurrentEventFrame();
if (!frame && (aVisitor.mEvent->mMessage == eMouseUp ||
aVisitor.mEvent->mMessage == eTouchEnd)) {
// Redirect BUTTON_UP and TOUCH_END events to the root frame to ensure
// that capturing is released.
frame = mPresShell->GetRootFrame();
}
if (frame) {
frame->HandleEvent(aVisitor.mPresContext, aVisitor.mEvent->AsGUIEvent(),
&aVisitor.mEventStatus);
}
}
}
RefPtr<PresShell> mPresShell;
};
class nsBeforeFirstPaintDispatcher : public Runnable {
public:
explicit nsBeforeFirstPaintDispatcher(Document* aDocument)
: mozilla::Runnable("nsBeforeFirstPaintDispatcher"),
mDocument(aDocument) {}
// Fires the "before-first-paint" event so that interested parties (right now,
// the mobile browser) are aware of it.
NS_IMETHOD Run() override {
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
observerService->NotifyObservers(ToSupports(mDocument),
"before-first-paint", nullptr);
}
return NS_OK;
}
private:
RefPtr<Document> mDocument;
};
// This is a helper class to track whether the targeted frame is destroyed after
// dispatching pointer events. In that case, we need the original targeted
// content so that we can dispatch the mouse events to it.
class MOZ_RAII AutoPointerEventTargetUpdater final {
public:
AutoPointerEventTargetUpdater(PresShell* aShell, WidgetEvent* aEvent,
nsIFrame* aFrame, nsIContent* aTargetContent,
nsIContent** aOutTargetContent) {
MOZ_ASSERT(aEvent);
if (!aOutTargetContent || aEvent->mClass != ePointerEventClass) {
// Make the destructor happy.
mOutTargetContent = nullptr;
return;
}
MOZ_ASSERT(aShell);
MOZ_ASSERT_IF(aFrame && aFrame->GetContent(),
aShell->GetDocument() == aFrame->GetContent()->OwnerDoc());
mShell = aShell;
mWeakFrame = aFrame;
mOutTargetContent = aOutTargetContent;
mFromTouch = aEvent->AsPointerEvent()->mFromTouchEvent;
// Touch event target may have no frame, e.g., removed from the DOM
MOZ_ASSERT_IF(!mFromTouch, aFrame);
// The frame may be a text frame, but the event target should be an element
// node. Therefore, refer aTargetContent first, then, if we have only a
// frame, we should use inclusive ancestor of the content.
mOriginalPointerEventTarget =
aShell->mPointerEventTarget = [&]() -> nsIContent* {
nsIContent* const target =
aTargetContent ? aTargetContent
: (aFrame ? aFrame->GetContent() : nullptr);
if (MOZ_UNLIKELY(!target)) {
return nullptr;
}
if (target->IsElement() ||
!IsForbiddenDispatchingToNonElementContent(aEvent->mMessage)) {
return target;
}
return target->GetInclusiveFlattenedTreeAncestorElement();
}();
}
~AutoPointerEventTargetUpdater() {
if (!mOutTargetContent || !mShell || mWeakFrame.IsAlive()) {
return;
}
if (mFromTouch) {
// If the source event is a touch event, the touch event target should
// always be same target as preceding ePointerDown. Therefore, we should
// always set it back to the original event target.
mOriginalPointerEventTarget.swap(*mOutTargetContent);
} else {
// If the source event is not a touch event (must be a mouse event in
// this case), the event should be fired on the closest inclusive ancestor
// of the pointer event target which is still connected. The mutations
// are tracked by PresShell::ContentRemoved. Therefore, we should set it.
mShell->mPointerEventTarget.swap(*mOutTargetContent);
}
}
private:
RefPtr<PresShell> mShell;
nsCOMPtr<nsIContent> mOriginalPointerEventTarget;
AutoWeakFrame mWeakFrame;
nsIContent** mOutTargetContent;
bool mFromTouch = false;
};
bool PresShell::sDisableNonTestMouseEvents = false;
LazyLogModule PresShell::gLog("PresShell");
TimeStamp PresShell::EventHandler::sLastInputCreated;
TimeStamp PresShell::EventHandler::sLastInputProcessed;
StaticRefPtr<Element> PresShell::EventHandler::sLastKeyDownEventTargetElement;
bool PresShell::sProcessInteractable = false;
Modifiers PresShell::sCurrentModifiers = MODIFIER_NONE;
static bool gVerifyReflowEnabled;
bool PresShell::GetVerifyReflowEnable() {
#ifdef DEBUG
static bool firstTime = true;
if (firstTime) {
firstTime = false;
char* flags = PR_GetEnv("GECKO_VERIFY_REFLOW_FLAGS");
if (flags) {
bool error = false;
for (;;) {
char* comma = strchr(flags, ',');
if (comma) *comma = '\0';
bool found = false;
const VerifyReflowFlagData* flag = gFlags;
const VerifyReflowFlagData* limit = gFlags + NUM_VERIFY_REFLOW_FLAGS;
while (flag < limit) {
if (nsCRT::strcasecmp(flag->name, flags) == 0) {
gVerifyReflowFlags |= flag->bit;
found = true;
break;
}
++flag;
}
if (!found) error = true;
if (!comma) break;
*comma = ',';
flags = comma + 1;
}
if (error) ShowVerifyReflowFlags();
}
if (VerifyReflowFlags::On & gVerifyReflowFlags) {
gVerifyReflowEnabled = true;
printf("Note: verifyreflow is enabled");
if (VerifyReflowFlags::Noisy & gVerifyReflowFlags) {
printf(" (noisy)");
}
if (VerifyReflowFlags::All & gVerifyReflowFlags) {
printf(" (all)");
}
if (VerifyReflowFlags::DumpCommands & gVerifyReflowFlags) {
printf(" (show reflow commands)");
}
if (VerifyReflowFlags::NoisyCommands & gVerifyReflowFlags) {
printf(" (noisy reflow commands)");
if (VerifyReflowFlags::ReallyNoisyCommands & gVerifyReflowFlags) {
printf(" (REALLY noisy reflow commands)");
}
}
printf("\n");
}
}
#endif
return gVerifyReflowEnabled;
}
void PresShell::SetVerifyReflowEnable(bool aEnabled) {
gVerifyReflowEnabled = aEnabled;
}
void PresShell::AddAutoWeakFrame(AutoWeakFrame* aWeakFrame) {
if (aWeakFrame->GetFrame()) {
aWeakFrame->GetFrame()->AddStateBits(NS_FRAME_EXTERNAL_REFERENCE);
}
aWeakFrame->SetPreviousWeakFrame(mAutoWeakFrames);
mAutoWeakFrames = aWeakFrame;
}
void PresShell::AddWeakFrame(WeakFrame* aWeakFrame) {
if (aWeakFrame->GetFrame()) {
aWeakFrame->GetFrame()->AddStateBits(NS_FRAME_EXTERNAL_REFERENCE);
}
MOZ_ASSERT(!mWeakFrames.Contains(aWeakFrame));
mWeakFrames.Insert(aWeakFrame);
}
void PresShell::RemoveAutoWeakFrame(AutoWeakFrame* aWeakFrame) {
if (mAutoWeakFrames == aWeakFrame) {
mAutoWeakFrames = aWeakFrame->GetPreviousWeakFrame();
return;
}
AutoWeakFrame* nextWeak = mAutoWeakFrames;
while (nextWeak && nextWeak->GetPreviousWeakFrame() != aWeakFrame) {
nextWeak = nextWeak->GetPreviousWeakFrame();
}
if (nextWeak) {
nextWeak->SetPreviousWeakFrame(aWeakFrame->GetPreviousWeakFrame());
}
}
void PresShell::RemoveWeakFrame(WeakFrame* aWeakFrame) {
MOZ_ASSERT(mWeakFrames.Contains(aWeakFrame));
mWeakFrames.Remove(aWeakFrame);
}
already_AddRefed<nsFrameSelection> PresShell::FrameSelection() {
RefPtr<nsFrameSelection> ret = mSelection;
return ret.forget();
}
//----------------------------------------------------------------------
static uint32_t sNextPresShellId = 0;
/* static */
bool PresShell::AccessibleCaretEnabled(nsIDocShell* aDocShell) {
// If the pref forces it on, then enable it.
if (StaticPrefs::layout_accessiblecaret_enabled()) {
return true;
}
// If the touch pref is on, and touch events are enabled (this depends
// on the specific device running), then enable it.
if (StaticPrefs::layout_accessiblecaret_enabled_on_touch() &&
dom::TouchEvent::PrefEnabled(aDocShell)) {
return true;
}
// Otherwise, disabled.
return false;
}
PresShell::PresShell(Document* aDocument)
: mDocument(aDocument),
mViewManager(nullptr),
mLastSelectionForToString(nullptr),
mAutoWeakFrames(nullptr),
#ifdef ACCESSIBILITY
mDocAccessible(nullptr),
#endif // ACCESSIBILITY
mLastResolutionChangeOrigin(ResolutionChangeOrigin::Apz),
mPaintCount(0),
mAPZFocusSequenceNumber(0),
mActiveSuppressDisplayport(0),
mPresShellId(++sNextPresShellId),
mFontSizeInflationEmPerLine(0),
mFontSizeInflationMinTwips(0),
mFontSizeInflationLineThreshold(0),
mSelectionFlags(nsISelectionDisplay::DISPLAY_TEXT |
nsISelectionDisplay::DISPLAY_IMAGES),
mChangeNestCount(0),
mRenderingStateFlags(RenderingStateFlags::None),
mCaretEnabled(false),
mNeedLayoutFlush(true),
mNeedStyleFlush(true),
mNeedThrottledAnimationFlush(true),
mVisualViewportSizeSet(false),
mDidInitialize(false),
mIsDestroying(false),
mIsReflowing(false),
mIsObservingDocument(false),
mForbiddenToFlush(false),
mIsDocumentGone(false),
mHaveShutDown(false),
mPaintingSuppressed(false),
mShouldUnsuppressPainting(false),
mIgnoreFrameDestruction(false),
mIsActive(true),
mFrozen(false),
mIsFirstPaint(true),
mObservesMutationsForPrint(false),
mWasLastReflowInterrupted(false),
mResizeEventPending(false),
mVisualViewportResizeEventPending(false),
mFontSizeInflationForceEnabled(false),
mFontSizeInflationDisabledInMasterProcess(false),
mFontSizeInflationEnabled(false),
mIsNeverPainting(false),
mResolutionUpdated(false),
mResolutionUpdatedByApz(false),
mUnderHiddenEmbedderElement(false),
mDocumentLoading(false),
mNoDelayedMouseEvents(false),
mNoDelayedKeyEvents(false),
mApproximateFrameVisibilityVisited(false),
mIsLastChromeOnlyEscapeKeyConsumed(false),
mHasReceivedPaintMessage(false),
mIsLastKeyDownCanceled(false),
mHasHandledUserInput(false),
mForceDispatchKeyPressEventsForNonPrintableKeys(false),
mForceUseLegacyKeyCodeAndCharCodeValues(false),
mInitializedWithKeyPressEventDispatchingBlacklist(false),
mHasTriedFastUnsuppress(false),
mProcessingReflowCommands(false),
mPendingDidDoReflow(false) {
MOZ_LOG(gLog, LogLevel::Debug, ("PresShell::PresShell this=%p", this));
MOZ_ASSERT(aDocument);
#ifdef MOZ_REFLOW_PERF
mReflowCountMgr = MakeUnique<ReflowCountMgr>();
mReflowCountMgr->SetPresContext(mPresContext);
mReflowCountMgr->SetPresShell(this);
#endif
mLastOSWake = mLoadBegin = TimeStamp::Now();
}
NS_INTERFACE_TABLE_HEAD(PresShell)
NS_INTERFACE_TABLE_BEGIN
// In most cases, PresShell should be treated as concrete class, but need to
// QI for weak reference. Therefore, the case needed by do_QueryReferent()
// should be tested first.
NS_INTERFACE_TABLE_ENTRY(PresShell, PresShell)
NS_INTERFACE_TABLE_ENTRY(PresShell, nsIDocumentObserver)
NS_INTERFACE_TABLE_ENTRY(PresShell, nsISelectionController)
NS_INTERFACE_TABLE_ENTRY(PresShell, nsISelectionDisplay)
NS_INTERFACE_TABLE_ENTRY(PresShell, nsIObserver)
NS_INTERFACE_TABLE_ENTRY(PresShell, nsISupportsWeakReference)
NS_INTERFACE_TABLE_ENTRY(PresShell, nsIMutationObserver)
NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(PresShell, nsISupports, nsIObserver)
NS_INTERFACE_TABLE_END
NS_INTERFACE_TABLE_TO_MAP_SEGUE
NS_INTERFACE_MAP_END
NS_IMPL_ADDREF(PresShell)
NS_IMPL_RELEASE(PresShell)
PresShell::~PresShell() {
MOZ_RELEASE_ASSERT(!mForbiddenToFlush,
"Flag should only be set temporarily, while doing things "
"that shouldn't cause destruction");
MOZ_LOG(gLog, LogLevel::Debug, ("PresShell::~PresShell this=%p", this));
if (!mHaveShutDown) {
MOZ_ASSERT_UNREACHABLE("Someone did not call PresShell::Destroy()");
Destroy();
}
NS_ASSERTION(mCurrentEventTargetStack.IsEmpty(),
"Huh, event content left on the stack in pres shell dtor!");
NS_ASSERTION(mFirstCallbackEventRequest == nullptr &&
mLastCallbackEventRequest == nullptr,
"post-reflow queues not empty. This means we're leaking");
MOZ_ASSERT(!mAllocatedPointers || mAllocatedPointers->IsEmpty(),
"Some pres arena objects were not freed");
mFrameConstructor = nullptr;
}
/**
* Initialize the presentation shell. Create view manager and style
* manager.
* Note this can't be merged into our constructor because caret initialization
* calls AddRef() on us.
*/
void PresShell::Init(nsPresContext* aPresContext, nsViewManager* aViewManager) {
MOZ_ASSERT(mDocument);
MOZ_ASSERT(aPresContext);
MOZ_ASSERT(aViewManager);
MOZ_ASSERT(!mViewManager, "already initialized");
mViewManager = aViewManager;
// mDocument is now set. It might have a display document whose "need layout/
// style" flush flags are not set, but ours will be set. To keep these
// consistent, call the flag setting functions to propagate those flags up
// to the display document.
SetNeedLayoutFlush();
SetNeedStyleFlush();
// Create our frame constructor.
mFrameConstructor = MakeUnique<nsCSSFrameConstructor>(mDocument, this);
// The document viewer owns both view manager and pres shell.
mViewManager->SetPresShell(this);
// Bind the context to the presentation shell.
// FYI: We cannot initialize mPresContext in the constructor because we
// cannot call AttachPresShell() in it and once we initialize
// mPresContext, other objects may refer refresh driver or restyle
// manager via mPresContext and that causes hitting MOZ_ASSERT in some
// places. Therefore, we should initialize mPresContext here with
// const_cast hack since we want to guarantee that mPresContext lives
// as long as the PresShell.
const_cast<RefPtr<nsPresContext>&>(mPresContext) = aPresContext;
mPresContext->AttachPresShell(this);
mPresContext->InitFontCache();
// FIXME(emilio, bug 1544185): Some Android code somehow depends on the shell
// being eagerly registered as a style flush observer. This shouldn't be
// needed otherwise.
EnsureStyleFlush();
const bool accessibleCaretEnabled =
AccessibleCaretEnabled(mDocument->GetDocShell());
if (accessibleCaretEnabled) {
// Need to happen before nsFrameSelection has been set up.
mAccessibleCaretEventHub = new AccessibleCaretEventHub(this);
mAccessibleCaretEventHub->Init();
}
mSelection = new nsFrameSelection(this, accessibleCaretEnabled);
// Important: this has to happen after the selection has been set up
#ifdef SHOW_CARET
// make the caret
mCaret = new nsCaret();
mCaret->Init(this);
mOriginalCaret = mCaret;
// SetCaretEnabled(true); // make it show in browser windows
#endif
// set up selection to be displayed in document
// Don't enable selection for print media
nsPresContext::nsPresContextType type = mPresContext->Type();
if (type != nsPresContext::eContext_PrintPreview &&
type != nsPresContext::eContext_Print) {
SetDisplaySelection(nsISelectionController::SELECTION_DISABLED);
}
if (gMaxRCProcessingTime == -1) {
gMaxRCProcessingTime =
Preferences::GetInt("layout.reflow.timeslice", NS_MAX_REFLOW_TIME);
}
if (nsStyleSheetService* ss = nsStyleSheetService::GetInstance()) {
ss->RegisterPresShell(this);
}
{
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
os->AddObserver(this, "memory-pressure", false);
os->AddObserver(this, NS_WIDGET_WAKE_OBSERVER_TOPIC, false);
if (XRE_IsParentProcess() && !sProcessInteractable) {
os->AddObserver(this, "sessionstore-one-or-no-tab-restored", false);
}
os->AddObserver(this, "font-info-updated", false);
os->AddObserver(this, "internal-look-and-feel-changed", false);
}
}
#ifdef MOZ_REFLOW_PERF
if (mReflowCountMgr) {
bool paintFrameCounts =
Preferences::GetBool("layout.reflow.showframecounts");
bool dumpFrameCounts =
Preferences::GetBool("layout.reflow.dumpframecounts");
bool dumpFrameByFrameCounts =
Preferences::GetBool("layout.reflow.dumpframebyframecounts");
mReflowCountMgr->SetDumpFrameCounts(dumpFrameCounts);
mReflowCountMgr->SetDumpFrameByFrameCounts(dumpFrameByFrameCounts);
mReflowCountMgr->SetPaintFrameCounts(paintFrameCounts);
}
#endif
for (DocumentTimeline* timelines : mDocument->Timelines()) {
timelines->UpdateLastRefreshDriverTime();
}
// Get our activeness from the docShell.
ActivenessMaybeChanged();
// Setup our font inflation preferences.
mFontSizeInflationEmPerLine = StaticPrefs::font_size_inflation_emPerLine();
mFontSizeInflationMinTwips = StaticPrefs::font_size_inflation_minTwips();
mFontSizeInflationLineThreshold =
StaticPrefs::font_size_inflation_lineThreshold();
mFontSizeInflationForceEnabled =
StaticPrefs::font_size_inflation_forceEnabled();
mFontSizeInflationDisabledInMasterProcess =
StaticPrefs::font_size_inflation_disabledInMasterProcess();
// We'll compute the font size inflation state in Initialize(), when we know
// the document type.
mTouchManager.Init(this, mDocument);
if (mPresContext->IsRootContentDocumentCrossProcess()) {
mZoomConstraintsClient = new ZoomConstraintsClient();
mZoomConstraintsClient->Init(this, mDocument);
// We call this to create mMobileViewportManager, if it is needed.
MaybeRecreateMobileViewportManager(false);
}
if (nsCOMPtr<nsIDocShell> docShell = mPresContext->GetDocShell()) {
if (BrowsingContext* bc = docShell->GetBrowsingContext()) {
mUnderHiddenEmbedderElement = bc->IsUnderHiddenEmbedderElement();
}
}
}
enum TextPerfLogType { eLog_reflow, eLog_loaddone, eLog_totals };
static void LogTextPerfStats(gfxTextPerfMetrics* aTextPerf,
PresShell* aPresShell,
const gfxTextPerfMetrics::TextCounts& aCounts,
float aTime, TextPerfLogType aLogType,
const char* aURL) {
LogModule* tpLog = gfxPlatform::GetLog(eGfxLog_textperf);
// ignore XUL contexts unless at debug level
mozilla::LogLevel logLevel = LogLevel::Warning;
if (aCounts.numContentTextRuns == 0) {
logLevel = LogLevel::Debug;
}
if (!MOZ_LOG_TEST(tpLog, logLevel)) {
return;
}
char prefix[256];
switch (aLogType) {
case eLog_reflow:
SprintfLiteral(prefix, "(textperf-reflow) %p time-ms: %7.0f", aPresShell,
aTime);
break;
case eLog_loaddone:
SprintfLiteral(prefix, "(textperf-loaddone) %p time-ms: %7.0f",
aPresShell, aTime);
break;
default:
MOZ_ASSERT(aLogType == eLog_totals, "unknown textperf log type");
SprintfLiteral(prefix, "(textperf-totals) %p", aPresShell);
}
double hitRatio = 0.0;
uint32_t lookups = aCounts.wordCacheHit + aCounts.wordCacheMiss;
if (lookups) {
hitRatio = double(aCounts.wordCacheHit) / double(lookups);
}
if (aLogType == eLog_loaddone) {
MOZ_LOG(
tpLog, logLevel,
("%s reflow: %d chars: %d "
"[%s] "
"content-textruns: %d chrome-textruns: %d "
"max-textrun-len: %d "
"word-cache-lookups: %d word-cache-hit-ratio: %4.3f "
"word-cache-space: %d word-cache-long: %d "
"pref-fallbacks: %d system-fallbacks: %d "
"textruns-const: %d textruns-destr: %d "
"generic-lookups: %d "
"cumulative-textruns-destr: %d\n",
prefix, aTextPerf->reflowCount, aCounts.numChars, (aURL ? aURL : ""),
aCounts.numContentTextRuns, aCounts.numChromeTextRuns,
aCounts.maxTextRunLen, lookups, hitRatio, aCounts.wordCacheSpaceRules,
aCounts.wordCacheLong, aCounts.fallbackPrefs, aCounts.fallbackSystem,
aCounts.textrunConst, aCounts.textrunDestr, aCounts.genericLookups,
aTextPerf->cumulative.textrunDestr));
} else {
MOZ_LOG(
tpLog, logLevel,
("%s reflow: %d chars: %d "
"content-textruns: %d chrome-textruns: %d "
"max-textrun-len: %d "
"word-cache-lookups: %d word-cache-hit-ratio: %4.3f "
"word-cache-space: %d word-cache-long: %d "
"pref-fallbacks: %d system-fallbacks: %d "
"textruns-const: %d textruns-destr: %d "
"generic-lookups: %d "
"cumulative-textruns-destr: %d\n",
prefix, aTextPerf->reflowCount, aCounts.numChars,
aCounts.numContentTextRuns, aCounts.numChromeTextRuns,
aCounts.maxTextRunLen, lookups, hitRatio, aCounts.wordCacheSpaceRules,
aCounts.wordCacheLong, aCounts.fallbackPrefs, aCounts.fallbackSystem,
aCounts.textrunConst, aCounts.textrunDestr, aCounts.genericLookups,
aTextPerf->cumulative.textrunDestr));
}
}
bool PresShell::InRDMPane() {
if (Document* doc = GetDocument()) {
if (BrowsingContext* bc = doc->GetBrowsingContext()) {
return bc->InRDMPane();
}
}
return false;
}
#if defined(MOZ_WIDGET_ANDROID)
void PresShell::MaybeNotifyShowDynamicToolbar() {
const DynamicToolbarState dynToolbarState = GetDynamicToolbarState();
if ((dynToolbarState == DynamicToolbarState::Collapsed ||
dynToolbarState == DynamicToolbarState::InTransition)) {
MOZ_ASSERT(mPresContext &&
mPresContext->IsRootContentDocumentCrossProcess());
if (BrowserChild* browserChild = BrowserChild::GetFrom(this)) {
browserChild->SendShowDynamicToolbar();
}
}
}
#endif // defined(MOZ_WIDGET_ANDROID)
void PresShell::Destroy() {
// Do not add code before this line please!
if (mHaveShutDown) {
return;
}
NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(),
"destroy called on presshell while scripts not blocked");
[[maybe_unused]] nsIURI* uri = mDocument->GetDocumentURI();
AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING_RELEVANT_FOR_JS(
"Layout tree destruction", LAYOUT_Destroy,
uri ? uri->GetSpecOrDefault() : "N/A"_ns);
// Try to determine if the page is the user had a meaningful opportunity to
// zoom this page. This is not 100% accurate but should be "good enough" for
// telemetry purposes.
auto isUserZoomablePage = [&]() -> bool {
if (mIsFirstPaint) {
// Page was never painted, so it wasn't zoomable by the user. We get a
// handful of these "transient" presShells.
return false;
}
if (!mPresContext->IsRootContentDocumentCrossProcess()) {
// Not a root content document, so APZ doesn't support zooming it.
return false;
}
if (InRDMPane()) {
// Responsive design mode is a special case that we want to ignore here.
return false;
}
if (mDocument && mDocument->IsInitialDocument()) {
// Ignore initial about:blank page loads
return false;
}
if (XRE_IsContentProcess() &&
IsExtensionRemoteType(ContentChild::GetSingleton()->GetRemoteType())) {
// Also omit presShells from the extension process because they sometimes
// can't be zoomed by the user.
return false;
}
// Otherwise assume the page is user-zoomable.
return true;
};
if (isUserZoomablePage()) {
glean::apz_zoom::activity
.EnumGet(static_cast<glean::apz_zoom::ActivityLabel>(
IsResolutionUpdatedByApz()))
.Add();
}
// dump out cumulative text perf metrics
gfxTextPerfMetrics* tp;
if (mPresContext && (tp = mPresContext->GetTextPerfMetrics())) {
tp->Accumulate();
if (tp->cumulative.numChars > 0) {
LogTextPerfStats(tp, this, tp->cumulative, 0.0, eLog_totals, nullptr);
}
}
if (mPresContext) {
if (gfxUserFontSet* fs = mPresContext->GetUserFontSet()) {
uint32_t fontCount;
uint64_t fontSize;
fs->GetLoadStatistics(fontCount, fontSize);
glean::webfont::per_page.Add(fontCount);
glean::webfont::size_per_page.Accumulate(uint32_t(fontSize / 1024));
} else {
glean::webfont::per_page.Add(0);
glean::webfont::size_per_page.Accumulate(0);
}
}
#ifdef MOZ_REFLOW_PERF
DumpReflows();
mReflowCountMgr = nullptr;
#endif
if (mZoomConstraintsClient) {
mZoomConstraintsClient->Destroy();
mZoomConstraintsClient = nullptr;
}
if (mMobileViewportManager) {
mMobileViewportManager->Destroy();
mMobileViewportManager = nullptr;
mMVMContext = nullptr;
}
#ifdef ACCESSIBILITY
if (mDocAccessible) {
# ifdef DEBUG
if (a11y::logging::IsEnabled(a11y::logging::eDocDestroy))
a11y::logging::DocDestroy("presshell destroyed", mDocument);
# endif
mDocAccessible->Shutdown();
mDocAccessible = nullptr;
}
#endif // ACCESSIBILITY
MaybeReleaseCapturingContent();
EventHandler::OnPresShellDestroy(mDocument);
if (mContentToScrollTo) {
mContentToScrollTo->RemoveProperty(nsGkAtoms::scrolling);
mContentToScrollTo = nullptr;
}
if (mPresContext) {
// We need to notify the destroying the nsPresContext to ESM for
// suppressing to use from ESM.
mPresContext->EventStateManager()->NotifyDestroyPresContext(mPresContext);
}
if (nsStyleSheetService* ss = nsStyleSheetService::GetInstance()) {
ss->UnregisterPresShell(this);
}
{
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
os->RemoveObserver(this, "memory-pressure");
os->RemoveObserver(this, NS_WIDGET_WAKE_OBSERVER_TOPIC);
if (XRE_IsParentProcess()) {
os->RemoveObserver(this, "sessionstore-one-or-no-tab-restored");
}
os->RemoveObserver(this, "font-info-updated");
os->RemoveObserver(this, "internal-look-and-feel-changed");
}
}
// If our paint suppression timer is still active, kill it.
CancelPaintSuppressionTimer();
mSynthMouseMoveEvent.Revoke();
mUpdateApproximateFrameVisibilityEvent.Revoke();
ClearApproximatelyVisibleFramesList(Some(OnNonvisible::DiscardImages));
if (mOriginalCaret) {
mOriginalCaret->Terminate();
}
if (mCaret && mCaret != mOriginalCaret) {
mCaret->Terminate();
}
mCaret = mOriginalCaret = nullptr;
mFocusedFrameSelection = nullptr;
if (mSelection) {
RefPtr<nsFrameSelection> frameSelection = mSelection;
frameSelection->DisconnectFromPresShell();
}
mIsDestroying = true;
// We can't release all the event content in
// mCurrentEventContentStack here since there might be code on the
// stack that will release the event content too. Double release
// bad!
// The frames will be torn down, so remove them from the current
// event frame stack (since they'd be dangling references if we'd
// leave them in) and null out the mCurrentEventFrame pointer as
// well.
mCurrentEventTarget.ClearFrame();
for (EventTargetInfo& eventTargetInfo : mCurrentEventTargetStack) {
eventTargetInfo.ClearFrame();
}
mFramesToDirty.Clear();
mPendingScrollAnchorSelection.Clear();
mPendingScrollAnchorAdjustment.Clear();
mPendingScrollResnap.Clear();
if (mViewManager) {
// Clear the view manager's weak pointer back to |this| in case it
// was leaked.
mViewManager->SetPresShell(nullptr);
mViewManager = nullptr;
}
// This shell must be removed from the document before the frame
// hierarchy is torn down to avoid finding deleted frames through
// this presshell while the frames are being torn down
if (mDocument) {
NS_ASSERTION(mDocument->GetPresShell() == this, "Wrong shell?");
mDocument->ClearServoRestyleRoot();
mDocument->DeletePresShell();
}
if (mPresContext) {
mPresContext->AnimationEventDispatcher()->ClearEventQueue();
}
// Revoke any pending events. We need to do this and cancel pending reflows
// before we destroy the frame constructor, since apparently frame destruction
// sometimes spins the event queue when plug-ins are involved(!).
// XXXmats is this still needed now that plugins are gone?
CancelAllPendingReflows();
CancelPostedReflowCallbacks();
// Destroy the frame constructor. This will destroy the frame hierarchy
mFrameConstructor->WillDestroyFrameTree();
NS_WARNING_ASSERTION(!mAutoWeakFrames && mWeakFrames.IsEmpty(),
"Weak frames alive after destroying FrameManager");
while (mAutoWeakFrames) {
mAutoWeakFrames->Clear(this);
}
const nsTArray<WeakFrame*> weakFrames = ToArray(mWeakFrames);
for (WeakFrame* weakFrame : weakFrames) {
weakFrame->Clear(this);
}
// Terminate AccessibleCaretEventHub after tearing down the frame tree so that
// we don't need to remove caret element's frame in
// AccessibleCaret::RemoveCaretElement().
if (mAccessibleCaretEventHub) {
mAccessibleCaretEventHub->Terminate();
mAccessibleCaretEventHub = nullptr;
}
if (mPresContext) {
// We hold a reference to the pres context, and it holds a weak link back
// to us. To avoid the pres context having a dangling reference, set its
// pres shell to nullptr
mPresContext->DetachPresShell();
}
mHaveShutDown = true;
mTouchManager.Destroy();
}
void PresShell::StartObservingRefreshDriver() {
nsRefreshDriver* rd = mPresContext->RefreshDriver();
if (mResizeEventPending || mVisualViewportResizeEventPending) {
rd->ScheduleRenderingPhase(mozilla::RenderingPhase::ResizeSteps);
}
if (mNeedLayoutFlush || mNeedStyleFlush) {
rd->ScheduleRenderingPhase(mozilla::RenderingPhase::Layout);
}
}
nsRefreshDriver* PresShell::GetRefreshDriver() const {
return mPresContext ? mPresContext->RefreshDriver() : nullptr;
}
void PresShell::SetAuthorStyleDisabled(bool aStyleDisabled) {
if (aStyleDisabled != StyleSet()->GetAuthorStyleDisabled()) {
StyleSet()->SetAuthorStyleDisabled(aStyleDisabled);
mDocument->ApplicableStylesChanged();
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
observerService->NotifyObservers(
ToSupports(mDocument), "author-style-disabled-changed", nullptr);
}
}
}
bool PresShell::GetAuthorStyleDisabled() const {
return StyleSet()->GetAuthorStyleDisabled();
}
void PresShell::AddUserSheet(StyleSheet* aSheet) {
// Make sure this does what nsDocumentViewer::CreateStyleSet does wrt
// ordering. We want this new sheet to come after all the existing stylesheet
// service sheets (which are at the start), but before other user sheets; see
// nsIStyleSheetService.idl for the ordering.
nsStyleSheetService* sheetService = nsStyleSheetService::GetInstance();
nsTArray<RefPtr<StyleSheet>>& userSheets = *sheetService->UserStyleSheets();
// Search for the place to insert the new user sheet. Since all of the
// stylesheet service provided user sheets should be at the start of the style
// set's list, and aSheet should be at the end of userSheets. Given that, we
// can find the right place to insert the new sheet based on the length of
// userSheets.
MOZ_ASSERT(aSheet);
MOZ_ASSERT(userSheets.LastElement() == aSheet);
size_t index = userSheets.Length() - 1;
// Assert that all of userSheets (except for the last, new element) matches up
// with what's in the style set.
for (size_t i = 0; i < index; ++i) {
MOZ_ASSERT(StyleSet()->SheetAt(StyleOrigin::User, i) == userSheets[i]);
}
if (index == static_cast<size_t>(StyleSet()->SheetCount(StyleOrigin::User))) {
StyleSet()->AppendStyleSheet(*aSheet);
} else {
StyleSheet* ref = StyleSet()->SheetAt(StyleOrigin::User, index);
StyleSet()->InsertStyleSheetBefore(*aSheet, *ref);
}
mDocument->ApplicableStylesChanged();
}
void PresShell::AddAgentSheet(StyleSheet* aSheet) {
// Make sure this does what nsDocumentViewer::CreateStyleSet does
// wrt ordering.
StyleSet()->AppendStyleSheet(*aSheet);
mDocument->ApplicableStylesChanged();
}
void PresShell::AddAuthorSheet(StyleSheet* aSheet) {
// Document specific "additional" Author sheets should be stronger than the
// ones added with the StyleSheetService.
StyleSheet* firstAuthorSheet = mDocument->GetFirstAdditionalAuthorSheet();
if (firstAuthorSheet) {
StyleSet()->InsertStyleSheetBefore(*aSheet, *firstAuthorSheet);
} else {
StyleSet()->AppendStyleSheet(*aSheet);
}
mDocument->ApplicableStylesChanged();
}
bool PresShell::NeedsFocusFixUp() const {
if (NS_WARN_IF(!mDocument)) {
return false;
}
nsIContent* currentFocus = mDocument->GetUnretargetedFocusedContent(
Document::IncludeChromeOnly::Yes);
if (!currentFocus) {
return false;
}
// If focus target is an area element with one or more shapes that are
// focusable areas.
if (auto* area = HTMLAreaElement::FromNode(currentFocus)) {
if (nsFocusManager::IsAreaElementFocusable(*area)) {
return false;
}
}
nsIFrame* f = currentFocus->GetPrimaryFrame();
if (f && f->IsFocusable()) {
return false;
}
if (currentFocus == mDocument->GetBody() ||
currentFocus == mDocument->GetRootElement()) {
return false;
}
return true;
}
bool PresShell::FixUpFocus() {
if (!NeedsFocusFixUp()) {
return false;
}
RefPtr fm = nsFocusManager::GetFocusManager();
nsCOMPtr<nsPIDOMWindowOuter> window = mDocument->GetWindow();
if (NS_WARN_IF(!window)) {
return false;
}
fm->ClearFocus(window);
return true;
}
void PresShell::SelectionWillTakeFocus() {
if (mSelection) {
FrameSelectionWillTakeFocus(*mSelection,
CanMoveLastSelectionForToString::No);
}
}
void PresShell::SelectionWillLoseFocus() {
// Do nothing, the main selection is the default focused selection.
}
// Selection repainting code relies on selection offsets being properly
// adjusted (see bug 1626291), so we need to wait until the DOM is finished
// notifying.
static void RepaintNormalSelectionWhenSafe(nsFrameSelection& aFrameSelection) {
if (nsContentUtils::IsSafeToRunScript()) {
aFrameSelection.RepaintSelection(SelectionType::eNormal);
return;
}
// Note that importantly we don't defer changing the DisplaySelection. That'd
// be potentially racy with other code that may change it.
nsContentUtils::AddScriptRunner(NS_NewRunnableFunction(
"RepaintNormalSelectionWhenSafe",
[sel = RefPtr<nsFrameSelection>(&aFrameSelection)] {
sel->RepaintSelection(SelectionType::eNormal);
}));
}
void PresShell::FrameSelectionWillLoseFocus(nsFrameSelection& aFrameSelection) {
if (mFocusedFrameSelection != &aFrameSelection) {
return;
}
// Do nothing, the main selection is the default focused selection.
if (&aFrameSelection == mSelection) {
return;
}
RefPtr<nsFrameSelection> old = std::move(mFocusedFrameSelection);
MOZ_ASSERT(!mFocusedFrameSelection);
if (old->GetDisplaySelection() != nsISelectionController::SELECTION_HIDDEN) {
old->SetDisplaySelection(nsISelectionController::SELECTION_HIDDEN);
RepaintNormalSelectionWhenSafe(*old);
}
if (mSelection) {
FrameSelectionWillTakeFocus(*mSelection,
CanMoveLastSelectionForToString::No);
}
}
void PresShell::FrameSelectionWillTakeFocus(
nsFrameSelection& aFrameSelection,
CanMoveLastSelectionForToString aCanMoveLastSelectionForToString) {
if (StaticPrefs::dom_selection_mimic_chrome_tostring_enabled()) {
if (aCanMoveLastSelectionForToString ==
CanMoveLastSelectionForToString::Yes) {
UpdateLastSelectionForToString(&aFrameSelection);
}
}
if (mFocusedFrameSelection == &aFrameSelection) {
#ifdef XP_MACOSX
// FIXME: Mac needs to update the global selection cache, even if the
// document's focused selection doesn't change, and this is currently done
// from RepaintSelection. Maybe we should move part of the global selection
// handling here, or something of that sort, unclear.
RepaintNormalSelectionWhenSafe(aFrameSelection);
#endif
return;
}
RefPtr<nsFrameSelection> old = std::move(mFocusedFrameSelection);
mFocusedFrameSelection = &aFrameSelection;
if (old &&
old->GetDisplaySelection() != nsISelectionController::SELECTION_HIDDEN) {
old->SetDisplaySelection(nsISelectionController::SELECTION_HIDDEN);
RepaintNormalSelectionWhenSafe(*old);
}
if (aFrameSelection.GetDisplaySelection() !=
nsISelectionController::SELECTION_ON) {
aFrameSelection.SetDisplaySelection(nsISelectionController::SELECTION_ON);
RepaintNormalSelectionWhenSafe(aFrameSelection);
}
}
void PresShell::UpdateLastSelectionForToString(
const nsFrameSelection* aFrameSelection) {
if (mLastSelectionForToString != aFrameSelection) {
mLastSelectionForToString = aFrameSelection;
}
}
NS_IMETHODIMP
PresShell::SetDisplaySelection(int16_t aToggle) {
mSelection->SetDisplaySelection(aToggle);
return NS_OK;
}
NS_IMETHODIMP
PresShell::GetDisplaySelection(int16_t* aToggle) {
*aToggle = mSelection->GetDisplaySelection();
return NS_OK;
}
NS_IMETHODIMP
PresShell::GetSelectionFromScript(RawSelectionType aRawSelectionType,
Selection** aSelection) {
if (!aSelection || !mSelection) {
return NS_ERROR_NULL_POINTER;
}
RefPtr<Selection> selection =
mSelection->GetSelection(ToSelectionType(aRawSelectionType));
if (!selection) {
return NS_ERROR_INVALID_ARG;
}
selection.forget(aSelection);
return NS_OK;
}
Selection* PresShell::GetSelection(RawSelectionType aRawSelectionType) {
if (!mSelection) {
return nullptr;
}
return mSelection->GetSelection(ToSelectionType(aRawSelectionType));
}
Selection* PresShell::GetCurrentSelection(SelectionType aSelectionType) {
if (!mSelection) {
return nullptr;
}
return mSelection->GetSelection(aSelectionType);
}
nsFrameSelection* PresShell::GetLastFocusedFrameSelection() {
return mFocusedFrameSelection ? mFocusedFrameSelection : mSelection;
}
NS_IMETHODIMP
PresShell::ScrollSelectionIntoView(RawSelectionType aRawSelectionType,
SelectionRegion aRegion,
ControllerScrollFlags aFlags) {
if (!mSelection) {
return NS_ERROR_NULL_POINTER;
}
RefPtr<nsFrameSelection> frameSelection = mSelection;
return frameSelection->ScrollSelectionIntoView(
ToSelectionType(aRawSelectionType), aRegion, aFlags);
}
NS_IMETHODIMP
PresShell::RepaintSelection(RawSelectionType aRawSelectionType) {
if (!mSelection) {
return NS_ERROR_NULL_POINTER;
}
if (MOZ_UNLIKELY(mIsDestroying)) {
return NS_OK;
}
RefPtr<nsFrameSelection> frameSelection = mSelection;
return frameSelection->RepaintSelection(ToSelectionType(aRawSelectionType));
}
// Make shell be a document observer
void PresShell::BeginObservingDocument() {
if (mDocument && !mIsDestroying) {
mIsObservingDocument = true;
if (mIsDocumentGone) {
NS_WARNING(
"Adding a presshell that was disconnected from the document "
"as a document observer? Sounds wrong...");
mIsDocumentGone = false;
}
}
}
// Make shell stop being a document observer
void PresShell::EndObservingDocument() {
// XXXbz do we need to tell the frame constructor that the document
// is gone, perhaps? Except for printing it's NOT gone, sometimes.
mIsDocumentGone = true;
mIsObservingDocument = false;
}
void PresShell::InitPaintSuppressionTimer() {
// Default to PAINTLOCK_EVENT_DELAY if we can't get the pref value.
Document* doc = mDocument->GetDisplayDocument()
? mDocument->GetDisplayDocument()
: mDocument.get();
const bool inProcess = !doc->GetBrowsingContext() ||
doc->GetBrowsingContext()->Top()->IsInProcess();
int32_t delay = inProcess
? StaticPrefs::nglayout_initialpaint_delay()
: StaticPrefs::nglayout_initialpaint_delay_in_oopif();
mPaintSuppressionTimer->InitWithNamedFuncCallback(
[](nsITimer* aTimer, void* aPresShell) {
RefPtr<PresShell> self = static_cast<PresShell*>(aPresShell);
self->UnsuppressPainting();
},
this, delay, nsITimer::TYPE_ONE_SHOT,
"PresShell::sPaintSuppressionCallback");
}
nsresult PresShell::Initialize() {
if (mIsDestroying) {
return NS_OK;
}
if (!mDocument) {
// Nothing to do
return NS_OK;
}
MOZ_LOG(gLog, LogLevel::Debug, ("PresShell::Initialize this=%p", this));
NS_ASSERTION(!mDidInitialize, "Why are we being called?");
RefPtr<PresShell> kungFuDeathGrip(this);
RecomputeFontSizeInflationEnabled();
MOZ_DIAGNOSTIC_ASSERT(!mIsDestroying);
// Ensure the pres context doesn't think it has changed, since we haven't even
// started layout. This avoids spurious restyles / reflows afterwards.
//
// Note that this is very intentionally before setting mDidInitialize so it
// doesn't notify the document, or run media query change events.
mPresContext->FlushPendingMediaFeatureValuesChanged();
MOZ_DIAGNOSTIC_ASSERT(!mIsDestroying);
mDidInitialize = true;
#ifdef DEBUG
if (VerifyReflowFlags::NoisyCommands & gVerifyReflowFlags) {
if (mDocument) {
nsIURI* uri = mDocument->GetDocumentURI();
if (uri) {
printf("*** PresShell::Initialize (this=%p, url='%s')\n", (void*)this,
uri->GetSpecOrDefault().get());
}
}
}
#endif
// Get the root frame from the frame constructor.
// XXXbz it would be nice to move this somewhere else... like frame manager
// Init(), say. But we need to make sure our views are all set up by the
// time we do this!
MOZ_ASSERT(!mFrameConstructor->GetRootFrame(),
"How did that happen, exactly?");
ViewportFrame* rootFrame;
{
nsAutoScriptBlocker scriptBlocker;
rootFrame = mFrameConstructor->ConstructRootFrame();
mFrameConstructor->SetRootFrame(rootFrame);
}
NS_ENSURE_STATE(!mHaveShutDown);
if (!rootFrame) {
return NS_ERROR_OUT_OF_MEMORY;
}
if (Element* root = mDocument->GetRootElement()) {
{
nsAutoCauseReflowNotifier reflowNotifier(this);
// Have the style sheet processor construct frame for the root
// content object down
mFrameConstructor->ContentInserted(
root, nsCSSFrameConstructor::InsertionKind::Sync);
}
// Something in mFrameConstructor->ContentInserted may have caused
// Destroy() to get called, bug 337586. Or, nsAutoCauseReflowNotifier
// (which sets up a script blocker) going out of scope may have killed us
// too
NS_ENSURE_STATE(!mHaveShutDown);
}
mDocument->MaybeScheduleRendering();
NS_ASSERTION(rootFrame, "How did that happen?");
// Note: when the frame was created above it had the NS_FRAME_IS_DIRTY bit
// set, but XBL processing could have caused a reflow which clears it.
if (MOZ_LIKELY(rootFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY))) {
// Unset the DIRTY bits so that FrameNeedsReflow() will work right.
rootFrame->RemoveStateBits(NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN);
NS_ASSERTION(!mDirtyRoots.Contains(rootFrame),
"Why is the root in mDirtyRoots already?");
FrameNeedsReflow(rootFrame, IntrinsicDirty::None, NS_FRAME_IS_DIRTY);
NS_ASSERTION(mDirtyRoots.Contains(rootFrame),
"Should be in mDirtyRoots now");
NS_ASSERTION(mNeedStyleFlush || mNeedLayoutFlush,
"Why no reflow scheduled?");
}
// Restore our root scroll position now if we're getting here after EndLoad
// got called, since this is our one chance to do it. Note that we need not
// have reflowed for this to work; when the scrollframe is finally reflowed
// it'll pick up the position we store in it here.
if (!mDocumentLoading) {
RestoreRootScrollPosition();
}
// For printing, we just immediately unsuppress.
if (!mPresContext->IsPaginated()) {
// Kick off a one-shot timer based off our pref value. When this timer
// fires, if painting is still locked down, then we will go ahead and
// trigger a full invalidate and allow painting to proceed normally.
mPaintingSuppressed = true;
// Don't suppress painting if the document isn't loading.
Document::ReadyState readyState = mDocument->GetReadyStateEnum();
if (readyState != Document::READYSTATE_COMPLETE) {
mPaintSuppressionTimer = NS_NewTimer();
}
if (!mPaintSuppressionTimer) {
mPaintingSuppressed = false;
} else {
// Initialize the timer.
mPaintSuppressionTimer->SetTarget(GetMainThreadSerialEventTarget());
InitPaintSuppressionTimer();
if (mHasTriedFastUnsuppress) {
// Someone tried to unsuppress painting before Initialize was called so
// unsuppress painting rather soon.
mHasTriedFastUnsuppress = false;
TryUnsuppressPaintingSoon();
MOZ_ASSERT(mHasTriedFastUnsuppress);
}
}
}
// If we get here and painting is not suppressed, we still want to run the
// unsuppression logic, so set mShouldUnsuppressPainting to true.
if (!mPaintingSuppressed) {
mShouldUnsuppressPainting = true;
}
return NS_OK; // XXX this needs to be real. MMP
}
void PresShell::TryUnsuppressPaintingSoon() {
if (mHasTriedFastUnsuppress) {
return;
}
mHasTriedFastUnsuppress = true;
if (!mDidInitialize || !IsPaintingSuppressed() || !XRE_IsContentProcess()) {
return;
}
if (!mDocument->IsInitialDocument() &&
mDocument->DidHitCompleteSheetCache() &&
mPresContext->IsRootContentDocumentCrossProcess()) {
// Try to unsuppress faster on a top level page if it uses stylesheet
// cache, since that hints that many resources can be painted sooner than
// in a cold page load case.
NS_DispatchToCurrentThreadQueue(
NS_NewRunnableFunction("PresShell::TryUnsuppressPaintingSoon",
[self = RefPtr{this}]() -> void {
if (self->IsPaintingSuppressed()) {
PROFILER_MARKER_UNTYPED(
"Fast paint unsuppression", GRAPHICS);
self->UnsuppressPainting();
}
}),
EventQueuePriority::Control);
}
}
void PresShell::RefreshZoomConstraintsForScreenSizeChange() {
if (mZoomConstraintsClient) {
mZoomConstraintsClient->ScreenSizeChanged();
}
}
void PresShell::ForceResizeReflowWithCurrentDimensions() {
nscoord currentWidth = 0;
nscoord currentHeight = 0;
mViewManager->GetWindowDimensions(¤tWidth, ¤tHeight);
ResizeReflow(currentWidth, currentHeight);
}
void PresShell::ResizeReflow(nscoord aWidth, nscoord aHeight,
ResizeReflowOptions aOptions) {
if (mZoomConstraintsClient) {
// If we have a ZoomConstraintsClient and the available screen area
// changed, then we might need to disable double-tap-to-zoom, so notify
// the ZCC to update itself.
mZoomConstraintsClient->ScreenSizeChanged();
}
if (UsesMobileViewportSizing()) {
// If we are using mobile viewport sizing, request a reflow from the MVM.
// It can recompute the final CSS viewport and trigger a call to
// ResizeReflowIgnoreOverride if it changed. We don't force adjusting
// of resolution, because that is only necessary when we are destroying
// the MVM.
MOZ_ASSERT(mMobileViewportManager);
mMobileViewportManager->RequestReflow(false);
return;
}
ResizeReflowIgnoreOverride(aWidth, aHeight, aOptions);
}
bool PresShell::SimpleResizeReflow(nscoord aWidth, nscoord aHeight) {
MOZ_ASSERT(aWidth != NS_UNCONSTRAINEDSIZE);
MOZ_ASSERT(aHeight != NS_UNCONSTRAINEDSIZE);
nsSize oldSize = mPresContext->GetVisibleArea().Size();
mPresContext->SetVisibleArea(nsRect(0, 0, aWidth, aHeight));
nsIFrame* rootFrame = GetRootFrame();
if (!rootFrame) {
return false;
}
WritingMode wm = rootFrame->GetWritingMode();
bool isBSizeChanging =
wm.IsVertical() ? oldSize.width != aWidth : oldSize.height != aHeight;
if (isBSizeChanging) {
nsLayoutUtils::MarkIntrinsicISizesDirtyIfDependentOnBSize(rootFrame);
rootFrame->SetHasBSizeChange(true);
}
FrameNeedsReflow(rootFrame, IntrinsicDirty::None,
NS_FRAME_HAS_DIRTY_CHILDREN);
if (mMobileViewportManager) {
mMobileViewportManager->UpdateSizesBeforeReflow();
}
return true;
}
bool PresShell::CanHandleUserInputEvents(WidgetGUIEvent* aGUIEvent) {
if (XRE_IsParentProcess()) {
return true;
}
if (aGUIEvent->mFlags.mIsSynthesizedForTests &&
!StaticPrefs::dom_input_events_security_isUserInputHandlingDelayTest()) {
return true;
}
if (!aGUIEvent->IsUserAction()) {
return true;
}
if (nsPresContext* rootPresContext = mPresContext->GetRootPresContext()) {
return rootPresContext->UserInputEventsAllowed();
}
return true;
}
void PresShell::PostScrollEvent(Runnable* aEvent) {
MOZ_ASSERT(aEvent);
mPendingScrollEvents.AppendElement(aEvent);
// If we (or any descendant docs) have any content visibility: auto elements,
// we also need to run its proximity to the viewport on scroll. Same for
// intersection observers.
//
// We don't need to mark ourselves as needing a layout flush. We don't need to
// get flushed, we just need the viewport relevancy / content-visibility: auto
// viewport proximity phases to run.
mPresContext->RefreshDriver()->ScheduleRenderingPhases(
{RenderingPhase::ScrollSteps, RenderingPhase::Layout,
RenderingPhase::UpdateIntersectionObservations});
}
void PresShell::ScheduleResizeEventIfNeeded(ResizeEventKind aKind) {
if (mIsDestroying) {
return;
}
if (MOZ_UNLIKELY(mDocument->GetBFCacheEntry())) {
return;
}
if (aKind == ResizeEventKind::Regular) {
mResizeEventPending = true;
} else {
MOZ_ASSERT(aKind == ResizeEventKind::Visual);
mVisualViewportResizeEventPending = true;
}
mPresContext->RefreshDriver()->ScheduleRenderingPhase(
RenderingPhase::ResizeSteps);
}
bool PresShell::ResizeReflowIgnoreOverride(nscoord aWidth, nscoord aHeight,
ResizeReflowOptions aOptions) {
MOZ_ASSERT(!mIsReflowing, "Shouldn't be in reflow here!");
// Historically we never fired resize events if there was no root frame by the
// time this function got called.
const bool initialized = mDidInitialize;
RefPtr<PresShell> kungFuDeathGrip(this);
auto postResizeEventIfNeeded = [this, initialized]() {
if (initialized) {
ScheduleResizeEventIfNeeded(ResizeEventKind::Regular);
}
};
// If there are orthogonal flows that were dependent on the ICB size, mark
// them as dirty to ensure they will be reflowed.
for (auto* frame : mOrthogonalFlows) {
FrameNeedsReflow(frame, IntrinsicDirty::None, NS_FRAME_HAS_DIRTY_CHILDREN);
}
mOrthogonalFlows.Clear();
if (!(aOptions & ResizeReflowOptions::BSizeLimit)) {
nsSize oldSize = mPresContext->GetVisibleArea().Size();
if (oldSize == nsSize(aWidth, aHeight)) {
return false;
}
bool changed = SimpleResizeReflow(aWidth, aHeight);
postResizeEventIfNeeded();
return changed;
}
// Make sure that style is flushed before setting the pres context
// VisibleArea.
//
// Otherwise we may end up with bogus viewport units resolved against the
// unconstrained bsize, or restyling the whole document resolving viewport
// units against targetWidth, which may end up doing wasteful work.
mDocument->FlushPendingNotifications(FlushType::Frames);
nsIFrame* rootFrame = GetRootFrame();
if (mIsDestroying || !rootFrame) {
// If we don't have a root frame yet, that means we haven't had our initial
// reflow... If that's the case, and aWidth or aHeight is unconstrained,
// ignore them altogether.
if (aHeight == NS_UNCONSTRAINEDSIZE || aWidth == NS_UNCONSTRAINEDSIZE) {
// We can't do the work needed for SizeToContent without a root
// frame, and we want to return before setting the visible area.
return false;
}
mPresContext->SetVisibleArea(nsRect(0, 0, aWidth, aHeight));
// There isn't anything useful we can do if the initial reflow hasn't
// happened.
return true;
}
WritingMode wm = rootFrame->GetWritingMode();
MOZ_ASSERT((wm.IsVertical() ? aHeight : aWidth) != NS_UNCONSTRAINEDSIZE,
"unconstrained isize not allowed");
nscoord targetWidth = aWidth;
nscoord targetHeight = aHeight;
if (wm.IsVertical()) {
targetWidth = NS_UNCONSTRAINEDSIZE;
} else {
targetHeight = NS_UNCONSTRAINEDSIZE;
}
mPresContext->SetVisibleArea(nsRect(0, 0, targetWidth, targetHeight));
// XXX Do a full invalidate at the beginning so that invalidates along
// the way don't have region accumulation issues?
// For height:auto BSizes (i.e. layout-controlled), descendant
// intrinsic sizes can't depend on them. So the only other case is
// viewport-controlled BSizes which we handle here.
nsLayoutUtils::MarkIntrinsicISizesDirtyIfDependentOnBSize(rootFrame);
rootFrame->SetHasBSizeChange(true);
FrameNeedsReflow(rootFrame, IntrinsicDirty::None,
NS_FRAME_HAS_DIRTY_CHILDREN);
{
nsAutoCauseReflowNotifier crNotifier(this);
WillDoReflow();
// Kick off a top-down reflow
AUTO_LAYOUT_PHASE_ENTRY_POINT(GetPresContext(), Reflow);
nsViewManager::AutoDisableRefresh refreshBlocker(mViewManager);
mDirtyRoots.Remove(rootFrame);
DoReflow(rootFrame, true, nullptr);
const bool reflowAgain =
wm.IsVertical() ? mPresContext->GetVisibleArea().width > aWidth
: mPresContext->GetVisibleArea().height > aHeight;
if (reflowAgain) {
mPresContext->SetVisibleArea(nsRect(0, 0, aWidth, aHeight));
rootFrame->SetHasBSizeChange(true);
DoReflow(rootFrame, true, nullptr);
}
}
// Now, we may have been destroyed by the destructor of
// `nsAutoCauseReflowNotifier`.
mPendingDidDoReflow = true;
DidDoReflow(true);
// the reflow above should've set our bsize if it was NS_UNCONSTRAINEDSIZE,
// and the isize shouldn't be NS_UNCONSTRAINEDSIZE anyway.
MOZ_DIAGNOSTIC_ASSERT(
mPresContext->GetVisibleArea().width != NS_UNCONSTRAINEDSIZE,
"width should not be NS_UNCONSTRAINEDSIZE after reflow");
MOZ_DIAGNOSTIC_ASSERT(
mPresContext->GetVisibleArea().height != NS_UNCONSTRAINEDSIZE,
"height should not be NS_UNCONSTRAINEDSIZE after reflow");
postResizeEventIfNeeded();
return true;
}
// https://drafts.csswg.org/cssom-view/#document-run-the-resize-steps
void PresShell::RunResizeSteps() {
if (!mResizeEventPending && !mVisualViewportResizeEventPending) {
return;
}
if (mIsDocumentGone) {
return;
}
RefPtr window = nsGlobalWindowInner::Cast(mDocument->GetInnerWindow());
if (!window) {
return;
}
if (mResizeEventPending) {
// Clear it before firing, just in case the event triggers another resize
// event. Such event will fire next tick.
mResizeEventPending = false;
WidgetEvent event(true, mozilla::eResize);
nsEventStatus status = nsEventStatus_eIgnore;
if (RefPtr<nsPIDOMWindowOuter> outer = window->GetOuterWindow()) {
// MOZ_KnownLive due to bug 1506441
EventDispatcher::Dispatch(MOZ_KnownLive(nsGlobalWindowOuter::Cast(outer)),
mPresContext, &event, nullptr, &status);
}
}
if (mVisualViewportResizeEventPending) {
mVisualViewportResizeEventPending = false;
RefPtr vv = window->VisualViewport();
vv->FireResizeEvent();
}
}
// https://drafts.csswg.org/cssom-view/#document-run-the-scroll-steps
// But note: https://github.com/w3c/csswg-drafts/issues/11164
void PresShell::RunScrollSteps() {
// Scroll events are one-shot, so after running them we can drop them.
// However, dispatching a scroll event can potentially cause more scroll
// events to be posted, so we move the initial set into a temporary array
// first. (Newly posted scroll events will be dispatched on the next tick.)
auto events = std::move(mPendingScrollEvents);
for (auto& event : events) {
event->Run();
}
}
static nsIContent* GetNativeAnonymousSubtreeRoot(nsIContent* aContent) {
if (!aContent) {
return nullptr;
}
return aContent->GetClosestNativeAnonymousSubtreeRoot();
}
void PresShell::NativeAnonymousContentWillBeRemoved(nsIContent* aAnonContent) {
MOZ_ASSERT(aAnonContent->IsRootOfNativeAnonymousSubtree());
mPresContext->EventStateManager()->NativeAnonymousContentRemoved(
aAnonContent);
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
accService->ContentRemoved(this, aAnonContent);
}
#endif
if (mDocument->DevToolsAnonymousAndShadowEventsEnabled()) {
aAnonContent->QueueDevtoolsAnonymousEvent(/* aIsRemove = */ true);
}
if (nsIContent* root =
GetNativeAnonymousSubtreeRoot(mCurrentEventTarget.mContent)) {
if (aAnonContent == root) {
mCurrentEventTarget.UpdateFrameAndContent(
nullptr, aAnonContent->GetFlattenedTreeParent());
}
}
for (EventTargetInfo& eventTargetInfo : mCurrentEventTargetStack) {
nsIContent* anon = GetNativeAnonymousSubtreeRoot(eventTargetInfo.mContent);
if (aAnonContent == anon) {
eventTargetInfo.UpdateFrameAndContent(
nullptr, aAnonContent->GetFlattenedTreeParent());
}
}
}
void PresShell::SetIgnoreFrameDestruction(bool aIgnore) {
if (mDocument) {
// We need to tell the ImageLoader to drop all its references to frames
// because they're about to go away and it won't get notifications of that.
mDocument->StyleImageLoader()->ClearFrames(mPresContext);
}
mIgnoreFrameDestruction = aIgnore;
}
void PresShell::NotifyDestroyingFrame(nsIFrame* aFrame) {
// We must remove these from FrameLayerBuilder::DisplayItemData::mFrameList
// here, otherwise the DisplayItemData destructor will use the destroyed frame
// when it tries to remove it from the (array) value of this property.
aFrame->RemoveDisplayItemDataForDeletion();
if (!mIgnoreFrameDestruction) {
if (aFrame->HasImageRequest()) {
mDocument->StyleImageLoader()->DropRequestsForFrame(aFrame);
}
mFrameConstructor->NotifyDestroyingFrame(aFrame);
mDirtyRoots.Remove(aFrame);
// Remove frame properties
aFrame->RemoveAllProperties();
const auto ComputeTargetContent =
[&aFrame](const EventTargetInfo& aEventTargetInfo) -> nsIContent* {
if (!IsForbiddenDispatchingToNonElementContent(
aEventTargetInfo.mEventMessage)) {
return aFrame->GetContent();
}
return aFrame->GetContent()
? aFrame->GetContent()
->GetInclusiveFlattenedTreeAncestorElement()
: nullptr;
};
if (aFrame == mCurrentEventTarget.mFrame) {
mCurrentEventTarget.UpdateFrameAndContent(
nullptr, ComputeTargetContent(mCurrentEventTarget));
}
for (EventTargetInfo& eventTargetInfo : mCurrentEventTargetStack) {
if (aFrame == eventTargetInfo.mFrame) {
// One of our stack frames was deleted. Get its content so that when we
// pop it we can still get its new frame from its content
eventTargetInfo.UpdateFrameAndContent(
nullptr, ComputeTargetContent(eventTargetInfo));
}
}
mFramesToDirty.Remove(aFrame);
mOrthogonalFlows.Remove(aFrame);
if (ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(aFrame)) {
mPendingScrollAnchorSelection.Remove(scrollContainerFrame);
mPendingScrollAnchorAdjustment.Remove(scrollContainerFrame);
mPendingScrollResnap.Remove(scrollContainerFrame);
}
}
}
already_AddRefed<nsCaret> PresShell::GetCaret() const {
RefPtr<nsCaret> caret = mCaret;
return caret.forget();
}
already_AddRefed<AccessibleCaretEventHub>
PresShell::GetAccessibleCaretEventHub() const {
RefPtr<AccessibleCaretEventHub> eventHub = mAccessibleCaretEventHub;
return eventHub.forget();
}
void PresShell::SetCaret(nsCaret* aNewCaret) {
if (mCaret == aNewCaret) {
return;
}
if (mCaret) {
mCaret->SchedulePaint();
}
mCaret = aNewCaret;
if (aNewCaret) {
aNewCaret->SchedulePaint();
}
}
void PresShell::RestoreCaret() { SetCaret(mOriginalCaret); }
NS_IMETHODIMP PresShell::SetCaretEnabled(bool aInEnable) {
bool oldEnabled = mCaretEnabled;
mCaretEnabled = aInEnable;
if (mCaretEnabled != oldEnabled) {
MOZ_ASSERT(mCaret);
if (mCaret) {
mCaret->SetVisible(mCaretEnabled);
}
}
return NS_OK;
}
NS_IMETHODIMP PresShell::SetCaretReadOnly(bool aReadOnly) {
if (mCaret) {
mCaret->SetCaretReadOnly(aReadOnly);
}
return NS_OK;
}
NS_IMETHODIMP PresShell::GetCaretEnabled(bool* aOutEnabled) {
NS_ENSURE_ARG_POINTER(aOutEnabled);
*aOutEnabled = mCaretEnabled;
return NS_OK;
}
NS_IMETHODIMP PresShell::SetCaretVisibilityDuringSelection(bool aVisibility) {
if (mCaret) {
mCaret->SetVisibilityDuringSelection(aVisibility);
}
return NS_OK;
}
NS_IMETHODIMP PresShell::GetCaretVisible(bool* aOutIsVisible) {
*aOutIsVisible = false;
if (mCaret) {
*aOutIsVisible = mCaret->IsVisible();
}
return NS_OK;
}
NS_IMETHODIMP PresShell::SetSelectionFlags(int16_t aFlags) {
mSelectionFlags = aFlags;
return NS_OK;
}
NS_IMETHODIMP PresShell::GetSelectionFlags(int16_t* aFlags) {
if (!aFlags) {
return NS_ERROR_INVALID_ARG;
}
*aFlags = mSelectionFlags;
return NS_OK;
}
// implementation of nsISelectionController
NS_IMETHODIMP
PresShell::PhysicalMove(int16_t aDirection, int16_t aAmount, bool aExtend) {
RefPtr<nsFrameSelection> frameSelection = mSelection;
return frameSelection->PhysicalMove(aDirection, aAmount, aExtend);
}
NS_IMETHODIMP
PresShell::CharacterMove(bool aForward, bool aExtend) {
RefPtr<nsFrameSelection> frameSelection = mSelection;
return frameSelection->CharacterMove(aForward, aExtend);
}
NS_IMETHODIMP
PresShell::WordMove(bool aForward, bool aExtend) {
RefPtr<nsFrameSelection> frameSelection = mSelection;
nsresult result = frameSelection->WordMove(aForward, aExtend);
// if we can't go down/up any more we must then move caret completely to
// end/beginning respectively.
if (NS_FAILED(result)) {
result = CompleteMove(aForward, aExtend);
}
return result;
}
NS_IMETHODIMP
PresShell::LineMove(bool aForward, bool aExtend) {
RefPtr<nsFrameSelection> frameSelection = mSelection;
nsresult result = frameSelection->LineMove(aForward, aExtend);
// if we can't go down/up any more we must then move caret completely to
// end/beginning respectively.
if (NS_FAILED(result)) {
result = CompleteMove(aForward, aExtend);
}
return result;
}
NS_IMETHODIMP
PresShell::IntraLineMove(bool aForward, bool aExtend) {
RefPtr<nsFrameSelection> frameSelection = mSelection;
return frameSelection->IntraLineMove(aForward, aExtend);
}
NS_IMETHODIMP
PresShell::PageMove(bool aForward, bool aExtend) {
nsIFrame* frame = nullptr;
if (!aExtend) {
frame = GetScrollContainerFrameToScroll(VerticalScrollDirection);
// If there is no scrollable frame, get the frame to move caret instead.
}
if (!frame || frame->PresContext() != mPresContext) {
frame = mSelection->GetFrameToPageSelect();
if (!frame) {
return NS_OK;
}
}
// We may scroll parent scrollable element of current selection limiter.
// In such case, we don't want to scroll selection into view unless
// selection is changed.
RefPtr<nsFrameSelection> frameSelection = mSelection;
return frameSelection->PageMove(
aForward, aExtend, frame, nsFrameSelection::SelectionIntoView::IfChanged);
}
NS_IMETHODIMP
PresShell::ScrollPage(bool aForward) {
ScrollContainerFrame* scrollContainerFrame =
GetScrollContainerFrameToScroll(VerticalScrollDirection);
ScrollMode scrollMode = apz::GetScrollModeForOrigin(ScrollOrigin::Pages);
if (scrollContainerFrame) {
scrollContainerFrame->ScrollBy(nsIntPoint(0, aForward ? 1 : -1),
ScrollUnit::PAGES, scrollMode, nullptr,
mozilla::ScrollOrigin::NotSpecified,
ScrollContainerFrame::NOT_MOMENTUM,
ScrollSnapFlags::IntendedDirection |
ScrollSnapFlags::IntendedEndPosition);
}
return NS_OK;
}
NS_IMETHODIMP
PresShell::ScrollLine(bool aForward) {
ScrollContainerFrame* scrollContainerFrame =
GetScrollContainerFrameToScroll(VerticalScrollDirection);
ScrollMode scrollMode = apz::GetScrollModeForOrigin(ScrollOrigin::Lines);
if (scrollContainerFrame) {
nsRect scrollPort = scrollContainerFrame->GetScrollPortRect();
nsSize lineSize = scrollContainerFrame->GetLineScrollAmount();
int32_t lineCount = StaticPrefs::toolkit_scrollbox_verticalScrollDistance();
if (lineCount * lineSize.height > scrollPort.Height()) {
return ScrollPage(aForward);
}
scrollContainerFrame->ScrollBy(
nsIntPoint(0, aForward ? lineCount : -lineCount), ScrollUnit::LINES,
scrollMode, nullptr, mozilla::ScrollOrigin::NotSpecified,
ScrollContainerFrame::NOT_MOMENTUM, ScrollSnapFlags::IntendedDirection);
}
return NS_OK;
}
NS_IMETHODIMP
PresShell::ScrollCharacter(bool aRight) {
ScrollContainerFrame* scrollContainerFrame =
GetScrollContainerFrameToScroll(HorizontalScrollDirection);
ScrollMode scrollMode = apz::GetScrollModeForOrigin(ScrollOrigin::Lines);
if (scrollContainerFrame) {
int32_t h = StaticPrefs::toolkit_scrollbox_horizontalScrollDistance();
scrollContainerFrame->ScrollBy(
nsIntPoint(aRight ? h : -h, 0), ScrollUnit::LINES, scrollMode, nullptr,
mozilla::ScrollOrigin::NotSpecified, ScrollContainerFrame::NOT_MOMENTUM,
ScrollSnapFlags::IntendedDirection);
}
return NS_OK;
}
NS_IMETHODIMP
PresShell::CompleteScroll(bool aForward) {
ScrollContainerFrame* scrollContainerFrame =
GetScrollContainerFrameToScroll(VerticalScrollDirection);
ScrollMode scrollMode = apz::GetScrollModeForOrigin(ScrollOrigin::Other);
if (scrollContainerFrame) {
scrollContainerFrame->ScrollBy(nsIntPoint(0, aForward ? 1 : -1),
ScrollUnit::WHOLE, scrollMode, nullptr,
mozilla::ScrollOrigin::NotSpecified,
ScrollContainerFrame::NOT_MOMENTUM,
ScrollSnapFlags::IntendedEndPosition);
}
return NS_OK;
}
NS_IMETHODIMP
PresShell::CompleteMove(bool aForward, bool aExtend) {
// Beware! This may flush notifications via synchronous
// ScrollSelectionIntoView.
RefPtr<nsFrameSelection> frameSelection = mSelection;
Element* const limiter = frameSelection->GetAncestorLimiter();
nsIFrame* frame = limiter ? limiter->GetPrimaryFrame()
: FrameConstructor()->GetRootElementFrame();
if (!frame) {
return NS_ERROR_FAILURE;
}
nsIFrame::CaretPosition pos = frame->GetExtremeCaretPosition(!aForward);
const nsFrameSelection::FocusMode focusMode =
aExtend ? nsFrameSelection::FocusMode::kExtendSelection
: nsFrameSelection::FocusMode::kCollapseToNewPoint;
frameSelection->HandleClick(
MOZ_KnownLive(pos.mResultContent) /* bug 1636889 */, pos.mContentOffset,
pos.mContentOffset, focusMode,
aForward ? CaretAssociationHint::After : CaretAssociationHint::Before);
if (limiter) {
// HandleClick resets ancestorLimiter, so set it again.
frameSelection->SetAncestorLimiter(limiter);
}
// After ScrollSelectionIntoView(), the pending notifications might be
// flushed and PresShell/PresContext/Frames may be dead. See bug 418470.
return ScrollSelectionIntoView(SelectionType::eNormal,
nsISelectionController::SELECTION_FOCUS_REGION,
SelectionScrollMode::SyncFlush);
}
// end implementations nsISelectionController
ScrollContainerFrame* PresShell::GetRootScrollContainerFrame() const {
if (!mFrameConstructor) {
return nullptr;
}
nsIFrame* rootFrame = mFrameConstructor->GetRootFrame();
if (!rootFrame) {
return nullptr;
}
nsIFrame* theFrame = rootFrame->PrincipalChildList().FirstChild();
if (!theFrame || !theFrame->IsScrollContainerFrame()) {
return nullptr;
}
return static_cast<ScrollContainerFrame*>(theFrame);
}
nsPageSequenceFrame* PresShell::GetPageSequenceFrame() const {
return mFrameConstructor->GetPageSequenceFrame();
}
nsCanvasFrame* PresShell::GetCanvasFrame() const {
return mFrameConstructor->GetCanvasFrame();
}
void PresShell::RestoreRootScrollPosition() {
if (ScrollContainerFrame* sf = GetRootScrollContainerFrame()) {
sf->ScrollToRestoredPosition();
}
}
void PresShell::MaybeReleaseCapturingContent() {
RefPtr<nsFrameSelection> frameSelection = FrameSelection();
if (frameSelection) {
frameSelection->SetDragState(false);
}
if (sCapturingContentInfo.mContent &&
sCapturingContentInfo.mContent->OwnerDoc() == mDocument) {
PresShell::ReleaseCapturingContent();
}
}
void PresShell::BeginLoad(Document* aDocument) {
mDocumentLoading = true;
gfxTextPerfMetrics* tp = nullptr;
if (mPresContext) {
tp = mPresContext->GetTextPerfMetrics();
}
bool shouldLog = MOZ_LOG_TEST(gLog, LogLevel::Debug);
if (shouldLog || tp) {
mLoadBegin = TimeStamp::Now();
}
if (shouldLog) {
nsIURI* uri = mDocument->GetDocumentURI();
MOZ_LOG(gLog, LogLevel::Debug,
("(presshell) %p load begin [%s]\n", this,
uri ? uri->GetSpecOrDefault().get() : ""));
}
}
void PresShell::EndLoad(Document* aDocument) {
MOZ_ASSERT(aDocument == mDocument, "Wrong document");
RestoreRootScrollPosition();
mDocumentLoading = false;
}
void PresShell::LoadComplete() {
gfxTextPerfMetrics* tp = nullptr;
if (mPresContext) {
tp = mPresContext->GetTextPerfMetrics();
}
// log load
bool shouldLog = MOZ_LOG_TEST(gLog, LogLevel::Debug);
if (shouldLog || tp) {
TimeDuration loadTime = TimeStamp::Now() - mLoadBegin;
nsIURI* uri = mDocument->GetDocumentURI();
nsAutoCString spec;
if (uri) {
spec = uri->GetSpecOrDefault();
}
if (shouldLog) {
MOZ_LOG(gLog, LogLevel::Debug,
("(presshell) %p load done time-ms: %9.2f [%s]\n", this,
loadTime.ToMilliseconds(), spec.get()));
}
if (tp) {
tp->Accumulate();
if (tp->cumulative.numChars > 0) {
LogTextPerfStats(tp, this, tp->cumulative, loadTime.ToMilliseconds(),
eLog_loaddone, spec.get());
}
}
}
}
#ifdef DEBUG
void PresShell::VerifyHasDirtyRootAncestor(nsIFrame* aFrame) {
// XXXbz due to bug 372769, can't actually assert anything here...
// XXX Since bug 372769 is now fixed, the assertion is being enabled in bug
// 1758104.
# if 0
// XXXbz shouldn't need this part; remove it once FrameNeedsReflow
// handles the root frame correctly.
if (!aFrame->GetParent()) {
return;
}
// Make sure that there is a reflow root ancestor of |aFrame| that's
// in mDirtyRoots already.
while (aFrame && aFrame->HasAnyStateBits(NS_FRAME_HAS_DIRTY_CHILDREN)) {
if ((aFrame->HasAnyStateBits(NS_FRAME_REFLOW_ROOT |
NS_FRAME_DYNAMIC_REFLOW_ROOT) ||
!aFrame->GetParent()) &&
mDirtyRoots.Contains(aFrame)) {
return;
}
aFrame = aFrame->GetParent();
}
MOZ_ASSERT_UNREACHABLE(
"Frame has dirty bits set but isn't scheduled to be "
"reflowed?");
# endif
}
#endif
void PresShell::PostPendingScrollAnchorSelection(
mozilla::layout::ScrollAnchorContainer* aContainer) {
mPendingScrollAnchorSelection.Insert(aContainer->ScrollContainer());
}
void PresShell::FlushPendingScrollAnchorSelections() {
for (ScrollContainerFrame* scroll : mPendingScrollAnchorSelection) {
scroll->Anchor()->SelectAnchor();
}
mPendingScrollAnchorSelection.Clear();
}
void PresShell::PostPendingScrollAnchorAdjustment(
ScrollAnchorContainer* aContainer) {
mPendingScrollAnchorAdjustment.Insert(aContainer->ScrollContainer());
}
void PresShell::FlushPendingScrollAnchorAdjustments() {
for (ScrollContainerFrame* scroll : mPendingScrollAnchorAdjustment) {
scroll->Anchor()->ApplyAdjustments();
}
mPendingScrollAnchorAdjustment.Clear();
}
void PresShell::PostPendingScrollResnap(
ScrollContainerFrame* aScrollContainerFrame) {
mPendingScrollResnap.Insert(aScrollContainerFrame);
}
void PresShell::FlushPendingScrollResnap() {
for (ScrollContainerFrame* scrollContainerFrame : mPendingScrollResnap) {
scrollContainerFrame->TryResnap();
}
mPendingScrollResnap.Clear();
}
void PresShell::FrameNeedsReflow(nsIFrame* aFrame,
IntrinsicDirty aIntrinsicDirty,
nsFrameState aBitToAdd,
ReflowRootHandling aRootHandling) {
MOZ_ASSERT(aBitToAdd == NS_FRAME_IS_DIRTY ||
aBitToAdd == NS_FRAME_HAS_DIRTY_CHILDREN || !aBitToAdd,
"Unexpected bits being added");
// FIXME bug 478135
NS_ASSERTION(
aIntrinsicDirty != IntrinsicDirty::FrameAncestorsAndDescendants ||
aBitToAdd != NS_FRAME_HAS_DIRTY_CHILDREN,
"bits don't correspond to style change reason");
// FIXME bug 457400
NS_ASSERTION(!mIsReflowing, "can't mark frame dirty during reflow");
// If we've not yet done the initial reflow, then don't bother
// enqueuing a reflow command yet.
if (!mDidInitialize) {
return;
}
// If we're already destroying, don't bother with this either.
if (mIsDestroying) {
return;
}
#ifdef DEBUG
// printf("gShellCounter: %d\n", gShellCounter++);
if (mInVerifyReflow) return;
if (VerifyReflowFlags::NoisyCommands & gVerifyReflowFlags) {
printf("\nPresShell@%p: frame %p needs reflow\n", (void*)this,
(void*)aFrame);
if (VerifyReflowFlags::ReallyNoisyCommands & gVerifyReflowFlags) {
printf("Current content model:\n");
Element* rootElement = mDocument->GetRootElement();
if (rootElement) {
rootElement->List(stdout, 0);
}
}
}
#endif
AutoTArray<nsIFrame*, 4> subtrees;
subtrees.AppendElement(aFrame);
do {
nsIFrame* subtreeRoot = subtrees.PopLastElement();
// Grab |wasDirty| now so we can go ahead and update the bits on
// subtreeRoot.
bool wasDirty = subtreeRoot->IsSubtreeDirty();
subtreeRoot->AddStateBits(aBitToAdd);
// Determine whether we need to keep looking for the next ancestor
// reflow root if subtreeRoot itself is a reflow root.
bool targetNeedsReflowFromParent;
switch (aRootHandling) {
case ReflowRootHandling::PositionOrSizeChange:
targetNeedsReflowFromParent = true;
break;
case ReflowRootHandling::NoPositionOrSizeChange:
targetNeedsReflowFromParent = false;
break;
case ReflowRootHandling::InferFromBitToAdd:
targetNeedsReflowFromParent = (aBitToAdd == NS_FRAME_IS_DIRTY);
break;
}
auto FrameIsReflowRoot = [](const nsIFrame* aFrame) {
return aFrame->HasAnyStateBits(NS_FRAME_REFLOW_ROOT |
NS_FRAME_DYNAMIC_REFLOW_ROOT);
};
auto CanStopClearingAncestorIntrinsics = [&](const nsIFrame* aFrame) {
return FrameIsReflowRoot(aFrame) && aFrame != subtreeRoot;
};
auto IsReflowBoundary = [&](const nsIFrame* aFrame) {
return FrameIsReflowRoot(aFrame) &&
(aFrame != subtreeRoot || !targetNeedsReflowFromParent);
};
// Mark the intrinsic widths as dirty on the frame, all of its ancestors,
// and all of its descendants, if needed:
if (aIntrinsicDirty != IntrinsicDirty::None) {
// Mark argument and all ancestors dirty. (Unless we hit a reflow root
// that should contain the reflow.
for (nsIFrame* a = subtreeRoot;
a && !CanStopClearingAncestorIntrinsics(a); a = a->GetParent()) {
a->MarkIntrinsicISizesDirty();
if (a->IsAbsolutelyPositioned()) {
// If we get here, 'a' is abspos, so its subtree's intrinsic sizing
// has no effect on its ancestors' intrinsic sizing. So, don't loop
// upwards any further.
break;
}
}
}
const bool frameAncestorAndDescendantISizesDirty =
(aIntrinsicDirty == IntrinsicDirty::FrameAncestorsAndDescendants);
const bool dirty = (aBitToAdd == NS_FRAME_IS_DIRTY);
if (frameAncestorAndDescendantISizesDirty || dirty) {
// Mark all descendants dirty (using an nsTArray stack rather than
// recursion).
// Note that ReflowInput::InitResizeFlags has some similar
// code; see comments there for how and why it differs.
AutoTArray<nsIFrame*, 32> stack;
stack.AppendElement(subtreeRoot);
do {
nsIFrame* f = stack.PopLastElement();
if (frameAncestorAndDescendantISizesDirty && f->IsPlaceholderFrame()) {
// Call `GetOutOfFlowFrame` directly because we can get here from
// frame destruction and the placeholder might be already torn down.
if (nsIFrame* oof =
static_cast<nsPlaceholderFrame*>(f)->GetOutOfFlowFrame()) {
if (!nsLayoutUtils::IsProperAncestorFrame(subtreeRoot, oof)) {
// We have another distinct subtree we need to mark.
subtrees.AppendElement(oof);
}
}
}
for (const auto& childList : f->ChildLists()) {
for (nsIFrame* kid : childList.mList) {
if (frameAncestorAndDescendantISizesDirty) {
kid->MarkIntrinsicISizesDirty();
}
if (dirty) {
kid->AddStateBits(NS_FRAME_IS_DIRTY);
}
stack.AppendElement(kid);
}
}
} while (stack.Length() != 0);
}
// Skip setting dirty bits up the tree if we weren't given a bit to add.
if (!aBitToAdd) {
continue;
}
// Set NS_FRAME_HAS_DIRTY_CHILDREN bits (via nsIFrame::ChildIsDirty)
// up the tree until we reach either a frame that's already dirty or
// a reflow root.
nsIFrame* f = subtreeRoot;
for (;;) {
if (IsReflowBoundary(f) || !f->GetParent()) {
// we've hit a reflow root or the root frame
if (!wasDirty) {
mDirtyRoots.Add(f);
SetNeedLayoutFlush();
}
#ifdef DEBUG
else {
VerifyHasDirtyRootAncestor(f);
}
#endif
break;
}
nsIFrame* child = f;
f = f->GetParent();
wasDirty = f->IsSubtreeDirty();
f->ChildIsDirty(child);
NS_ASSERTION(f->HasAnyStateBits(NS_FRAME_HAS_DIRTY_CHILDREN),
"ChildIsDirty didn't do its job");
if (wasDirty) {
// This frame was already marked dirty.
#ifdef DEBUG
VerifyHasDirtyRootAncestor(f);
#endif
break;
}
}
} while (subtrees.Length() != 0);
EnsureLayoutFlush();
}
void PresShell::FrameNeedsToContinueReflow(nsIFrame* aFrame) {
NS_ASSERTION(mIsReflowing, "Must be in reflow when marking path dirty.");
MOZ_ASSERT(mCurrentReflowRoot, "Must have a current reflow root here");
NS_ASSERTION(
aFrame == mCurrentReflowRoot ||
nsLayoutUtils::IsProperAncestorFrame(mCurrentReflowRoot, aFrame),
"Frame passed in is not the descendant of mCurrentReflowRoot");
NS_ASSERTION(aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW),
"Frame passed in not in reflow?");
mFramesToDirty.Insert(aFrame);
}
already_AddRefed<nsIContent> PresShell::GetContentForScrolling() const {
if (nsCOMPtr<nsIContent> focused = GetFocusedContentInOurWindow()) {
return focused.forget();
}
return GetSelectedContentForScrolling();
}
already_AddRefed<nsIContent> PresShell::GetSelectedContentForScrolling() const {
nsCOMPtr<nsIContent> selectedContent;
if (mSelection) {
Selection& domSelection = mSelection->NormalSelection();
selectedContent = nsIContent::FromNodeOrNull(domSelection.GetFocusNode());
}
return selectedContent.forget();
}
ScrollContainerFrame* PresShell::GetScrollContainerFrameToScrollForContent(
nsIContent* aContent, ScrollDirections aDirections) {
ScrollContainerFrame* scrollContainerFrame = nullptr;
if (aContent) {
nsIFrame* startFrame = aContent->GetPrimaryFrame();
if (startFrame) {
scrollContainerFrame = startFrame->GetScrollTargetFrame();
if (scrollContainerFrame) {
startFrame = scrollContainerFrame->GetScrolledFrame();
}
scrollContainerFrame =
nsLayoutUtils::GetNearestScrollableFrameForDirection(startFrame,
aDirections);
}
}
if (!scrollContainerFrame) {
scrollContainerFrame = GetRootScrollContainerFrame();
if (!scrollContainerFrame || !scrollContainerFrame->GetScrolledFrame()) {
return nullptr;
}
scrollContainerFrame = nsLayoutUtils::GetNearestScrollableFrameForDirection(
scrollContainerFrame->GetScrolledFrame(), aDirections);
}
return scrollContainerFrame;
}
ScrollContainerFrame* PresShell::GetScrollContainerFrameToScroll(
ScrollDirections aDirections) {
nsCOMPtr<nsIContent> content = GetContentForScrolling();
return GetScrollContainerFrameToScrollForContent(content.get(), aDirections);
}
void PresShell::CancelAllPendingReflows() { mDirtyRoots.Clear(); }
static bool DestroyFramesAndStyleDataFor(
Element* aElement, nsPresContext& aPresContext,
RestyleManager::IncludeRoot aIncludeRoot) {
bool didReconstruct =
aPresContext.FrameConstructor()->DestroyFramesFor(aElement);
RestyleManager::ClearServoDataFromSubtree(aElement, aIncludeRoot);
return didReconstruct;
}
void PresShell::SlotAssignmentWillChange(Element& aElement,
HTMLSlotElement* aOldSlot,
HTMLSlotElement* aNewSlot) {
MOZ_ASSERT(aOldSlot != aNewSlot);
if (MOZ_UNLIKELY(!mDidInitialize)) {
return;
}
// If the old slot is about to become empty and show fallback, let layout know
// that it needs to do work.
if (aOldSlot && aOldSlot->AssignedNodes().Length() == 1 &&
aOldSlot->HasChildren()) {
DestroyFramesForAndRestyle(aOldSlot);
}
// Ensure the new element starts off clean.
DestroyFramesAndStyleDataFor(&aElement, *mPresContext,
RestyleManager::IncludeRoot::Yes);
if (aNewSlot) {
// If the new slot will stop showing fallback content, we need to reframe it
// altogether.
if (aNewSlot->AssignedNodes().IsEmpty() && aNewSlot->HasChildren()) {
DestroyFramesForAndRestyle(aNewSlot);
// Otherwise we just care about the element, but we need to ensure that
// something takes care of traversing to the relevant slot, if needed.
} else if (aNewSlot->HasServoData() &&
!Servo_Element_IsDisplayNone(aNewSlot)) {
// Set the reframe bits...
aNewSlot->NoteDescendantsNeedFramesForServo();
aElement.SetFlags(NODE_NEEDS_FRAME);
// Now the style dirty bits. Note that we can't just do
// aElement.NoteDirtyForServo(), because the new slot is not setup yet.
aNewSlot->SetHasDirtyDescendantsForServo();
aNewSlot->NoteDirtySubtreeForServo();
}
}
}
#ifdef DEBUG
static void AssertNoFramesOrStyleDataInDescendants(Element& aElement) {
for (nsINode* node : ShadowIncludingTreeIterator(aElement)) {
nsIContent* c = nsIContent::FromNode(node);
if (c == &aElement) {
continue;
}
// FIXME(emilio): The <area> check is needed because of bug 135040.
MOZ_ASSERT(!c->GetPrimaryFrame() || c->IsHTMLElement(nsGkAtoms::area));
MOZ_ASSERT(!c->IsElement() || !c->AsElement()->HasServoData());
}
}
#endif
void PresShell::DestroyFramesForAndRestyle(Element* aElement) {
#ifdef DEBUG
auto postCondition = MakeScopeExit([&]() {
MOZ_ASSERT(!aElement->GetPrimaryFrame());
AssertNoFramesOrStyleDataInDescendants(*aElement);
});
#endif
MOZ_ASSERT(aElement);
if (!aElement->HasServoData()) {
// Nothing to do here, the element already is out of the flat tree or is not
// styled.
return;
}
// Mark ourselves as not safe to flush while we're doing frame destruction.
nsAutoScriptBlocker scriptBlocker;
++mChangeNestCount;
const bool didReconstruct = FrameConstructor()->DestroyFramesFor(aElement);
// Clear the style data from all the flattened tree descendants, but _not_
// from us, since otherwise we wouldn't see the reframe.
RestyleManager::ClearServoDataFromSubtree(aElement,
RestyleManager::IncludeRoot::No);
auto changeHint =
didReconstruct ? nsChangeHint(0) : nsChangeHint_ReconstructFrame;
mPresContext->RestyleManager()->PostRestyleEvent(
aElement, RestyleHint::RestyleSubtree(), changeHint);
--mChangeNestCount;
}
void PresShell::ShadowRootWillBeAttached(Element& aElement) {
#ifdef DEBUG
auto postCondition = MakeScopeExit(
[&]() { AssertNoFramesOrStyleDataInDescendants(aElement); });
#endif
if (!aElement.HasServoData()) {
// Nothing to do here, the element already is out of the flat tree or is not
// styled.
return;
}
if (!aElement.HasChildren()) {
// The element has no children, just avoid the work.
return;
}
// Mark ourselves as not safe to flush while we're doing frame destruction.
nsAutoScriptBlocker scriptBlocker;
++mChangeNestCount;
// NOTE(emilio): We use FlattenedChildIterator intentionally here (rather than
// StyleChildrenIterator), since we don't want to remove ::before / ::after
// content.
FlattenedChildIterator iter(&aElement);
nsCSSFrameConstructor* fc = FrameConstructor();
for (nsIContent* c = iter.GetNextChild(); c; c = iter.GetNextChild()) {
fc->DestroyFramesFor(c);
if (c->IsElement()) {
RestyleManager::ClearServoDataFromSubtree(c->AsElement());
}
}
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
accService->ScheduleAccessibilitySubtreeUpdate(this, &aElement);
}
#endif
--mChangeNestCount;
}
void PresShell::PostRecreateFramesFor(Element* aElement) {
if (MOZ_UNLIKELY(!mDidInitialize)) {
// Nothing to do here. In fact, if we proceed and aElement is the root, we
// will crash.
return;
}
mPresContext->RestyleManager()->PostRestyleEvent(
aElement, RestyleHint{0}, nsChangeHint_ReconstructFrame);
}
void PresShell::RestyleForAnimation(Element* aElement, RestyleHint aHint) {
// Now that we no longer have separate non-animation and animation
// restyles, this method having a distinct identity is less important,
// but it still seems useful to offer as a "more public" API and as a
// checkpoint for these restyles to go through.
mPresContext->RestyleManager()->PostRestyleEvent(aElement, aHint,
nsChangeHint(0));
}
void PresShell::SetForwardingContainer(const WeakPtr<nsDocShell>& aContainer) {
mForwardingContainer = aContainer;
}
void PresShell::ClearFrameRefs(nsIFrame* aFrame) {
mPresContext->EventStateManager()->ClearFrameRefs(aFrame);
AutoWeakFrame* weakFrame = mAutoWeakFrames;
while (weakFrame) {
AutoWeakFrame* prev = weakFrame->GetPreviousWeakFrame();
if (weakFrame->GetFrame() == aFrame) {
// This removes weakFrame from mAutoWeakFrames.
weakFrame->Clear(this);
}
weakFrame = prev;
}
AutoTArray<WeakFrame*, 4> toRemove;
for (WeakFrame* weakFrame : mWeakFrames) {
if (weakFrame->GetFrame() == aFrame) {
toRemove.AppendElement(weakFrame);
}
}
for (WeakFrame* weakFrame : toRemove) {
weakFrame->Clear(this);
}
}
UniquePtr<gfxContext> PresShell::CreateReferenceRenderingContext() {
if (mPresContext->IsScreen()) {
return gfxContext::CreateOrNull(
gfxPlatform::GetPlatform()->ScreenReferenceDrawTarget().get());
}
// We assume the devCtx has positive width and height for this call.
// However, width and height, may be outside of the reasonable range
// so rc may still be null.
nsDeviceContext* devCtx = mPresContext->DeviceContext();
return devCtx->CreateReferenceRenderingContext();
}
// https://html.spec.whatwg.org/#scroll-to-the-fragment-identifier
nsresult PresShell::GoToAnchor(const nsAString& aAnchorName,
const nsRange* aFirstTextDirective, bool aScroll,
ScrollFlags aAdditionalScrollFlags) {
if (!mDocument) {
return NS_ERROR_FAILURE;
}
const Element* root = mDocument->GetRootElement();
if (root && root->IsSVGElement(nsGkAtoms::svg)) {
// We need to execute this even if there is an empty anchor name
// so that any existing SVG fragment identifier effect is removed
if (SVGFragmentIdentifier::ProcessFragmentIdentifier(mDocument,
aAnchorName)) {
return NS_OK;
}
}
// Hold a reference to the ESM in case event dispatch tears us down.
RefPtr<EventStateManager> esm = mPresContext->EventStateManager();
// https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
// From "Monkeypatching HTML § 7.4.6.3 Scrolling to a fragment:"
// 3.4. If target is a range, then:
// 3.4.1 Set target to be the first common ancestor of target's start node and
// end node.
// 3.4.2 While target is non-null and is not an element, set target to
// target's parent.
// ------
// Common closest ancestor is not suitable here, as it can scroll to positions
// where no text directive is visible. Instead, scroll to the start container
// of the text directive.
// see https://bugzil.la/1906895 and
// https://github.com/WICG/scroll-to-text-fragment/issues/259
Element* textFragmentTargetElement = [&aFirstTextDirective]() -> Element* {
nsINode* node = aFirstTextDirective
? aFirstTextDirective->GetStartContainer()
: nullptr;
while (node && !node->IsElement()) {
node = node->GetParent();
}
return Element::FromNodeOrNull(node);
}();
const bool thereIsATextFragment = !!textFragmentTargetElement;
// 1. If there is no indicated part of the document, set the Document's target
// element to null.
//
// FIXME(emilio): Per spec empty fragment string should take the same
// code-path as "top"!
if (aAnchorName.IsEmpty() && !thereIsATextFragment) {
NS_ASSERTION(!aScroll, "can't scroll to empty anchor name");
esm->SetContentState(nullptr, ElementState::URLTARGET);
return NS_OK;
}
// 2. If the indicated part of the document is the top of the document,
// then:
// (handled below when `target` is null, and anchor is `top`)
// 3.1. Let target be element that is the indicated part of the document.
//
// https://html.spec.whatwg.org/#target-element
// https://html.spec.whatwg.org/#find-a-potential-indicated-element
RefPtr<Element> target = textFragmentTargetElement;
if (!target) {
target = nsContentUtils::GetTargetElement(mDocument, aAnchorName);
}
// 1. If there is no indicated part of the document, set the Document's
// target element to null.
// 2.1. Set the Document's target element to null.
// 3.2. Set the Document's target element to target.
esm->SetContentState(target, ElementState::URLTARGET);
// TODO: Spec probably needs a section to account for this.
if (ScrollContainerFrame* rootScroll = GetRootScrollContainerFrame()) {
if (rootScroll->DidHistoryRestore()) {
// Scroll position restored from history trumps scrolling to anchor.
aScroll = false;
rootScroll->ClearDidHistoryRestore();
}
}
if (target) {
// 3.4 Run the ancestor details revealing algorithm on target.
target->RevealAncestorClosedDetails();
// 3.5 Run the ancestor hidden-until-found revealing algorithm on target.
// https://html.spec.whatwg.org/#ancestor-hidden-until-found-revealing-algorithm
ErrorResult rv;
target->RevealAncestorHiddenUntilFoundAndFireBeforematchEvent(rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
if (aScroll) {
// https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
// From "Monkeypatching HTML § 7.4.6.3 Scrolling to a fragment:"
// 3.9 Let blockPosition be "center" if scrollTarget is a range, "start"
// otherwise.
// Implementation note: Use `ScrollSelectionIntoView` for text fragment,
// since the text fragment is stored as a `eTargetText` selection.
//
// 3.4. Scroll target into view, with behavior set to "auto", block set to
// "start", and inline set to "nearest".
// FIXME(emilio): Not all callers pass ScrollSmoothAuto (but we use auto
// smooth scroll for `top` regardless below, so maybe they should!).
ScrollingInteractionContext scrollToAnchorContext(true);
if (thereIsATextFragment) {
MOZ_TRY(ScrollSelectionIntoView(
SelectionType::eTargetText,
nsISelectionController::SELECTION_ANCHOR_REGION,
ScrollAxis(WhereToScroll::Center, WhenToScroll::Always),
ScrollAxis(),
ScrollFlags::AnchorScrollFlags | aAdditionalScrollFlags,
SelectionScrollMode::SyncFlush));
} else {
MOZ_TRY(ScrollContentIntoView(
target, ScrollAxis(WhereToScroll::Start, WhenToScroll::Always),
ScrollAxis(),
ScrollFlags::AnchorScrollFlags | aAdditionalScrollFlags));
}
if (ScrollContainerFrame* rootScroll = GetRootScrollContainerFrame()) {
mLastAnchorScrolledTo = target;
mLastAnchorScrollPositionY = rootScroll->GetScrollPosition().y;
mLastAnchorScrollType = thereIsATextFragment
? AnchorScrollType::TextDirective
: AnchorScrollType::Anchor;
}
}
{
// 3.6. Move the sequential focus navigation starting point to target.
//
// Move the caret to the anchor. That way tabbing will start from the new
// location.
//
// TODO(emilio): Do we want to do this even if aScroll is false?
//
// NOTE: Intentionally out of order for now with the focus steps, see
// https://github.com/whatwg/html/issues/7759
RefPtr<nsRange> jumpToRange = nsRange::Create(mDocument);
nsCOMPtr<nsIContent> nodeToSelect = target.get();
while (nodeToSelect->GetFirstChild()) {
nodeToSelect = nodeToSelect->GetFirstChild();
}
jumpToRange->SelectNodeContents(*nodeToSelect, IgnoreErrors());
RefPtr sel = &mSelection->NormalSelection();
MOZ_ASSERT(sel);
sel->RemoveAllRanges(IgnoreErrors());
sel->AddRangeAndSelectFramesAndNotifyListeners(*jumpToRange,
IgnoreErrors());
if (!StaticPrefs::layout_selectanchor()) {
// Use a caret (collapsed selection) at the start of the anchor.
sel->CollapseToStart(IgnoreErrors());
}
}
// 3.5. Run the focusing steps for target, with the Document's viewport as
// the fallback target.
//
// Note that ScrollContentIntoView flushes, so we don't need to do that
// again here. We also don't need to scroll again either.
//
// We intentionally focus the target only when aScroll is true, we need to
// sort out if the spec needs to differentiate these cases. When aScroll is
// false we still clear the focus unconditionally, that's legacy behavior,
// maybe we shouldn't do it.
//
// TODO(emilio): Do we really want to clear the focus even if aScroll is
// false?
const bool shouldFocusTarget = [&] {
if (!aScroll || thereIsATextFragment) {
return false;
}
nsIFrame* targetFrame = target->GetPrimaryFrame();
return targetFrame && targetFrame->IsFocusable();
}();
if (shouldFocusTarget) {
FocusOptions options;
options.mPreventScroll = true;
target->Focus(options, CallerType::NonSystem, IgnoreErrors());
} else if (RefPtr<nsIFocusManager> fm = nsFocusManager::GetFocusManager()) {
if (nsPIDOMWindowOuter* win = mDocument->GetWindow()) {
// Now focus the document itself if focus is on an element within it.
nsCOMPtr<mozIDOMWindowProxy> focusedWindow;
fm->GetFocusedWindow(getter_AddRefs(focusedWindow));
if (SameCOMIdentity(win, focusedWindow)) {
fm->ClearFocus(focusedWindow);
}
}
}
// If the target is an animation element, activate the animation
if (auto* animationElement = SVGAnimationElement::FromNode(target.get())) {
animationElement->ActivateByHyperlink();
}
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
nsIContent* a11yTarget = target;
if (thereIsATextFragment) {
// A text fragment starts in a text leaf node. `target` is the element
// parent, but there may be many other children of that element before
// the start of the text fragment. Explicitly use the start leaf node
// here to get a11y clients as close as possible to the fragment (on
// platforms which support this).
a11yTarget = nsIContent::FromNodeOrNull(
aFirstTextDirective->GetStartContainer());
if (!a11yTarget) {
a11yTarget = target;
}
}
accService->NotifyOfAnchorJumpTo(a11yTarget);
}
#endif
} else if (nsContentUtils::EqualsIgnoreASCIICase(aAnchorName, u"top"_ns)) {
// 2.2. Scroll to the beginning of the document for the Document.
ScrollContainerFrame* sf = GetRootScrollContainerFrame();
// Check |aScroll| after setting |rv| so we set |rv| to the same
// thing whether or not |aScroll| is true.
if (aScroll && sf) {
ScrollMode scrollMode =
sf->IsSmoothScroll() ? ScrollMode::SmoothMsd : ScrollMode::Instant;
// Scroll to the top of the page
sf->ScrollTo(nsPoint(0, 0), scrollMode);
}
} else {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
nsresult PresShell::ScrollToAnchor() {
NS_ASSERTION(mDidInitialize, "should have done initial reflow by now");
if (mLastAnchorScrollType == AnchorScrollType::Anchor) {
nsCOMPtr<nsIContent> lastAnchor = std::move(mLastAnchorScrolledTo);
if (!lastAnchor) {
return NS_OK;
}
ScrollContainerFrame* rootScroll = GetRootScrollContainerFrame();
if (!rootScroll ||
mLastAnchorScrollPositionY != rootScroll->GetScrollPosition().y) {
return NS_OK;
}
return ScrollContentIntoView(
lastAnchor, ScrollAxis(WhereToScroll::Start, WhenToScroll::Always),
ScrollAxis(), ScrollFlags::AnchorScrollFlags);
}
return ScrollSelectionIntoView(
SelectionType::eTargetText,
nsISelectionController::SELECTION_ANCHOR_REGION,
ScrollAxis(WhereToScroll::Center, WhenToScroll::Always), ScrollAxis(),
ScrollFlags::AnchorScrollFlags, SelectionScrollMode::SyncFlush);
}
/*
* Helper (per-continuation) for ScrollContentIntoView.
*
* @param aContainerFrame [in] the frame which aRect is relative to
* @param aFrame [in] Frame whose bounds should be unioned
* @param aUseWholeLineHeightForInlines [in] if true, then for inline frames
* we should include the top of the line in the added rectangle
* @param aRect [inout] rect into which its bounds should be unioned
* @param aHaveRect [inout] whether aRect contains data yet
* @param aPrevBlock [inout] the block aLines is a line iterator for
* @param aLines [inout] the line iterator we're using
* @param aCurLine [inout] the line to start looking from in this iterator
*/
static void AccumulateFrameBounds(nsIFrame* aContainerFrame, nsIFrame* aFrame,
bool aUseWholeLineHeightForInlines,
nsRect& aRect, bool& aHaveRect,
nsIFrame*& aPrevBlock,
nsILineIterator*& aLines, int32_t& aCurLine) {
nsIFrame* frame = aFrame;
nsRect frameBounds = nsRect(nsPoint(0, 0), aFrame->GetSize());
// If this is an inline frame and either the bounds height is 0 (quirks
// layout model) or aUseWholeLineHeightForInlines is set, we need to
// change the top of the bounds to include the whole line.
if (frameBounds.height == 0 || aUseWholeLineHeightForInlines) {
nsIFrame* prevFrame = aFrame;
nsIFrame* f = aFrame;
while (f && f->IsLineParticipant() && !f->IsTransformed() &&
!f->IsAbsPosContainingBlock()) {
prevFrame = f;
f = prevFrame->GetParent();
}
if (f != aFrame && f && f->IsBlockFrame()) {
// find the line containing aFrame and increase the top of |offset|.
if (f != aPrevBlock) {
aLines = f->GetLineIterator();
aPrevBlock = f;
aCurLine = 0;
}
if (aLines) {
int32_t index = aLines->FindLineContaining(prevFrame, aCurLine);
if (index >= 0) {
auto line = aLines->GetLine(index).unwrap();
frameBounds += frame->GetOffsetTo(f);
frame = f;
if (line.mLineBounds.y < frameBounds.y) {
frameBounds.height = frameBounds.YMost() - line.mLineBounds.y;
frameBounds.y = line.mLineBounds.y;
}
}
}
}
}
nsRect transformedBounds = nsLayoutUtils::TransformFrameRectToAncestor(
frame, frameBounds, aContainerFrame);
if (aHaveRect) {
// We can't use nsRect::UnionRect since it drops empty rects on
// the floor, and we need to include them. (Thus we need
// aHaveRect to know when to drop the initial value on the floor.)
aRect = aRect.UnionEdges(transformedBounds);
} else {
aHaveRect = true;
aRect = transformedBounds;
}
}
static bool ComputeNeedToScroll(WhenToScroll aWhenToScroll, nscoord aLineSize,
nscoord aRectMin, nscoord aRectMax,
nscoord aViewMin, nscoord aViewMax) {
// See how the rect should be positioned in a given axis.
switch (aWhenToScroll) {
case WhenToScroll::Always:
// The caller wants the frame as visible as possible
return true;
case WhenToScroll::IfNotVisible:
if (aLineSize > (aRectMax - aRectMin)) {
// If the line size is greater than the size of the rect
// to scroll into view, do not use the line size to determine
// if we need to scroll.
aLineSize = 0;
}
// Scroll only if no part of the frame is visible in this view.
return aRectMax - aLineSize <= aViewMin ||
aRectMin + aLineSize >= aViewMax;
case WhenToScroll::IfNotFullyVisible:
// Scroll only if part of the frame is hidden and more can fit in view
return !(aRectMin >= aViewMin && aRectMax <= aViewMax) &&
std::min(aViewMax, aRectMax) - std::max(aRectMin, aViewMin) <
aViewMax - aViewMin;
}
return false;
}
static nscoord ComputeWhereToScroll(WhereToScroll aWhereToScroll,
nscoord aOriginalCoord, nscoord aRectMin,
nscoord aRectMax, nscoord aViewMin,
nscoord aViewMax, nscoord* aRangeMin,
nscoord* aRangeMax) {
nscoord resultCoord = aOriginalCoord;
nscoord scrollPortLength = aViewMax - aViewMin;
if (!aWhereToScroll.mPercentage) {
// Scroll the minimum amount necessary to show as much as possible of the
// frame. If the frame is too large, don't hide any initially visible part
// of it.
nscoord min = std::min(aRectMin, aRectMax - scrollPortLength);
nscoord max = std::max(aRectMin, aRectMax - scrollPortLength);
resultCoord = std::clamp(aOriginalCoord, min, max);
} else {
float percent = aWhereToScroll.mPercentage.value() / 100.0f;
nscoord frameAlignCoord =
NSToCoordRound(aRectMin + (aRectMax - aRectMin) * percent);
resultCoord = NSToCoordRound(frameAlignCoord - scrollPortLength * percent);
}
// Force the scroll range to extend to include resultCoord.
*aRangeMin = std::min(resultCoord, aRectMax - scrollPortLength);
*aRangeMax = std::max(resultCoord, aRectMin);
return resultCoord;
}
static WhereToScroll GetApplicableWhereToScroll(
const ScrollContainerFrame* aScrollContainerFrame,
const nsIFrame* aScrollableFrame, const nsIFrame* aTarget,
ScrollDirection aScrollDirection, WhereToScroll aOriginal) {
MOZ_ASSERT(do_QueryFrame(aScrollContainerFrame) == aScrollableFrame);
if (aTarget == aScrollableFrame) {
return aOriginal;
}
StyleScrollSnapAlignKeyword align =
aScrollDirection == ScrollDirection::eHorizontal
? aScrollContainerFrame->GetScrollSnapAlignFor(aTarget).first
: aScrollContainerFrame->GetScrollSnapAlignFor(aTarget).second;
switch (align) {
case StyleScrollSnapAlignKeyword::None:
return aOriginal;
case StyleScrollSnapAlignKeyword::Start:
return WhereToScroll::Start;
case StyleScrollSnapAlignKeyword::Center:
return WhereToScroll::Center;
case StyleScrollSnapAlignKeyword::End:
return WhereToScroll::End;
}
return aOriginal;
}
static ScrollMode GetScrollModeForScrollIntoView(
const ScrollContainerFrame* aScrollContainerFrame,
ScrollFlags aScrollFlags) {
ScrollMode scrollMode = ScrollMode::Instant;
// Default to an instant scroll, but if the scroll behavior given is "auto"
// or "smooth", use that as the specified behavior. If the user has disabled
// smooth scrolls, a given mode of "auto" or "smooth" should not result in
// a smooth scroll.
ScrollBehavior behavior = ScrollBehavior::Instant;
if (aScrollFlags & ScrollFlags::ScrollSmooth) {
behavior = ScrollBehavior::Smooth;
} else if (aScrollFlags & ScrollFlags::ScrollSmoothAuto) {
behavior = ScrollBehavior::Auto;
}
if (aScrollContainerFrame->IsSmoothScroll(behavior)) {
scrollMode = ScrollMode::SmoothMsd;
}
return scrollMode;
}
/**
* This function takes a scroll container frame, a rect in the coordinate system
* of the scrolled frame, and a desired percentage-based scroll
* position and attempts to scroll the rect to that position in the
* visual viewport.
*
* This needs to work even if aRect has a width or height of zero.
*/
static Maybe<nsPoint> ScrollToShowRect(
ScrollContainerFrame* aScrollContainerFrame,
const nsIFrame* aScrollableFrame, const nsIFrame* aTarget,
const nsRect& aRect, const Sides aScrollPaddingSkipSides,
const nsMargin& aMargin, ScrollAxis aVertical, ScrollAxis aHorizontal,
ScrollFlags aScrollFlags) {
nsPoint scrollPt = aScrollContainerFrame->GetVisualViewportOffset();
const nsPoint originalScrollPt = scrollPt;
const nsRect visibleRect(scrollPt,
aScrollContainerFrame->GetVisualViewportSize());
const nsMargin padding = [&] {
nsMargin p = aScrollContainerFrame->GetScrollPadding();
p.ApplySkipSides(aScrollPaddingSkipSides);
return p + aMargin;
}();
const nsRect rectToScrollIntoView = [&] {
nsRect r(aRect);
r.Inflate(padding);
return r.Intersect(aScrollContainerFrame->GetScrolledRect());
}();
nsSize lineSize;
// Don't call GetLineScrollAmount unless we actually need it. Not only
// does this save time, but it's not safe to call GetLineScrollAmount
// during reflow (because it depends on font size inflation and doesn't
// use the in-reflow-safe font-size inflation path). If we did call it,
// it would assert and possible give the wrong result.
if (aVertical.mWhenToScroll == WhenToScroll::IfNotVisible ||
aHorizontal.mWhenToScroll == WhenToScroll::IfNotVisible) {
lineSize = aScrollContainerFrame->GetLineScrollAmount();
}
ScrollStyles ss = aScrollContainerFrame->GetScrollStyles();
nsRect allowedRange(scrollPt, nsSize(0, 0));
ScrollDirections directions =
aScrollContainerFrame->GetAvailableScrollingDirections();
if (((aScrollFlags & ScrollFlags::ScrollOverflowHidden) ||
ss.mVertical != StyleOverflow::Hidden) &&
(!aVertical.mOnlyIfPerceivedScrollableDirection ||
(directions.contains(ScrollDirection::eVertical)))) {
if (ComputeNeedToScroll(aVertical.mWhenToScroll, lineSize.height, aRect.y,
aRect.YMost(), visibleRect.y + padding.top,
visibleRect.YMost() - padding.bottom)) {
// If the scroll-snap-align on the frame is valid, we need to respect it.
WhereToScroll whereToScroll = GetApplicableWhereToScroll(
aScrollContainerFrame, aScrollableFrame, aTarget,
ScrollDirection::eVertical, aVertical.mWhereToScroll);
nscoord maxHeight;
scrollPt.y = ComputeWhereToScroll(
whereToScroll, scrollPt.y, rectToScrollIntoView.y,
rectToScrollIntoView.YMost(), visibleRect.y, visibleRect.YMost(),
&allowedRange.y, &maxHeight);
allowedRange.height = maxHeight - allowedRange.y;
}
}
if (((aScrollFlags & ScrollFlags::ScrollOverflowHidden) ||
ss.mHorizontal != StyleOverflow::Hidden) &&
(!aHorizontal.mOnlyIfPerceivedScrollableDirection ||
(directions.contains(ScrollDirection::eHorizontal)))) {
if (ComputeNeedToScroll(aHorizontal.mWhenToScroll, lineSize.width, aRect.x,
aRect.XMost(), visibleRect.x + padding.left,
visibleRect.XMost() - padding.right)) {
// If the scroll-snap-align on the frame is valid, we need to respect it.
WhereToScroll whereToScroll = GetApplicableWhereToScroll(
aScrollContainerFrame, aScrollableFrame, aTarget,
ScrollDirection::eHorizontal, aHorizontal.mWhereToScroll);
nscoord maxWidth;
scrollPt.x = ComputeWhereToScroll(
whereToScroll, scrollPt.x, rectToScrollIntoView.x,
rectToScrollIntoView.XMost(), visibleRect.x, visibleRect.XMost(),
&allowedRange.x, &maxWidth);
allowedRange.width = maxWidth - allowedRange.x;
}
}
// If we don't need to scroll, then don't try since it might cancel
// a current smooth scroll operation.
if (scrollPt == originalScrollPt) {
return Nothing();
}
ScrollMode scrollMode =
GetScrollModeForScrollIntoView(aScrollContainerFrame, aScrollFlags);
nsIFrame* frame = do_QueryFrame(aScrollContainerFrame);
AutoWeakFrame weakFrame(frame);
aScrollContainerFrame->ScrollTo(scrollPt, scrollMode, &allowedRange,
ScrollSnapFlags::IntendedEndPosition,
aScrollFlags & ScrollFlags::TriggeredByScript
? ScrollTriggeredByScript::Yes
: ScrollTriggeredByScript::No);
return Some(scrollPt);
}
nsresult PresShell::ScrollContentIntoView(nsIContent* aContent,
ScrollAxis aVertical,
ScrollAxis aHorizontal,
ScrollFlags aScrollFlags) {
NS_ENSURE_TRUE(aContent, NS_ERROR_NULL_POINTER);
RefPtr<Document> composedDoc = aContent->GetComposedDoc();
NS_ENSURE_STATE(composedDoc);
NS_ASSERTION(mDidInitialize, "should have done initial reflow by now");
if (mContentToScrollTo) {
mContentToScrollTo->RemoveProperty(nsGkAtoms::scrolling);
}
mContentToScrollTo = aContent;
ScrollIntoViewData* data = new ScrollIntoViewData();
data->mContentScrollVAxis = aVertical;
data->mContentScrollHAxis = aHorizontal;
data->mContentToScrollToFlags = aScrollFlags;
if (NS_FAILED(mContentToScrollTo->SetProperty(
nsGkAtoms::scrolling, data,
nsINode::DeleteProperty<PresShell::ScrollIntoViewData>))) {
mContentToScrollTo = nullptr;
}
// If the target frame has an ancestor of a `content-visibility: auto`
// element ensure that it is laid out, so that the boundary rectangle is
// correct.
// Additionally, ensure that all ancestor elements with 'content-visibility:
// auto' are set to 'visible'. so that they are laid out as visible before
// scrolling, improving the accuracy of the scroll position, especially when
// the scroll target is within the overflow area. And here invoking
// 'SetTemporarilyVisibleForScrolledIntoViewDescendant' would make the
// intersection observer knows that it should generate entries for these
// c-v:auto ancestors, so that the content relevancy could be checked again
// after scrolling. https://drafts.csswg.org/css-contain-2/#cv-notes
bool reflowedForHiddenContent = false;
if (mContentToScrollTo) {
if (nsIFrame* frame = mContentToScrollTo->GetPrimaryFrame()) {
bool hasContentVisibilityAutoAncestor = false;
auto* ancestor = frame->GetClosestContentVisibilityAncestor(
nsIFrame::IncludeContentVisibility::Auto);
while (ancestor) {
if (auto* element = Element::FromNodeOrNull(ancestor->GetContent())) {
hasContentVisibilityAutoAncestor = true;
element->SetTemporarilyVisibleForScrolledIntoViewDescendant(true);
element->SetVisibleForContentVisibility(true);
}
ancestor = ancestor->GetClosestContentVisibilityAncestor(
nsIFrame::IncludeContentVisibility::Auto);
}
if (hasContentVisibilityAutoAncestor) {
UpdateHiddenContentInForcedLayout(frame);
// TODO: There might be the other already scheduled relevancy updates,
// other than caused be scrollIntoView.
UpdateContentRelevancyImmediately(ContentRelevancyReason::Visible);
reflowedForHiddenContent = ReflowForHiddenContentIfNeeded();
}
}
}
if (!reflowedForHiddenContent) {
// Flush layout and attempt to scroll in the process.
if (PresShell* presShell = composedDoc->GetPresShell()) {
presShell->SetNeedLayoutFlush();
}
composedDoc->FlushPendingNotifications(FlushType::InterruptibleLayout);
}
// If mContentToScrollTo is non-null, that means we interrupted the reflow
// (or suppressed it altogether because we're suppressing interruptible
// flushes right now) and won't necessarily get the position correct, but do
// a best-effort scroll here. The other option would be to do this inside
// FlushPendingNotifications, but I'm not sure the repeated scrolling that
// could trigger if reflows keep getting interrupted would be more desirable
// than a single best-effort scroll followed by one final scroll on the first
// completed reflow.
if (mContentToScrollTo) {
DoScrollContentIntoView();
}
return NS_OK;
}
static nsMargin GetScrollMargin(const nsIFrame* aFrame) {
MOZ_ASSERT(aFrame);
// If we're focusing something that can't be targeted by content, allow
// content to customize the margin.
//
// TODO: This is also a bit of an issue for delegated focus, see
// https://github.com/whatwg/html/issues/7033.
if (aFrame->GetContent() && aFrame->GetContent()->ChromeOnlyAccess()) {
// XXX Should we use nsIContent::FindFirstNonChromeOnlyAccessContent()
// instead of nsINode::GetClosestNativeAnonymousSubtreeRootParentOrHost()?
if (const nsIContent* userContent =
aFrame->GetContent()
->GetClosestNativeAnonymousSubtreeRootParentOrHost()) {
if (const nsIFrame* frame = userContent->GetPrimaryFrame()) {
return frame->StyleMargin()->GetScrollMargin();
}
}
}
return aFrame->StyleMargin()->GetScrollMargin();
}
void PresShell::DoScrollContentIntoView() {
NS_ASSERTION(mDidInitialize, "should have done initial reflow by now");
nsIFrame* frame = mContentToScrollTo->GetPrimaryFrame();
if (!frame || frame->IsHiddenByContentVisibilityOnAnyAncestor(
nsIFrame::IncludeContentVisibility::Hidden)) {
mContentToScrollTo->RemoveProperty(nsGkAtoms::scrolling);
mContentToScrollTo = nullptr;
return;
}
if (frame->HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
// The reflow flush before this scroll got interrupted, and this frame's
// coords and size are all zero, and it has no content showing anyway.
// Don't bother scrolling to it. We'll try again when we finish up layout.
return;
}
auto* data = static_cast<ScrollIntoViewData*>(
mContentToScrollTo->GetProperty(nsGkAtoms::scrolling));
if (MOZ_UNLIKELY(!data)) {
mContentToScrollTo = nullptr;
return;
}
ScrollFrameIntoView(frame, Nothing(), data->mContentScrollVAxis,
data->mContentScrollHAxis, data->mContentToScrollToFlags);
}
static bool NeedToVisuallyScroll(const nsSize& aLayoutViewportSize,
const nsRect& aPositionFixedRect) {
// position:fixed elements are fixed to the layout viewport, thus the
// coordinate system is (0, 0) origin.
// (and the maximum visible position is the layout viewport size, elements
// outside of the size will never be laid out)
const nsRect layoutViewport = nsRect(nsPoint(), aLayoutViewportSize);
// `BaseRect::Intersects(const Sub& aRect)` does return false if `aRect` is
// empty, but we do want to visually scroll to empty position:fixed elements
// if the elements are inside the layout viewport.
if (aPositionFixedRect.IsEmpty()) {
if (aPositionFixedRect.x > layoutViewport.XMost() ||
aPositionFixedRect.XMost() < layoutViewport.x ||
aPositionFixedRect.y > layoutViewport.YMost() ||
aPositionFixedRect.YMost() < layoutViewport.y) {
return false;
}
return true;
}
if (!layoutViewport.Intersects(aPositionFixedRect)) {
return false;
}
return true;
}
void PresShell::ScrollFrameIntoVisualViewport(Maybe<nsPoint>& aDestination,
const nsRect& aPositionFixedRect,
ScrollFlags aScrollFlags) {
PresShell* root = GetRootPresShell();
if (!root) {
return;
}
if (!root->GetPresContext()->IsRootContentDocumentCrossProcess()) {
return;
}
ScrollContainerFrame* rootScrollContainer =
root->GetRootScrollContainerFrame();
if (!rootScrollContainer) {
return;
}
if (!aDestination) {
// If we have in the top level content document but we didn't reach to
// the root scroll container in the frame tree walking up loop in
// ScrollFrameIntoView, it means the target element is inside a
// position:fixed subtree.
if (!StaticPrefs::layout_scroll_fixed_content_into_view_visually()) {
return;
}
const nsSize visualViewportSize =
rootScrollContainer->GetVisualViewportSize();
const nsSize layoutViewportSize = root->GetLayoutViewportSize();
const nsRect layoutViewport = nsRect(nsPoint(), layoutViewportSize);
// `positon:fixed` element are attached/fixed to the ViewportFrame, which is
// the parent of the root scroll container frame, thus what we need here is
// the visible area of the position:fixed element inside the root scroll
// container frame.
// For example, if the top left position of the fixed element is (-100,
// -100), it's outside of the scrollable range either in the layout viewport
// or the visual viewport. Likewise, if the right bottom position of the
// fixed element is (110vw, 110vh), it's also outside of the scrollable
// range.
const nsRect clampedPositionFixedRect =
aPositionFixedRect.MoveInsideAndClamp(layoutViewport);
// If the position:fixed element is already inside the visual viewport, we
// don't need to scroll visually.
if (clampedPositionFixedRect.y >= 0 &&
clampedPositionFixedRect.YMost() <= visualViewportSize.height &&
clampedPositionFixedRect.x >= 0 &&
clampedPositionFixedRect.XMost() <= visualViewportSize.width) {
return;
}
// If the position:fixed element is totally outside of the the layout
// viewport, it will never be in the viewport.
if (!NeedToVisuallyScroll(layoutViewportSize, aPositionFixedRect)) {
return;
}
// Offset the position:fixed element position by the layout scroll
// position because the position:fixed origin (0, 0) is the layout scroll
// position. Otherwise if we've already scrolled, this scrollIntoView
// operaiton will jump back to near (0, 0) position.
// Bug 1947470: We need to calculate the destination with `WhereToScroll`
// options.
const nsPoint layoutOffset = rootScrollContainer->GetScrollPosition();
aDestination = Some(aPositionFixedRect.TopLeft() + layoutOffset);
}
// NOTE: It seems chrome doesn't respect the root element's
// scroll-behavior for visual scrolling.
ScrollMode scrollMode =
GetScrollModeForScrollIntoView(rootScrollContainer, aScrollFlags);
root->ScrollToVisual(*aDestination, FrameMetrics::eMainThread, scrollMode);
}
bool PresShell::ScrollFrameIntoView(
nsIFrame* aTargetFrame, const Maybe<nsRect>& aKnownRectRelativeToTarget,
ScrollAxis aVertical, ScrollAxis aHorizontal, ScrollFlags aScrollFlags) {
// If the AxesAreLogical flag is set, the aVertical and aHorizontal params
// actually refer to block and inline axes respectively, so we resolve them
// to physical axes/directions here.
// XXX Maybe we should convert more of the following code to logical axes,
// if it's convenient for more callers to work that way?
if (aScrollFlags & ScrollFlags::AxesAreLogical) {
// The aVertical parameter actually refers to the element's block axis,
// and aHorizontal to its inline axis. Potentially reverse/swap them,
// according to its writing mode and directionality.
WritingMode wm = aTargetFrame->GetWritingMode();
if (wm.IsVerticalRL()) {
// Reverse the block-axis percentage.
if (aVertical.mWhereToScroll.mPercentage) {
aVertical.mWhereToScroll.mPercentage =
Some(100 - aVertical.mWhereToScroll.mPercentage.value());
}
}
if (wm.IsInlineReversed()) {
// Reverse the inline-axis percentage.
if (aHorizontal.mWhereToScroll.mPercentage) {
aHorizontal.mWhereToScroll.mPercentage =
Some(100 - aHorizontal.mWhereToScroll.mPercentage.value());
}
}
if (wm.IsVertical()) {
std::swap(aVertical, aHorizontal);
}
// Remove the AxesAreLogical flag, to make it clear that methods we call
// always get physical axes from here on.
aScrollFlags &= ~ScrollFlags::AxesAreLogical;
}
// The scroll margin only applies to the whole bounds of the element, so don't
// apply it if we get an arbitrary rect / point to scroll to.
const nsMargin scrollMargin =
aKnownRectRelativeToTarget ? nsMargin() : GetScrollMargin(aTargetFrame);
Sides skipPaddingSides;
const auto MaybeSkipPaddingSides = [&](nsIFrame* aFrame) {
if (!aFrame->IsStickyPositioned()) {
return;
}
const nsPoint pos = aFrame->GetPosition();
const nsPoint normalPos = aFrame->GetNormalPosition();
if (pos == normalPos) {
return; // Frame is not stuck.
}
// If we're targetting a sticky element, make sure not to apply
// scroll-padding on the direction we're stuck.
const auto* stylePosition = aFrame->StylePosition();
const auto anchorResolutionParams =
AnchorPosOffsetResolutionParams::UseCBFrameSize(
AnchorPosResolutionParams::From(aFrame));
for (auto side : AllPhysicalSides()) {
if (stylePosition->GetAnchorResolvedInset(side, anchorResolutionParams)
->IsAuto()) {
continue;
}
// See if this axis is stuck.
const bool yAxis = side == eSideTop || side == eSideBottom;
const bool stuck = yAxis ? pos.y != normalPos.y : pos.x != normalPos.x;
if (!stuck) {
continue;
}
skipPaddingSides |= SideToSideBit(side);
}
};
nsIFrame* container = aTargetFrame;
bool inPositionFixedSubtree = false;
auto isPositionFixed = [&](const nsIFrame* aFrame) -> bool {
return aFrame->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
nsLayoutUtils::IsReallyFixedPos(aFrame);
};
// This function needs to work even if rect has a width or height of 0.
nsRect rect = [&] {
if (aKnownRectRelativeToTarget) {
return *aKnownRectRelativeToTarget;
}
MaybeSkipPaddingSides(aTargetFrame);
while (nsIFrame* parent = container->GetParent()) {
if (isPositionFixed(container)) {
inPositionFixedSubtree = true;
}
container = parent;
if (container->IsScrollContainerOrSubclass()) {
// We really just need a non-fragmented frame so that we can accumulate
// the bounds of all our continuations relative to it. We shouldn't jump
// out of our nearest scrollable frame, and that's an ok reference
// frame, so try to use that, or the root frame if there's nothing to
// scroll in this document.
break;
}
MaybeSkipPaddingSides(container);
}
MOZ_DIAGNOSTIC_ASSERT(container);
nsRect targetFrameBounds;
{
bool haveRect = false;
const bool useWholeLineHeightForInlines =
aVertical.mWhenToScroll != WhenToScroll::IfNotFullyVisible;
AutoAssertNoDomMutations
guard; // Ensure use of nsILineIterators is safe.
nsIFrame* prevBlock = nullptr;
// Reuse the same line iterator across calls to AccumulateFrameBounds.
// We set it every time we detect a new block (stored in prevBlock).
nsILineIterator* lines = nullptr;
// The last line we found a continuation on in |lines|. We assume that
// later continuations cannot come on earlier lines.
int32_t curLine = 0;
nsIFrame* frame = aTargetFrame;
do {
AccumulateFrameBounds(container, frame, useWholeLineHeightForInlines,
targetFrameBounds, haveRect, prevBlock, lines,
curLine);
} while ((frame = frame->GetNextContinuation()));
}
return targetFrameBounds;
}();
bool didScroll = false;
const nsIFrame* target = aTargetFrame;
Maybe<nsPoint> rootScrollDestination;
// Walk up the frame hierarchy scrolling the rect into view and
// keeping rect relative to container
do {
if (isPositionFixed(container)) {
inPositionFixedSubtree = true;
}
if (ScrollContainerFrame* sf = do_QueryFrame(container)) {
nsPoint oldPosition = sf->GetScrollPosition();
nsRect targetRect = rect;
// Inflate the scrolled rect by the container's padding in each dimension,
// unless we have 'overflow-clip-box-*: content-box' in that dimension.
auto* disp = container->StyleDisplay();
if (disp->mOverflowClipBoxBlock == StyleOverflowClipBox::ContentBox ||
disp->mOverflowClipBoxInline == StyleOverflowClipBox::ContentBox) {
WritingMode wm = container->GetWritingMode();
bool cbH = (wm.IsVertical() ? disp->mOverflowClipBoxBlock
: disp->mOverflowClipBoxInline) ==
StyleOverflowClipBox::ContentBox;
bool cbV = (wm.IsVertical() ? disp->mOverflowClipBoxInline
: disp->mOverflowClipBoxBlock) ==
StyleOverflowClipBox::ContentBox;
nsMargin padding = container->GetUsedPadding();
if (!cbH) {
padding.left = padding.right = nscoord(0);
}
if (!cbV) {
padding.top = padding.bottom = nscoord(0);
}
targetRect.Inflate(padding);
}
targetRect -= sf->GetScrolledFrame()->GetPosition();
{
AutoWeakFrame wf(container);
Maybe<nsPoint> destination = ScrollToShowRect(
sf, container, target, targetRect, skipPaddingSides, scrollMargin,
aVertical, aHorizontal, aScrollFlags);
if (!wf.IsAlive()) {
return didScroll;
}
if (sf->IsRootScrollFrameOfDocument() &&
sf->PresContext()->IsRootContentDocumentCrossProcess()) {
rootScrollDestination = destination;
}
}
nsPoint newPosition = sf->LastScrollDestination();
// If the scroll position increased, that means our content moved up,
// so our rect's offset should decrease
rect += oldPosition - newPosition;
if (oldPosition != newPosition) {
didScroll = true;
}
// only scroll one container when this flag is set
if (aScrollFlags & ScrollFlags::ScrollFirstAncestorOnly) {
break;
}
// This scroll container will be the next target element in the nearest
// ancestor scroll container.
target = container;
// We found a sticky scroll container, we shouldn't skip that side
// anymore.
skipPaddingSides = {};
}
MaybeSkipPaddingSides(container);
nsIFrame* parent = container->GetParent();
NS_ASSERTION(parent || !container->IsTransformed(),
"viewport shouldnt be transformed");
if (parent && container->IsTransformed()) {
rect =
nsLayoutUtils::TransformFrameRectToAncestor(container, rect, parent);
} else {
rect += container->GetPosition();
}
if (!parent && !(aScrollFlags & ScrollFlags::ScrollNoParentFrames)) {
nsPoint extraOffset(0, 0);
int32_t APD = container->PresContext()->AppUnitsPerDevPixel();
parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(container,
&extraOffset);
if (parent) {
int32_t parentAPD = parent->PresContext()->AppUnitsPerDevPixel();
rect = rect.ScaleToOtherAppUnitsRoundOut(APD, parentAPD);
rect += extraOffset;
} else {
nsCOMPtr<nsIDocShell> docShell =
container->PresContext()->GetDocShell();
if (BrowserChild* browserChild = BrowserChild::GetFrom(docShell)) {
// Defer to the parent document if this is an out-of-process iframe.
Unused << browserChild->SendScrollRectIntoView(
rect, aVertical, aHorizontal, aScrollFlags, APD);
}
}
}
container = parent;
} while (container);
// If this is inside the top level content document process (and a direct
// descendant of it), also call ScrollToVisual() since we want to
// scroll the rect into view visually, and that may require scrolling
// the visual viewport in scenarios where there is not enough layout
// scroll range.
if (!rootScrollDestination && !inPositionFixedSubtree) {
return didScroll;
}
ScrollFrameIntoVisualViewport(rootScrollDestination, rect, aScrollFlags);
return didScroll;
}
void PresShell::SchedulePaint() {
if (MOZ_UNLIKELY(mIsDestroying)) {
return;
}
if (nsPresContext* presContext = GetPresContext()) {
presContext->RefreshDriver()->SchedulePaint();
}
}
void PresShell::DispatchSynthMouseOrPointerMove(
WidgetMouseEvent* aMouseOrPointerMoveEvent) {
AUTO_PROFILER_TRACING_MARKER_DOCSHELL("Paint",
"DispatchSynthMouseOrPointerMove",
GRAPHICS, mPresContext->GetDocShell());
nsEventStatus status = nsEventStatus_eIgnore;
nsView* targetView = nsView::GetViewFor(aMouseOrPointerMoveEvent->mWidget);
if (!targetView) {
return;
}
RefPtr<nsViewManager> viewManager = targetView->GetViewManager();
viewManager->DispatchEvent(aMouseOrPointerMoveEvent, targetView, &status);
}
void PresShell::ClearMouseCaptureOnView(nsView* aView) {
if (nsIContent* capturingContent = GetCapturingContent()) {
if (aView) {
// if a view was specified, ensure that the captured content is within
// this view.
nsIFrame* frame = capturingContent->GetPrimaryFrame();
if (frame) {
nsView* view = frame->GetClosestView();
// if there is no view, capturing won't be handled any more, so
// just release the capture.
if (view) {
do {
if (view == aView) {
ReleaseCapturingContent();
// the view containing the captured content likely disappeared so
// disable capture for now.
AllowMouseCapture(false);
break;
}
view = view->GetParent();
} while (view);
// return if the view wasn't found
return;
}
}
}
ReleaseCapturingContent();
}
// disable mouse capture until the next mousedown as a dialog has opened
// or a drag has started. Otherwise, someone could start capture during
// the modal dialog or drag.
AllowMouseCapture(false);
}
void PresShell::ClearMouseCapture() {
ReleaseCapturingContent();
AllowMouseCapture(false);
}
void PresShell::ClearMouseCapture(nsIFrame* aFrame) {
MOZ_ASSERT(aFrame);
nsIContent* capturingContent = GetCapturingContent();
if (!capturingContent) {
return;
}
nsIFrame* capturingFrame = capturingContent->GetPrimaryFrame();
const bool shouldClear =
!capturingFrame ||
nsLayoutUtils::IsAncestorFrameCrossDocInProcess(aFrame, capturingFrame);
if (shouldClear) {
ClearMouseCapture();
}
}
nsresult PresShell::CaptureHistoryState(nsILayoutHistoryState** aState) {
MOZ_ASSERT(nullptr != aState, "null state pointer");
// We actually have to mess with the docshell here, since we want to
// store the state back in it.
// XXXbz this isn't really right, since this is being called in the
// content viewer's Hide() method... by that point the docshell's
// state could be wrong. We should sort out a better ownership
// model for the layout history state.
nsCOMPtr<nsIDocShell> docShell(mPresContext->GetDocShell());
if (!docShell) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsILayoutHistoryState> historyState;
docShell->GetLayoutHistoryState(getter_AddRefs(historyState));
if (!historyState) {
// Create the document state object
historyState = NS_NewLayoutHistoryState();
docShell->SetLayoutHistoryState(historyState);
}
*aState = historyState;
NS_IF_ADDREF(*aState);
// Capture frame state for the entire frame hierarchy
nsIFrame* rootFrame = mFrameConstructor->GetRootFrame();
if (!rootFrame) {
return NS_OK;
}
mFrameConstructor->CaptureFrameState(rootFrame, historyState);
return NS_OK;
}
void PresShell::ScheduleBeforeFirstPaint() {
if (!mDocument->IsResourceDoc()) {
// Notify observers that a new page is about to be drawn. Execute this
// as soon as it is safe to run JS, which is guaranteed to be before we
// go back to the event loop and actually draw the page.
MOZ_LOG(gLog, LogLevel::Debug,
("PresShell::ScheduleBeforeFirstPaint this=%p", this));
nsContentUtils::AddScriptRunner(
new nsBeforeFirstPaintDispatcher(mDocument));
}
}
void PresShell::UnsuppressAndInvalidate() {
// Note: We ignore the EnsureVisible check for resource documents, because
// they won't have a docshell, so they'll always fail EnsureVisible.
if ((!mDocument->IsResourceDoc() && !mPresContext->EnsureVisible()) ||
mHaveShutDown) {
// No point; we're about to be torn down anyway.
return;
}
ScheduleBeforeFirstPaint();
PROFILER_MARKER_UNTYPED("UnsuppressAndInvalidate", GRAPHICS);
mPaintingSuppressed = false;
if (nsIFrame* rootFrame = mFrameConstructor->GetRootFrame()) {
// let's assume that outline on a root frame is not supported
rootFrame->InvalidateFrame();
}
if (mPresContext->IsRootContentDocumentCrossProcess()) {
if (auto* bc = BrowserChild::GetFrom(mDocument->GetDocShell())) {
if (mDocument->IsInitialDocument()) {
bc->SendDidUnsuppressPaintingNormalPriority();
} else {
bc->SendDidUnsuppressPainting();
}
}
}
// now that painting is unsuppressed, focus may be set on the document
if (nsPIDOMWindowOuter* win = mDocument->GetWindow()) {
win->SetReadyForFocus();
}
if (!mHaveShutDown) {
SynthesizeMouseMove(false);
ScheduleApproximateFrameVisibilityUpdateNow();
}
}
void PresShell::CancelPaintSuppressionTimer() {
if (mPaintSuppressionTimer) {
mPaintSuppressionTimer->Cancel();
mPaintSuppressionTimer = nullptr;
}
}
void PresShell::UnsuppressPainting() {
CancelPaintSuppressionTimer();
if (mIsDocumentGone || !mPaintingSuppressed) {
return;
}
// If we have reflows pending, just wait until we process
// the reflows and get all the frames where we want them
// before actually unlocking the painting. Otherwise
// go ahead and unlock now.
if (!mDirtyRoots.IsEmpty()) {
mShouldUnsuppressPainting = true;
} else {
UnsuppressAndInvalidate();
}
}
// Post a request to handle an arbitrary callback after reflow has finished.
nsresult PresShell::PostReflowCallback(nsIReflowCallback* aCallback) {
void* result = AllocateByObjectID(eArenaObjectID_nsCallbackEventRequest,
sizeof(nsCallbackEventRequest));
nsCallbackEventRequest* request = (nsCallbackEventRequest*)result;
request->callback = aCallback;
request->next = nullptr;
if (mLastCallbackEventRequest) {
mLastCallbackEventRequest = mLastCallbackEventRequest->next = request;
} else {
mFirstCallbackEventRequest = request;
mLastCallbackEventRequest = request;
}
return NS_OK;
}
void PresShell::CancelReflowCallback(nsIReflowCallback* aCallback) {
nsCallbackEventRequest* before = nullptr;
nsCallbackEventRequest* node = mFirstCallbackEventRequest;
while (node) {
nsIReflowCallback* callback = node->callback;
if (callback == aCallback) {
nsCallbackEventRequest* toFree = node;
if (node == mFirstCallbackEventRequest) {
node = node->next;
mFirstCallbackEventRequest = node;
NS_ASSERTION(before == nullptr, "impossible");
} else {
node = node->next;
before->next = node;
}
if (toFree == mLastCallbackEventRequest) {
mLastCallbackEventRequest = before;
}
FreeByObjectID(eArenaObjectID_nsCallbackEventRequest, toFree);
} else {
before = node;
node = node->next;
}
}
}
void PresShell::CancelPostedReflowCallbacks() {
while (mFirstCallbackEventRequest) {
nsCallbackEventRequest* node = mFirstCallbackEventRequest;
mFirstCallbackEventRequest = node->next;
if (!mFirstCallbackEventRequest) {
mLastCallbackEventRequest = nullptr;
}
nsIReflowCallback* callback = node->callback;
FreeByObjectID(eArenaObjectID_nsCallbackEventRequest, node);
if (callback) {
callback->ReflowCallbackCanceled();
}
}
}
void PresShell::HandlePostedReflowCallbacks(bool aInterruptible) {
while (true) {
// Call all our callbacks, tell us if we need to flush again.
bool shouldFlush = false;
while (mFirstCallbackEventRequest) {
nsCallbackEventRequest* node = mFirstCallbackEventRequest;
mFirstCallbackEventRequest = node->next;
if (!mFirstCallbackEventRequest) {
mLastCallbackEventRequest = nullptr;
}
nsIReflowCallback* callback = node->callback;
FreeByObjectID(eArenaObjectID_nsCallbackEventRequest, node);
if (callback && callback->ReflowFinished()) {
shouldFlush = true;
}
}
if (!shouldFlush || mIsDestroying) {
return;
}
// The flush might cause us to have more callbacks.
const auto flushType =
aInterruptible ? FlushType::InterruptibleLayout : FlushType::Layout;
FlushPendingNotifications(flushType);
}
}
bool PresShell::IsSafeToFlush() const {
// Not safe if we are getting torn down, reflowing, or in the middle of frame
// construction.
if (mIsReflowing || mChangeNestCount || mIsDestroying) {
return false;
}
// Not safe if we are painting
if (nsViewManager* viewManager = GetViewManager()) {
bool isPainting = false;
viewManager->IsPainting(isPainting);
if (isPainting) {
return false;
}
}
return true;
}
void PresShell::NotifyFontFaceSetOnRefresh() {
if (FontFaceSet* set = mDocument->GetFonts()) {
set->DidRefresh();
}
}
void PresShell::DoFlushPendingNotifications(FlushType aType) {
// by default, flush animations if aType >= FlushType::Style
mozilla::ChangesToFlush flush(aType, aType >= FlushType::Style,
aType >= FlushType::Layout);
FlushPendingNotifications(flush);
}
#ifdef DEBUG
static void AssertFrameSubtreeIsSane(const nsIFrame& aRoot) {
if (const nsIContent* content = aRoot.GetContent()) {
MOZ_ASSERT(content->GetFlattenedTreeParentNodeForStyle(),
"Node not in the flattened tree still has a frame?");
}
for (const auto& childList : aRoot.ChildLists()) {
for (const nsIFrame* child : childList.mList) {
AssertFrameSubtreeIsSane(*child);
}
}
}
#endif
static inline void AssertFrameTreeIsSane(const PresShell& aPresShell) {
#ifdef DEBUG
if (const nsIFrame* root = aPresShell.GetRootFrame()) {
AssertFrameSubtreeIsSane(*root);
}
#endif
}
static void TriggerPendingScrollTimelineAnimations(Document* aDocument) {
auto* tracker = aDocument->GetScrollTimelineAnimationTracker();
if (!tracker || !tracker->HasPendingAnimations()) {
return;
}
tracker->TriggerPendingAnimations();
}
void PresShell::DoFlushPendingNotifications(mozilla::ChangesToFlush aFlush) {
// FIXME(emilio, bug 1530177): Turn into a release assert when bug 1530188 and
// bug 1530190 are fixed.
MOZ_DIAGNOSTIC_ASSERT(!mForbiddenToFlush, "This is bad!");
// Per our API contract, hold a strong ref to ourselves until we return.
RefPtr<PresShell> kungFuDeathGrip = this;
/**
* VERY IMPORTANT: If you add some sort of new flushing to this
* method, make sure to add the relevant SetNeedLayoutFlush or
* SetNeedStyleFlush calls on the shell.
*/
FlushType flushType = aFlush.mFlushType;
if (aFlush.mUpdateRelevancy) {
// If needed, first update the relevancy of any content of elements with
// `content-visibility: auto` so that the values returned from e.g. script
// queries are up-to-date.
UpdateRelevancyOfContentVisibilityAutoFrames();
}
MOZ_ASSERT(NeedFlush(flushType), "Why did we get called?");
AUTO_PROFILER_MARKER_TEXT(
"DoFlushPendingNotifications", LAYOUT,
MarkerOptions(MarkerStack::Capture(), MarkerInnerWindowIdFromDocShell(
mPresContext->GetDocShell())),
nsDependentCString(kFlushTypeNames[flushType]));
AUTO_PROFILER_LABEL_DYNAMIC_CSTR_NONSENSITIVE(
"PresShell::DoFlushPendingNotifications", LAYOUT,
kFlushTypeNames[flushType]);
#ifdef ACCESSIBILITY
# ifdef DEBUG
if (nsAccessibilityService* accService = GetAccService()) {
NS_ASSERTION(!accService->IsProcessingRefreshDriverNotification(),
"Flush during accessible tree update!");
}
# endif
#endif
NS_ASSERTION(flushType >= FlushType::Style, "Why did we get called?");
bool isSafeToFlush = IsSafeToFlush();
// If layout could possibly trigger scripts, then it's only safe to flush if
// it's safe to run script.
bool hasHadScriptObject;
if (mDocument->GetScriptHandlingObject(hasHadScriptObject) ||
hasHadScriptObject) {
isSafeToFlush = isSafeToFlush && nsContentUtils::IsSafeToRunScript();
}
// Don't flush if the doc is already in the bfcache.
if (MOZ_UNLIKELY(mDocument->GetPresShell() != this)) {
MOZ_DIAGNOSTIC_ASSERT(!mDocument->GetPresShell(),
"Where did this shell come from?");
isSafeToFlush = false;
}
MOZ_DIAGNOSTIC_ASSERT(!mIsDestroying || !isSafeToFlush);
MOZ_DIAGNOSTIC_ASSERT(mIsDestroying || mViewManager);
MOZ_DIAGNOSTIC_ASSERT(mIsDestroying || mDocument->HasShellOrBFCacheEntry());
if (!isSafeToFlush) {
return;
}
// Make sure the view manager stays alive.
RefPtr<nsViewManager> viewManager = mViewManager;
// We need to make sure external resource documents are flushed too (for
// example, svg filters that reference a filter in an external document
// need the frames in the external document to be constructed for the
// filter to work). We only need external resources to be flushed when the
// main document is flushing >= FlushType::Frames, so we flush external
// resources here instead of Document::FlushPendingNotifications.
mDocument->FlushExternalResources(flushType);
// Force flushing of any pending content notifications that might have
// queued up while our event was pending. That will ensure that we don't
// construct frames for content right now that's still waiting to be
// notified on,
mDocument->FlushPendingNotifications(FlushType::ContentAndNotify);
mDocument->UpdateSVGUseElementShadowTrees();
// Process pending restyles, since any flush of the presshell wants
// up-to-date style data.
if (MOZ_LIKELY(!mIsDestroying)) {
viewManager->FlushDelayedResize();
mPresContext->FlushPendingMediaFeatureValuesChanged();
}
if (MOZ_LIKELY(!mIsDestroying)) {
// Now that we have flushed media queries, update the rules before looking
// up @font-face / @counter-style / @font-feature-values rules.
StyleSet()->UpdateStylistIfNeeded();
// Flush any pending update of the user font set, since that could
// cause style changes (for updating ex/ch units, and to cause a
// reflow).
mDocument->FlushUserFontSet();
mPresContext->FlushCounterStyles();
mPresContext->FlushFontFeatureValues();
mPresContext->FlushFontPaletteValues();
// Flush any requested SMIL samples.
if (mDocument->HasAnimationController()) {
mDocument->GetAnimationController()->FlushResampleRequests();
}
}
// The FlushResampleRequests() above might have flushed style changes.
if (MOZ_LIKELY(!mIsDestroying)) {
if (aFlush.mFlushAnimations) {
mPresContext->EffectCompositor()->PostRestyleForThrottledAnimations();
mNeedThrottledAnimationFlush = false;
}
nsAutoScriptBlocker scriptBlocker;
Maybe<uint64_t> innerWindowID;
if (auto* window = mDocument->GetInnerWindow()) {
innerWindowID = Some(window->WindowID());
}
AutoProfilerStyleMarker tracingStyleFlush(std::move(mStyleCause),
innerWindowID);
PerfStats::AutoMetricRecording<PerfStats::Metric::Styling> autoRecording;
mPresContext->RestyleManager()->ProcessPendingRestyles();
mNeedStyleFlush = false;
}
AssertFrameTreeIsSane(*this);
if (flushType >= (SuppressInterruptibleReflows()
? FlushType::Layout
: FlushType::InterruptibleLayout) &&
!mIsDestroying) {
if (DoFlushLayout(/* aInterruptible = */ flushType < FlushType::Layout)) {
if (mContentToScrollTo) {
DoScrollContentIntoView();
if (mContentToScrollTo) {
mContentToScrollTo->RemoveProperty(nsGkAtoms::scrolling);
mContentToScrollTo = nullptr;
}
}
}
// FIXME(emilio): Maybe we should assert here but it's not 100% sure it'd
// hold right now, UnsuppressAndInvalidate and so on can run script...
if (MOZ_LIKELY(mDirtyRoots.IsEmpty())) {
mNeedLayoutFlush = false;
}
}
FlushPendingScrollResnap();
if (MOZ_LIKELY(!mIsDestroying)) {
// Try to trigger pending scroll-driven animations after we flush
// style and layout (if any). If we try to trigger them after flushing
// style but the frame tree is not ready, we will check them again after
// we flush layout because the requirement to trigger scroll-driven
// animations is that the associated scroll containers are ready (i.e. the
// scroll-timeline is active), and this depends on the readiness of the
// scrollable frame and the primary frame of the scroll container.
TriggerPendingScrollTimelineAnimations(mDocument);
}
if (flushType >= FlushType::Layout) {
if (!mIsDestroying) {
viewManager->UpdateWidgetGeometry();
}
}
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::CharacterDataChanged(
nsIContent* aContent, const CharacterDataChangeInfo& aInfo) {
MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript());
MOZ_ASSERT(!mIsDocumentGone, "Unexpected CharacterDataChanged");
MOZ_ASSERT(aContent->OwnerDoc() == mDocument, "Unexpected document");
nsAutoCauseReflowNotifier crNotifier(this);
mPresContext->RestyleManager()->CharacterDataChanged(aContent, aInfo);
mFrameConstructor->CharacterDataChanged(aContent, aInfo);
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::ElementStateChanged(
Document* aDocument, Element* aElement, ElementState aStateMask) {
MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript());
MOZ_ASSERT(!mIsDocumentGone, "Unexpected ContentStateChanged");
MOZ_ASSERT(aDocument == mDocument, "Unexpected aDocument");
if (mDidInitialize) {
nsAutoCauseReflowNotifier crNotifier(this);
mPresContext->RestyleManager()->ElementStateChanged(aElement, aStateMask);
}
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::CustomStatesWillChange(
Element& aElement) {
if (MOZ_UNLIKELY(!mDidInitialize)) {
return;
}
mPresContext->RestyleManager()->CustomStatesWillChange(aElement);
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::CustomStateChanged(
Element& aElement, nsAtom* aState) {
MOZ_ASSERT(!mIsDocumentGone, "Unexpected CustomStateChanged");
MOZ_ASSERT(aState, "Unexpected empty state");
if (mDidInitialize) {
nsAutoCauseReflowNotifier crNotifier(this);
mPresContext->RestyleManager()->CustomStateChanged(aElement, aState);
}
}
void PresShell::DocumentStatesChanged(DocumentState aStateMask) {
MOZ_ASSERT(!mIsDocumentGone, "Unexpected DocumentStatesChanged");
MOZ_ASSERT(mDocument);
MOZ_ASSERT(!aStateMask.IsEmpty());
if (mDidInitialize) {
StyleSet()->InvalidateStyleForDocumentStateChanges(aStateMask);
}
if (aStateMask.HasState(DocumentState::WINDOW_INACTIVE)) {
if (nsIFrame* root = mFrameConstructor->GetRootFrame()) {
root->SchedulePaint();
}
}
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::AttributeWillChange(
Element* aElement, int32_t aNameSpaceID, nsAtom* aAttribute,
int32_t aModType) {
MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript());
MOZ_ASSERT(!mIsDocumentGone, "Unexpected AttributeWillChange");
MOZ_ASSERT(aElement->OwnerDoc() == mDocument, "Unexpected document");
// XXXwaterson it might be more elegant to wait until after the
// initial reflow to begin observing the document. That would
// squelch any other inappropriate notifications as well.
if (mDidInitialize) {
nsAutoCauseReflowNotifier crNotifier(this);
mPresContext->RestyleManager()->AttributeWillChange(aElement, aNameSpaceID,
aAttribute, aModType);
}
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::AttributeChanged(
Element* aElement, int32_t aNameSpaceID, nsAtom* aAttribute,
int32_t aModType, const nsAttrValue* aOldValue) {
MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript());
MOZ_ASSERT(!mIsDocumentGone, "Unexpected AttributeChanged");
MOZ_ASSERT(aElement->OwnerDoc() == mDocument, "Unexpected document");
// XXXwaterson it might be more elegant to wait until after the
// initial reflow to begin observing the document. That would
// squelch any other inappropriate notifications as well.
if (mDidInitialize) {
nsAutoCauseReflowNotifier crNotifier(this);
mPresContext->RestyleManager()->AttributeChanged(
aElement, aNameSpaceID, aAttribute, aModType, aOldValue);
}
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::ContentAppended(
nsIContent* aFirstNewContent) {
MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript());
MOZ_ASSERT(!mIsDocumentGone, "Unexpected ContentAppended");
MOZ_ASSERT(aFirstNewContent->OwnerDoc() == mDocument, "Unexpected document");
// We never call ContentAppended with a document as the container, so we can
// assert that we have an nsIContent parent.
MOZ_ASSERT(aFirstNewContent->GetParent());
MOZ_ASSERT(aFirstNewContent->GetParent()->IsElement() ||
aFirstNewContent->GetParent()->IsShadowRoot());
if (!mDidInitialize) {
return;
}
nsAutoCauseReflowNotifier crNotifier(this);
// Call this here so it only happens for real content mutations and
// not cases when the frame constructor calls its own methods to force
// frame reconstruction.
mPresContext->RestyleManager()->ContentAppended(aFirstNewContent);
mFrameConstructor->ContentAppended(
aFirstNewContent, nsCSSFrameConstructor::InsertionKind::Async);
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::ContentInserted(
nsIContent* aChild) {
MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript());
MOZ_ASSERT(!mIsDocumentGone, "Unexpected ContentInserted");
MOZ_ASSERT(aChild->OwnerDoc() == mDocument, "Unexpected document");
if (!mDidInitialize) {
return;
}
nsAutoCauseReflowNotifier crNotifier(this);
// Call this here so it only happens for real content mutations and
// not cases when the frame constructor calls its own methods to force
// frame reconstruction.
mPresContext->RestyleManager()->ContentInserted(aChild);
mFrameConstructor->ContentInserted(
aChild, nsCSSFrameConstructor::InsertionKind::Async);
}
MOZ_CAN_RUN_SCRIPT_BOUNDARY void PresShell::ContentWillBeRemoved(
nsIContent* aChild, const BatchRemovalState*) {
MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript());
MOZ_ASSERT(!mIsDocumentGone, "Unexpected ContentRemoved");
MOZ_ASSERT(aChild->OwnerDoc() == mDocument, "Unexpected document");
// Notify the ESM that the content has been removed, so that
// it can clean up any state related to the content.
mPresContext->EventStateManager()->ContentRemoved(mDocument, aChild);
nsAutoCauseReflowNotifier crNotifier(this);
// After removing aChild from tree we should save information about live
// ancestor
if (mPointerEventTarget &&
mPointerEventTarget->IsInclusiveDescendantOf(aChild)) {
mPointerEventTarget = aChild->GetParent();
}
mFrameConstructor->ContentWillBeRemoved(
aChild, nsCSSFrameConstructor::REMOVE_CONTENT);
// NOTE(emilio): It's important that this goes after the frame constructor
// stuff, otherwise the frame constructor can't see elements which are
// display: contents / display: none, because we'd have cleared all the style
// data from there.
mPresContext->RestyleManager()->ContentWillBeRemoved(aChild);
}
void PresShell::NotifyCounterStylesAreDirty() {
// TODO: Looks like that nsFrameConstructor::NotifyCounterStylesAreDirty()
// does not run script. If so, we don't need to block script with
// nsAutoCauseReflowNotifier here. Instead, there should be methods
// and stack only class which manages only mChangeNestCount for
// avoiding unnecessary `MOZ_CAN_RUN_SCRIPT` marking.
nsAutoCauseReflowNotifier reflowNotifier(this);
mFrameConstructor->NotifyCounterStylesAreDirty();
}
bool PresShell::FrameIsAncestorOfDirtyRoot(nsIFrame* aFrame) const {
return mDirtyRoots.FrameIsAncestorOfAnyElement(aFrame);
}
void PresShell::ReconstructFrames() {
MOZ_ASSERT(!mFrameConstructor->GetRootFrame() || mDidInitialize,
"Must not have root frame before initial reflow");
if (!mDidInitialize || mIsDestroying) {
// Nothing to do here
return;
}
if (Element* root = mDocument->GetRootElement()) {
PostRecreateFramesFor(root);
}
mDocument->FlushPendingNotifications(FlushType::Frames);
}
nsresult PresShell::RenderDocument(const nsRect& aRect,
RenderDocumentFlags aFlags,
nscolor aBackgroundColor,
gfxContext* aThebesContext) {
NS_ENSURE_TRUE(!(aFlags & RenderDocumentFlags::IsUntrusted),
NS_ERROR_NOT_IMPLEMENTED);
nsRootPresContext* rootPresContext = mPresContext->GetRootPresContext();
if (rootPresContext) {
rootPresContext->FlushWillPaintObservers();
if (mIsDestroying) {
return NS_OK;
}
}
nsAutoScriptBlocker blockScripts;
// Set up the rectangle as the path in aThebesContext
gfxRect r(0, 0, nsPresContext::AppUnitsToFloatCSSPixels(aRect.width),
nsPresContext::AppUnitsToFloatCSSPixels(aRect.height));
aThebesContext->NewPath();
#ifdef MOZ_GFX_OPTIMIZE_MOBILE
aThebesContext->SnappedRectangle(r);
#else
aThebesContext->Rectangle(r);
#endif
nsIFrame* rootFrame = mFrameConstructor->GetRootFrame();
if (!rootFrame) {
// Nothing to paint, just fill the rect
aThebesContext->SetColor(sRGBColor::FromABGR(aBackgroundColor));
aThebesContext->Fill();
return NS_OK;
}
gfxContextAutoSaveRestore save(aThebesContext);
MOZ_ASSERT(aThebesContext->CurrentOp() == CompositionOp::OP_OVER);
aThebesContext->Clip();
nsDeviceContext* devCtx = mPresContext->DeviceContext();
gfxPoint offset(-nsPresContext::AppUnitsToFloatCSSPixels(aRect.x),
-nsPresContext::AppUnitsToFloatCSSPixels(aRect.y));
gfxFloat scale =
gfxFloat(devCtx->AppUnitsPerDevPixel()) / AppUnitsPerCSSPixel();
// Since canvas APIs use floats to set up their matrices, we may have some
// slight rounding errors here. We use NudgeToIntegers() here to adjust
// matrix components that are integers up to the accuracy of floats to be
// those integers.
gfxMatrix newTM = aThebesContext->CurrentMatrixDouble()
.PreTranslate(offset)
.PreScale(scale, scale)
.NudgeToIntegers();
aThebesContext->SetMatrixDouble(newTM);
AutoSaveRestoreRenderingState _(this);
bool wouldFlushRetainedLayers = false;
PaintFrameFlags flags = PaintFrameFlags::IgnoreSuppression;
if (aThebesContext->CurrentMatrix().HasNonIntegerTranslation()) {
flags |= PaintFrameFlags::InTransform;
}
if (!(aFlags & RenderDocumentFlags::AsyncDecodeImages)) {
flags |= PaintFrameFlags::SyncDecodeImages;
}
if (aFlags & RenderDocumentFlags::UseHighQualityScaling) {
flags |= PaintFrameFlags::UseHighQualityScaling;
}
if (aFlags & RenderDocumentFlags::UseWidgetLayers) {
// We only support using widget layers on display root's with widgets.
nsView* view = rootFrame->GetView();
if (view && view->GetWidget() &&
nsLayoutUtils::GetDisplayRootFrame(rootFrame) == rootFrame) {
WindowRenderer* renderer = view->GetWidget()->GetWindowRenderer();
// WebRenderLayerManagers in content processes
// don't support taking snapshots.
if (renderer &&
(!renderer->AsKnowsCompositor() || XRE_IsParentProcess())) {
flags |= PaintFrameFlags::WidgetLayers;
}
}
}
if (!(aFlags & RenderDocumentFlags::DrawCaret)) {
wouldFlushRetainedLayers = true;
flags |= PaintFrameFlags::HideCaret;
}
if (aFlags & RenderDocumentFlags::IgnoreViewportScrolling) {
wouldFlushRetainedLayers = !IgnoringViewportScrolling();
mRenderingStateFlags |= RenderingStateFlags::IgnoringViewportScrolling;
}
if (aFlags & RenderDocumentFlags::ResetViewportScrolling) {
wouldFlushRetainedLayers = true;
flags |= PaintFrameFlags::ResetViewportScrolling;
}
if (aFlags & RenderDocumentFlags::DrawWindowNotFlushing) {
mRenderingStateFlags |= RenderingStateFlags::DrawWindowNotFlushing;
}
if (aFlags & RenderDocumentFlags::DocumentRelative) {
// XXX be smarter about this ... drawWindow might want a rect
// that's "pretty close" to what our retained layer tree covers.
// In that case, it wouldn't disturb normal rendering too much,
// and we should allow it.
wouldFlushRetainedLayers = true;
flags |= PaintFrameFlags::DocumentRelative;
}
// Don't let drawWindow blow away our retained layer tree
if ((flags & PaintFrameFlags::WidgetLayers) && wouldFlushRetainedLayers) {
flags &= ~PaintFrameFlags::WidgetLayers;
}
nsLayoutUtils::PaintFrame(aThebesContext, rootFrame, nsRegion(aRect),
aBackgroundColor,
nsDisplayListBuilderMode::Painting, flags);
return NS_OK;
}
/*
* Clip the display list aList to a range. Returns the clipped
* rectangle surrounding the range.
*/
nsRect PresShell::ClipListToRange(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList, nsRange* aRange) {
// iterate though the display items and add up the bounding boxes of each.
// This will allow the total area of the frames within the range to be
// determined. To do this, remove an item from the bottom of the list, check
// whether it should be part of the range, and if so, append it to the top
// of the temporary list tmpList. If the item is a text frame at the end of
// the selection range, clip it to the portion of the text frame that is
// part of the selection. Then, append the wrapper to the top of the list.
// Otherwise, just delete the item and don't append it.
nsRect surfaceRect;
for (nsDisplayItem* i : aList->TakeItems()) {
if (i->GetType() == DisplayItemType::TYPE_CONTAINER) {
aList->AppendToTop(i);
surfaceRect.UnionRect(
surfaceRect, ClipListToRange(aBuilder, i->GetChildren(), aRange));
continue;
}
// itemToInsert indiciates the item that should be inserted into the
// temporary list. If null, no item should be inserted.
nsDisplayItem* itemToInsert = nullptr;
nsIFrame* frame = i->Frame();
nsIContent* content = frame->GetContent();
if (content) {
bool atStart =
content == aRange->GetMayCrossShadowBoundaryStartContainer();
bool atEnd = content == aRange->GetMayCrossShadowBoundaryEndContainer();
if ((atStart || atEnd) && frame->IsTextFrame()) {
auto [frameStartOffset, frameEndOffset] = frame->GetOffsets();
int32_t highlightStart =
atStart ? std::max(static_cast<int32_t>(
aRange->MayCrossShadowBoundaryStartOffset()),
frameStartOffset)
: frameStartOffset;
int32_t highlightEnd =
atEnd ? std::min(static_cast<int32_t>(
aRange->MayCrossShadowBoundaryEndOffset()),
frameEndOffset)
: frameEndOffset;
if (highlightStart < highlightEnd) {
// determine the location of the start and end edges of the range.
nsPoint startPoint, endPoint;
frame->GetPointFromOffset(highlightStart, &startPoint);
frame->GetPointFromOffset(highlightEnd, &endPoint);
// The clip rectangle is determined by taking the the start and
// end points of the range, offset from the reference frame.
// Because of rtl, the end point may be to the left of (or above,
// in vertical mode) the start point, so x (or y) is set to the
// lower of the values.
nsRect textRect(aBuilder->ToReferenceFrame(frame), frame->GetSize());
if (frame->GetWritingMode().IsVertical()) {
nscoord y = std::min(startPoint.y, endPoint.y);
textRect.y += y;
textRect.height = std::max(startPoint.y, endPoint.y) - y;
} else {
nscoord x = std::min(startPoint.x, endPoint.x);
textRect.x += x;
textRect.width = std::max(startPoint.x, endPoint.x) - x;
}
surfaceRect.UnionRect(surfaceRect, textRect);
const ActiveScrolledRoot* asr = i->GetActiveScrolledRoot();
DisplayItemClip newClip;
newClip.SetTo(textRect);
const DisplayItemClipChain* newClipChain =
aBuilder->AllocateDisplayItemClipChain(newClip, asr, nullptr);
i->IntersectClip(aBuilder, newClipChain, true);
itemToInsert = i;
}
}
// Don't try to descend into subdocuments.
// If this ever changes we'd need to add handling for subdocuments with
// different zoom levels.
else if (content->GetComposedDoc() ==
aRange->GetMayCrossShadowBoundaryStartContainer()
->GetComposedDoc()) {
// if the node is within the range, append it to the temporary list
bool before, after;
nsresult rv =
RangeUtils::CompareNodeToRange<TreeKind::ShadowIncludingDOM>(
content, aRange, &before, &after);
if (NS_SUCCEEDED(rv) && !before && !after) {
itemToInsert = i;
bool snap;
surfaceRect.UnionRect(surfaceRect, i->GetBounds(aBuilder, &snap));
}
}
}
// insert the item into the list if necessary. If the item has a child
// list, insert that as well
nsDisplayList* sublist = i->GetSameCoordinateSystemChildren();
if (itemToInsert || sublist) {
aList->AppendToTop(itemToInsert ? itemToInsert : i);
// if the item is a list, iterate over it as well
if (sublist) {
surfaceRect.UnionRect(surfaceRect,
ClipListToRange(aBuilder, sublist, aRange));
}
} else {
// otherwise, just delete the item and don't readd it to the list
i->Destroy(aBuilder);
}
}
return surfaceRect;
}
#ifdef DEBUG
# include <stdio.h>
static bool gDumpRangePaintList = false;
#endif
UniquePtr<RangePaintInfo> PresShell::CreateRangePaintInfo(
nsRange* aRange, nsRect& aSurfaceRect, bool aForPrimarySelection) {
nsIFrame* ancestorFrame = nullptr;
nsIFrame* rootFrame = GetRootFrame();
// If the start or end of the range is the document, just use the root
// frame, otherwise get the common ancestor of the two endpoints of the
// range.
nsINode* startContainer = aRange->GetMayCrossShadowBoundaryStartContainer();
nsINode* endContainer = aRange->GetMayCrossShadowBoundaryEndContainer();
Document* doc = startContainer->GetComposedDoc();
if (startContainer == doc || endContainer == doc) {
ancestorFrame = rootFrame;
} else {
nsINode* ancestor =
StaticPrefs::dom_shadowdom_selection_across_boundary_enabled()
? nsContentUtils::GetClosestCommonShadowIncludingInclusiveAncestor(
startContainer, endContainer)
: nsContentUtils::GetClosestCommonInclusiveAncestor(startContainer,
endContainer);
NS_ASSERTION(!ancestor || ancestor->IsContent(),
"common ancestor is not content");
while (ancestor && ancestor->IsContent()) {
ancestorFrame = ancestor->AsContent()->GetPrimaryFrame();
if (ancestorFrame) {
break;
}
ancestor = ancestor->GetParentOrShadowHostNode();
}
// use the nearest ancestor frame that includes all continuations as the
// root for building the display list
while (ancestorFrame &&
nsLayoutUtils::GetNextContinuationOrIBSplitSibling(ancestorFrame)) {
ancestorFrame = ancestorFrame->GetParent();
}
}
if (!ancestorFrame) {
return nullptr;
}
// get a display list containing the range
auto info = MakeUnique<RangePaintInfo>(ancestorFrame);
info->mBuilder.SetIncludeAllOutOfFlows();
if (aForPrimarySelection) {
info->mBuilder.SetSelectedFramesOnly();
}
info->mBuilder.EnterPresShell(ancestorFrame);
ContentSubtreeIterator subtreeIter;
nsresult rv = StaticPrefs::dom_shadowdom_selection_across_boundary_enabled()
? subtreeIter.InitWithAllowCrossShadowBoundary(aRange)
: subtreeIter.Init(aRange);
if (NS_FAILED(rv)) {
return nullptr;
}
auto BuildDisplayListForNode = [&](nsINode* aNode) {
if (MOZ_UNLIKELY(!aNode->IsContent())) {
return;
}
nsIFrame* frame = aNode->AsContent()->GetPrimaryFrame();
// XXX deal with frame being null due to display:contents
for (; frame;
frame = nsLayoutUtils::GetNextContinuationOrIBSplitSibling(frame)) {
info->mBuilder.SetVisibleRect(frame->InkOverflowRect());
info->mBuilder.SetDirtyRect(frame->InkOverflowRect());
frame->BuildDisplayListForStackingContext(&info->mBuilder, &info->mList);
}
};
if (startContainer->NodeType() == nsINode::TEXT_NODE) {
BuildDisplayListForNode(startContainer);
}
for (; !subtreeIter.IsDone(); subtreeIter.Next()) {
nsCOMPtr<nsINode> node = subtreeIter.GetCurrentNode();
BuildDisplayListForNode(node);
}
if (endContainer != startContainer &&
endContainer->NodeType() == nsINode::TEXT_NODE) {
BuildDisplayListForNode(endContainer);
}
// If one of the ancestor presShells (including this one) has a resolution
// set, we may have some APZ zoom applied. That means we may want to rasterize
// the nodes at that zoom level. Populate `info` with the relevant information
// so that the caller can decide what to do. Also wrap the display list in
// appropriate nsDisplayAsyncZoom display items. This code handles the general
// case with nested async zooms (even though that never actually happens),
// because it fell out of the implementation for free.
//
// TODO: Do we need to do the same for ancestor transforms?
for (nsPresContext* ctx = GetPresContext(); ctx;
ctx = ctx->GetParentPresContext()) {
PresShell* shell = ctx->PresShell();
float resolution = shell->GetResolution();
// If we are at the root document in the process, try to see if documents
// in enclosing processes have a resolution and include that as well.
if (!ctx->GetParentPresContext()) {
// xScale is an arbitrary choice. Outside of edge cases involving CSS
// transforms, xScale == yScale so it doesn't matter.
resolution *= ViewportUtils::TryInferEnclosingResolution(shell).xScale;
}
if (resolution == 1.0) {
continue;
}
info->mResolution *= resolution;
nsIFrame* rootScrollContainerFrame = shell->GetRootScrollContainerFrame();
ViewID zoomedId = nsLayoutUtils::FindOrCreateIDFor(
rootScrollContainerFrame->GetContent());
nsDisplayList wrapped(&info->mBuilder);
wrapped.AppendNewToTop<nsDisplayAsyncZoom>(&info->mBuilder,
rootScrollContainerFrame,
&info->mList, nullptr, zoomedId);
info->mList.AppendToTop(&wrapped);
}
#ifdef DEBUG
if (gDumpRangePaintList) {
fprintf(stderr, "CreateRangePaintInfo --- before ClipListToRange:\n");
nsIFrame::PrintDisplayList(&(info->mBuilder), info->mList);
}
#endif
nsRect rangeRect = ClipListToRange(&info->mBuilder, &info->mList, aRange);
info->mBuilder.LeavePresShell(ancestorFrame, &info->mList);
#ifdef DEBUG
if (gDumpRangePaintList) {
fprintf(stderr, "CreateRangePaintInfo --- after ClipListToRange:\n");
nsIFrame::PrintDisplayList(&(info->mBuilder), info->mList);
}
#endif
// determine the offset of the reference frame for the display list
// to the root frame. This will allow the coordinates used when painting
// to all be offset from the same point
info->mRootOffset = ancestorFrame->GetBoundingClientRect().TopLeft();
rangeRect.MoveBy(info->mRootOffset);
aSurfaceRect.UnionRect(aSurfaceRect, rangeRect);
return info;
}
already_AddRefed<SourceSurface> PresShell::PaintRangePaintInfo(
const nsTArray<UniquePtr<RangePaintInfo>>& aItems, Selection* aSelection,
const Maybe<CSSIntRegion>& aRegion, nsRect aArea,
const LayoutDeviceIntPoint aPoint, LayoutDeviceIntRect* aScreenRect,
RenderImageFlags aFlags) {
nsPresContext* pc = GetPresContext();
if (!pc || aArea.width == 0 || aArea.height == 0) {
return nullptr;
}
// use the rectangle to create the surface
LayoutDeviceIntRect pixelArea = LayoutDeviceIntRect::FromAppUnitsToOutside(
aArea, pc->AppUnitsPerDevPixel());
// if the image should not be resized, scale must be 1
float scale = 1.0;
const nsRect maxSize = pc->DeviceContext()->GetClientRect();
// check if the image should be resized
bool resize = !!(aFlags & RenderImageFlags::AutoScale);
if (resize) {
// check if image-resizing-algorithm should be used
if (aFlags & RenderImageFlags::IsImage) {
// get max screensize
int32_t maxWidth = pc->AppUnitsToDevPixels(maxSize.width);
int32_t maxHeight = pc->AppUnitsToDevPixels(maxSize.height);
// resize image relative to the screensize
// get best height/width relative to screensize
float bestHeight = float(maxHeight) * RELATIVE_SCALEFACTOR;
float bestWidth = float(maxWidth) * RELATIVE_SCALEFACTOR;
// calculate scale for bestWidth
float adjustedScale = bestWidth / float(pixelArea.width);
// get the worst height (height when width is perfect)
float worstHeight = float(pixelArea.height) * adjustedScale;
// get the difference of best and worst height
float difference = bestHeight - worstHeight;
// halve the difference and add it to worstHeight to get
// the best compromise between bestHeight and bestWidth,
// then calculate the corresponding scale factor
adjustedScale = (worstHeight + difference / 2) / float(pixelArea.height);
// prevent upscaling
scale = std::min(scale, adjustedScale);
} else {
// get half of max screensize
int32_t maxWidth = pc->AppUnitsToDevPixels(maxSize.width >> 1);
int32_t maxHeight = pc->AppUnitsToDevPixels(maxSize.height >> 1);
if (pixelArea.width > maxWidth || pixelArea.height > maxHeight) {
// divide the maximum size by the image size in both directions.
// Whichever direction produces the smallest result determines how much
// should be scaled.
if (pixelArea.width > maxWidth) {
scale = std::min(scale, float(maxWidth) / pixelArea.width);
}
if (pixelArea.height > maxHeight) {
scale = std::min(scale, float(maxHeight) / pixelArea.height);
}
}
}
// Pick a resolution scale factor that is the highest we need for any of
// the items. This means some items may get rendered at a higher-than-needed
// resolution but at least nothing will be avoidably blurry.
float resolutionScale = 1.0;
for (const UniquePtr<RangePaintInfo>& rangeInfo : aItems) {
resolutionScale = std::max(resolutionScale, rangeInfo->mResolution);
}
float unclampedResolution = resolutionScale;
// Clamp the resolution scale so that `pixelArea` when scaled by `scale` and
// `resolutionScale` isn't bigger than `maxSize`. This prevents creating
// giant/unbounded images.
resolutionScale =
std::min(resolutionScale, maxSize.width / (scale * pixelArea.width));
resolutionScale =
std::min(resolutionScale, maxSize.height / (scale * pixelArea.height));
// The following assert should only get hit if pixelArea scaled by `scale`
// alone would already have been bigger than `maxSize`, which should never
// be the case. For release builds we handle gracefully by reverting
// resolutionScale to 1.0 to avoid unexpected consequences.
MOZ_ASSERT(resolutionScale >= 1.0);
resolutionScale = std::max(1.0f, resolutionScale);
scale *= resolutionScale;
// Now we need adjust the output screen position of the surface based on the
// scaling factor and any APZ zoom that may be in effect. The goal is here
// to set `aScreenRect`'s top-left corner (in screen-relative LD pixels)
// such that the scaling effect on the surface appears anchored at `aPoint`
// ("anchor" here is like "transform-origin"). When this code is e.g. used
// to generate a drag image for dragging operations, `aPoint` refers to the
// position of the mouse cursor (also in screen-relative LD pixels), and the
// user-visible effect of doing this is that the point at which the user
// clicked to start the drag remains under the mouse during the drag.
// In order to do this we first compute the top-left corner of the
// pixelArea is screen-relative LD pixels.
LayoutDevicePoint visualPoint = ViewportUtils::ToScreenRelativeVisual(
LayoutDevicePoint(pixelArea.TopLeft()), pc);
// And then adjust the output screen position based on that, which we can do
// since everything here is screen-relative LD pixels. Note that the scale
// factor we use here is the effective "transform" scale applied to the
// content we're painting, relative to the scale at which it would normally
// get painted at as part of page rendering (`unclampedResolution`).
float scaleRelativeToNormalContent = scale / unclampedResolution;
aScreenRect->x =
NSToIntFloor(aPoint.x - float(aPoint.x.value - visualPoint.x.value) *
scaleRelativeToNormalContent);
aScreenRect->y =
NSToIntFloor(aPoint.y - float(aPoint.y.value - visualPoint.y.value) *
scaleRelativeToNormalContent);
pixelArea.width = NSToIntFloor(float(pixelArea.width) * scale);
pixelArea.height = NSToIntFloor(float(pixelArea.height) * scale);
if (!pixelArea.width || !pixelArea.height) {
return nullptr;
}
} else {
// move aScreenRect to the position of the surface in screen coordinates
LayoutDevicePoint visualPoint = ViewportUtils::ToScreenRelativeVisual(
LayoutDevicePoint(pixelArea.TopLeft()), pc);
aScreenRect->MoveTo(RoundedToInt(visualPoint));
}
aScreenRect->width = pixelArea.width;
aScreenRect->height = pixelArea.height;
RefPtr<DrawTarget> dt =
gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
IntSize(pixelArea.width, pixelArea.height), SurfaceFormat::B8G8R8A8);
if (!dt || !dt->IsValid()) {
return nullptr;
}
gfxContext ctx(dt);
if (aRegion) {
RefPtr<PathBuilder> builder = dt->CreatePathBuilder(FillRule::FILL_WINDING);
// Convert aRegion from CSS pixels to dev pixels
nsIntRegion region = aRegion->ToAppUnits(AppUnitsPerCSSPixel())
.ToOutsidePixels(pc->AppUnitsPerDevPixel());
for (auto iter = region.RectIter(); !iter.Done(); iter.Next()) {
const IntRect& rect = iter.Get();
builder->MoveTo(rect.TopLeft());
builder->LineTo(rect.TopRight());
builder->LineTo(rect.BottomRight());
builder->LineTo(rect.BottomLeft());
builder->LineTo(rect.TopLeft());
}
RefPtr<Path> path = builder->Finish();
ctx.Clip(path);
}
gfxMatrix initialTM = ctx.CurrentMatrixDouble();
if (resize) {
initialTM.PreScale(scale, scale);
}
// translate so that points are relative to the surface area
gfxPoint surfaceOffset = nsLayoutUtils::PointToGfxPoint(
-aArea.TopLeft(), pc->AppUnitsPerDevPixel());
initialTM.PreTranslate(surfaceOffset);
// temporarily hide the selection so that text is drawn normally. If a
// selection is being rendered, use that, otherwise use the presshell's
// selection.
RefPtr<nsFrameSelection> frameSelection;
if (aSelection) {
frameSelection = aSelection->GetFrameSelection();
} else {
frameSelection = FrameSelection();
}
int16_t oldDisplaySelection = frameSelection->GetDisplaySelection();
frameSelection->SetDisplaySelection(nsISelectionController::SELECTION_HIDDEN);
// next, paint each range in the selection
for (const UniquePtr<RangePaintInfo>& rangeInfo : aItems) {
// the display lists paint relative to the offset from the reference
// frame, so account for that translation too:
gfxPoint rootOffset = nsLayoutUtils::PointToGfxPoint(
rangeInfo->mRootOffset, pc->AppUnitsPerDevPixel());
ctx.SetMatrixDouble(initialTM.PreTranslate(rootOffset));
aArea.MoveBy(-rangeInfo->mRootOffset.x, -rangeInfo->mRootOffset.y);
nsRegion visible(aArea);
rangeInfo->mList.PaintRoot(&rangeInfo->mBuilder, &ctx,
nsDisplayList::PAINT_DEFAULT, Nothing());
aArea.MoveBy(rangeInfo->mRootOffset.x, rangeInfo->mRootOffset.y);
}
// restore the old selection display state
frameSelection->SetDisplaySelection(oldDisplaySelection);
return dt->Snapshot();
}
already_AddRefed<SourceSurface> PresShell::RenderNode(
nsINode* aNode, const Maybe<CSSIntRegion>& aRegion,
const LayoutDeviceIntPoint aPoint, LayoutDeviceIntRect* aScreenRect,
RenderImageFlags aFlags) {
// area will hold the size of the surface needed to draw the node, measured
// from the root frame.
nsRect area;
nsTArray<UniquePtr<RangePaintInfo>> rangeItems;
// nothing to draw if the node isn't in a document
if (!aNode->IsInComposedDoc()) {
return nullptr;
}
RefPtr<nsRange> range = nsRange::Create(aNode);
IgnoredErrorResult rv;
range->SelectNode(*aNode, rv);
if (rv.Failed()) {
return nullptr;
}
UniquePtr<RangePaintInfo> info = CreateRangePaintInfo(range, area, false);
if (info) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier, or change the return type to void.
rangeItems.AppendElement(std::move(info));
}
Maybe<CSSIntRegion> region = aRegion;
if (region) {
// combine the area with the supplied region
CSSIntRect rrectPixels = region->GetBounds();
nsRect rrect = ToAppUnits(rrectPixels, AppUnitsPerCSSPixel());
area.IntersectRect(area, rrect);
nsPresContext* pc = GetPresContext();
if (!pc) {
return nullptr;
}
// move the region so that it is offset from the topleft corner of the
// surface
region->MoveBy(-nsPresContext::AppUnitsToIntCSSPixels(area.x),
-nsPresContext::AppUnitsToIntCSSPixels(area.y));
}
return PaintRangePaintInfo(rangeItems, nullptr, region, area, aPoint,
aScreenRect, aFlags);
}
already_AddRefed<SourceSurface> PresShell::RenderSelection(
Selection* aSelection, const LayoutDeviceIntPoint aPoint,
LayoutDeviceIntRect* aScreenRect, RenderImageFlags aFlags) {
// area will hold the size of the surface needed to draw the selection,
// measured from the root frame.
nsRect area;
nsTArray<UniquePtr<RangePaintInfo>> rangeItems;
// iterate over each range and collect them into the rangeItems array.
// This is done so that the size of selection can be determined so as
// to allocate a surface area
const uint32_t rangeCount = aSelection->RangeCount();
NS_ASSERTION(rangeCount > 0, "RenderSelection called with no selection");
for (const uint32_t r : IntegerRange(rangeCount)) {
MOZ_ASSERT(aSelection->RangeCount() == rangeCount);
RefPtr<nsRange> range = aSelection->GetRangeAt(r);
UniquePtr<RangePaintInfo> info = CreateRangePaintInfo(range, area, true);
if (info) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier.
rangeItems.AppendElement(std::move(info));
}
}
return PaintRangePaintInfo(rangeItems, aSelection, Nothing(), area, aPoint,
aScreenRect, aFlags);
}
static void AddDisplayItemToBottom(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList, nsDisplayItem* aItem) {
nsDisplayList list(aBuilder);
list.AppendToTop(aItem);
list.AppendToTop(aList);
aList->AppendToTop(&list);
}
void PresShell::AddCanvasBackgroundColorItem(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList,
nsIFrame* aFrame,
const nsRect& aBounds,
nscolor aBackstopColor) {
if (aBounds.IsEmpty() || !aFrame->IsViewportFrame()) {
// We don't want to add an item for the canvas background color if the frame
// (sub)tree we are painting doesn't include any canvas frames.
return;
}
const SingleCanvasBackground& canvasBg = mCanvasBackground.mViewport;
const nscolor bgcolor = NS_ComposeColors(aBackstopColor, canvasBg.mColor);
if (NS_GET_A(bgcolor) == 0) {
return;
}
// With async scrolling, we'd like to have two instances of the background
// color: one that scrolls with the content and one underneath which does not
// scroll with the content, but which can be shown during checkerboarding and
// overscroll and the dynamic toolbar movement. We can only do that if the
// color is opaque.
//
// We also need to paint the background if CSS hasn't specified it (since
// otherwise nsCanvasFrame might not paint it). Note that non-CSS-specified
// backgrounds shouldn't ever be semi-transparent.
const bool forceUnscrolledItem =
nsLayoutUtils::UsesAsyncScrolling(aFrame) && NS_GET_A(bgcolor) == 255;
if (canvasBg.mCSSSpecified && !forceUnscrolledItem) {
return;
}
MOZ_ASSERT(NS_GET_A(bgcolor) == 255);
const bool isRootContentDocumentCrossProcess =
mPresContext->IsRootContentDocumentCrossProcess();
MOZ_ASSERT_IF(
!aFrame->GetParent() && isRootContentDocumentCrossProcess &&
mPresContext->HasDynamicToolbar(),
aBounds.Size() ==
nsLayoutUtils::ExpandHeightForDynamicToolbar(
mPresContext, aFrame->InkOverflowRectRelativeToSelf().Size()));
nsDisplaySolidColor* item =
MakeDisplayItem<nsDisplaySolidColor>(aBuilder, aFrame, aBounds, bgcolor);
if (canvasBg.mCSSSpecified && isRootContentDocumentCrossProcess) {
item->SetIsCheckerboardBackground();
}
AddDisplayItemToBottom(aBuilder, aList, item);
}
bool PresShell::IsTransparentContainerElement() const {
if (mDocument->IsInitialDocument()) {
switch (StaticPrefs::layout_css_initial_document_transparency()) {
case 3:
return true;
case 2:
if (!mDocument->IsTopLevelContentDocument()) {
return true;
}
[[fallthrough]];
case 1:
if (mDocument->IsLikelyContentInaccessibleTopLevelAboutBlank()) {
return true;
}
[[fallthrough]];
default:
break;
}
}
nsPresContext* pc = GetPresContext();
if (!pc->IsRootContentDocumentCrossProcess()) {
if (mDocument->IsInChromeDocShell()) {
return true;
}
// Frames are transparent except if their used embedder color-scheme is
// mismatched, in which case we use an opaque background to avoid
// black-on-black or white-on-white text, see
// https://github.com/w3c/csswg-drafts/issues/4772
if (BrowsingContext* bc = mDocument->GetBrowsingContext()) {
switch (bc->GetEmbedderColorSchemes().mUsed) {
case dom::PrefersColorSchemeOverride::Light:
return pc->DefaultBackgroundColorScheme() == ColorScheme::Light;
case dom::PrefersColorSchemeOverride::Dark:
return pc->DefaultBackgroundColorScheme() == ColorScheme::Dark;
case dom::PrefersColorSchemeOverride::None:
break;
}
}
return true;
}
nsIDocShell* docShell = pc->GetDocShell();
if (!docShell) {
return false;
}
nsPIDOMWindowOuter* pwin = docShell->GetWindow();
if (!pwin) {
return false;
}
if (Element* containerElement = pwin->GetFrameElementInternal()) {
return containerElement->HasAttr(nsGkAtoms::transparent);
}
if (BrowserChild* tab = BrowserChild::GetFrom(docShell)) {
// Check if presShell is the top PresShell. Only the top can influence the
// canvas background color.
return this == tab->GetTopLevelPresShell() && tab->IsTransparent();
}
return false;
}
nscolor PresShell::GetDefaultBackgroundColorToDraw() const {
if (!mPresContext) {
return NS_RGB(255, 255, 255);
}
return mPresContext->DefaultBackgroundColor();
}
void PresShell::UpdateCanvasBackground() {
mCanvasBackground = ComputeCanvasBackground();
}
static SingleCanvasBackground ComputeSingleCanvasBackground(nsIFrame* aCanvas) {
MOZ_ASSERT(aCanvas->IsCanvasFrame());
const nsIFrame* bgFrame = nsCSSRendering::FindBackgroundFrame(aCanvas);
static constexpr nscolor kTransparent = NS_RGBA(0, 0, 0, 0);
if (bgFrame->IsThemed()) {
// Ignore the CSS background-color if `appearance` is used on the root.
return {kTransparent, false};
}
bool drawBackgroundImage = false;
bool drawBackgroundColor = false;
nscolor color = nsCSSRendering::DetermineBackgroundColor(
aCanvas->PresContext(), bgFrame->Style(), aCanvas, drawBackgroundImage,
drawBackgroundColor);
if (!drawBackgroundColor) {
// No need to draw the CSS-specified background (or no CSS-specified
// background at all).
return {kTransparent, false};
}
return {color, true};
}
PresShell::CanvasBackground PresShell::ComputeCanvasBackground() const {
// If we have a frame tree and it has style information that
// specifies the background color of the canvas, update our local
// cache of that color.
nsIFrame* canvas = GetCanvasFrame();
if (!canvas) {
nscolor color = GetDefaultBackgroundColorToDraw();
// If the root element of the document (ie html) has style 'display: none'
// then the document's background color does not get drawn; return the color
// we actually draw.
return {{color, false}, {color, false}};
}
auto viewportBg = ComputeSingleCanvasBackground(canvas);
if (!IsTransparentContainerElement()) {
viewportBg.mColor =
NS_ComposeColors(GetDefaultBackgroundColorToDraw(), viewportBg.mColor);
}
auto pageBg = viewportBg;
nsCanvasFrame* docElementCb =
mFrameConstructor->GetDocElementContainingBlock();
if (canvas != docElementCb) {
// We're in paged mode / print / print-preview, and just computed the "root"
// canvas background. Compute the doc element containing block background
// too.
MOZ_ASSERT(mPresContext->IsRootPaginatedDocument());
pageBg = ComputeSingleCanvasBackground(docElementCb);
}
return {viewportBg, pageBg};
}
nscolor PresShell::ComputeBackstopColor(nsView* aDisplayRoot) {
nsIWidget* widget = aDisplayRoot->GetWidget();
if (widget &&
(widget->GetTransparencyMode() != widget::TransparencyMode::Opaque ||
widget->WidgetPaintsBackground())) {
// Within a transparent widget, so the backstop color must be
// totally transparent.
return NS_RGBA(0, 0, 0, 0);
}
// Within an opaque widget (or no widget at all), so the backstop
// color must be totally opaque. The user's default background
// as reported by the prescontext is guaranteed to be opaque.
return GetDefaultBackgroundColorToDraw();
}
struct PaintParams {
nscolor mBackgroundColor;
};
WindowRenderer* PresShell::GetWindowRenderer() {
NS_ASSERTION(mViewManager, "Should have view manager");
nsView* rootView = mViewManager->GetRootView();
if (rootView) {
if (nsIWidget* widget = rootView->GetWidget()) {
return widget->GetWindowRenderer();
}
}
return nullptr;
}
bool PresShell::AsyncPanZoomEnabled() {
NS_ASSERTION(mViewManager, "Should have view manager");
nsView* rootView = mViewManager->GetRootView();
if (rootView) {
if (nsIWidget* widget = rootView->GetWidget()) {
return widget->AsyncPanZoomEnabled();
}
}
return gfxPlatform::AsyncPanZoomEnabled();
}
nsresult PresShell::SetResolutionAndScaleTo(float aResolution,
ResolutionChangeOrigin aOrigin) {
if (!(aResolution > 0.0)) {
return NS_ERROR_ILLEGAL_VALUE;
}
if (aResolution == mResolution.valueOr(0.0)) {
MOZ_ASSERT(mResolution.isSome());
return NS_OK;
}
// GetResolution handles mResolution being nothing by returning 1 so this
// is checking that the resolution is actually changing.
bool resolutionUpdated = aResolution != GetResolution();
mLastResolutionChangeOrigin = aOrigin;
RenderingState state(this);
state.mResolution = Some(aResolution);
SetRenderingState(state);
if (mMobileViewportManager) {
mMobileViewportManager->ResolutionUpdated(aOrigin);
}
// Changing the resolution changes the visual viewport size which may
// make the current visual viewport offset out-of-bounds (if the size
// increased). APZ will reconcile this by sending a clamped visual
// viewport offset on the next repaint, but to avoid main-thread code
// observing an out-of-bounds offset until then, reclamp it here.
if (IsVisualViewportOffsetSet()) {
SetVisualViewportOffset(GetVisualViewportOffset(),
GetLayoutViewportOffset());
}
if (aOrigin == ResolutionChangeOrigin::Apz) {
mResolutionUpdatedByApz = true;
} else if (resolutionUpdated) {
mResolutionUpdated = true;
}
if (auto* window = nsGlobalWindowInner::Cast(mDocument->GetInnerWindow())) {
window->VisualViewport()->PostResizeEvent();
}
return NS_OK;
}
float PresShell::GetCumulativeResolution() const {
float resolution = GetResolution();
nsPresContext* parentCtx = GetPresContext()->GetParentPresContext();
if (parentCtx) {
resolution *= parentCtx->PresShell()->GetCumulativeResolution();
}
return resolution;
}
void PresShell::SetRestoreResolution(float aResolution,
LayoutDeviceIntSize aDisplaySize) {
if (mMobileViewportManager) {
mMobileViewportManager->SetRestoreResolution(aResolution, aDisplaySize);
}
}
void PresShell::SetRenderingState(const RenderingState& aState) {
if (GetResolution() != aState.mResolution.valueOr(1.f)) {
if (nsIFrame* frame = GetRootFrame()) {
frame->SchedulePaint();
}
}
mRenderingStateFlags = aState.mRenderingStateFlags;
mResolution = aState.mResolution;
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
accService->NotifyOfResolutionChange(this, GetResolution());
}
#endif
}
void PresShell::SynthesizeMouseMove(bool aFromScroll) {
if (!StaticPrefs::layout_reflow_synthMouseMove()) {
return;
}
if (mPaintingSuppressed || !mIsActive || !mPresContext) {
return;
}
if (!IsRoot()) {
if (PresShell* rootPresShell = GetRootPresShell()) {
rootPresShell->SynthesizeMouseMove(aFromScroll);
}
return;
}
if (mLastMousePointerId.isNothing() && !mPointerIds.IsEmpty()) {
return;
}
if (!mSynthMouseMoveEvent.IsPending()) {
auto ev = MakeRefPtr<nsSynthMouseMoveEvent>(this, aFromScroll);
GetPresContext()->RefreshDriver()->AddRefreshObserver(
ev, FlushType::Display, "Synthetic mouse move event");
mSynthMouseMoveEvent = std::move(ev);
}
}
static nsView* FindFloatingViewContaining(nsPresContext* aRootPresContext,
nsIWidget* aRootWidget,
const LayoutDeviceIntPoint& aPt) {
nsIFrame* popupFrame = nsLayoutUtils::GetPopupFrameForPoint(
aRootPresContext, aRootWidget, aPt,
nsLayoutUtils::GetPopupFrameForPointFlags::OnlyReturnFramesWithWidgets);
return popupFrame ? popupFrame->GetView() : nullptr;
}
/*
* This finds the first view with a frame that contains the given point in a
* postorder traversal of the view tree, assuming that the point is not in a
* floating view. It assumes that only floating views extend outside the bounds
* of their parents.
*
* This methods should only be called if FindFloatingViewContaining returns
* null.
*
* aPt is relative aRelativeToView with the viewport type
* aRelativeToViewportType. aRelativeToView will always have a frame. If aView
* has a frame then aRelativeToView will be aView. (The reason aRelativeToView
* and aView are separate is because we need to traverse into views without
* frames (ie the inner view of a subdocument frame) but we can only easily
* transform between views using TransformPoint which takes frames.)
*/
static nsView* FindViewContaining(nsView* aRelativeToView,
ViewportType aRelativeToViewportType,
nsView* aView, nsPoint aPt) {
MOZ_ASSERT(aRelativeToView->GetFrame());
if (aView->GetVisibility() == ViewVisibility::Hide) {
return nullptr;
}
nsIFrame* frame = aView->GetFrame();
if (frame) {
if (!frame->PresShell()->IsActive() ||
!frame->IsVisibleConsideringAncestors(
nsIFrame::VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY)) {
return nullptr;
}
// We start out in visual coords and then if we cross the zoom boundary we
// become in layout coords. The zoom boundary always occurs in a document
// with IsRootContentDocumentCrossProcess. The root view of such a document
// is outside the zoom boundary and any child view must be inside the zoom
// boundary because we only create views for certain kinds of frames and
// none of them can be between the root frame and the zoom boundary.
bool crossingZoomBoundary = false;
if (aRelativeToViewportType == ViewportType::Visual) {
if (!aRelativeToView->GetParent() ||
aRelativeToView->GetViewManager() !=
aRelativeToView->GetParent()->GetViewManager()) {
if (aRelativeToView->GetFrame()
->PresContext()
->IsRootContentDocumentCrossProcess()) {
crossingZoomBoundary = true;
}
}
}
ViewportType nextRelativeToViewportType = aRelativeToViewportType;
if (crossingZoomBoundary) {
nextRelativeToViewportType = ViewportType::Layout;
}
nsLayoutUtils::TransformResult result = nsLayoutUtils::TransformPoint(
RelativeTo{aRelativeToView->GetFrame(), aRelativeToViewportType},
RelativeTo{frame, nextRelativeToViewportType}, aPt);
if (result != nsLayoutUtils::TRANSFORM_SUCCEEDED) {
return nullptr;
}
// Even though aPt is in visual coordinates until we cross the zoom boundary
// it is valid to compare it to view coords (which are in layout coords)
// because visual coords are the same as layout coords for every view
// outside of the zoom boundary except for the root view of the root content
// document.
// For the root view of the root content document, its bounds don't
// actually correspond to what is visible when we have a
// MobileViewportManager. So we skip the hit test. This is okay because the
// point has already been hit test: 1) if we are the root view in the
// process then the point comes from a real mouse event so it must have been
// over our widget, or 2) if we are the root of a subdocument then
// hittesting against the view of the subdocument frame that contains us
// already happened and succeeded before getting here.
if (!crossingZoomBoundary) {
if (!aView->GetDimensions().Contains(aPt)) {
return nullptr;
}
}
aRelativeToView = aView;
aRelativeToViewportType = nextRelativeToViewportType;
}
for (nsView* v = aView->GetFirstChild(); v; v = v->GetNextSibling()) {
nsView* r =
FindViewContaining(aRelativeToView, aRelativeToViewportType, v, aPt);
if (r) {
return r;
}
}
return frame ? aView : nullptr;
}
static BrowserBridgeChild* GetChildBrowser(nsView* aView) {
if (!aView) {
return nullptr;
}
nsIFrame* frame = aView->GetFrame();
if (!frame && aView->GetParent()) {
// If frame is null then view is an anonymous inner view, and we want
// the frame from the corresponding outer view.
frame = aView->GetParent()->GetFrame();
}
if (!frame || !frame->GetContent()) {
return nullptr;
}
return BrowserBridgeChild::GetFrom(frame->GetContent());
}
void PresShell::ProcessSynthMouseMoveEvent(bool aFromScroll) {
auto forgetMouseMove = MakeScopeExit([&]() {
// Must be safe to refer `this` without grabbing it with a RefPtr since this
// method is marked as MOZ_CAN_RUN_SCRIPT, and we don't want to use RefPtr
// here because of a hot path
mSynthMouseMoveEvent.Forget();
});
// If drag session has started, we shouldn't synthesize mousemove event.
nsView* rootView = mViewManager ? mViewManager->GetRootView() : nullptr;
if (!rootView || !rootView->HasWidget()) {
return;
}
nsCOMPtr<nsIDragSession> dragSession =
nsContentUtils::GetDragSession(rootView->GetWidget());
if (dragSession) {
// Don't forget it. We need to synthesize a mouse move when the drag
// session ends.
forgetMouseMove.release();
return;
}
if (!mPresContext) {
return;
}
// allow new event to be posted while handling this one only if the
// source of the event is a scroll (to prevent infinite reflow loops)
if (aFromScroll) {
mSynthMouseMoveEvent.Forget();
forgetMouseMove.release();
}
NS_ASSERTION(IsRoot(), "Only a root pres shell should be here");
if (StaticPrefs::dom_event_pointer_boundary_dispatch_when_layout_change()) {
const AutoTArray<uint32_t, 16> pointerIds(mPointerIds.Clone());
for (const uint32_t pointerId : pointerIds) {
const PointerInfo* const pointerInfo =
PointerEventHandler::GetPointerInfo(pointerId);
if (MOZ_UNLIKELY(!pointerInfo) || !pointerInfo->HasLastState() ||
// We shouldn't dispatch pointer boundary events when a layout change
// if the pointer is not a stationary device.
!pointerInfo->InputSourceSupportsHover()) {
continue;
}
// If the pointer is captured, we don't need to dispatch pointer boundary
// events since pointer boundary events should be fired before
// gotpointercapture.
PointerCaptureInfo* const captureInfo =
PointerEventHandler::GetPointerCaptureInfo(pointerId);
if (captureInfo && captureInfo->mOverrideElement) {
continue;
}
ProcessSynthMouseOrPointerMoveEvent(ePointerMove, pointerId,
*pointerInfo);
}
}
if (mLastMousePointerId.isSome()) {
if (const PointerInfo* const lastMouseInfo =
PointerEventHandler::GetLastMouseInfo(this)) {
if (lastMouseInfo->HasLastState()) {
ProcessSynthMouseOrPointerMoveEvent(eMouseMove, *mLastMousePointerId,
*lastMouseInfo);
}
}
}
}
void PresShell::ProcessSynthMouseOrPointerMoveEvent(
EventMessage aMoveMessage, uint32_t aPointerId,
const PointerInfo& aPointerInfo) {
MOZ_ASSERT(aMoveMessage == eMouseMove || aMoveMessage == ePointerMove);
NS_ASSERTION(IsRoot(), "Only a root pres shell should be here");
#ifdef DEBUG
if (aMoveMessage == eMouseMove) {
MOZ_LOG(PointerEventHandler::MouseLocationLogRef(), LogLevel::Info,
("[ps=%p]synthesizing %s to (%d,%d)\n", this, ToChar(aMoveMessage),
aPointerInfo.mLastRefPointInRootDoc.x,
aPointerInfo.mLastRefPointInRootDoc.y));
}
#endif
int32_t APD = mPresContext->AppUnitsPerDevPixel();
// We need a widget to put in the event we are going to dispatch so we look
// for a view that has a widget and the mouse location is over. We first look
// for floating views, if there isn't one we use the root view. |view| holds
// that view.
nsView* view = nullptr;
// The appunits per devpixel ratio of |view|.
int32_t viewAPD;
// mRefPoint will be mMouseLocation relative to the widget of |view|, the
// widget we will put in the event we dispatch, in viewAPD appunits
nsPoint refpoint(0, 0);
// We always dispatch the event to the pres shell that contains the view that
// the mouse is over. pointVM is the VM of that pres shell.
nsViewManager* pointVM = nullptr;
nsView* const rootView = mViewManager ? mViewManager->GetRootView() : nullptr;
if (!rootView || !rootView->HasWidget()) {
return;
}
#ifdef DEBUG
nsCOMPtr<nsIDragSession> dragSession =
nsContentUtils::GetDragSession(rootView->GetWidget());
MOZ_ASSERT(!dragSession);
#endif
if (rootView->GetFrame()) {
view =
FindFloatingViewContaining(mPresContext, rootView->GetWidget(),
LayoutDeviceIntPoint::FromAppUnitsToNearest(
aPointerInfo.mLastRefPointInRootDoc +
rootView->ViewToWidgetOffset(),
APD));
}
nsView* pointView = view;
if (!view) {
view = rootView;
if (rootView->GetFrame()) {
pointView = FindViewContaining(rootView, ViewportType::Visual, rootView,
aPointerInfo.mLastRefPointInRootDoc);
} else {
pointView = rootView;
}
// pointView can be null in situations related to mouse capture
pointVM = (pointView ? pointView : view)->GetViewManager();
refpoint =
aPointerInfo.mLastRefPointInRootDoc + rootView->ViewToWidgetOffset();
viewAPD = APD;
} else {
pointVM = view->GetViewManager();
nsIFrame* frame = view->GetFrame();
NS_ASSERTION(frame, "floating views can't be anonymous");
viewAPD = frame->PresContext()->AppUnitsPerDevPixel();
refpoint = aPointerInfo.mLastRefPointInRootDoc;
DebugOnly<nsLayoutUtils::TransformResult> result =
nsLayoutUtils::TransformPoint(
RelativeTo{rootView->GetFrame(), ViewportType::Visual},
RelativeTo{frame, ViewportType::Layout}, refpoint);
MOZ_ASSERT(result == nsLayoutUtils::TRANSFORM_SUCCEEDED);
refpoint += view->ViewToWidgetOffset();
}
NS_ASSERTION(view->GetWidget(), "view should have a widget here");
Maybe<WidgetMouseEvent> mouseMoveEvent;
Maybe<WidgetPointerEvent> pointerMoveEvent;
if (aMoveMessage == eMouseMove) {
mouseMoveEvent.emplace(true, eMouseMove, view->GetWidget(),
WidgetMouseEvent::eSynthesized);
// We don't want to dispatch preceding pointer event since the caller
// should've already been dispatched it. However, if the target is an OOP
// iframe, we'll set this to true again below.
mouseMoveEvent->convertToPointer = false;
} else {
pointerMoveEvent.emplace(true, ePointerMove, view->GetWidget());
pointerMoveEvent->mReason = WidgetMouseEvent::eSynthesized;
}
WidgetMouseEvent& event =
mouseMoveEvent ? mouseMoveEvent.ref() : pointerMoveEvent.ref();
// If the last cursor location was set by a synthesized mouse event for tests,
// running test should expect a restyle or a DOM mutation under the cursor may
// cause mouse boundary events in a remote process if the cursor is over a
// remote content. Therefore, the events should not be ignored by
// PresShell::HandleEvent in the remote process. So we need to mark the
// synthesized eMouseMove as "synthesized for tests".
event.mFlags.mIsSynthesizedForTests = aPointerInfo.mIsSynthesizedForTests;
event.mRefPoint =
LayoutDeviceIntPoint::FromAppUnitsToNearest(refpoint, viewAPD);
event.mButtons = aPointerInfo.mLastButtons;
event.mInputSource = aPointerInfo.mInputSource;
event.pointerId = aPointerId;
event.mModifiers = PresShell::GetCurrentModifiers();
if (BrowserBridgeChild* bbc = GetChildBrowser(pointView)) {
// If we have a BrowserBridgeChild, we're going to be dispatching this
// mouse event into an OOP iframe of the current document if and only if
// we're synthesizing a mouse move.
// FIXME: We may need to dispatch ePointerMove in the OOP iframe too.
// However, it may require to change the active pointer state in both this
// process and the OOP iframe process too. Therefore, we will fire
// ePointerMove as a preceding pointer event of the synthesized eMouseMove
// in PointerEventHandler::DispatchPointerFromMouseOrTouch().
if (aMoveMessage == eMouseMove) {
event.mLayersId = bbc->GetLayersId();
event.convertToPointer = true;
bbc->SendDispatchSynthesizedMouseEvent(event);
}
return;
}
if (RefPtr<PresShell> presShell = pointVM->GetPresShell()) {
// Since this gets run in a refresh tick there isn't an InputAPZContext on
// the stack from the nsBaseWidget. We need to simulate one with at least
// the correct target guid, so that the correct callback transform gets
// applied if this event goes to a child process. The input block id is set
// to 0 because this is a synthetic event which doesn't really belong to any
// input block. Same for the APZ response field.
InputAPZContext apzContext(aPointerInfo.mLastTargetGuid, 0,
nsEventStatus_eIgnore);
presShell->DispatchSynthMouseOrPointerMove(&event);
}
}
/* static */
void PresShell::MarkFramesInListApproximatelyVisible(
const nsDisplayList& aList) {
for (nsDisplayItem* item : aList) {
nsDisplayList* sublist = item->GetChildren();
if (sublist) {
MarkFramesInListApproximatelyVisible(*sublist);
continue;
}
nsIFrame* frame = item->Frame();
MOZ_ASSERT(frame);
if (!frame->TrackingVisibility()) {
continue;
}
// Use the presshell containing the frame.
PresShell* presShell = frame->PresShell();
MOZ_ASSERT(!presShell->AssumeAllFramesVisible());
if (presShell->mApproximatelyVisibleFrames.EnsureInserted(frame)) {
// The frame was added to mApproximatelyVisibleFrames, so increment its
// visible count.
frame->IncApproximateVisibleCount();
}
}
}
/* static */
void PresShell::DecApproximateVisibleCount(
VisibleFrames& aFrames, const Maybe<OnNonvisible>& aNonvisibleAction
/* = Nothing() */) {
for (nsIFrame* frame : aFrames) {
// Decrement the frame's visible count if we're still tracking its
// visibility. (We may not be, if the frame disabled visibility tracking
// after we added it to the visible frames list.)
if (frame->TrackingVisibility()) {
frame->DecApproximateVisibleCount(aNonvisibleAction);
}
}
}
void PresShell::RebuildApproximateFrameVisibilityDisplayList(
const nsDisplayList& aList) {
MOZ_ASSERT(!mApproximateFrameVisibilityVisited, "already visited?");
mApproximateFrameVisibilityVisited = true;
// Remove the entries of the mApproximatelyVisibleFrames hashtable and put
// them in oldApproxVisibleFrames.
VisibleFrames oldApproximatelyVisibleFrames =
std::move(mApproximatelyVisibleFrames);
MarkFramesInListApproximatelyVisible(aList);
DecApproximateVisibleCount(oldApproximatelyVisibleFrames);
}
/* static */
void PresShell::ClearApproximateFrameVisibilityVisited(nsView* aView,
bool aClear) {
nsViewManager* vm = aView->GetViewManager();
if (aClear) {
PresShell* presShell = vm->GetPresShell();
if (!presShell->mApproximateFrameVisibilityVisited) {
presShell->ClearApproximatelyVisibleFramesList();
}
presShell->mApproximateFrameVisibilityVisited = false;
}
for (nsView* v = aView->GetFirstChild(); v; v = v->GetNextSibling()) {
ClearApproximateFrameVisibilityVisited(v, v->GetViewManager() != vm);
}
}
void PresShell::ClearApproximatelyVisibleFramesList(
const Maybe<OnNonvisible>& aNonvisibleAction
/* = Nothing() */) {
DecApproximateVisibleCount(mApproximatelyVisibleFrames, aNonvisibleAction);
mApproximatelyVisibleFrames.Clear();
}
void PresShell::MarkFramesInSubtreeApproximatelyVisible(
nsIFrame* aFrame, const nsRect& aRect, bool aRemoveOnly /* = false */) {
MOZ_DIAGNOSTIC_ASSERT(aFrame, "aFrame arg should be a valid frame pointer");
MOZ_ASSERT(aFrame->PresShell() == this, "wrong presshell");
if (aFrame->TrackingVisibility() && aFrame->StyleVisibility()->IsVisible() &&
(!aRemoveOnly ||
aFrame->GetVisibility() == Visibility::ApproximatelyVisible)) {
MOZ_ASSERT(!AssumeAllFramesVisible());
if (mApproximatelyVisibleFrames.EnsureInserted(aFrame)) {
// The frame was added to mApproximatelyVisibleFrames, so increment its
// visible count.
aFrame->IncApproximateVisibleCount();
}
}
nsSubDocumentFrame* subdocFrame = do_QueryFrame(aFrame);
if (subdocFrame) {
PresShell* presShell = subdocFrame->GetSubdocumentPresShellForPainting(
nsSubDocumentFrame::IGNORE_PAINT_SUPPRESSION);
if (presShell && !presShell->AssumeAllFramesVisible()) {
nsRect rect = aRect;
nsIFrame* root = presShell->GetRootFrame();
if (root) {
rect.MoveBy(aFrame->GetOffsetToCrossDoc(root));
} else {
rect.MoveBy(-aFrame->GetContentRectRelativeToSelf().TopLeft());
}
rect = rect.ScaleToOtherAppUnitsRoundOut(
aFrame->PresContext()->AppUnitsPerDevPixel(),
presShell->GetPresContext()->AppUnitsPerDevPixel());
presShell->RebuildApproximateFrameVisibility(&rect);
}
return;
}
nsRect rect = aRect;
if (ScrollContainerFrame* scrollFrame = do_QueryFrame(aFrame)) {
bool ignoreDisplayPort = false;
if (DisplayPortUtils::IsMissingDisplayPortBaseRect(aFrame->GetContent())) {
// We can properly set the base rect for root scroll frames on top level
// and root content documents. Otherwise the base rect we compute might
// be way too big without the limiting that
// ScrollContainerFrame::DecideScrollableLayer does, so we just ignore the
// displayport in that case.
nsPresContext* pc = aFrame->PresContext();
if (scrollFrame->IsRootScrollFrameOfDocument() &&
(pc->IsRootContentDocumentCrossProcess() ||
(pc->IsChrome() && !pc->GetParentPresContext()))) {
nsRect baseRect(
nsPoint(), nsLayoutUtils::CalculateCompositionSizeForFrame(aFrame));
DisplayPortUtils::SetDisplayPortBase(aFrame->GetContent(), baseRect);
} else {
ignoreDisplayPort = true;
}
}
nsRect displayPort;
bool usingDisplayport =
!ignoreDisplayPort &&
DisplayPortUtils::GetDisplayPortForVisibilityTesting(
aFrame->GetContent(), &displayPort);
scrollFrame->NotifyApproximateFrameVisibilityUpdate(!usingDisplayport);
if (usingDisplayport) {
rect = displayPort;
} else {
rect = rect.Intersect(scrollFrame->GetScrollPortRect());
}
rect = scrollFrame->ExpandRectToNearlyVisible(rect);
}
bool preserves3DChildren = aFrame->Extend3DContext();
for (const auto& [list, listID] : aFrame->ChildLists()) {
for (nsIFrame* child : list) {
// Note: This assert should be trivially satisfied, just by virtue of how
// nsFrameList and its iterator works (with nullptr being an end-of-list
// sentinel which should terminate the loop). But we do somehow get
// crash reports inside this loop that suggest `child` is null...
MOZ_DIAGNOSTIC_ASSERT(child, "shouldn't have null values in child lists");
nsRect r = rect - child->GetPosition();
if (!r.IntersectRect(r, child->InkOverflowRect())) {
continue;
}
if (child->IsTransformed()) {
// for children of a preserve3d element we just pass down the same dirty
// rect
if (!preserves3DChildren ||
!child->Combines3DTransformWithAncestors()) {
const nsRect overflow = child->InkOverflowRectRelativeToSelf();
nsRect out;
if (nsDisplayTransform::UntransformRect(r, overflow, child, &out)) {
r = out;
} else {
r.SetEmpty();
}
}
}
MarkFramesInSubtreeApproximatelyVisible(child, r, aRemoveOnly);
}
}
}
void PresShell::RebuildApproximateFrameVisibility(
nsRect* aRect, bool aRemoveOnly /* = false */) {
MOZ_ASSERT(!mApproximateFrameVisibilityVisited, "already visited?");
mApproximateFrameVisibilityVisited = true;
nsIFrame* rootFrame = GetRootFrame();
if (!rootFrame) {
return;
}
// Remove the entries of the mApproximatelyVisibleFrames hashtable and put
// them in oldApproximatelyVisibleFrames.
VisibleFrames oldApproximatelyVisibleFrames =
std::move(mApproximatelyVisibleFrames);
nsRect vis(nsPoint(0, 0), rootFrame->GetSize());
if (aRect) {
vis = *aRect;
}
// If we are in-process root but not the top level content, we need to take
// the intersection with the iframe visible rect.
if (mPresContext->IsRootContentDocumentInProcess() &&
!mPresContext->IsRootContentDocumentCrossProcess()) {
// There are two possibilities that we can't get the iframe's visible
// rect other than the iframe is out side of ancestors' display ports.
// a) the BrowserChild is being torn down
// b) the visible rect hasn't been delivered the BrowserChild
// In both cases we consider the visible rect is empty.
Maybe<nsRect> visibleRect;
if (BrowserChild* browserChild = BrowserChild::GetFrom(this)) {
visibleRect = browserChild->GetVisibleRect();
}
vis = vis.Intersect(visibleRect.valueOr(nsRect()));
}
MarkFramesInSubtreeApproximatelyVisible(rootFrame, vis, aRemoveOnly);
DecApproximateVisibleCount(oldApproximatelyVisibleFrames);
}
void PresShell::UpdateApproximateFrameVisibility() {
DoUpdateApproximateFrameVisibility(/* aRemoveOnly = */ false);
}
void PresShell::DoUpdateApproximateFrameVisibility(bool aRemoveOnly) {
MOZ_ASSERT(
!mPresContext || mPresContext->IsRootContentDocumentInProcess(),
"Updating approximate frame visibility on a non-root content document?");
mUpdateApproximateFrameVisibilityEvent.Revoke();
if (mHaveShutDown || mIsDestroying) {
return;
}
// call update on that frame
nsIFrame* rootFrame = GetRootFrame();
if (!rootFrame) {
ClearApproximatelyVisibleFramesList(Some(OnNonvisible::DiscardImages));
return;
}
RebuildApproximateFrameVisibility(/* aRect = */ nullptr, aRemoveOnly);
ClearApproximateFrameVisibilityVisited(rootFrame->GetView(), true);
#ifdef DEBUG_FRAME_VISIBILITY_DISPLAY_LIST
// This can be used to debug the frame walker by comparing beforeFrameList
// and mApproximatelyVisibleFrames in RebuildFrameVisibilityDisplayList to see
// if they produce the same results (mApproximatelyVisibleFrames holds the
// frames the display list thinks are visible, beforeFrameList holds the
// frames the frame walker thinks are visible).
nsDisplayListBuilder builder(
rootFrame, nsDisplayListBuilderMode::FRAME_VISIBILITY, false);
nsRect updateRect(nsPoint(0, 0), rootFrame->GetSize());
nsIFrame* rootScroll = GetRootScrollFrame();
if (rootScroll) {
nsIContent* content = rootScroll->GetContent();
if (content) {
Unused << nsLayoutUtils::GetDisplayPortForVisibilityTesting(
content, &updateRect, RelativeTo::ScrollFrame);
}
if (IgnoringViewportScrolling()) {
builder.SetIgnoreScrollFrame(rootScroll);
}
}
builder.IgnorePaintSuppression();
builder.EnterPresShell(rootFrame);
nsDisplayList list;
rootFrame->BuildDisplayListForStackingContext(&builder, updateRect, &list);
builder.LeavePresShell(rootFrame, &list);
RebuildApproximateFrameVisibilityDisplayList(list);
ClearApproximateFrameVisibilityVisited(rootFrame->GetView(), true);
list.DeleteAll(&builder);
#endif
}
bool PresShell::AssumeAllFramesVisible() {
if (!StaticPrefs::layout_framevisibility_enabled() || !mPresContext ||
!mDocument) {
return true;
}
// We assume all frames are visible in print, print preview, chrome, and
// resource docs and don't keep track of them.
if (mPresContext->Type() == nsPresContext::eContext_PrintPreview ||
mPresContext->Type() == nsPresContext::eContext_Print ||
mPresContext->IsChrome() || mDocument->IsResourceDoc()) {
return true;
}
// If we're assuming all frames are visible in the top level content
// document, we need to in subdocuments as well. Otherwise we can get in a
// situation where things like animations won't work in subdocuments because
// their frames appear not to be visible, since we won't schedule an image
// visibility update if the top level content document is assuming all
// frames are visible.
//
// Note that it's not safe to call IsRootContentDocumentInProcess() if we're
// currently being destroyed, so we have to check that first.
if (!mHaveShutDown && !mIsDestroying &&
!mPresContext->IsRootContentDocumentInProcess()) {
nsPresContext* presContext =
mPresContext->GetInProcessRootContentDocumentPresContext();
if (presContext && presContext->PresShell()->AssumeAllFramesVisible()) {
return true;
}
}
return false;
}
void PresShell::ScheduleApproximateFrameVisibilityUpdateSoon() {
if (AssumeAllFramesVisible()) {
return;
}
if (!mPresContext) {
return;
}
nsRefreshDriver* refreshDriver = mPresContext->RefreshDriver();
if (!refreshDriver) {
return;
}
// Ask the refresh driver to update frame visibility soon.
refreshDriver->ScheduleFrameVisibilityUpdate();
}
void PresShell::ScheduleApproximateFrameVisibilityUpdateNow() {
if (AssumeAllFramesVisible()) {
return;
}
if (!mPresContext->IsRootContentDocumentInProcess()) {
nsPresContext* presContext =
mPresContext->GetInProcessRootContentDocumentPresContext();
if (!presContext) {
return;
}
MOZ_ASSERT(presContext->IsRootContentDocumentInProcess(),
"Didn't get a root prescontext from "
"GetInProcessRootContentDocumentPresContext?");
presContext->PresShell()->ScheduleApproximateFrameVisibilityUpdateNow();
return;
}
if (mHaveShutDown || mIsDestroying) {
return;
}
if (mUpdateApproximateFrameVisibilityEvent.IsPending()) {
return;
}
RefPtr<nsRunnableMethod<PresShell>> event =
NewRunnableMethod("PresShell::UpdateApproximateFrameVisibility", this,
&PresShell::UpdateApproximateFrameVisibility);
nsresult rv = mDocument->Dispatch(do_AddRef(event));
if (NS_SUCCEEDED(rv)) {
mUpdateApproximateFrameVisibilityEvent = std::move(event);
}
}
void PresShell::EnsureFrameInApproximatelyVisibleList(nsIFrame* aFrame) {
if (!aFrame->TrackingVisibility()) {
return;
}
if (AssumeAllFramesVisible()) {
aFrame->IncApproximateVisibleCount();
return;
}
#ifdef DEBUG
// Make sure it's in this pres shell.
nsCOMPtr<nsIContent> content = aFrame->GetContent();
if (content) {
PresShell* presShell = content->OwnerDoc()->GetPresShell();
MOZ_ASSERT(!presShell || presShell == this, "wrong shell");
}
#endif
if (mApproximatelyVisibleFrames.EnsureInserted(aFrame)) {
// We inserted a new entry.
aFrame->IncApproximateVisibleCount();
}
}
void PresShell::RemoveFrameFromApproximatelyVisibleList(nsIFrame* aFrame) {
#ifdef DEBUG
// Make sure it's in this pres shell.
nsCOMPtr<nsIContent> content = aFrame->GetContent();
if (content) {
PresShell* presShell = content->OwnerDoc()->GetPresShell();
MOZ_ASSERT(!presShell || presShell == this, "wrong shell");
}
#endif
if (AssumeAllFramesVisible()) {
MOZ_ASSERT(mApproximatelyVisibleFrames.Count() == 0,
"Shouldn't have any frames in the table");
return;
}
if (mApproximatelyVisibleFrames.EnsureRemoved(aFrame) &&
aFrame->TrackingVisibility()) {
// aFrame was in the hashtable, and we're still tracking its visibility,
// so we need to decrement its visible count.
aFrame->DecApproximateVisibleCount();
}
}
void PresShell::PaintAndRequestComposite(nsView* aView, PaintFlags aFlags) {
if (!mIsActive) {
return;
}
WindowRenderer* renderer = aView->GetWidget()->GetWindowRenderer();
NS_ASSERTION(renderer, "Must be in paint event");
if (renderer->AsFallback()) {
// The fallback renderer doesn't do any retaining, so we
// just need to notify the view and widget that we're invalid, and
// we'll do a paint+composite from the PaintWindow callback.
GetViewManager()->InvalidateView(aView);
return;
}
// Otherwise we're a retained WebRenderLayerManager, so we want to call
// Paint to update with any changes and push those to WR.
PaintInternalFlags flags = PaintInternalFlags::None;
if (aFlags & PaintFlags::PaintSyncDecodeImages) {
flags |= PaintInternalFlags::PaintSyncDecodeImages;
}
if (aFlags & PaintFlags::PaintCompositeOffscreen) {
flags |= PaintInternalFlags::PaintCompositeOffscreen;
}
PaintInternal(aView, flags);
}
void PresShell::SyncPaintFallback(nsView* aView) {
if (!mIsActive) {
return;
}
WindowRenderer* renderer = aView->GetWidget()->GetWindowRenderer();
NS_ASSERTION(renderer->AsFallback(),
"Can't do Sync paint for remote renderers");
if (!renderer->AsFallback()) {
return;
}
PaintInternal(aView, PaintInternalFlags::PaintComposite);
GetPresContext()->NotifyDidPaintForSubtree();
}
void PresShell::PaintInternal(nsView* aViewToPaint, PaintInternalFlags aFlags) {
nsCString url;
nsIURI* uri = mDocument->GetDocumentURI();
Document* contentRoot = GetPrimaryContentDocument();
if (contentRoot) {
uri = contentRoot->GetDocumentURI();
}
url = uri ? uri->GetSpecOrDefault() : "N/A"_ns;
AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING_RELEVANT_FOR_JS(
"Paint", GRAPHICS, Substring(url, std::min(size_t(128), url.Length())));
Maybe<js::AutoAssertNoContentJS> nojs;
// On Android, Flash can call into content JS during painting, so we can't
// assert there. However, we don't rely on this assertion on Android because
// we don't paint while JS is running.
#if !defined(MOZ_WIDGET_ANDROID)
if (!(aFlags & PaintInternalFlags::PaintComposite)) {
// We need to allow content JS when the flag is set since we may trigger
// MozAfterPaint events in content in those cases.
nojs.emplace(dom::danger::GetJSContext());
}
#endif
NS_ASSERTION(!mIsDestroying, "painting a destroyed PresShell");
NS_ASSERTION(aViewToPaint, "null view");
MOZ_ASSERT(!mApproximateFrameVisibilityVisited, "Should have been cleared");
if (!mIsActive) {
return;
}
nsIFrame* frame = aViewToPaint->GetFrame();
FocusTarget focusTarget;
if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
// Update the focus target for async keyboard scrolling. This will be
// forwarded to APZ by nsDisplayList::PaintRoot. We need to to do this
// before we enter the paint phase because dispatching eVoid events can
// cause layout to happen.
uint64_t focusSequenceNumber;
if (nsMenuPopupFrame* popup = do_QueryFrame(frame)) {
focusSequenceNumber = popup->GetAPZFocusSequenceNumber();
} else {
focusSequenceNumber = mAPZFocusSequenceNumber;
}
focusTarget = FocusTarget(this, focusSequenceNumber);
}
nsPresContext* presContext = GetPresContext();
AUTO_LAYOUT_PHASE_ENTRY_POINT(presContext, Paint);
WindowRenderer* renderer = aViewToPaint->GetWidget()->GetWindowRenderer();
NS_ASSERTION(renderer, "Must be in paint event");
WebRenderLayerManager* layerManager = renderer->AsWebRender();
// Whether or not we should set first paint when painting is suppressed
// is debatable. For now we'll do it because B2G relied on first paint
// to configure the viewport and we only want to do that when we have
// real content to paint. See Bug 798245
if (mIsFirstPaint && !mPaintingSuppressed) {
MOZ_LOG(gLog, LogLevel::Debug,
("PresShell::Paint, first paint, this=%p", this));
if (layerManager) {
layerManager->SetIsFirstPaint();
}
mIsFirstPaint = false;
}
const bool offscreen =
bool(aFlags & PaintInternalFlags::PaintCompositeOffscreen);
if (!renderer->BeginTransaction(url)) {
return;
}
// Send an updated focus target with this transaction. Be sure to do this
// before we paint in the case this is an empty transaction.
if (layerManager) {
layerManager->SetFocusTarget(focusTarget);
}
if (frame) {
if (!(aFlags & PaintInternalFlags::PaintSyncDecodeImages) &&
!frame->HasAnyStateBits(NS_FRAME_UPDATE_LAYER_TREE)) {
if (layerManager) {
layerManager->SetTransactionIdAllocator(presContext->RefreshDriver());
}
if (renderer->EndEmptyTransaction(
(aFlags & PaintInternalFlags::PaintComposite)
? WindowRenderer::END_DEFAULT
: WindowRenderer::END_NO_COMPOSITE)) {
return;
}
}
frame->RemoveStateBits(NS_FRAME_UPDATE_LAYER_TREE);
}
nscolor bgcolor = ComputeBackstopColor(aViewToPaint);
PaintFrameFlags flags =
PaintFrameFlags::WidgetLayers | PaintFrameFlags::ExistingTransaction;
// We force sync-decode for printing / print-preview (printing already does
// this from nsPageSequenceFrame::PrintNextSheet).
// We also force sync-decoding via pref for reftests.
if (aFlags & PaintInternalFlags::PaintSyncDecodeImages ||
mDocument->IsStaticDocument() ||
StaticPrefs::image_testing_decode_sync_enabled()) {
flags |= PaintFrameFlags::SyncDecodeImages;
}
if (aFlags & PaintInternalFlags::PaintCompositeOffscreen) {
flags |= PaintFrameFlags::CompositeOffscreen;
}
if (renderer->GetBackendType() == layers::LayersBackend::LAYERS_WR) {
flags |= PaintFrameFlags::ForWebRender;
}
if (frame) {
// We can paint directly into the widget using its layer manager.
SelectionNodeCache cache(*this);
nsLayoutUtils::PaintFrame(nullptr, frame, nsRegion(), bgcolor,
nsDisplayListBuilderMode::Painting, flags);
return;
}
bgcolor = NS_ComposeColors(bgcolor, mCanvasBackground.mViewport.mColor);
if (renderer->GetBackendType() == layers::LayersBackend::LAYERS_WR) {
LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
presContext->GetVisibleArea(), presContext->AppUnitsPerDevPixel());
WebRenderBackgroundData data(wr::ToLayoutRect(bounds),
wr::ToColorF(ToDeviceColor(bgcolor)));
WrFiltersHolder wrFilters;
layerManager->SetTransactionIdAllocator(presContext->RefreshDriver());
layerManager->EndTransactionWithoutLayer(
nullptr, nullptr, std::move(wrFilters), &data, 0, offscreen);
return;
}
FallbackRenderer* fallback = renderer->AsFallback();
MOZ_ASSERT(fallback);
if (aFlags & PaintInternalFlags::PaintComposite) {
nsIntRect bounds = presContext->GetVisibleArea().ToOutsidePixels(
presContext->AppUnitsPerDevPixel());
fallback->EndTransactionWithColor(bounds, ToDeviceColor(bgcolor));
}
}
// static
void PresShell::SetCapturingContent(nsIContent* aContent, CaptureFlags aFlags,
WidgetEvent* aEvent) {
// If capture was set for pointer lock, don't unlock unless we are coming
// out of pointer lock explicitly.
if (!aContent && sCapturingContentInfo.mPointerLock &&
!(aFlags & CaptureFlags::PointerLock)) {
return;
}
sCapturingContentInfo.mContent = nullptr;
sCapturingContentInfo.mRemoteTarget = nullptr;
// only set capturing content if allowed or the
// CaptureFlags::IgnoreAllowedState or CaptureFlags::PointerLock are used.
if ((aFlags & CaptureFlags::IgnoreAllowedState) ||
sCapturingContentInfo.mAllowed || (aFlags & CaptureFlags::PointerLock)) {
if (aContent) {
sCapturingContentInfo.mContent = aContent;
}
if (aEvent) {
MOZ_ASSERT(XRE_IsParentProcess());
MOZ_ASSERT(aEvent->mMessage == eMouseDown);
MOZ_ASSERT(aEvent->HasBeenPostedToRemoteProcess());
sCapturingContentInfo.mRemoteTarget =
BrowserParent::GetLastMouseRemoteTarget();
MOZ_ASSERT(sCapturingContentInfo.mRemoteTarget);
}
// CaptureFlags::PointerLock is the same as
// CaptureFlags::RetargetToElement & CaptureFlags::IgnoreAllowedState.
sCapturingContentInfo.mRetargetToElement =
!!(aFlags & CaptureFlags::RetargetToElement) ||
!!(aFlags & CaptureFlags::PointerLock);
sCapturingContentInfo.mPreventDrag =
!!(aFlags & CaptureFlags::PreventDragStart);
sCapturingContentInfo.mPointerLock = !!(aFlags & CaptureFlags::PointerLock);
}
}
nsIContent* PresShell::GetCurrentEventContent() {
if (mCurrentEventTarget.mContent &&
mCurrentEventTarget.mContent->GetComposedDoc() != mDocument) {
mCurrentEventTarget.Clear();
}
return mCurrentEventTarget.mContent;
}
nsIFrame* PresShell::GetCurrentEventFrame() {
if (MOZ_UNLIKELY(mIsDestroying)) {
return nullptr;
}
// GetCurrentEventContent() makes sure the content is still in the
// same document that this pres shell belongs to. If not, then the
// frame shouldn't get an event, nor should we even assume its safe
// to try and find the frame.
nsIContent* content = GetCurrentEventContent();
if (!mCurrentEventTarget.mFrame && content) {
mCurrentEventTarget.mFrame = content->GetPrimaryFrame();
MOZ_ASSERT_IF(
mCurrentEventTarget.mFrame,
mCurrentEventTarget.mFrame->PresContext()->GetPresShell() == this);
}
return mCurrentEventTarget.mFrame;
}
already_AddRefed<nsIContent> PresShell::GetEventTargetContent(
WidgetEvent* aEvent) {
nsCOMPtr<nsIContent> content = GetCurrentEventContent();
if (!content) {
if (nsIFrame* currentEventFrame = GetCurrentEventFrame()) {
content = currentEventFrame->GetContentForEvent(aEvent);
NS_ASSERTION(!content || content->GetComposedDoc() == mDocument,
"handing out content from a different doc");
}
}
return content.forget();
}
void PresShell::PushCurrentEventInfo(const EventTargetInfo& aInfo) {
if (mCurrentEventTarget.IsSet()) {
// XXX Why do we insert first item instead of append it? This requires to
// move the previous items...
mCurrentEventTargetStack.InsertElementAt(0, std::move(mCurrentEventTarget));
}
mCurrentEventTarget = aInfo;
}
void PresShell::PushCurrentEventInfo(EventTargetInfo&& aInfo) {
if (mCurrentEventTarget.IsSet()) {
mCurrentEventTargetStack.InsertElementAt(0, std::move(mCurrentEventTarget));
}
mCurrentEventTarget = std::move(aInfo);
}
void PresShell::PopCurrentEventInfo() {
mCurrentEventTarget.Clear();
if (!mCurrentEventTargetStack.IsEmpty()) {
mCurrentEventTarget = std::move(mCurrentEventTargetStack[0]);
mCurrentEventTargetStack.RemoveElementAt(0);
// Don't use it if it has moved to a different document.
if (mCurrentEventTarget.mContent &&
mCurrentEventTarget.mContent->GetComposedDoc() != mDocument) {
mCurrentEventTarget.Clear();
}
}
}
// static
bool PresShell::EventHandler::InZombieDocument(nsIContent* aContent) {
// If a content node points to a null document, or the document is not
// attached to a window, then it is possibly in a zombie document,
// about to be replaced by a newly loading document.
// Such documents cannot handle DOM events.
// It might actually be in a node not attached to any document,
// in which case there is not parent presshell to retarget it to.
Document* doc = aContent->GetComposedDoc();
return !doc || !doc->GetWindow();
}
already_AddRefed<nsPIDOMWindowOuter> PresShell::GetRootWindow() {
nsCOMPtr<nsPIDOMWindowOuter> window = mDocument->GetWindow();
if (window) {
nsCOMPtr<nsPIDOMWindowOuter> rootWindow = window->GetPrivateRoot();
NS_ASSERTION(rootWindow, "nsPIDOMWindow::GetPrivateRoot() returns NULL");
return rootWindow.forget();
}
// If we don't have DOM window, we're zombie, we should find the root window
// with our parent shell.
RefPtr<PresShell> parentPresShell = GetParentPresShellForEventHandling();
NS_ENSURE_TRUE(parentPresShell, nullptr);
return parentPresShell->GetRootWindow();
}
already_AddRefed<nsPIDOMWindowOuter>
PresShell::GetFocusedDOMWindowInOurWindow() {
nsCOMPtr<nsPIDOMWindowOuter> rootWindow = GetRootWindow();
NS_ENSURE_TRUE(rootWindow, nullptr);
nsCOMPtr<nsPIDOMWindowOuter> focusedWindow;
nsFocusManager::GetFocusedDescendant(rootWindow,
nsFocusManager::eIncludeAllDescendants,
getter_AddRefs(focusedWindow));
return focusedWindow.forget();
}
already_AddRefed<nsIContent> PresShell::GetFocusedContentInOurWindow() const {
nsFocusManager* fm = nsFocusManager::GetFocusManager();
if (fm && mDocument) {
RefPtr<Element> focusedElement;
fm->GetFocusedElementForWindow(mDocument->GetWindow(), false, nullptr,
getter_AddRefs(focusedElement));
return focusedElement.forget();
}
return nullptr;
}
already_AddRefed<PresShell> PresShell::GetParentPresShellForEventHandling() {
if (!mPresContext) {
return nullptr;
}
// Now, find the parent pres shell and send the event there
RefPtr<nsDocShell> docShell = mPresContext->GetDocShell();
if (!docShell) {
docShell = mForwardingContainer.get();
}
// Might have gone away, or never been around to start with
if (!docShell) {
return nullptr;
}
BrowsingContext* bc = docShell->GetBrowsingContext();
if (!bc) {
return nullptr;
}
RefPtr<BrowsingContext> parentBC;
if (XRE_IsParentProcess()) {
parentBC = bc->Canonical()->GetParentCrossChromeBoundary();
} else {
parentBC = bc->GetParent();
}
RefPtr<nsIDocShell> parentDocShell =
parentBC ? parentBC->GetDocShell() : nullptr;
if (!parentDocShell) {
return nullptr;
}
RefPtr<PresShell> parentPresShell = parentDocShell->GetPresShell();
return parentPresShell.forget();
}
nsresult PresShell::EventHandler::RetargetEventToParent(
WidgetGUIEvent* aGUIEvent, nsEventStatus* aEventStatus) {
// Send this events straight up to the parent pres shell.
// We do this for keystroke events in zombie documents or if either a frame
// or a root content is not present.
// That way at least the UI key bindings can work.
RefPtr<PresShell> parentPresShell = GetParentPresShellForEventHandling();
NS_ENSURE_TRUE(parentPresShell, NS_ERROR_FAILURE);
// Fake the event as though it's from the parent pres shell's root frame.
return parentPresShell->HandleEvent(parentPresShell->GetRootFrame(),
aGUIEvent, true, aEventStatus);
}
void PresShell::DisableNonTestMouseEvents(bool aDisable) {
sDisableNonTestMouseEvents = aDisable;
}
nsPoint PresShell::GetEventLocation(const WidgetMouseEvent& aEvent) const {
nsIFrame* rootFrame = GetRootFrame();
if (rootFrame) {
RelativeTo relativeTo{rootFrame};
if (rootFrame->PresContext()->IsRootContentDocumentCrossProcess()) {
relativeTo.mViewportType = ViewportType::Visual;
}
return nsLayoutUtils::GetEventCoordinatesRelativeTo(&aEvent, relativeTo);
}
nsView* rootView = mViewManager->GetRootView();
return nsLayoutUtils::TranslateWidgetToView(mPresContext, aEvent.mWidget,
aEvent.mRefPoint, rootView);
}
void PresShell::RecordPointerLocation(WidgetGUIEvent* aEvent) {
if (!mPresContext) {
return;
}
if (!IsRoot()) {
PresShell* rootPresShell = GetRootPresShell();
if (rootPresShell) {
rootPresShell->RecordPointerLocation(aEvent);
}
return;
}
const auto StoreMouseLocation = [&](const WidgetMouseEvent& aMouseEvent) {
if (aMouseEvent.mMessage == eMouseMove && aMouseEvent.IsSynthesized()) {
return false;
}
PointerEventHandler::RecordMouseState(*this, aMouseEvent);
mLastMousePointerId = Some(aMouseEvent.pointerId);
return true;
};
const auto ClearMouseLocation = [&](const WidgetMouseEvent& aMouseEvent) {
PointerEventHandler::ClearMouseState(*this, aMouseEvent);
mLastMousePointerId.reset();
};
const auto ClearMouseLocationIfSetByTouch =
[&](const WidgetPointerEvent& aPointerEvent) {
const PointerInfo* lastMouseInfo =
PointerEventHandler::GetLastMouseInfo(this);
if (lastMouseInfo && lastMouseInfo->HasLastState() &&
lastMouseInfo->mInputSource ==
MouseEvent_Binding::MOZ_SOURCE_TOUCH &&
aPointerEvent.mInputSource ==
MouseEvent_Binding::MOZ_SOURCE_TOUCH) {
ClearMouseLocation(aPointerEvent);
}
};
const auto StorePointerLocation =
[&](const WidgetMouseEvent& aMouseOrPointerEvent) {
if (!mPointerIds.Contains(aMouseOrPointerEvent.pointerId)) {
mPointerIds.AppendElement(aMouseOrPointerEvent.pointerId);
}
PointerEventHandler::RecordPointerState(
GetEventLocation(aMouseOrPointerEvent), aMouseOrPointerEvent);
};
const auto ClearPointerLocation =
[&](const WidgetMouseEvent& aMouseOrPointerEvent) {
mPointerIds.RemoveElement(aMouseOrPointerEvent.pointerId);
PointerEventHandler::RecordPointerState(
nsPoint(NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE),
aMouseOrPointerEvent);
};
const auto StoreLastPointerEventLocation =
[&](const WidgetMouseEvent& aMouseOrPointerEvent) {
// TODO: instead, encapsulate mMouseLocation and
// `mLastOverWindowPointerLocation` in a struct.
mLastOverWindowPointerLocation = GetEventLocation(aMouseOrPointerEvent);
};
switch (aEvent->mMessage) {
case eMouseMove:
case eMouseEnterIntoWidget:
case eMouseDown:
case eMouseUp:
case eDragEnter:
case eDragStart:
case eDragOver:
case eDrop: {
const WidgetMouseEvent& mouseEvent = *aEvent->AsMouseEvent();
if (StoreMouseLocation(mouseEvent) &&
(aEvent->mMessage == eMouseEnterIntoWidget ||
aEvent->mClass == eDragEventClass)) {
SynthesizeMouseMove(false);
}
// In a drag session, we won't dispatch pointer events except
// ePointerCancel immediately after eDragStart. However, once the drag
// session ends, we want to synthesize ePointerMove at the dropped point.
// Therefore, we should update the last state of the pointer when we start
// handling a drag event.
if (aEvent->mClass == eDragEventClass) {
StorePointerLocation(mouseEvent);
}
break;
}
case eDragExit: {
const WidgetMouseEvent& mouseEvent = *aEvent->AsMouseEvent();
if (aEvent->mRelatedTarget) {
// not exit from the widget
break;
}
ClearMouseLocation(mouseEvent);
ClearPointerLocation(mouseEvent);
break;
}
case eMouseExitFromWidget: {
const WidgetMouseEvent& mouseEvent = *aEvent->AsMouseEvent();
// Although we only care about the mouse moving into an area for which
// this pres shell doesn't receive mouse move events, we don't check which
// widget the mouse exit was for since this seems to vary by platform.
// Hopefully this won't matter at all since we'll get the mouse move or
// enter after the mouse exit when the mouse moves from one of our widgets
// into another.
ClearMouseLocation(mouseEvent);
ClearPointerLocation(mouseEvent);
break;
}
case ePointerMove:
case ePointerRawUpdate:
case eMouseRawUpdate: {
const WidgetMouseEvent& mouseEvent = *aEvent->AsMouseEvent();
if (!mouseEvent.IsReal()) {
break;
}
StoreLastPointerEventLocation(mouseEvent);
if (const WidgetPointerEvent* const pointerEvent =
mouseEvent.AsPointerEvent()) {
StorePointerLocation(*pointerEvent);
}
break;
}
case ePointerDown: {
const WidgetPointerEvent& pointerEvent = *aEvent->AsPointerEvent();
StoreLastPointerEventLocation(pointerEvent);
StorePointerLocation(pointerEvent);
break;
}
case ePointerUp: {
const WidgetPointerEvent& pointerEvent = *aEvent->AsPointerEvent();
StoreLastPointerEventLocation(pointerEvent);
// If the pointer supports hover, we need to keep storing the last
// position to synthesize ePointerMove after layout changes.
if (pointerEvent.InputSourceSupportsHover()) {
StorePointerLocation(pointerEvent);
}
// If the pointer does not support hover, we won't synthesize ePointerMove
// for that. So, we can clear the pointer location.
else {
ClearPointerLocation(pointerEvent);
}
// If the pointer is for a touch, we need to forget the last state of
// mMouseLocation if it was set by a touch because the touch is being
// removed from the active pointers.
ClearMouseLocationIfSetByTouch(pointerEvent);
break;
}
case ePointerCancel: {
// If a touch is canceled, it means that the touch input is tracked by a
// gesture like swipe to scroll, pinch to zoom or DnD. So, it means that
// a normal touch sequence finished. Then, we shouldn't give `:hover`
// state to the element underneath the last touch point anymore. For
// example, it's odd that new element which comes underneath the first
// touch position gets `:hover` style even though the scroll is caused
// by swipe (i.e., has moved the touch position).
ClearMouseLocationIfSetByTouch(*aEvent->AsPointerEvent());
break;
}
default:
break;
}
}
// static
void PresShell::RecordModifiers(WidgetGUIEvent* aEvent) {
switch (aEvent->mMessage) {
case eKeyPress:
case eKeyUp:
case eKeyDown:
case eMouseMove:
case eMouseUp:
case eMouseDown:
case eMouseEnterIntoWidget:
case eMouseExitFromWidget:
case eMouseActivate:
case eMouseTouchDrag:
case eMouseLongTap:
case eMouseRawUpdate:
case eMouseExploreByTouch:
case ePointerCancel:
case eContextMenu:
case eTouchStart:
case eTouchMove:
case eTouchEnd:
case eTouchCancel:
case eTouchPointerCancel:
case eTouchRawUpdate:
case eWheel:
sCurrentModifiers = aEvent->AsInputEvent()->mModifiers;
break;
default:
break;
}
}
void PresShell::nsSynthMouseMoveEvent::Revoke() {
if (mPresShell) {
mPresShell->GetPresContext()->RefreshDriver()->RemoveRefreshObserver(
this, FlushType::Display);
mPresShell = nullptr;
}
}
nsIFrame* PresShell::GetClosestAncestorFrameForAncestorView() const {
nsViewManager* vm = GetViewManager();
if (!vm) {
return nullptr;
}
nsView* view = vm->GetRootView();
while (view && !view->GetFrame()) {
view = view->GetParent();
}
nsIFrame* frame = nullptr;
if (view) {
frame = view->GetFrame();
}
return frame;
}
static CallState FlushThrottledStyles(Document& aDocument) {
PresShell* presShell = aDocument.GetPresShell();
if (presShell && presShell->IsVisible()) {
if (nsPresContext* presContext = presShell->GetPresContext()) {
presContext->RestyleManager()->UpdateOnlyAnimationStyles();
}
}
aDocument.EnumerateSubDocuments(FlushThrottledStyles);
return CallState::Continue;
}
bool PresShell::CanDispatchEvent(const WidgetGUIEvent* aEvent) const {
bool rv =
mPresContext && !mHaveShutDown && nsContentUtils::IsSafeToRunScript();
if (aEvent) {
rv &= (aEvent && aEvent->mWidget && !aEvent->mWidget->Destroyed());
}
return rv;
}
/* static */
PresShell* PresShell::GetShellForEventTarget(nsIFrame* aFrame,
nsIContent* aContent) {
if (aFrame) {
return aFrame->PresShell();
}
if (aContent) {
Document* doc = aContent->GetComposedDoc();
if (!doc) {
return nullptr;
}
return doc->GetPresShell();
}
return nullptr;
}
/* static */
PresShell* PresShell::GetShellForTouchEvent(WidgetGUIEvent* aEvent) {
switch (aEvent->mMessage) {
case eTouchMove:
case eTouchRawUpdate:
case eTouchCancel:
case eTouchEnd: {
// get the correct shell to dispatch to
WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent();
for (dom::Touch* touch : touchEvent->mTouches) {
if (!touch) {
return nullptr;
}
RefPtr<dom::Touch> oldTouch =
TouchManager::GetCapturedTouch(touch->Identifier());
if (!oldTouch) {
return nullptr;
}
nsIContent* const content =
nsIContent::FromEventTargetOrNull(oldTouch->GetTarget());
if (!content) {
return nullptr;
}
if (PresShell* const presShell = content->OwnerDoc()->GetPresShell()) {
return presShell;
}
}
return nullptr;
}
default:
return nullptr;
}
}
nsresult PresShell::HandleEvent(nsIFrame* aFrameForPresShell,
WidgetGUIEvent* aGUIEvent,
bool aDontRetargetEvents,
nsEventStatus* aEventStatus) {
MOZ_ASSERT(aGUIEvent);
RecordModifiers(aGUIEvent);
AutoWeakFrame weakFrameForPresShell(aFrameForPresShell);
// Running tests must not expect that some mouse boundary events are fired
// when something occurs in the parent process, e.g., when a popup is
// opened/closed at the last mouse cursor position in the parent process (the
// position may be different from the position which stored in this process).
// Therefore, let's ignore synthesized mouse events coming form another
// process if and only if they are not caused by the API.
if (aGUIEvent->CameFromAnotherProcess() && XRE_IsContentProcess() &&
!aGUIEvent->mFlags.mIsSynthesizedForTests) {
const PointerInfo* const lastMouseInfo =
PointerEventHandler::GetLastMouseInfo();
if (lastMouseInfo && lastMouseInfo->mIsSynthesizedForTests) {
switch (aGUIEvent->mMessage) {
// Synthesized eMouseMove will case mouse boundary events like
// mouseover, mouseout, and :hover state is changed at dispatching the
// events.
case eMouseMove:
// eMouseExitFromWidget comes from the parent process if the cursor
// crosses a puppet widget boundary. Then, the event will be handled as
// a synthesized eMouseMove in this process and may cause unexpected
// `mouseout` and `mouseleave`.
case eMouseExitFromWidget:
// eMouseEnterIntoWidget causes updating the hover state under the event
// position which may be different from the last cursor position
// synthesized in this process.
case eMouseEnterIntoWidget:
if (!aGUIEvent->AsMouseEvent()->IsReal()) {
return NS_OK;
}
break;
default:
break;
}
}
}
// Here we are granting some delays to ensure that user input events are
// created while the page content may not be visible to the user are not
// processed.
// The main purpose of this is to avoid user inputs are handled in the
// new document where as the user inputs were originally targeting some
// content in the old document.
if (!CanHandleUserInputEvents(aGUIEvent)) {
return NS_OK;
}
// If there is a composition and we got a pointing device events which may not
// impossible to continue the composition, we should notify the editor of the
// event before dispatching it. Then, composition will be commited before
// the editor loses focus. This behavior is compatible with Chrome.
// FIXME: Perhaps, we should do same thing before dispatching touch events.
switch (aGUIEvent->mMessage) {
case eMouseDown:
case eMouseUp: {
nsPIDOMWindowOuter* const focusedWindow =
nsFocusManager::GetFocusedWindowStatic();
if (!focusedWindow) {
break;
}
Document* const focusedDocument = focusedWindow->GetExtantDoc();
if (!focusedDocument) {
break;
}
nsPresContext* const focusedPresContext =
focusedDocument->GetPresContext();
if (!focusedPresContext) {
break;
}
const RefPtr<TextComposition> textComposition =
IMEStateManager::GetTextCompositionFor(focusedPresContext);
if (!textComposition) {
break;
}
// If there is a composition and it's managed by an editor, let's notify
// the editor of mouse button event. The editor commits the composition
// unless IME consumes the event.
if (RefPtr<EditorBase> editorBase = textComposition->GetEditorBase()) {
MOZ_ASSERT(aGUIEvent->AsMouseEvent());
editorBase->WillHandleMouseButtonEvent(*aGUIEvent->AsMouseEvent());
}
// Otherwise, we should commit the orphan composition instead.
else if (nsCOMPtr<nsIWidget> widget = textComposition->GetWidget()) {
textComposition->RequestToCommit(widget, false);
}
if (!CanHandleUserInputEvents(aGUIEvent)) {
return NS_OK;
}
// Before bug 1945988, we dispatched the mouse button event without
// committing composition and the editor will commit composition.
// However, for compatibility with the other browsers, we started
// committing composition before dispatching the mouse event. To keep
// the traditional behavior, we should compute aFrameForPresShell if it's
// reframed by dispatching the composition events (and input events)
// above. Otherwise, we stop dispatching the mouse button events newly in
// such case.
if (MOZ_UNLIKELY(!weakFrameForPresShell.IsAlive())) {
FlushPendingNotifications(FlushType::Layout);
if (MOZ_UNLIKELY(IsDestroying())) {
return NS_OK;
}
nsIFrame* const newFrameForPresShell =
GetClosestAncestorFrameForAncestorView();
if (MOZ_UNLIKELY(!newFrameForPresShell)) {
return NS_OK;
}
weakFrameForPresShell = newFrameForPresShell;
}
break;
}
default:
break;
}
if (mPresContext) {
switch (aGUIEvent->mMessage) {
case eMouseMove:
case eMouseRawUpdate:
if (!aGUIEvent->AsMouseEvent()->IsReal()) {
break;
}
[[fallthrough]];
case eMouseDown:
case eMouseUp: {
// We should flush pending mousemove event now because some mouse
// boundary events which should've already been dispatched before a user
// input may have not been dispatched. E.g., if a mousedown event
// listener removed or appended an element under the cursor and mouseup
// event comes immediately after that, mouseover or mouseout may have
// not been dispatched on the new element yet.
// XXX If eMouseMove is not propery dispatched before eMouseDown and
// a `mousedown` event listener removes the event target or its
// ancestor, eMouseOver will be dispatched between eMouseDown and
// eMouseUp. That could cause unexpected behavior if a `mouseover`
// event listener assumes it's always disptached before `mousedown`.
// However, we're not sure whether it could happen with users' input.
// FIXME: Perhaps, we need to do this for all events which are directly
// caused by user input, e.g., eKeyDown, etc.
const RefPtr<PresShell> rootPresShell =
IsRoot() ? this : GetRootPresShell();
if (rootPresShell && rootPresShell->mSynthMouseMoveEvent.IsPending()) {
RefPtr<nsSynthMouseMoveEvent> synthMouseMoveEvent =
rootPresShell->mSynthMouseMoveEvent.get();
synthMouseMoveEvent->Run();
if (IsDestroying()) {
return NS_OK;
}
// XXX If the frame or "this" is reframed, it might be better to
// recompute the frame. However, it could treat the user input on
// unexpected element. Therefore, we should not do that until we'd
// get a bug report caused by that.
if (MOZ_UNLIKELY(!weakFrameForPresShell.IsAlive())) {
return NS_OK;
}
}
break;
}
default:
break;
}
}
// If the event may cause ePointerMove, we need to dispatch ePointerRawUpdate
// before that if and only if there are some `pointerrawupdate` event
// listeners. Note that if a `pointerrawupdate` event listener destroys its
// document/window, we need to dispatch the following pointer event (e.g.,
// ePointerMove) in the parent document/window with the parent PresShell.
// Therefore, we need to consider the target PresShell for each event
// (ePointerRawUpdate and the following pointer event) in
// EventHandler::HandleEvent(). Thus, we need to dispatch the internal event
// for ePointerRawUpdate before calling EventHandler::HandleEvent() below.
if (!aDontRetargetEvents &&
StaticPrefs::dom_event_pointer_rawupdate_enabled()) {
nsresult rv = EnsurePrecedingPointerRawUpdate(
weakFrameForPresShell, *aGUIEvent, aDontRetargetEvents);
if (NS_FAILED(rv)) {
return rv;
}
if (!CanHandleUserInputEvents(aGUIEvent)) {
return NS_OK;
}
}
EventHandler eventHandler(*this);
return eventHandler.HandleEvent(weakFrameForPresShell, aGUIEvent,
aDontRetargetEvents, aEventStatus);
}
nsresult PresShell::EnsurePrecedingPointerRawUpdate(
AutoWeakFrame& aWeakFrameForPresShell, const WidgetGUIEvent& aSourceEvent,
bool aDontRetargetEvents) {
MOZ_ASSERT(StaticPrefs::dom_event_pointer_rawupdate_enabled());
if (PointerEventHandler::ToPointerEventMessage(&aSourceEvent) !=
ePointerMove) {
return NS_OK;
}
// We should not dispatch ePointerRawUpdate directly because dispatching
// it requires some steps which are defined by "fire a pointer event" section
// in the spec. https://w3c.github.io/pointerevents/#dfn-fire-a-pointer-event
// We handle the steps when we call DispatchPrecedingPointerEvent().
// Therefore, this method dispatches eMouseRawUpdate or eTouchRawUpdate event
// if the event should follow a ePointerRawUpdate. Then,
// HandleEventUsingCoordinates() will stop handling the internal events after
// calling DispatchPrecedingPointerEvent().
MOZ_ASSERT(aSourceEvent.mMessage != eMouseRawUpdate);
MOZ_ASSERT(aSourceEvent.mMessage != eTouchRawUpdate);
// If no window in the browser child has `pointerrawupdate` event listener,
// we should do nothing.
if (auto* const browserChild = BrowserChild::GetFrom(this)) {
if (!browserChild->HasPointerRawUpdateEventListeners()) {
return NS_OK;
}
}
if (const WidgetMouseEvent* const mouseEvent = aSourceEvent.AsMouseEvent()) {
// If `convertToPointer` is `false`, it means that we've already handled the
// event to dispatch a preceding pointer event. Therefore, its preceding
// event should've already been handled.
// If `convertToPointerRawUpdate` is `false`, it means that the event was in
// the queue in BrowserChild and BrowserChild has already dispatched
// `eMouseRawUpdate`. Therefore, we don't need to dispatch it again here.
if (mouseEvent->IsSynthesized() || !mouseEvent->convertToPointer ||
!mouseEvent->convertToPointerRawUpdate) {
return NS_OK;
}
WidgetMouseEvent mouseRawUpdateEvent(*mouseEvent);
mouseRawUpdateEvent.mMessage = eMouseRawUpdate;
mouseRawUpdateEvent.mCoalescedWidgetEvents = nullptr;
nsEventStatus rawUpdateStatus = nsEventStatus_eIgnore;
EventHandler eventHandler(*this);
return eventHandler.HandleEvent(aWeakFrameForPresShell,
&mouseRawUpdateEvent, aDontRetargetEvents,
&rawUpdateStatus);
}
if (const WidgetTouchEvent* const touchEvent = aSourceEvent.AsTouchEvent()) {
WidgetTouchEvent touchRawUpdate(*touchEvent,
WidgetTouchEvent::CloneTouches::No);
touchRawUpdate.mMessage = eTouchRawUpdate;
touchRawUpdate.mTouches.Clear();
for (const RefPtr<Touch>& touch : touchEvent->mTouches) {
// If `convertToPointer` is `false`, it means that we've already handled
// the event to dispatch a preceding pointer event. Therefore, its
// preceding event should've already been handled.
// If ShouldConvertTouchToPointer() returns `false`, the touch is not an
// active pointer or the touch hasn't been changed from the previous
// state. Therefore, we don't need to dispatch ePointerRawUpdate for the
// touch.
if (!touch->convertToPointerRawUpdate ||
!TouchManager::ShouldConvertTouchToPointer(touch, &touchRawUpdate)) {
continue;
}
RefPtr<Touch> newTouch = new Touch(*touch);
newTouch->mMessage = eTouchRawUpdate;
newTouch->mCoalescedWidgetEvents = nullptr;
touchRawUpdate.mTouches.AppendElement(std::move(newTouch));
}
nsEventStatus rawUpdateStatus = nsEventStatus_eIgnore;
if (touchRawUpdate.mTouches.IsEmpty()) {
return NS_OK;
}
EventHandler eventHandler(*this);
return eventHandler.HandleEvent(aWeakFrameForPresShell, &touchRawUpdate,
aDontRetargetEvents, &rawUpdateStatus);
}
MOZ_ASSERT_UNREACHABLE("Handle the event to dispatch ePointerRawUpdate");
return NS_OK;
}
bool PresShell::EventHandler::UpdateFocusSequenceNumber(
nsIFrame* aFrameForPresShell, uint64_t aEventFocusSequenceNumber) {
uint64_t focusSequenceNumber;
nsMenuPopupFrame* popup = do_QueryFrame(aFrameForPresShell);
if (popup) {
focusSequenceNumber = popup->GetAPZFocusSequenceNumber();
} else {
focusSequenceNumber = mPresShell->mAPZFocusSequenceNumber;
}
if (focusSequenceNumber >= aEventFocusSequenceNumber) {
return false;
}
if (popup) {
popup->UpdateAPZFocusSequenceNumber(aEventFocusSequenceNumber);
} else {
mPresShell->mAPZFocusSequenceNumber = aEventFocusSequenceNumber;
}
return true;
}
nsresult PresShell::EventHandler::HandleEvent(
AutoWeakFrame& aWeakFrameForPresShell, WidgetGUIEvent* aGUIEvent,
bool aDontRetargetEvents, nsEventStatus* aEventStatus) {
MOZ_ASSERT(aGUIEvent);
MOZ_DIAGNOSTIC_ASSERT(aGUIEvent->IsTrusted());
MOZ_ASSERT(aEventStatus);
NS_ASSERTION(aWeakFrameForPresShell.IsAlive(),
"aWeakFrameForPresShell should refer a frame");
// Update the latest focus sequence number with this new sequence number;
// the next transasction that gets sent to the compositor will carry this over
if (UpdateFocusSequenceNumber(aWeakFrameForPresShell.GetFrame(),
aGUIEvent->mFocusSequenceNumber)) {
if (aWeakFrameForPresShell.IsAlive() &&
StaticPrefs::apz_keyboard_focus_optimization()) {
aWeakFrameForPresShell->SchedulePaint(nsIFrame::PAINT_COMPOSITE_ONLY);
}
}
if (mPresShell->IsDestroying() ||
(PresShell::sDisableNonTestMouseEvents &&
!aGUIEvent->mFlags.mIsSynthesizedForTests &&
aGUIEvent->HasMouseEventMessage())) {
return NS_OK;
}
mPresShell->RecordPointerLocation(aGUIEvent);
const bool wasFrameForPresShellNull = !aWeakFrameForPresShell.GetFrame();
if (MaybeHandleEventWithAccessibleCaret(aWeakFrameForPresShell, aGUIEvent,
aEventStatus)) {
// Handled by AccessibleCaretEventHub.
return NS_OK;
}
if (MaybeDiscardEvent(aGUIEvent)) {
// Cannot handle the event for now.
return NS_OK;
}
if (!aDontRetargetEvents) {
const DebugOnly<bool> wasFrameForPresShellAlive =
aWeakFrameForPresShell.IsAlive();
// If aGUIEvent should be handled in another PresShell, we should call its
// HandleEvent() and do nothing here.
nsresult rv = NS_OK;
if (MaybeHandleEventWithAnotherPresShell(aWeakFrameForPresShell, aGUIEvent,
aEventStatus, &rv)) {
// Handled by another PresShell or nobody can handle the event.
return rv;
}
// If MaybeHandleEventWithAnotherPresShell() returns false, it shouldn't
// have run any script. So, aWeakFrameForPresShell must be alive.
MOZ_ASSERT_IF(wasFrameForPresShellAlive, aWeakFrameForPresShell.IsAlive());
}
if (MaybeDiscardOrDelayKeyboardEvent(aGUIEvent)) {
// The event is discarded or put into the delayed event queue.
return NS_OK;
}
if (aGUIEvent->IsUsingCoordinates()) {
return HandleEventUsingCoordinates(aWeakFrameForPresShell, aGUIEvent,
aEventStatus, aDontRetargetEvents);
}
// Activation events need to be dispatched even if no frame was found, since
// we don't want the focus to be out of sync.
if (MOZ_UNLIKELY(wasFrameForPresShellNull)) {
if (!NS_EVENT_NEEDS_FRAME(aGUIEvent)) {
// Push nullptr for both current event target content and frame since
// there is no frame but the event does not require a frame.
AutoCurrentEventInfoSetter eventInfoSetter(*this);
return HandleEventWithCurrentEventInfo(aGUIEvent, aEventStatus, true,
nullptr);
}
if (aGUIEvent->HasKeyEventMessage()) {
// Keypress events in new blank tabs should not be completely thrown away.
// Retarget them -- the parent chrome shell might make use of them.
return RetargetEventToParent(aGUIEvent, aEventStatus);
}
return NS_OK;
}
if (aGUIEvent->IsTargetedAtFocusedContent()) {
return HandleEventAtFocusedContent(aGUIEvent, aEventStatus);
}
return HandleEventWithFrameForPresShell(aWeakFrameForPresShell, aGUIEvent,
aEventStatus);
}
nsresult PresShell::EventHandler::HandleEventUsingCoordinates(
AutoWeakFrame& aWeakFrameForPresShell, WidgetGUIEvent* aGUIEvent,
nsEventStatus* aEventStatus, bool aDontRetargetEvents) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aGUIEvent->IsUsingCoordinates());
MOZ_ASSERT(aEventStatus);
// Flush pending notifications to handle the event with the latest layout.
// But if it causes destroying the frame for mPresShell, stop handling the
// event. (why?)
MaybeFlushPendingNotifications(aGUIEvent);
if (MOZ_UNLIKELY(!aWeakFrameForPresShell.IsAlive())) {
*aEventStatus = nsEventStatus_eIgnore;
return NS_OK;
}
// If we are trying to dispatch an ePointerRawUpdate but it's not allowed in
// the (maybe retargetted) document, we should not flush the capture state
// below.
if (aGUIEvent->mMessage == eMouseRawUpdate ||
aGUIEvent->mMessage == eTouchRawUpdate) {
EventTargetDataWithCapture eventTargetData =
EventTargetDataWithCapture::QueryEventTargetUsingCoordinates(
*this, aWeakFrameForPresShell,
EventTargetDataWithCapture::Query::PendingState, aGUIEvent);
if (!PointerEventHandler::NeedToDispatchPointerRawUpdate(
eventTargetData.GetDocument())) {
return NS_OK;
}
// Then, we need to recompute the target with processing the pending pointer
// capture. Note that the result may be differnet since `gotpointercapture`
// event listener does something tricky things.
}
EventTargetDataWithCapture eventTargetData =
EventTargetDataWithCapture::QueryEventTargetUsingCoordinates(
*this, aWeakFrameForPresShell,
EventTargetDataWithCapture::Query::LatestState, aGUIEvent,
aEventStatus);
if (MOZ_UNLIKELY(!eventTargetData.CanHandleEvent())) {
// We cannot handle the event within the PresShell anymore. Let's stop
// handling the event without returning error since it's not illegal
// case.
return NS_OK;
}
if (MOZ_UNLIKELY(!eventTargetData.GetFrame())) {
if (eventTargetData.mPointerCapturingElement &&
aWeakFrameForPresShell.IsAlive()) {
return HandleEventWithPointerCapturingContentWithoutItsFrame(
aWeakFrameForPresShell, aGUIEvent,
MOZ_KnownLive(eventTargetData.mPointerCapturingElement),
aEventStatus);
}
return NS_OK;
}
// Suppress mouse event if it's being targeted at an element inside
// a document which needs events suppressed
if (MaybeDiscardOrDelayMouseEvent(eventTargetData.GetFrame(), aGUIEvent)) {
return NS_OK;
}
// Check if we have an active EventStateManager which isn't the
// EventStateManager of the current PresContext. If that is the case, and
// mouse is over some ancestor document, forward event handling to the
// active document. This way content can get mouse events even when mouse
// is over the chrome or outside the window.
if (eventTargetData.MaybeRetargetToActiveDocument(aGUIEvent) &&
NS_WARN_IF(!eventTargetData.GetFrame())) {
return NS_OK;
}
// Wheel events only apply to elements. If this is a wheel event, attempt to
// update the event target from the current wheel transaction before we
// compute the element from the target frame.
eventTargetData.UpdateWheelEventTarget(aGUIEvent);
if (!eventTargetData.ComputeElementFromFrame(aGUIEvent)) {
return NS_OK;
}
// Note that even if ComputeElementFromFrame() returns true,
// eventTargetData.mContent can be nullptr here.
// Dispatch a pointer event if Pointer Events is enabled. Note that if
// pointer event listeners change the layout, eventTargetData is
// automatically updated.
if (!DispatchPrecedingPointerEvent(
aWeakFrameForPresShell, aGUIEvent,
MOZ_KnownLive(eventTargetData.mPointerCapturingElement),
aDontRetargetEvents, &eventTargetData, aEventStatus)) {
return NS_OK;
}
// Handle the event in the correct shell.
// We pass the subshell's root frame as the frame to start from. This is
// the only correct alternative; if the event was captured then it
// must have been captured by us or some ancestor shell and we
// now ask the subshell to dispatch it normally.
EventHandler eventHandler(*eventTargetData.mPresShell);
AutoCurrentEventInfoSetter eventInfoSetter(eventHandler, aGUIEvent->mMessage,
eventTargetData);
// eventTargetData is on the stack and is guaranteed to keep its
// mOverrideClickTarget alive, so we can just use MOZ_KnownLive here.
nsresult rv = eventHandler.HandleEventWithCurrentEventInfo(
aGUIEvent, aEventStatus, true,
MOZ_KnownLive(eventTargetData.mOverrideClickTarget));
if (NS_FAILED(rv) ||
MOZ_UNLIKELY(eventTargetData.mPresShell->IsDestroying())) {
return rv;
}
if (aGUIEvent->mMessage == eTouchEnd) {
MaybeSynthesizeCompatMouseEventsForTouchEnd(aGUIEvent->AsTouchEvent(),
aEventStatus);
}
return NS_OK;
}
// static
PresShell::EventHandler::EventTargetDataWithCapture::EventTargetDataWithCapture(
EventHandler& aEventHandler, AutoWeakFrame& aWeakFrameForPresShell,
Query aQueryState, WidgetGUIEvent* aGUIEvent,
nsEventStatus* aEventStatus /* = nullptr*/)
: EventTargetData(aWeakFrameForPresShell.GetFrame()) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aGUIEvent->IsUsingCoordinates());
// EventHandler::GetFrameToHandleNonTouchEvent() may need to flush pending
// notifications of the target child document if eMouseDown or eMouseUp.
// Currently, this class does not support the case with Query::PendingState.
MOZ_ASSERT_IF(aQueryState == Query::PendingState,
aGUIEvent->mMessage != eMouseDown);
MOZ_ASSERT_IF(aQueryState == Query::PendingState,
aGUIEvent->mMessage != eMouseUp);
const bool queryLatestState = aQueryState == Query::LatestState;
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
nsMutationGuard mutationGuard;
const auto assertMutation = MakeScopeExit([&]() {
if (!queryLatestState) {
MOZ_DIAGNOSTIC_ASSERT(!mutationGuard.Mutated(0));
}
});
Maybe<JS::AutoAssertNoGC> assertNoGC;
if (!queryLatestState) {
assertNoGC.emplace();
}
#endif // #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
// XXX Retrieving capturing content here. However, some of the following
// methods allow to run script. So, isn't it possible the capturing
// content outdated?
mCapturingContent = EventHandler::GetCapturingContentFor(aGUIEvent);
if (queryLatestState) {
if (GetDocument() && aGUIEvent->mClass == eTouchEventClass) {
PointerLockManager::Unlock("TouchEvent");
}
// XXX If aGUIEvent is eMouseRawUpdate or eTouchRawUpdate and it's
// dispatched by BrowserChild, i.e., the event won't cause ePointerMove
// immediately after ePointerRawUpdate, should we skip fluhsing pending
// animations here? Doing this could cause different animation result while
// the user moves mouse cursor during a long animation whether there is a
// `pointerrawupdate` event listener or not.
aEventHandler.MaybeFlushThrottledStyles(aWeakFrameForPresShell);
// Previously, MaybeFlushThrottledStyles() recomputed the closest ancestor
// frame for view of mPresShell if it's reframed. Therefore, we should keep
// computing it here.
// FIXME: GetFrame() may be target content's frame if aGUIEvent is a touch
// event. So, we need to use different computation for such cases.
if (MOZ_UNLIKELY(!aWeakFrameForPresShell.IsAlive())) {
Clear();
MOZ_ASSERT(!CanHandleEvent());
return;
}
}
AutoWeakFrame weakRootFrameToHandleEvent =
aEventHandler.ComputeRootFrameToHandleEvent(
aWeakFrameForPresShell.GetFrame(), aGUIEvent, mCapturingContent,
&mCapturingContentIgnored, &mCaptureRetargeted);
if (mCapturingContentIgnored) {
mCapturingContent = nullptr;
}
// The order to generate pointer event is
// 1. check pending pointer capture.
// 2. check if there is a capturing content.
// 3. hit test
// 4. dispatch pointer events
// 5. check whether the targets of all Touch instances are in the same
// document and suppress invalid instances.
// 6. dispatch mouse or touch events.
// Try to keep frame for following check, because frame can be damaged
// during MaybeProcessPointerCapture.
if (queryLatestState) {
PointerEventHandler::MaybeProcessPointerCapture(aGUIEvent);
// Prevent application crashes, in case damaged frame.
if (NS_WARN_IF(!weakRootFrameToHandleEvent.IsAlive())) {
Clear();
MOZ_ASSERT(!CanHandleEvent());
return;
}
}
// We want to query the pointer capture element which **will** capture the
// following pointer event. If we've already processed the pointer capture
// above, current override element is it. Otherwise, we will process the
// pending pointer capture before dispatching a pointer event. Therefore,
// the pending pointer capture element will be the next override element
// if and only if they are different. (If they are the same element, the
// element will keep capturing the pointer. So, referring to the pending
// element is also fine in the case.)
mPointerCapturingElement =
queryLatestState
? PointerEventHandler::GetPointerCapturingElement(aGUIEvent)
: PointerEventHandler::GetPendingPointerCapturingElement(aGUIEvent);
if (mPointerCapturingElement) {
weakRootFrameToHandleEvent = mPointerCapturingElement->GetPrimaryFrame();
if (!weakRootFrameToHandleEvent.IsAlive()) {
// The caller should not keep handling the event with the frame stored by
// the super class. Therefore, we need to clear the frame.
ClearFrameToHandleEvent();
// Although the pointer capturing element does not have a frame, the event
// should be handled on the element.
MOZ_ASSERT(CanHandleEvent());
return;
}
}
const WidgetMouseEvent* mouseEvent = aGUIEvent->AsMouseEvent();
const bool isWindowLevelMouseExit =
(aGUIEvent->mMessage == eMouseExitFromWidget) &&
(mouseEvent &&
(mouseEvent->mExitFrom.value() == WidgetMouseEvent::ePlatformTopLevel ||
mouseEvent->mExitFrom.value() == WidgetMouseEvent::ePuppet));
// Get the frame at the event point. However, don't do this if we're
// capturing and retargeting the event because the captured frame will
// be used instead below. Also keep using the root frame if we're dealing
// with a window-level mouse exit event since we want to start sending
// mouse out events at the root EventStateManager.
SetFrameAndComputePresShell(weakRootFrameToHandleEvent.GetFrame());
if (!mCaptureRetargeted && !isWindowLevelMouseExit &&
!mPointerCapturingElement) {
if (!aEventHandler.ComputeEventTargetFrameAndPresShellAtEventPoint(
weakRootFrameToHandleEvent, aGUIEvent, this)) {
Clear();
MOZ_ASSERT(!CanHandleEvent());
if (aEventStatus) {
*aEventStatus = nsEventStatus_eIgnore;
}
return;
}
}
// if a node is capturing the mouse, check if the event needs to be
// retargeted at the capturing content instead. This will be the case when
// capture retargeting is being used, no frame was found or the frame's
// content is not a descendant of the capturing content.
if (mCapturingContent && !mPointerCapturingElement &&
(PresShell::sCapturingContentInfo.mRetargetToElement ||
!GetFrameContent() ||
!nsContentUtils::ContentIsCrossDocDescendantOf(GetFrameContent(),
mCapturingContent))) {
if (nsIFrame* const capturingFrame = mCapturingContent->GetPrimaryFrame()) {
SetFrameAndComputePresShell(capturingFrame);
}
}
MOZ_ASSERT(CanHandleEvent());
}
bool PresShell::EventHandler::MaybeFlushPendingNotifications(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
switch (aGUIEvent->mMessage) {
case eMouseDown:
case eMouseUp: {
RefPtr<nsPresContext> presContext = mPresShell->GetPresContext();
if (NS_WARN_IF(!presContext)) {
return false;
}
uint64_t framesConstructedCount = presContext->FramesConstructedCount();
uint64_t framesReflowedCount = presContext->FramesReflowedCount();
MOZ_KnownLive(mPresShell)->FlushPendingNotifications(FlushType::Layout);
return framesConstructedCount != presContext->FramesConstructedCount() ||
framesReflowedCount != presContext->FramesReflowedCount();
}
default:
return false;
}
}
// The type of coordinates to use for hit-testing input events
// that are relative to the RCD's viewport frame.
// On most platforms, use visual coordinates so that scrollbars
// can be targeted.
// On mobile, use layout coordinates because hit-testing in
// visual coordinates clashes with mobile viewport sizing, where
// the ViewportFrame is sized to the initial containing block
// (ICB) size, which is in layout coordinates. This is fine
// because we don't need to be able to target scrollbars on mobile
// (scrollbar dragging isn't supported).
static ViewportType ViewportTypeForInputEventsRelativeToRoot() {
#ifdef MOZ_WIDGET_ANDROID
return ViewportType::Layout;
#else
return ViewportType::Visual;
#endif
}
nsIFrame* PresShell::EventHandler::GetFrameToHandleNonTouchEvent(
AutoWeakFrame& aWeakRootFrameToHandleEvent, WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aGUIEvent->mClass != eTouchEventClass);
if (MOZ_UNLIKELY(!aWeakRootFrameToHandleEvent.IsAlive())) {
return nullptr;
}
ViewportType viewportType = ViewportType::Layout;
if (aWeakRootFrameToHandleEvent->Type() == LayoutFrameType::Viewport) {
nsPresContext* pc = aWeakRootFrameToHandleEvent->PresContext();
if (pc->IsChrome()) {
viewportType = ViewportType::Visual;
} else if (pc->IsRootContentDocumentCrossProcess()) {
viewportType = ViewportTypeForInputEventsRelativeToRoot();
}
}
RelativeTo relativeTo{aWeakRootFrameToHandleEvent.GetFrame(), viewportType};
nsPoint eventPoint =
nsLayoutUtils::GetEventCoordinatesRelativeTo(aGUIEvent, relativeTo);
uint32_t flags = 0;
if (aGUIEvent->IsMouseEventClassOrHasClickRelatedPointerEvent()) {
WidgetMouseEvent* mouseEvent = aGUIEvent->AsMouseEvent();
if (mouseEvent && mouseEvent->mIgnoreRootScrollFrame) {
flags |= INPUT_IGNORE_ROOT_SCROLL_FRAME;
}
}
nsIFrame* targetFrame =
FindFrameTargetedByInputEvent(aGUIEvent, relativeTo, eventPoint, flags);
if (!targetFrame) {
return aWeakRootFrameToHandleEvent.GetFrame();
}
if (targetFrame->PresShell() == mPresShell) {
// If found target is in mPresShell, we've already found it in the latest
// layout so that we can use it.
return targetFrame;
}
// If target is in a child document, we've not flushed its layout yet.
PresShell* childPresShell = targetFrame->PresShell();
EventHandler childEventHandler(*childPresShell);
bool layoutChanged =
childEventHandler.MaybeFlushPendingNotifications(aGUIEvent);
if (!aWeakRootFrameToHandleEvent.IsAlive()) {
// Stop handling the event if the root frame to handle event is destroyed
// by the reflow. (but why?)
return nullptr;
}
if (!layoutChanged) {
// If the layout in the child PresShell hasn't been changed, we don't
// need to recompute the target.
return targetFrame;
}
// Finally, we need to recompute the target with the latest layout.
targetFrame =
FindFrameTargetedByInputEvent(aGUIEvent, relativeTo, eventPoint, flags);
return targetFrame ? targetFrame : aWeakRootFrameToHandleEvent.GetFrame();
}
bool PresShell::EventHandler::ComputeEventTargetFrameAndPresShellAtEventPoint(
AutoWeakFrame& aWeakRootFrameToHandleEvent, WidgetGUIEvent* aGUIEvent,
EventTargetData* aEventTargetData) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aEventTargetData);
if (aGUIEvent->mClass == eTouchEventClass) {
nsIFrame* targetFrameAtTouchEvent = TouchManager::SetupTarget(
aGUIEvent->AsTouchEvent(), aWeakRootFrameToHandleEvent.GetFrame());
aEventTargetData->SetFrameAndComputePresShell(targetFrameAtTouchEvent);
return true;
}
nsIFrame* targetFrame =
GetFrameToHandleNonTouchEvent(aWeakRootFrameToHandleEvent, aGUIEvent);
aEventTargetData->SetFrameAndComputePresShell(targetFrame);
return !!aEventTargetData->GetFrame();
}
bool PresShell::EventHandler::DispatchPrecedingPointerEvent(
AutoWeakFrame& aWeakFrameForPresShell, WidgetGUIEvent* aGUIEvent,
Element* aPointerCapturingElement, bool aDontRetargetEvents,
EventTargetData* aEventTargetData, nsEventStatus* aEventStatus) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aEventTargetData);
MOZ_ASSERT(aEventStatus);
// Dispatch pointer events from the mouse or touch events. Regarding
// pointer events from mouse, we should dispatch those pointer events to
// the same target as the source mouse events. We pass the frame found
// in hit test to PointerEventHandler and dispatch pointer events to it.
//
// Regarding pointer events from touch, the behavior is different. Touch
// events are dispatched to the same target as the target of touchstart.
// Multiple touch points must be dispatched to the same document. Pointer
// events from touch can be dispatched to different documents. We Pass the
// original frame to PointerEventHandler, reentry PresShell::HandleEvent,
// and do hit test for each point.
auto targetFrameOrError = [&]() -> Result<nsIFrame*, nsresult> {
if (aGUIEvent->mClass == eTouchEventClass) {
// If aWeakFrameForPresShell has already been reframed before this is
// called, we don't need to handle the event.
if (MOZ_UNLIKELY(!aWeakFrameForPresShell.IsAlive())) {
return Err(NS_ERROR_FAILURE);
}
return aWeakFrameForPresShell.GetFrame();
}
return aEventTargetData->GetFrame();
}();
if (MOZ_UNLIKELY(targetFrameOrError.isErr())) {
return false;
}
nsIFrame* targetFrame = targetFrameOrError.unwrap();
if (aPointerCapturingElement) {
Result<nsIContent*, nsresult> overrideClickTargetOrError =
GetOverrideClickTarget(aGUIEvent, aWeakFrameForPresShell.GetFrame(),
aPointerCapturingElement);
if (MOZ_UNLIKELY(overrideClickTargetOrError.isErr())) {
return false;
}
aEventTargetData->mOverrideClickTarget =
overrideClickTargetOrError.unwrap();
aEventTargetData->mPresShell =
PresShell::GetShellForEventTarget(nullptr, aPointerCapturingElement);
if (!aEventTargetData->mPresShell) {
// If we can't process event for the capturing content, release
// the capture.
PointerEventHandler::ReleaseIfCaptureByDescendant(
aPointerCapturingElement);
return false;
}
targetFrame = aPointerCapturingElement->GetPrimaryFrame();
aEventTargetData->SetFrameAndContent(targetFrame, aPointerCapturingElement);
}
AutoWeakFrame weakTargetFrame(targetFrame);
AutoWeakFrame weakFrame(aEventTargetData->GetFrame());
nsCOMPtr<nsIContent> pointerEventTargetContent(
aEventTargetData->GetContent());
RefPtr<PresShell> presShell(aEventTargetData->mPresShell);
nsCOMPtr<nsIContent> mouseOrTouchEventTargetContent;
PointerEventHandler::DispatchPointerFromMouseOrTouch(
presShell, aEventTargetData->GetFrame(), pointerEventTargetContent,
aPointerCapturingElement, aGUIEvent, aDontRetargetEvents, aEventStatus,
getter_AddRefs(mouseOrTouchEventTargetContent));
const bool maybeCallerCanHandleEvent =
aGUIEvent->mMessage != eMouseRawUpdate &&
aGUIEvent->mMessage != eTouchRawUpdate;
// If the target frame is alive, the caller should keep handling the event
// unless event target frame is destroyed.
if (weakTargetFrame.IsAlive() && weakFrame.IsAlive()) {
aEventTargetData->UpdateTouchEventTarget(aGUIEvent);
return maybeCallerCanHandleEvent;
}
presShell->FlushPendingNotifications(FlushType::Layout);
if (MOZ_UNLIKELY(mPresShell->IsDestroying())) {
return false;
}
// The spec defines that mouse events must be dispatched to the same target as
// the pointer event.
// The Touch Events spec defines that touch events must be dispatched to the
// same target as touch start and the other browsers dispatch touch events
// even if the touch event target is not connected to the document.
// Retargetting the event is handled by AutoPointerEventTargetUpdater and
// mouseOrTouchEventTargetContent stores the result.
// If the target is no longer participating in its ownerDocument's tree,
// fire the event at the original target's nearest ancestor node.
if (!mouseOrTouchEventTargetContent) {
MOZ_ASSERT(aGUIEvent->IsMouseEventClassOrHasClickRelatedPointerEvent());
return false;
}
aEventTargetData->SetFrameAndContent(
mouseOrTouchEventTargetContent->GetPrimaryFrame(),
mouseOrTouchEventTargetContent);
aEventTargetData->mPresShell =
mouseOrTouchEventTargetContent->IsInComposedDoc()
? PresShell::GetShellForEventTarget(aEventTargetData->GetFrame(),
aEventTargetData->GetContent())
: mouseOrTouchEventTargetContent->OwnerDoc()->GetPresShell();
// If new target PresShel is not found, we cannot keep handling the event.
if (!aEventTargetData->mPresShell) {
return false;
}
aEventTargetData->UpdateTouchEventTarget(aGUIEvent);
return maybeCallerCanHandleEvent;
}
/**
* Event retargetting may retarget a mouse event and change the reference point.
* If event retargetting changes the reference point of a event that accessible
* caret will not handle, restore the original reference point.
*/
class AutoEventTargetPointResetter {
public:
explicit AutoEventTargetPointResetter(WidgetGUIEvent* aGUIEvent)
: mGUIEvent(aGUIEvent),
mRefPoint(aGUIEvent->mRefPoint),
mHandledByAccessibleCaret(false) {}
void SetHandledByAccessibleCaret() { mHandledByAccessibleCaret = true; }
~AutoEventTargetPointResetter() {
if (!mHandledByAccessibleCaret) {
mGUIEvent->mRefPoint = mRefPoint;
}
}
private:
WidgetGUIEvent* mGUIEvent;
LayoutDeviceIntPoint mRefPoint;
bool mHandledByAccessibleCaret;
};
bool PresShell::EventHandler::MaybeHandleEventWithAccessibleCaret(
AutoWeakFrame& aWeakFrameForPresShell, WidgetGUIEvent* aGUIEvent,
nsEventStatus* aEventStatus) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aEventStatus);
// Don't dispatch event to AccessibleCaretEventHub when the event status
// is nsEventStatus_eConsumeNoDefault. This might be happened when content
// preventDefault on the pointer events. In such case, we also call
// preventDefault on mouse events to stop default behaviors.
if (*aEventStatus == nsEventStatus_eConsumeNoDefault) {
return false;
}
if (!AccessibleCaretEnabled(GetDocument()->GetDocShell())) {
return false;
}
// AccessibleCaretEventHub handles only mouse, touch, and keyboard events.
if (!aGUIEvent->IsMouseEventClassOrHasClickRelatedPointerEvent() &&
aGUIEvent->mClass != eTouchEventClass &&
aGUIEvent->mClass != eKeyboardEventClass) {
return false;
}
AutoEventTargetPointResetter autoEventTargetPointResetter(aGUIEvent);
// First, try the event hub at the event point to handle a long press to
// select a word in an unfocused window.
do {
EventTargetData eventTargetData(nullptr);
if (!ComputeEventTargetFrameAndPresShellAtEventPoint(
aWeakFrameForPresShell, aGUIEvent, &eventTargetData)) {
break;
}
if (!eventTargetData.mPresShell) {
break;
}
RefPtr<AccessibleCaretEventHub> eventHub =
eventTargetData.mPresShell->GetAccessibleCaretEventHub();
if (!eventHub) {
break;
}
*aEventStatus = eventHub->HandleEvent(aGUIEvent);
if (*aEventStatus != nsEventStatus_eConsumeNoDefault) {
break;
}
// If the event is consumed, cancel APZC panning by setting
// mMultipleActionsPrevented.
aGUIEvent->mFlags.mMultipleActionsPrevented = true;
autoEventTargetPointResetter.SetHandledByAccessibleCaret();
return true;
} while (false);
// Then, we target the event to the event hub at the focused window.
nsCOMPtr<nsPIDOMWindowOuter> window = GetFocusedDOMWindowInOurWindow();
if (!window) {
return false;
}
RefPtr<Document> retargetEventDoc = window->GetExtantDoc();
if (!retargetEventDoc) {
return false;
}
RefPtr<PresShell> presShell = retargetEventDoc->GetPresShell();
if (!presShell) {
return false;
}
RefPtr<AccessibleCaretEventHub> eventHub =
presShell->GetAccessibleCaretEventHub();
if (!eventHub) {
return false;
}
*aEventStatus = eventHub->HandleEvent(aGUIEvent);
if (*aEventStatus != nsEventStatus_eConsumeNoDefault) {
return false;
}
// If the event is consumed, cancel APZC panning by setting
// mMultipleActionsPrevented.
aGUIEvent->mFlags.mMultipleActionsPrevented = true;
autoEventTargetPointResetter.SetHandledByAccessibleCaret();
return true;
}
void PresShell::EventHandler::MaybeSynthesizeCompatMouseEventsForTouchEnd(
const WidgetTouchEvent* aTouchEndEvent,
const nsEventStatus* aStatus) const {
MOZ_ASSERT(aTouchEndEvent->mMessage == eTouchEnd);
// If the eTouchEnd event is dispatched via APZ, APZCCallbackHelper dispatches
// a set of mouse events with better handling. Therefore, we don't need to
// handle that here.
if (!aTouchEndEvent->mFlags.mIsSynthesizedForTests ||
StaticPrefs::test_events_async_enabled()) {
return;
}
auto cleanUpPointerCapturingElementAtLastPointerUp = MakeScopeExit([]() {
PointerEventHandler::ReleasePointerCapturingElementAtLastPointerUp();
});
// If the tap was consumed or 2 or more touches occurred, we don't need the
// compatibility mouse events.
if (*aStatus == nsEventStatus_eConsumeNoDefault ||
!TouchManager::IsSingleTapEndToDoDefault(aTouchEndEvent)) {
return;
}
if (NS_WARN_IF(!aTouchEndEvent->mWidget)) {
return;
}
nsCOMPtr<nsIWidget> widget = aTouchEndEvent->mWidget;
// NOTE: I think that we don't need to implement a double click here becase
// WebDriver does not support a way to synthesize a double click and Chrome
// does not fire "dblclick" even if doing `pointerDown().pointerUp()` twice.
// FIXME: Currently we don't support long tap.
RefPtr<PresShell> presShell = mPresShell;
for (const EventMessage message : {eMouseMove, eMouseDown, eMouseUp}) {
if (MOZ_UNLIKELY(presShell->IsDestroying())) {
break;
}
nsIFrame* const frameForPresShell =
presShell->GetClosestAncestorFrameForAncestorView();
if (!frameForPresShell) {
break;
}
WidgetMouseEvent event(true, message, widget, WidgetMouseEvent::eReal);
event.mFlags.mIsSynthesizedForTests =
aTouchEndEvent->mFlags.mIsSynthesizedForTests;
event.mRefPoint = aTouchEndEvent->mTouches[0]->mRefPoint;
event.mButton = MouseButton::ePrimary;
event.mButtons = message == eMouseDown ? MouseButtonsFlag::ePrimaryFlag
: MouseButtonsFlag::eNoButtons;
event.mInputSource = MouseEvent_Binding::MOZ_SOURCE_TOUCH;
event.mClickCount = message == eMouseMove ? 0 : 1;
event.mModifiers = aTouchEndEvent->mModifiers;
event.pointerId = aTouchEndEvent->mTouches[0]->mIdentifier;
event.convertToPointer = false;
if (TouchManager::IsPrecedingTouchPointerDownConsumedByContent()) {
event.PreventDefault(false);
event.mFlags.mOnlyChromeDispatch = true;
}
nsEventStatus mouseEventStatus = nsEventStatus_eIgnore;
presShell->HandleEvent(frameForPresShell, &event, false, &mouseEventStatus);
}
}
bool PresShell::EventHandler::MaybeDiscardEvent(WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
// If it is safe to dispatch events now, don't discard the event.
if (nsContentUtils::IsSafeToRunScript()) {
return false;
}
// If the event does not cause dispatching DOM event (i.e., internal event),
// we can keep handling it even when it's not safe to run script.
if (!aGUIEvent->IsAllowedToDispatchDOMEvent()) {
return false;
}
// If the event is a composition event, we need to let IMEStateManager know
// it's discarded because it needs to listen all composition events to manage
// TextComposition instance.
if (aGUIEvent->mClass == eCompositionEventClass) {
IMEStateManager::OnCompositionEventDiscarded(
aGUIEvent->AsCompositionEvent());
}
#ifdef DEBUG
if (aGUIEvent->IsIMERelatedEvent()) {
nsPrintfCString warning("%s event is discarded",
ToChar(aGUIEvent->mMessage));
NS_WARNING(warning.get());
}
#endif // #ifdef DEBUG
nsContentUtils::WarnScriptWasIgnored(GetDocument());
return true;
}
// static
nsIContent* PresShell::EventHandler::GetCapturingContentFor(
WidgetGUIEvent* aGUIEvent) {
if (aGUIEvent->mClass != ePointerEventClass &&
aGUIEvent->mClass != eWheelEventClass &&
!aGUIEvent->HasMouseEventMessage()) {
return nullptr;
}
// PointerEventHandler may synthesize ePointerMove event before releasing the
// mouse capture (it's done by a default handler of eMouseUp) after handling
// ePointerUp. Then, we need to dispatch pointer boundary events for the
// element under the pointer to emulate a pointer move after a pointer
// capture. Therefore, we need to ignore the capturing element if the event
// dispatcher requests it.
if (aGUIEvent->ShouldIgnoreCapturingContent()) {
return nullptr;
}
return PresShell::GetCapturingContent();
}
bool PresShell::EventHandler::GetRetargetEventDocument(
WidgetGUIEvent* aGUIEvent, Document** aRetargetEventDocument) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aRetargetEventDocument);
*aRetargetEventDocument = nullptr;
// key and IME related events should not cross top level window boundary.
// Basically, such input events should be fired only on focused widget.
// However, some IMEs might need to clean up composition after focused
// window is deactivated. And also some tests on MozMill want to test key
// handling on deactivated window because MozMill window can be activated
// during tests. So, there is no merit the events should be redirected to
// active window. So, the events should be handled on the last focused
// content in the last focused DOM window in same top level window.
// Note, if no DOM window has been focused yet, we can discard the events.
if (aGUIEvent->IsTargetedAtFocusedWindow()) {
nsCOMPtr<nsPIDOMWindowOuter> window = GetFocusedDOMWindowInOurWindow();
// No DOM window in same top level window has not been focused yet,
// discard the events.
if (!window) {
return false;
}
RefPtr<Document> retargetEventDoc = window->GetExtantDoc();
if (!retargetEventDoc) {
return false;
}
retargetEventDoc.forget(aRetargetEventDocument);
return true;
}
const nsIContent* const capturingContent =
aGUIEvent->ShouldIgnoreCapturingContent()
? nullptr
: EventHandler::GetCapturingContentFor(aGUIEvent);
if (capturingContent) {
// if the mouse is being captured then retarget the mouse event at the
// document that is being captured.
RefPtr<Document> retargetEventDoc = capturingContent->GetComposedDoc();
retargetEventDoc.forget(aRetargetEventDocument);
return true;
}
#ifdef ANDROID
if (aGUIEvent->mClass == eTouchEventClass ||
aGUIEvent->IsMouseEventClassOrHasClickRelatedPointerEvent() ||
aGUIEvent->mClass == eWheelEventClass) {
RefPtr<Document> retargetEventDoc = mPresShell->GetPrimaryContentDocument();
retargetEventDoc.forget(aRetargetEventDocument);
return true;
}
#endif // #ifdef ANDROID
// When we don't find another document to handle the event, we need to keep
// handling the event by ourselves.
return true;
}
nsIFrame* PresShell::EventHandler::GetFrameForHandlingEventWith(
WidgetGUIEvent* aGUIEvent, Document* aRetargetDocument,
nsIFrame* aFrameForPresShell) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aRetargetDocument);
RefPtr<PresShell> retargetPresShell = aRetargetDocument->GetPresShell();
// Even if the document doesn't have PresShell, i.e., it's invisible, we
// need to dispatch only KeyboardEvent in its nearest visible document
// because key focus shouldn't be caught by invisible document.
if (!retargetPresShell) {
if (!aGUIEvent->HasKeyEventMessage()) {
return nullptr;
}
Document* retargetEventDoc = aRetargetDocument;
while (!retargetPresShell) {
retargetEventDoc = retargetEventDoc->GetInProcessParentDocument();
if (!retargetEventDoc) {
return nullptr;
}
retargetPresShell = retargetEventDoc->GetPresShell();
}
}
// If the found PresShell is this instance, caller needs to keep handling
// aGUIEvent by itself. Therefore, return the given frame which was set
// to aFrame of HandleEvent().
if (retargetPresShell == mPresShell) {
return aFrameForPresShell;
}
// Use root frame of the new PresShell if there is.
nsIFrame* rootFrame = retargetPresShell->GetRootFrame();
if (rootFrame) {
return rootFrame;
}
// Otherwise, and if aGUIEvent requires content of PresShell, caller should
// stop handling the event.
if (aGUIEvent->mMessage == eQueryTextContent ||
aGUIEvent->IsContentCommandEvent()) {
return nullptr;
}
// Otherwise, use nearest ancestor frame which includes the PresShell.
return retargetPresShell->GetClosestAncestorFrameForAncestorView();
}
bool PresShell::EventHandler::MaybeHandleEventWithAnotherPresShell(
AutoWeakFrame& aWeakFrameForPresShell, WidgetGUIEvent* aGUIEvent,
nsEventStatus* aEventStatus, nsresult* aRv) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aEventStatus);
MOZ_ASSERT(aRv);
*aRv = NS_OK;
RefPtr<Document> retargetEventDoc;
if (!GetRetargetEventDocument(aGUIEvent, getter_AddRefs(retargetEventDoc))) {
// Nobody can handle this event. So, treat as handled by somebody to make
// caller do nothing anymore.
return true;
}
// If there is no proper retarget document, the caller should handle the
// event by itself.
if (!retargetEventDoc) {
return false;
}
nsIFrame* frame = GetFrameForHandlingEventWith(
aGUIEvent, retargetEventDoc, aWeakFrameForPresShell.GetFrame());
if (!frame) {
// Nobody can handle this event. So, treat as handled by somebody to make
// caller do nothing anymore.
// NOTE: If aWeakFrameForPresShell does not refer to a frame (i.e., it's
// already been reframed) and aGUIEvent needs to be handled in mPresShell,
// we are here because GetFrameForHandlingEventWith() returns
// aWeakFrameForPresShell.GetFrame() as-is. In the case, we don't need to
// handle aGUIEvent, so, it's fine to return true from this method.
return true;
}
// If we reached same frame as set to HandleEvent(), the caller should handle
// the event by itself.
if (frame == aWeakFrameForPresShell.GetFrame()) {
return false;
}
// We need to handle aGUIEvent with another PresShell.
RefPtr<PresShell> presShell = frame->PresContext()->PresShell();
*aRv = presShell->HandleEvent(frame, aGUIEvent, true, aEventStatus);
return true;
}
bool PresShell::EventHandler::MaybeDiscardOrDelayKeyboardEvent(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
if (aGUIEvent->mClass != eKeyboardEventClass) {
return false;
}
Document* document = GetDocument();
if (!document || !document->EventHandlingSuppressed()) {
return false;
}
MOZ_ASSERT_IF(InputTaskManager::CanSuspendInputEvent(),
!InputTaskManager::Get()->IsSuspended());
if (aGUIEvent->mMessage == eKeyDown) {
mPresShell->mNoDelayedKeyEvents = true;
} else if (!mPresShell->mNoDelayedKeyEvents) {
UniquePtr<DelayedKeyEvent> delayedKeyEvent =
MakeUnique<DelayedKeyEvent>(aGUIEvent->AsKeyboardEvent());
mPresShell->mDelayedEvents.AppendElement(std::move(delayedKeyEvent));
}
aGUIEvent->mFlags.mIsSuppressedOrDelayed = true;
return true;
}
bool PresShell::EventHandler::MaybeDiscardOrDelayMouseEvent(
nsIFrame* aFrameToHandleEvent, WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aFrameToHandleEvent);
MOZ_ASSERT(aGUIEvent);
// We must not need to let suspend listeners know ePointerRawUpdate events.
// And also the delayed events will be dispatched via widget. Therefore,
// ePointerRawUpdate event will be dispatched by PresShell::HandleEvent()
// again.
if (aGUIEvent->mMessage == eMouseRawUpdate ||
aGUIEvent->mMessage == eTouchRawUpdate ||
aGUIEvent->mMessage == ePointerRawUpdate) {
return false;
}
if (!aGUIEvent->IsMouseEventClassOrHasClickRelatedPointerEvent()) {
return false;
}
if (!aFrameToHandleEvent->PresContext()
->Document()
->EventHandlingSuppressed()) {
return false;
}
MOZ_ASSERT_IF(InputTaskManager::CanSuspendInputEvent() &&
aGUIEvent->mMessage != eMouseMove,
!InputTaskManager::Get()->IsSuspended());
RefPtr<PresShell> ps = aFrameToHandleEvent->PresShell();
if (aGUIEvent->mMessage == eMouseDown) {
ps->mNoDelayedMouseEvents = true;
} else if (!ps->mNoDelayedMouseEvents) {
if (aGUIEvent->mMessage == eMouseUp ||
aGUIEvent->mMessage == eMouseExitFromWidget) {
UniquePtr<DelayedMouseEvent> delayedMouseEvent =
MakeUnique<DelayedMouseEvent>(aGUIEvent->AsMouseEvent());
ps->mDelayedEvents.AppendElement(std::move(delayedMouseEvent));
}
// contextmenu is triggered after right mouseup on Windows and right
// mousedown on other platforms.
else if (aGUIEvent->mMessage == eContextMenu) {
UniquePtr<DelayedPointerEvent> delayedPointerEvent =
MakeUnique<DelayedPointerEvent>(aGUIEvent->AsPointerEvent());
ps->mDelayedEvents.AppendElement(std::move(delayedPointerEvent));
}
}
// If there is a suppressed event listener associated with the document,
// notify it about the suppressed mouse event. This allows devtools
// features to continue receiving mouse events even when the devtools
// debugger has paused execution in a page.
RefPtr<EventListener> suppressedListener = aFrameToHandleEvent->PresContext()
->Document()
->GetSuppressedEventListener();
if (!suppressedListener ||
aGUIEvent->AsMouseEvent()->mReason == WidgetMouseEvent::eSynthesized) {
return true;
}
if (auto* target = aFrameToHandleEvent->GetContentForEvent(aGUIEvent)) {
aGUIEvent->mTarget = target;
}
nsCOMPtr<EventTarget> eventTarget = aGUIEvent->mTarget;
RefPtr<Event> event = EventDispatcher::CreateEvent(
eventTarget, aFrameToHandleEvent->PresContext(), aGUIEvent, u""_ns);
suppressedListener->HandleEvent(*event);
return true;
}
void PresShell::EventHandler::MaybeFlushThrottledStyles(
AutoWeakFrame& aWeakFrameForPresShell) {
if (!GetDocument()) {
return;
}
PresShell* rootPresShell = mPresShell->GetRootPresShell();
if (NS_WARN_IF(!rootPresShell)) {
return;
}
Document* rootDocument = rootPresShell->GetDocument();
if (NS_WARN_IF(!rootDocument)) {
return;
}
{ // scope for scriptBlocker.
nsAutoScriptBlocker scriptBlocker;
FlushThrottledStyles(*rootDocument);
}
if (MOZ_UNLIKELY(!aWeakFrameForPresShell.IsAlive()) &&
MOZ_LIKELY(!mPresShell->IsDestroying())) {
// FIXME: aWeakFrameForPresShell may be target content's frame if aGUIEvent
// of the caller is a touch event. So, we need to use different computation
// for such cases.
aWeakFrameForPresShell =
mPresShell->GetClosestAncestorFrameForAncestorView();
}
}
nsIFrame* PresShell::EventHandler::ComputeRootFrameToHandleEvent(
nsIFrame* aFrameForPresShell, WidgetGUIEvent* aGUIEvent,
nsIContent* aCapturingContent, bool* aIsCapturingContentIgnored,
bool* aIsCaptureRetargeted) {
MOZ_ASSERT(aFrameForPresShell);
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aIsCapturingContentIgnored);
MOZ_ASSERT(aIsCaptureRetargeted);
nsIFrame* rootFrameToHandleEvent = ComputeRootFrameToHandleEventWithPopup(
aFrameForPresShell, aGUIEvent, aCapturingContent,
aIsCapturingContentIgnored);
if (*aIsCapturingContentIgnored) {
// If the capturing content is ignored, we don't need to respect it.
return rootFrameToHandleEvent;
}
if (!aCapturingContent) {
return rootFrameToHandleEvent;
}
// If we have capturing content, let's compute root frame with it again.
return ComputeRootFrameToHandleEventWithCapturingContent(
rootFrameToHandleEvent, aCapturingContent, aIsCapturingContentIgnored,
aIsCaptureRetargeted);
}
nsIFrame* PresShell::EventHandler::ComputeRootFrameToHandleEventWithPopup(
nsIFrame* aRootFrameToHandleEvent, WidgetGUIEvent* aGUIEvent,
nsIContent* aCapturingContent, bool* aIsCapturingContentIgnored) {
MOZ_ASSERT(aRootFrameToHandleEvent);
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aIsCapturingContentIgnored);
*aIsCapturingContentIgnored = false;
nsPresContext* framePresContext = aRootFrameToHandleEvent->PresContext();
nsPresContext* rootPresContext = framePresContext->GetRootPresContext();
NS_ASSERTION(rootPresContext == GetPresContext()->GetRootPresContext(),
"How did we end up outside the connected "
"prescontext/viewmanager hierarchy?");
nsIFrame* popupFrame = nsLayoutUtils::GetPopupFrameForEventCoordinates(
rootPresContext, aGUIEvent);
if (!popupFrame) {
return aRootFrameToHandleEvent;
}
// If a remote browser is currently capturing input break out if we
// detect a chrome generated popup.
// XXXedgar, do we need to check fission OOP iframe?
if (aCapturingContent &&
EventStateManager::IsTopLevelRemoteTarget(aCapturingContent)) {
*aIsCapturingContentIgnored = true;
}
// If the popupFrame is an ancestor of the 'frame', the frame should
// handle the event, otherwise, the popup should handle it.
if (nsContentUtils::ContentIsCrossDocDescendantOf(
framePresContext->GetPresShell()->GetDocument(),
popupFrame->GetContent())) {
return aRootFrameToHandleEvent;
}
// If we aren't starting our event dispatch from the root frame of the
// root prescontext, then someone must be capturing the mouse. In that
// case we only want to use the popup list if the capture is
// inside the popup.
if (framePresContext == rootPresContext &&
aRootFrameToHandleEvent == FrameConstructor()->GetRootFrame()) {
return popupFrame;
}
if (aCapturingContent && !*aIsCapturingContentIgnored &&
aCapturingContent->IsInclusiveDescendantOf(popupFrame->GetContent())) {
return popupFrame;
}
return aRootFrameToHandleEvent;
}
nsIFrame*
PresShell::EventHandler::ComputeRootFrameToHandleEventWithCapturingContent(
nsIFrame* aRootFrameToHandleEvent, nsIContent* aCapturingContent,
bool* aIsCapturingContentIgnored, bool* aIsCaptureRetargeted) {
MOZ_ASSERT(aRootFrameToHandleEvent);
MOZ_ASSERT(aCapturingContent);
MOZ_ASSERT(aIsCapturingContentIgnored);
MOZ_ASSERT(aIsCaptureRetargeted);
*aIsCapturingContentIgnored = false;
*aIsCaptureRetargeted = false;
// If a capture is active, determine if the BrowsingContext is active. If
// not, clear the capture and target the mouse event normally instead. This
// would occur if the mouse button is held down while a tab change occurs.
// If the BrowsingContext is active, look for a scrolling container.
BrowsingContext* bc = GetPresContext()->Document()->GetBrowsingContext();
if (!bc || !bc->IsActive()) {
ClearMouseCapture();
*aIsCapturingContentIgnored = true;
return aRootFrameToHandleEvent;
}
if (PresShell::sCapturingContentInfo.mRetargetToElement) {
*aIsCaptureRetargeted = true;
return aRootFrameToHandleEvent;
}
nsIFrame* captureFrame = aCapturingContent->GetPrimaryFrame();
if (!captureFrame) {
return aRootFrameToHandleEvent;
}
// scrollable frames should use the scrolling container as the root instead
// of the document
ScrollContainerFrame* scrollFrame = do_QueryFrame(captureFrame);
return scrollFrame ? scrollFrame->GetScrolledFrame()
: aRootFrameToHandleEvent;
}
nsresult
PresShell::EventHandler::HandleEventWithPointerCapturingContentWithoutItsFrame(
AutoWeakFrame& aWeakFrameForPresShell, WidgetGUIEvent* aGUIEvent,
Element* aPointerCapturingElement, nsEventStatus* aEventStatus) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aPointerCapturingElement);
MOZ_ASSERT(!aPointerCapturingElement->GetPrimaryFrame(),
"Handle the event with frame rather than only with the content");
MOZ_ASSERT(aEventStatus);
RefPtr<PresShell> presShellForCapturingContent =
PresShell::GetShellForEventTarget(nullptr, aPointerCapturingElement);
if (!presShellForCapturingContent) {
// If we can't process event for the capturing content, release
// the capture.
PointerEventHandler::ReleaseIfCaptureByDescendant(aPointerCapturingElement);
// Since we don't dispatch ePointeUp nor ePointerCancel in this case,
// EventStateManager::PostHandleEvent does not have a chance to dispatch
// ePointerLostCapture event. Therefore, we need to dispatch it here.
PointerEventHandler::MaybeImplicitlyReleasePointerCapture(aGUIEvent);
return NS_OK;
}
Result<nsIContent*, nsresult> overrideClickTargetOrError =
GetOverrideClickTarget(aGUIEvent, aWeakFrameForPresShell.GetFrame(),
aPointerCapturingElement);
if (MOZ_UNLIKELY(overrideClickTargetOrError.isErr())) {
return NS_OK;
}
nsCOMPtr<nsIContent> overrideClickTarget =
overrideClickTargetOrError.unwrap();
// Dispatch events to the capturing content even it's frame is
// destroyed.
PointerEventHandler::DispatchPointerFromMouseOrTouch(
presShellForCapturingContent, nullptr, aPointerCapturingElement,
aPointerCapturingElement, aGUIEvent, false, aEventStatus, nullptr);
if (presShellForCapturingContent == mPresShell) {
return HandleEventWithTarget(aGUIEvent, nullptr, aPointerCapturingElement,
aEventStatus, true, nullptr,
overrideClickTarget);
}
EventHandler eventHandlerForCapturingContent(
std::move(presShellForCapturingContent));
return eventHandlerForCapturingContent.HandleEventWithTarget(
aGUIEvent, nullptr, aPointerCapturingElement, aEventStatus, true, nullptr,
overrideClickTarget);
}
nsresult PresShell::EventHandler::HandleEventAtFocusedContent(
WidgetGUIEvent* aGUIEvent, nsEventStatus* aEventStatus) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aGUIEvent->IsTargetedAtFocusedContent());
MOZ_ASSERT(aEventStatus);
AutoCurrentEventInfoSetter eventInfoSetter(*this);
RefPtr<Element> eventTargetElement =
ComputeFocusedEventTargetElement(aGUIEvent);
// mCurrentEventTarget is cleared by eventInfoSetter and
// ComputeFocusedEventTargetElement shouldn't set it again.
MOZ_ASSERT(!mPresShell->mCurrentEventTarget.IsSet());
if (eventTargetElement) {
nsresult rv = NS_OK;
if (MaybeHandleEventWithAnotherPresShell(eventTargetElement, aGUIEvent,
aEventStatus, &rv)) {
return rv;
}
}
// If we cannot handle the event with mPresShell, let's try to handle it
// with parent PresShell.
// However, we don't want to handle IME related events with parent document
// because it may leak the content of parent document and the IME state was
// set for the empty document. So, dispatching on the parent document may be
// handled by nobody. Additionally, IMEContentObserver may send notifications
// to PuppetWidget in a content process while document which is in the design
// mode but does not have content nodes has focus. At that time, PuppetWidget
// makes ContentCacheInChild collect the latest content data with dispatching
// query content events. Therefore, we want they handle in the empty document
// rather than the parent document. So, we must not retarget in this case
// anyway.
mPresShell->mCurrentEventTarget.SetFrameAndContent(
aGUIEvent->mMessage, nullptr, eventTargetElement);
if (aGUIEvent->mClass != eCompositionEventClass &&
aGUIEvent->mClass != eQueryContentEventClass &&
aGUIEvent->mClass != eSelectionEventClass &&
(!mPresShell->GetCurrentEventContent() ||
!mPresShell->GetCurrentEventFrame() ||
InZombieDocument(mPresShell->mCurrentEventTarget.mContent))) {
return RetargetEventToParent(aGUIEvent, aEventStatus);
}
nsresult rv =
HandleEventWithCurrentEventInfo(aGUIEvent, aEventStatus, true, nullptr);
return rv;
}
Element* PresShell::EventHandler::ComputeFocusedEventTargetElement(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aGUIEvent->IsTargetedAtFocusedContent());
// key and IME related events go to the focused frame in this DOM window.
nsPIDOMWindowOuter* window = GetDocument()->GetWindow();
nsCOMPtr<nsPIDOMWindowOuter> focusedWindow;
Element* eventTargetElement = nsFocusManager::GetFocusedDescendant(
window, nsFocusManager::eOnlyCurrentWindow,
getter_AddRefs(focusedWindow));
// otherwise, if there is no focused content or the focused content has
// no frame, just use the root content. This ensures that key events
// still get sent to the window properly if nothing is focused or if a
// frame goes away while it is focused.
if (!eventTargetElement || !eventTargetElement->GetPrimaryFrame()) {
eventTargetElement = GetDocument()->GetUnfocusedKeyEventTarget();
}
switch (aGUIEvent->mMessage) {
case eKeyDown:
sLastKeyDownEventTargetElement = eventTargetElement;
return eventTargetElement;
case eKeyPress:
case eKeyUp:
if (!sLastKeyDownEventTargetElement) {
return eventTargetElement;
}
// If a different element is now focused for the keypress/keyup event
// than what was focused during the keydown event, check if the new
// focused element is not in a chrome document any more, and if so,
// retarget the event back at the keydown target. This prevents a
// content area from grabbing the focus from chrome in-between key
// events.
if (eventTargetElement) {
bool keyDownIsChrome = nsContentUtils::IsChromeDoc(
sLastKeyDownEventTargetElement->GetComposedDoc());
if (keyDownIsChrome != nsContentUtils::IsChromeDoc(
eventTargetElement->GetComposedDoc()) ||
(keyDownIsChrome && BrowserParent::GetFrom(eventTargetElement))) {
eventTargetElement = sLastKeyDownEventTargetElement;
}
}
if (aGUIEvent->mMessage == eKeyUp) {
sLastKeyDownEventTargetElement = nullptr;
}
[[fallthrough]];
default:
return eventTargetElement;
}
}
bool PresShell::EventHandler::MaybeHandleEventWithAnotherPresShell(
Element* aEventTargetElement, WidgetGUIEvent* aGUIEvent,
nsEventStatus* aEventStatus, nsresult* aRv) {
MOZ_ASSERT(aEventTargetElement);
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(!aGUIEvent->IsUsingCoordinates());
MOZ_ASSERT(aEventStatus);
MOZ_ASSERT(aRv);
Document* eventTargetDocument = aEventTargetElement->OwnerDoc();
if (!eventTargetDocument || eventTargetDocument == GetDocument()) {
*aRv = NS_OK;
return false;
}
RefPtr<PresShell> eventTargetPresShell = eventTargetDocument->GetPresShell();
if (!eventTargetPresShell) {
*aRv = NS_OK;
return true; // No PresShell can handle the event.
}
EventHandler eventHandler(std::move(eventTargetPresShell));
*aRv = eventHandler.HandleRetargetedEvent(aGUIEvent, aEventStatus,
aEventTargetElement);
return true;
}
nsresult PresShell::EventHandler::HandleEventWithFrameForPresShell(
AutoWeakFrame& aWeakFrameForPresShell, WidgetGUIEvent* aGUIEvent,
nsEventStatus* aEventStatus) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(!aGUIEvent->IsUsingCoordinates());
MOZ_ASSERT(!aGUIEvent->IsTargetedAtFocusedContent());
MOZ_ASSERT(aEventStatus);
AutoCurrentEventInfoSetter eventInfoSetter(
*this, EventTargetInfo(aGUIEvent->mMessage,
aWeakFrameForPresShell.GetFrame(), nullptr));
nsresult rv = NS_OK;
if (mPresShell->GetCurrentEventFrame()) {
rv =
HandleEventWithCurrentEventInfo(aGUIEvent, aEventStatus, true, nullptr);
}
return rv;
}
Document* PresShell::GetPrimaryContentDocument() {
nsPresContext* context = GetPresContext();
if (!context || !context->IsRoot()) {
return nullptr;
}
nsCOMPtr<nsIDocShellTreeItem> shellAsTreeItem = context->GetDocShell();
if (!shellAsTreeItem) {
return nullptr;
}
nsCOMPtr<nsIDocShellTreeOwner> owner;
shellAsTreeItem->GetTreeOwner(getter_AddRefs(owner));
if (!owner) {
return nullptr;
}
// now get the primary content shell (active tab)
nsCOMPtr<nsIDocShellTreeItem> item;
owner->GetPrimaryContentShell(getter_AddRefs(item));
nsCOMPtr<nsIDocShell> childDocShell = do_QueryInterface(item);
if (!childDocShell) {
return nullptr;
}
return childDocShell->GetExtantDocument();
}
nsresult PresShell::EventHandler::HandleEventWithTarget(
WidgetEvent* aEvent, nsIFrame* aNewEventFrame, nsIContent* aNewEventContent,
nsEventStatus* aEventStatus, bool aIsHandlingNativeEvent,
nsIContent** aTargetContent, nsIContent* aOverrideClickTarget) {
MOZ_ASSERT(aEvent);
MOZ_DIAGNOSTIC_ASSERT(aEvent->IsTrusted());
MOZ_ASSERT(!aNewEventFrame || aNewEventFrame->PresShell() == mPresShell,
"wrong shell");
// NOTE: We don't require that the document still have a PresShell.
// See bug 1375940.
NS_ASSERTION(!aNewEventContent || aNewEventContent->IsInComposedDoc(),
"event for content that isn't in a document");
NS_ENSURE_STATE(!aNewEventContent ||
aNewEventContent->GetComposedDoc() == GetDocument());
if (aEvent->mClass == ePointerEventClass ||
aEvent->mClass == eDragEventClass) {
mPresShell->RecordPointerLocation(aEvent->AsMouseEvent());
}
AutoPointerEventTargetUpdater updater(mPresShell, aEvent, aNewEventFrame,
aNewEventContent, aTargetContent);
AutoCurrentEventInfoSetter eventInfoSetter(
*this,
EventTargetInfo(aEvent->mMessage, aNewEventFrame, aNewEventContent));
nsresult rv = HandleEventWithCurrentEventInfo(aEvent, aEventStatus, false,
aOverrideClickTarget);
return rv;
}
namespace {
class MOZ_RAII AutoEventHandler final {
public:
AutoEventHandler(WidgetEvent* aEvent, Document* aDocument) : mEvent(aEvent) {
MOZ_ASSERT(mEvent);
MOZ_ASSERT(mEvent->IsTrusted());
if (mEvent->mMessage == eMouseDown) {
PresShell::ReleaseCapturingContent();
PresShell::AllowMouseCapture(true);
}
if (NeedsToUpdateCurrentMouseBtnState()) {
WidgetMouseEvent* mouseEvent = mEvent->AsMouseEvent();
if (mouseEvent) {
EventStateManager::sCurrentMouseBtn = mouseEvent->mButton;
}
}
}
~AutoEventHandler() {
if (mEvent->mMessage == eMouseDown) {
PresShell::AllowMouseCapture(false);
}
if (NeedsToUpdateCurrentMouseBtnState()) {
EventStateManager::sCurrentMouseBtn = MouseButton::eNotPressed;
}
}
protected:
bool NeedsToUpdateCurrentMouseBtnState() const {
return mEvent->mMessage == eMouseDown || mEvent->mMessage == eMouseUp ||
mEvent->mMessage == ePointerDown || mEvent->mMessage == ePointerUp;
}
WidgetEvent* mEvent;
};
} // anonymous namespace
nsresult PresShell::EventHandler::HandleEventWithCurrentEventInfo(
WidgetEvent* aEvent, nsEventStatus* aEventStatus,
bool aIsHandlingNativeEvent, nsIContent* aOverrideClickTarget) {
MOZ_ASSERT(aEvent);
MOZ_ASSERT(aEventStatus);
RefPtr<EventStateManager> manager = GetPresContext()->EventStateManager();
// If we cannot handle the event with mPresShell because of no target,
// just record the response time.
// XXX Is this intentional? In such case, the score is really good because
// of nothing to do. So, it may make average and median better.
if (NS_EVENT_NEEDS_FRAME(aEvent) && !mPresShell->GetCurrentEventFrame() &&
!mPresShell->GetCurrentEventContent()) {
RecordEventHandlingResponsePerformance(aEvent);
return NS_OK;
}
if (mPresShell->mCurrentEventTarget.mContent &&
aEvent->IsTargetedAtFocusedWindow() &&
aEvent->AllowFlushingPendingNotifications()) {
if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
// This may run script now. So, mPresShell might be destroyed after here.
nsCOMPtr<nsIContent> currentEventContent =
mPresShell->mCurrentEventTarget.mContent;
fm->FlushBeforeEventHandlingIfNeeded(currentEventContent);
}
}
bool touchIsNew = false;
if (!PrepareToDispatchEvent(aEvent, aEventStatus, &touchIsNew)) {
return NS_OK;
}
// We finished preparing to dispatch the event. So, let's record the
// performance.
RecordEventPreparationPerformance(aEvent);
AutoHandlingUserInputStatePusher userInpStatePusher(
UserActivation::IsUserInteractionEvent(aEvent), aEvent);
AutoEventHandler eventHandler(aEvent, GetDocument());
AutoPopupStatePusher popupStatePusher(
PopupBlocker::GetEventPopupControlState(aEvent));
// FIXME. If the event was reused, we need to clear the old target,
// bug 329430
aEvent->mTarget = nullptr;
nsresult rv = DispatchEvent(manager, aEvent, touchIsNew, aEventStatus,
aOverrideClickTarget);
if (!mPresShell->IsDestroying() && aIsHandlingNativeEvent &&
aEvent->mClass != eQueryContentEventClass) {
// Ensure that notifications to IME should be sent before getting next
// native event from the event queue.
// XXX Should we check the event message or event class instead of
// using aIsHandlingNativeEvent?
manager->TryToFlushPendingNotificationsToIME();
}
FinalizeHandlingEvent(aEvent, aEventStatus);
RecordEventHandlingResponsePerformance(aEvent);
return rv; // Result of DispatchEvent()
}
nsresult PresShell::EventHandler::DispatchEvent(
EventStateManager* aEventStateManager, WidgetEvent* aEvent,
bool aTouchIsNew, nsEventStatus* aEventStatus,
nsIContent* aOverrideClickTarget) {
MOZ_ASSERT(aEventStateManager);
MOZ_ASSERT(aEvent);
MOZ_ASSERT(aEventStatus);
// 1. Give event to event manager for pre event state changes and
// generation of synthetic events.
{ // Scope for presContext
RefPtr<nsPresContext> presContext = GetPresContext();
nsCOMPtr<nsIContent> eventContent =
mPresShell->mCurrentEventTarget.mContent;
nsresult rv = aEventStateManager->PreHandleEvent(
presContext, aEvent, mPresShell->mCurrentEventTarget.mFrame,
eventContent, aEventStatus, aOverrideClickTarget);
if (NS_FAILED(rv)) {
return rv;
}
// Let's retarget eMouseMove target if the preceding mouse boundary events
// caused removing the target from the tree and EventStateManager knows that
// the deepest connected mouseenter target which was an ancestor of the
// removed target. This matches with Chrome Canary with enabling the
// new mouse/pointer boundary event feature. However, they stop dispatching
// "pointermove" in the same case. Therefore, for now, we should do this
// only for eMouseMove.
if (eventContent && aEvent->mMessage == eMouseMove &&
(!eventContent->IsInComposedDoc() ||
eventContent->OwnerDoc() != mPresShell->GetDocument())) {
const OverOutElementsWrapper* const boundaryEventTargets =
aEventStateManager->GetExtantMouseBoundaryEventTarget();
const nsIContent* outEventTarget =
boundaryEventTargets ? boundaryEventTargets->GetOutEventTarget()
: nullptr;
nsIContent* const deepestLeaveEventTarget =
boundaryEventTargets
? boundaryEventTargets->GetDeepestLeaveEventTarget()
: nullptr;
// If the last "over" target (next "out" target) is there, it means that
// it was temporarily removed. In such case, EventStateManager treats
// it as never disconnected. Therefore, we need to do nothing here.
// Additionally, if there is no last deepest "enter" event target, we
// lost the target. Therefore, we should keep the traditional behavior,
// to dispatch it on the Document node.
if (!outEventTarget && deepestLeaveEventTarget) {
nsIFrame* const frame =
deepestLeaveEventTarget->GetPrimaryFrame(FlushType::Layout);
if (MOZ_UNLIKELY(mPresShell->IsDestroying())) {
return NS_OK;
}
if (frame) {
mPresShell->mCurrentEventTarget.mFrame = frame;
mPresShell->mCurrentEventTarget.mContent = deepestLeaveEventTarget;
}
}
}
}
// 2. Give event to the DOM for third party and JS use.
bool wasHandlingKeyBoardEvent = nsContentUtils::IsHandlingKeyBoardEvent();
if (aEvent->mClass == eKeyboardEventClass) {
nsContentUtils::SetIsHandlingKeyBoardEvent(true);
}
// If EventStateManager or something wants reply from remote process and
// needs to win any other event listeners in chrome, the event is both
// stopped its propagation and marked as "waiting reply from remote
// process". In this case, PresShell shouldn't dispatch the event into
// the DOM tree because they don't have a chance to stop propagation in
// the system event group. On the other hand, if its propagation is not
// stopped, that means that the event may be reserved by chrome. If it's
// reserved by chrome, the event shouldn't be sent to any remote
// processes. In this case, PresShell needs to dispatch the event to
// the DOM tree for checking if it's reserved.
if (aEvent->IsAllowedToDispatchDOMEvent() &&
!(aEvent->PropagationStopped() &&
aEvent->IsWaitingReplyFromRemoteProcess())) {
MOZ_ASSERT(nsContentUtils::IsSafeToRunScript(),
"Somebody changed aEvent to cause a DOM event!");
nsPresShellEventCB eventCB(mPresShell);
if (nsIFrame* target = mPresShell->GetCurrentEventFrame()) {
if (target->OnlySystemGroupDispatch(aEvent->mMessage)) {
aEvent->StopPropagation();
}
}
if (aEvent->mClass == eTouchEventClass) {
DispatchTouchEventToDOM(aEvent, aEventStatus, &eventCB, aTouchIsNew);
} else {
DispatchEventToDOM(aEvent, aEventStatus, &eventCB);
}
}
nsContentUtils::SetIsHandlingKeyBoardEvent(wasHandlingKeyBoardEvent);
if (mPresShell->IsDestroying()) {
return NS_OK;
}
// 3. Give event to event manager for post event state changes and
// generation of synthetic events.
// Refetch the prescontext, in case it changed.
RefPtr<nsPresContext> presContext = GetPresContext();
return aEventStateManager->PostHandleEvent(
presContext, aEvent, mPresShell->GetCurrentEventFrame(), aEventStatus,
aOverrideClickTarget);
}
bool PresShell::EventHandler::PrepareToDispatchEvent(
WidgetEvent* aEvent, nsEventStatus* aEventStatus, bool* aTouchIsNew) {
MOZ_ASSERT(aEvent->IsTrusted());
MOZ_ASSERT(aEventStatus);
MOZ_ASSERT(aTouchIsNew);
*aTouchIsNew = false;
if (aEvent->IsUserAction()) {
mPresShell->mHasHandledUserInput = true;
}
switch (aEvent->mMessage) {
case eKeyPress:
case eKeyDown:
case eKeyUp: {
WidgetKeyboardEvent* keyboardEvent = aEvent->AsKeyboardEvent();
MaybeHandleKeyboardEventBeforeDispatch(keyboardEvent);
return true;
}
case eMouseRawUpdate:
MOZ_ASSERT_UNREACHABLE(
"eMouseRawUpdate shouldn't be handled as a DOM event");
return false;
case eMouseMove: {
bool allowCapture = EventStateManager::GetActiveEventStateManager() &&
GetPresContext() &&
GetPresContext()->EventStateManager() ==
EventStateManager::GetActiveEventStateManager();
PresShell::AllowMouseCapture(allowCapture);
return true;
}
case eDrop: {
nsCOMPtr<nsIDragSession> session =
nsContentUtils::GetDragSession(GetPresContext());
if (session) {
bool onlyChromeDrop = false;
session->GetOnlyChromeDrop(&onlyChromeDrop);
if (onlyChromeDrop) {
aEvent->mFlags.mOnlyChromeDispatch = true;
}
}
return true;
}
case eDragExit: {
if (!StaticPrefs::dom_event_dragexit_enabled()) {
aEvent->mFlags.mOnlyChromeDispatch = true;
}
return true;
}
case eContextMenu: {
// If we cannot open context menu even though eContextMenu is fired, we
// should stop dispatching it into the DOM.
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
if (mouseEvent->IsContextMenuKeyEvent() &&
!AdjustContextMenuKeyEvent(mouseEvent)) {
return false;
}
// If "Shift" state is active, context menu should be forcibly opened even
// if web apps want to prevent it since we respect our users' intention.
// In this case, we don't fire "contextmenu" event on web content because
// of not cancelable.
if (mouseEvent->IsShift() &&
StaticPrefs::dom_event_contextmenu_shift_suppresses_event()) {
aEvent->mFlags.mOnlyChromeDispatch = true;
aEvent->mFlags.mRetargetToNonNativeAnonymous = true;
}
return true;
}
case eTouchStart:
case eTouchMove:
case eTouchEnd:
case eTouchCancel:
case eTouchPointerCancel:
return mPresShell->mTouchManager.PreHandleEvent(
aEvent, aEventStatus, *aTouchIsNew,
mPresShell->mCurrentEventTarget.mContent);
case eTouchRawUpdate:
MOZ_ASSERT_UNREACHABLE(
"eTouchRawUpdate shouldn't be handled as a DOM event");
return false;
default:
return true;
}
}
void PresShell::EventHandler::FinalizeHandlingEvent(
WidgetEvent* aEvent, const nsEventStatus* aStatus) {
switch (aEvent->mMessage) {
case eKeyPress:
case eKeyDown:
case eKeyUp: {
if (aEvent->AsKeyboardEvent()->mKeyCode == NS_VK_ESCAPE) {
if (aEvent->mMessage == eKeyUp) {
// Reset this flag after key up is handled.
mPresShell->mIsLastChromeOnlyEscapeKeyConsumed = false;
} else {
if (aEvent->mFlags.mOnlyChromeDispatch &&
aEvent->mFlags.mDefaultPreventedByChrome) {
mPresShell->mIsLastChromeOnlyEscapeKeyConsumed = true;
}
if (aEvent->mMessage == eKeyDown &&
!aEvent->mFlags.mDefaultPrevented) {
if (RefPtr<Document> doc = GetDocument()) {
if (StaticPrefs::dom_closewatcher_enabled()) {
doc->ProcessCloseRequest();
} else {
doc->HandleEscKey();
}
}
}
}
}
if (aEvent->mMessage == eKeyDown) {
mPresShell->mIsLastKeyDownCanceled = aEvent->mFlags.mDefaultPrevented;
}
break;
}
case eMouseUp:
// reset the capturing content now that the mouse button is up
PresShell::ReleaseCapturingContent();
break;
case eMouseRawUpdate:
MOZ_ASSERT_UNREACHABLE(
"eMouseRawUpdate shouldn't be handled as a DOM event");
break;
case eMouseMove:
PresShell::AllowMouseCapture(false);
break;
case eDrag:
case eDragEnd:
case eDragEnter:
case eDragExit:
case eDragLeave:
case eDragOver:
case eDrop: {
// After any drag event other than dragstart (which is handled
// separately, as we need to collect the data first), the DataTransfer
// needs to be made protected, and then disconnected.
DataTransfer* dataTransfer = aEvent->AsDragEvent()->mDataTransfer;
if (dataTransfer) {
dataTransfer->Disconnect();
}
break;
}
case eTouchStart:
case eTouchMove:
case eTouchEnd:
case eTouchCancel:
case eTouchPointerCancel:
case eMouseLongTap:
case eContextMenu: {
mPresShell->mTouchManager.PostHandleEvent(aEvent, aStatus);
break;
}
case eTouchRawUpdate:
MOZ_ASSERT_UNREACHABLE(
"eTouchRawUpdate shouldn't be handled as a DOM event");
break;
default:
break;
}
if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
if (mouseEvent->mSynthesizeMoveAfterDispatch) {
PointerEventHandler::SynthesizeMoveToDispatchBoundaryEvents(mouseEvent);
}
}
}
void PresShell::EventHandler::MaybeHandleKeyboardEventBeforeDispatch(
WidgetKeyboardEvent* aKeyboardEvent) {
MOZ_ASSERT(aKeyboardEvent);
if (aKeyboardEvent->mKeyCode != NS_VK_ESCAPE) {
return;
}
// If we're in fullscreen mode, exit from it forcibly when Escape key is
// pressed.
Document* doc = mPresShell->GetCurrentEventContent()
? mPresShell->mCurrentEventTarget.mContent->OwnerDoc()
: nullptr;
Document* root = nsContentUtils::GetInProcessSubtreeRootDocument(doc);
if (root && root->GetFullscreenElement()) {
// Prevent default action on ESC key press when exiting
// DOM fullscreen mode. This prevents the browser ESC key
// handler from stopping all loads in the document, which
// would cause <video> loads to stop.
// XXX We need to claim the Escape key event which will be
// dispatched only into chrome is already consumed by
// content because we need to prevent its default here
// for some reasons (not sure) but we need to detect
// if a chrome event handler will call PreventDefault()
// again and check it later.
aKeyboardEvent->PreventDefaultBeforeDispatch(CrossProcessForwarding::eStop);
aKeyboardEvent->mFlags.mOnlyChromeDispatch = true;
// The event listeners in chrome can prevent this ESC behavior by
// calling prevent default on the preceding keydown/press events.
if (aKeyboardEvent->mMessage == eKeyUp) {
bool shouldExitFullscreen =
!mPresShell->mIsLastChromeOnlyEscapeKeyConsumed;
if (!shouldExitFullscreen) {
if (mPresShell->mLastConsumedEscapeKeyUpForFullscreen &&
(aKeyboardEvent->mTimeStamp -
mPresShell->mLastConsumedEscapeKeyUpForFullscreen) <=
TimeDuration::FromMilliseconds(
StaticPrefs::
dom_fullscreen_force_exit_on_multiple_escape_interval())) {
shouldExitFullscreen = true;
mPresShell->mLastConsumedEscapeKeyUpForFullscreen = TimeStamp();
} else {
mPresShell->mLastConsumedEscapeKeyUpForFullscreen =
aKeyboardEvent->mTimeStamp;
}
}
if (shouldExitFullscreen) {
// ESC key released while in DOM fullscreen mode.
// Fully exit all browser windows and documents from
// fullscreen mode.
Document::AsyncExitFullscreen(nullptr);
}
}
}
if (XRE_IsParentProcess() &&
!mPresShell->mIsLastChromeOnlyEscapeKeyConsumed) {
if (PointerLockManager::GetLockedRemoteTarget() ||
PointerLockManager::IsLocked()) {
// XXX See above comment to understand the reason why this needs
// to claim that the Escape key event is consumed by content
// even though it will be dispatched only into chrome.
aKeyboardEvent->PreventDefaultBeforeDispatch(
CrossProcessForwarding::eStop);
aKeyboardEvent->mFlags.mOnlyChromeDispatch = true;
if (aKeyboardEvent->mMessage == eKeyUp) {
PointerLockManager::Unlock("EscapeKey");
}
}
}
}
void PresShell::EventHandler::RecordEventPreparationPerformance(
const WidgetEvent* aEvent) {
MOZ_ASSERT(aEvent);
switch (aEvent->mMessage) {
case eKeyPress:
case eKeyDown:
case eKeyUp:
if (aEvent->AsKeyboardEvent()->ShouldInteractionTimeRecorded()) {
GetPresContext()->RecordInteractionTime(
nsPresContext::InteractionType::KeyInteraction, aEvent->mTimeStamp);
}
glean::layout::input_event_queued_keyboard.AccumulateRawDuration(
TimeStamp::Now() - aEvent->mTimeStamp);
return;
case eMouseDown:
case eMouseUp:
glean::layout::input_event_queued_click.AccumulateRawDuration(
TimeStamp::Now() - aEvent->mTimeStamp);
[[fallthrough]];
case ePointerDown:
case ePointerUp:
GetPresContext()->RecordInteractionTime(
nsPresContext::InteractionType::ClickInteraction, aEvent->mTimeStamp);
return;
case eMouseRawUpdate:
MOZ_ASSERT_UNREACHABLE(
"eMouseRawUpdate shouldn't be handled as a DOM event");
break;
case eMouseMove:
GetPresContext()->RecordInteractionTime(
nsPresContext::InteractionType::MouseMoveInteraction,
aEvent->mTimeStamp);
return;
default:
return;
}
}
void PresShell::EventHandler::RecordEventHandlingResponsePerformance(
const WidgetEvent* aEvent) {
if (!Telemetry::CanRecordBase() || aEvent->mTimeStamp.IsNull() ||
aEvent->mTimeStamp <= mPresShell->mLastOSWake ||
!aEvent->AsInputEvent()) {
return;
}
TimeStamp now = TimeStamp::Now();
TimeDuration duration = now - aEvent->mTimeStamp;
glean::layout::input_event_response.AccumulateRawDuration(duration);
if (GetDocument() &&
GetDocument()->GetReadyStateEnum() != Document::READYSTATE_COMPLETE) {
glean::layout::load_input_event_response.AccumulateRawDuration(duration);
}
if (!sLastInputProcessed || sLastInputProcessed < aEvent->mTimeStamp) {
if (sLastInputProcessed) {
// This input event was created after we handled the last one.
// Accumulate the previous events' coalesced duration.
glean::layout::input_event_response_coalesced.AccumulateRawDuration(
sLastInputProcessed - sLastInputCreated);
if (MOZ_UNLIKELY(!PresShell::sProcessInteractable)) {
// For content process, we use the ready state of
// top-level-content-document to know if the process has finished the
// start-up.
// For parent process, see the topic
// 'sessionstore-one-or-no-tab-restored' in PresShell::Observe.
if (XRE_IsContentProcess() && GetDocument() &&
GetDocument()->IsTopLevelContentDocument()) {
switch (GetDocument()->GetReadyStateEnum()) {
case Document::READYSTATE_INTERACTIVE:
case Document::READYSTATE_COMPLETE:
PresShell::sProcessInteractable = true;
break;
default:
break;
}
}
}
}
sLastInputCreated = aEvent->mTimeStamp;
} else if (aEvent->mTimeStamp < sLastInputCreated) {
// This event was created before the last input. May be processing out
// of order, so coalesce backwards, too.
sLastInputCreated = aEvent->mTimeStamp;
}
sLastInputProcessed = now;
}
// static
nsIPrincipal*
PresShell::EventHandler::GetDocumentPrincipalToCompareWithBlacklist(
PresShell& aPresShell) {
nsPresContext* presContext = aPresShell.GetPresContext();
if (NS_WARN_IF(!presContext)) {
return nullptr;
}
return presContext->Document()->GetPrincipalForPrefBasedHacks();
}
nsresult PresShell::EventHandler::DispatchEventToDOM(
WidgetEvent* aEvent, nsEventStatus* aEventStatus,
nsPresShellEventCB* aEventCB) {
nsresult rv = NS_OK;
nsCOMPtr<nsINode> eventTarget = mPresShell->mCurrentEventTarget.mContent;
nsPresShellEventCB* eventCBPtr = aEventCB;
if (!eventTarget) {
nsCOMPtr<nsIContent> targetContent;
if (mPresShell->mCurrentEventTarget.mFrame) {
targetContent =
mPresShell->mCurrentEventTarget.mFrame->GetContentForEvent(aEvent);
if (targetContent && !targetContent->IsElement() &&
IsForbiddenDispatchingToNonElementContent(aEvent->mMessage)) {
targetContent =
targetContent->GetInclusiveFlattenedTreeAncestorElement();
}
}
if (targetContent) {
eventTarget = targetContent;
} else if (GetDocument()) {
eventTarget = GetDocument();
// If we don't have any content, the callback wouldn't probably
// do nothing.
eventCBPtr = nullptr;
}
}
if (eventTarget) {
if (eventTarget->OwnerDoc()->ShouldResistFingerprinting(
RFPTarget::WidgetEvents) &&
aEvent->IsBlockedForFingerprintingResistance()) {
aEvent->mFlags.mOnlySystemGroupDispatchInContent = true;
} else if (aEvent->mMessage == eKeyPress) {
// If eKeyPress event is marked as not dispatched in the default event
// group in web content, it's caused by non-printable key or key
// combination. In this case, UI Events declares that browsers
// shouldn't dispatch keypress event. However, some web apps may be
// broken with this strict behavior due to historical issue.
// Therefore, we need to keep dispatching keypress event for such keys
// even with breaking the standard.
// Similarly, the other browsers sets non-zero value of keyCode or
// charCode of keypress event to the other. Therefore, we should
// behave so, however, some web apps may be broken. On such web apps,
// we should keep using legacy our behavior.
if (!mPresShell->mInitializedWithKeyPressEventDispatchingBlacklist) {
mPresShell->mInitializedWithKeyPressEventDispatchingBlacklist = true;
nsCOMPtr<nsIPrincipal> principal =
GetDocumentPrincipalToCompareWithBlacklist(*mPresShell);
if (principal) {
mPresShell->mForceDispatchKeyPressEventsForNonPrintableKeys =
principal->IsURIInPrefList(
"dom.keyboardevent.keypress.hack.dispatch_non_printable_"
"keys") ||
principal->IsURIInPrefList(
"dom.keyboardevent.keypress.hack."
"dispatch_non_printable_keys.addl");
mPresShell->mForceUseLegacyKeyCodeAndCharCodeValues |=
principal->IsURIInPrefList(
"dom.keyboardevent.keypress.hack."
"use_legacy_keycode_and_charcode") ||
principal->IsURIInPrefList(
"dom.keyboardevent.keypress.hack."
"use_legacy_keycode_and_charcode.addl");
}
}
if (mPresShell->mForceDispatchKeyPressEventsForNonPrintableKeys) {
aEvent->mFlags.mOnlySystemGroupDispatchInContent = false;
}
if (mPresShell->mForceUseLegacyKeyCodeAndCharCodeValues) {
aEvent->AsKeyboardEvent()->mUseLegacyKeyCodeAndCharCodeValues = true;
}
}
if (aEvent->mClass == eCompositionEventClass) {
RefPtr<nsPresContext> presContext = GetPresContext();
RefPtr<BrowserParent> browserParent =
IMEStateManager::GetActiveBrowserParent();
IMEStateManager::DispatchCompositionEvent(
eventTarget, presContext, browserParent, aEvent->AsCompositionEvent(),
aEventStatus, eventCBPtr);
} else {
if (aEvent->IsMouseEventClassOrHasClickRelatedPointerEvent()) {
PointerEventHandler::RecordMouseButtons(*aEvent->AsMouseEvent());
#ifdef DEBUG
if (eventTarget->IsContent() && !eventTarget->IsElement()) {
NS_WARNING(nsPrintfCString(
"%s (IsReal()=%s) target is not an elemnet content "
"node, %s\n",
ToChar(aEvent->mMessage),
aEvent->AsMouseEvent()->IsReal() ? "true" : "false",
ToString(*eventTarget).c_str())
.get());
MOZ_CRASH("MouseEvent target must be an element");
}
#endif // #ifdef DEBUG
}
RefPtr<nsPresContext> presContext = GetPresContext();
EventDispatcher::Dispatch(eventTarget, presContext, aEvent, nullptr,
aEventStatus, eventCBPtr);
}
}
return rv;
}
void PresShell::EventHandler::DispatchTouchEventToDOM(
WidgetEvent* aEvent, nsEventStatus* aEventStatus,
nsPresShellEventCB* aEventCB, bool aTouchIsNew) {
MOZ_ASSERT(aEvent->mMessage != eTouchRawUpdate);
// calling preventDefault on touchstart or the first touchmove for a
// point prevents mouse events. calling it on the touchend should
// prevent click dispatching.
bool canPrevent = (aEvent->mMessage == eTouchStart) ||
(aEvent->mMessage == eTouchMove && aTouchIsNew) ||
(aEvent->mMessage == eTouchEnd);
bool preventDefault = false;
nsEventStatus tmpStatus = nsEventStatus_eIgnore;
WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent();
// loop over all touches and dispatch events on any that have changed
for (dom::Touch* touch : touchEvent->mTouches) {
// We should remove all suppressed touch instances in
// TouchManager::PreHandleEvent.
MOZ_ASSERT(!touch->mIsTouchEventSuppressed);
if (!touch || !touch->mChanged) {
continue;
}
nsCOMPtr<EventTarget> targetPtr = touch->mTarget;
nsCOMPtr<nsIContent> content = do_QueryInterface(targetPtr);
if (!content) {
continue;
}
Document* doc = content->OwnerDoc();
nsIContent* capturingContent = PresShell::GetCapturingContent();
if (capturingContent) {
if (capturingContent->OwnerDoc() != doc) {
// Wrong document, don't dispatch anything.
continue;
}
content = capturingContent;
}
// copy the event
MOZ_ASSERT(touchEvent->IsTrusted());
WidgetTouchEvent newEvent(true, touchEvent->mMessage, touchEvent->mWidget);
newEvent.AssignTouchEventData(*touchEvent, false);
newEvent.mTarget = targetPtr;
newEvent.mFlags.mHandledByAPZ = touchEvent->mFlags.mHandledByAPZ;
RefPtr<PresShell> contentPresShell;
if (doc == GetDocument()) {
contentPresShell = doc->GetPresShell();
if (contentPresShell) {
// XXXsmaug huge hack. Pushing possibly capturing content,
// even though event target is something else.
contentPresShell->PushCurrentEventInfo(EventTargetInfo(
newEvent.mMessage, content->GetPrimaryFrame(), content));
}
}
RefPtr<nsPresContext> presContext = doc->GetPresContext();
if (!presContext) {
if (contentPresShell) {
contentPresShell->PopCurrentEventInfo();
}
continue;
}
tmpStatus = nsEventStatus_eIgnore;
EventDispatcher::Dispatch(targetPtr, presContext, &newEvent, nullptr,
&tmpStatus, aEventCB);
if (nsEventStatus_eConsumeNoDefault == tmpStatus ||
newEvent.mFlags.mMultipleActionsPrevented) {
preventDefault = true;
}
if (newEvent.mFlags.mMultipleActionsPrevented) {
touchEvent->mFlags.mMultipleActionsPrevented = true;
}
if (contentPresShell) {
contentPresShell->PopCurrentEventInfo();
}
}
if (preventDefault && canPrevent) {
*aEventStatus = nsEventStatus_eConsumeNoDefault;
} else {
*aEventStatus = nsEventStatus_eIgnore;
}
}
// Dispatch event to content only (NOT full processing)
// See also HandleEventWithTarget which does full event processing.
nsresult PresShell::HandleDOMEventWithTarget(nsIContent* aTargetContent,
WidgetEvent* aEvent,
nsEventStatus* aStatus) {
nsresult rv = NS_OK;
PushCurrentEventInfo(
EventTargetInfo(aEvent->mMessage, nullptr, aTargetContent));
// Bug 41013: Check if the event should be dispatched to content.
// It's possible that we are in the middle of destroying the window
// and the js context is out of date. This check detects the case
// that caused a crash in bug 41013, but there may be a better way
// to handle this situation!
nsCOMPtr<nsISupports> container = mPresContext->GetContainerWeak();
if (container) {
// Dispatch event to content
rv = EventDispatcher::Dispatch(aTargetContent, mPresContext, aEvent,
nullptr, aStatus);
}
PopCurrentEventInfo();
return rv;
}
// See the method above.
nsresult PresShell::HandleDOMEventWithTarget(nsIContent* aTargetContent,
Event* aEvent,
nsEventStatus* aStatus) {
nsresult rv = NS_OK;
PushCurrentEventInfo(EventTargetInfo(aEvent->WidgetEventPtr()->mMessage,
nullptr, aTargetContent));
nsCOMPtr<nsISupports> container = mPresContext->GetContainerWeak();
if (container) {
rv = EventDispatcher::DispatchDOMEvent(aTargetContent, nullptr, aEvent,
mPresContext, aStatus);
}
PopCurrentEventInfo();
return rv;
}
bool PresShell::EventHandler::AdjustContextMenuKeyEvent(
WidgetMouseEvent* aMouseEvent) {
// if a menu is open, open the context menu relative to the active item on the
// menu.
if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
nsIFrame* popupFrame = pm->GetTopPopup(widget::PopupType::Menu);
if (popupFrame) {
nsIFrame* itemFrame = (static_cast<nsMenuPopupFrame*>(popupFrame))
->GetCurrentMenuItemFrame();
if (!itemFrame) {
itemFrame = popupFrame;
}
nsCOMPtr<nsIWidget> widget = popupFrame->GetNearestWidget();
aMouseEvent->mWidget = widget;
LayoutDeviceIntPoint widgetPoint = widget->WidgetToScreenOffset();
aMouseEvent->mRefPoint =
LayoutDeviceIntPoint::FromAppUnitsToNearest(
itemFrame->GetScreenRectInAppUnits().BottomLeft(),
itemFrame->PresContext()->AppUnitsPerDevPixel()) -
widgetPoint;
mPresShell->mCurrentEventTarget.SetFrameAndContent(
aMouseEvent->mMessage, itemFrame,
itemFrame->GetContent()
? itemFrame->GetContent()
->GetInclusiveFlattenedTreeAncestorElement()
: nullptr);
return true;
}
}
// If we're here because of the key-equiv for showing context menus, we
// have to twiddle with the NS event to make sure the context menu comes
// up in the upper left of the relevant content area before we create
// the DOM event. Since we never call InitMouseEvent() on the event,
// the client X/Y will be 0,0. We can make use of that if the widget is null.
// Use the root view manager's widget since it's most likely to have one,
// and the coordinates returned by GetCurrentItemAndPositionForElement
// are relative to the widget of the root of the root view manager.
nsRootPresContext* rootPC = GetPresContext()->GetRootPresContext();
aMouseEvent->mRefPoint = LayoutDeviceIntPoint(0, 0);
if (rootPC) {
aMouseEvent->mWidget =
rootPC->PresShell()->GetViewManager()->GetRootWidget();
if (aMouseEvent->mWidget) {
// default the refpoint to the topleft of our document
nsPoint offset(0, 0);
nsIFrame* rootFrame = FrameConstructor()->GetRootFrame();
if (rootFrame) {
nsView* view = rootFrame->GetClosestView(&offset);
offset += view->GetOffsetToWidget(aMouseEvent->mWidget);
aMouseEvent->mRefPoint = LayoutDeviceIntPoint::FromAppUnitsToNearest(
offset, GetPresContext()->AppUnitsPerDevPixel());
}
}
} else {
aMouseEvent->mWidget = nullptr;
}
// see if we should use the caret position for the popup
LayoutDeviceIntPoint caretPoint;
// Beware! This may flush notifications via synchronous
// ScrollSelectionIntoView.
if (PrepareToUseCaretPosition(MOZ_KnownLive(aMouseEvent->mWidget),
caretPoint)) {
// caret position is good
int32_t devPixelRatio = GetPresContext()->AppUnitsPerDevPixel();
caretPoint = LayoutDeviceIntPoint::FromAppUnitsToNearest(
ViewportUtils::LayoutToVisual(
LayoutDeviceIntPoint::ToAppUnits(caretPoint, devPixelRatio),
GetPresContext()->PresShell()),
devPixelRatio);
aMouseEvent->mRefPoint = caretPoint;
return true;
}
// If we're here because of the key-equiv for showing context menus, we
// have to reset the event target to the currently focused element. Get it
// from the focus controller.
RefPtr<Element> currentFocus = nsFocusManager::GetFocusedElementStatic();
// Reset event coordinates relative to focused frame in view
if (currentFocus) {
nsCOMPtr<nsIContent> currentPointElement;
GetCurrentItemAndPositionForElement(
currentFocus, getter_AddRefs(currentPointElement),
aMouseEvent->mRefPoint, MOZ_KnownLive(aMouseEvent->mWidget));
if (currentPointElement) {
mPresShell->mCurrentEventTarget.SetFrameAndContent(
aMouseEvent->mMessage, nullptr, currentPointElement);
mPresShell->GetCurrentEventFrame();
}
}
return true;
}
// PresShell::EventHandler::PrepareToUseCaretPosition
//
// This checks to see if we should use the caret position for popup context
// menus. Returns true if the caret position should be used, and the
// coordinates of that position is returned in aTargetPt. This function
// will also scroll the window as needed to make the caret visible.
//
// The event widget should be the widget that generated the event, and
// whose coordinate system the resulting event's mRefPoint should be
// relative to. The returned point is in device pixels realtive to the
// widget passed in.
bool PresShell::EventHandler::PrepareToUseCaretPosition(
nsIWidget* aEventWidget, LayoutDeviceIntPoint& aTargetPt) {
nsresult rv;
// check caret visibility
RefPtr<nsCaret> caret = mPresShell->GetCaret();
NS_ENSURE_TRUE(caret, false);
bool caretVisible = caret->IsVisible();
if (!caretVisible) {
return false;
}
// caret selection, this is a temporary weak reference, so no refcounting is
// needed
Selection* domSelection = caret->GetSelection();
NS_ENSURE_TRUE(domSelection, false);
// since the match could be an anonymous textnode inside a
// <textarea> or text <input>, we need to get the outer frame
// note: frames are not refcounted
nsIFrame* frame = nullptr; // may be nullptr
nsINode* node = domSelection->GetFocusNode();
NS_ENSURE_TRUE(node, false);
nsCOMPtr<nsIContent> content = nsIContent::FromNode(node);
if (content) {
nsIContent* nonNative = content->FindFirstNonChromeOnlyAccessContent();
content = nonNative;
}
if (content) {
// It seems like ScrollSelectionIntoView should be enough, but it's
// not. The problem is that scrolling the selection into view when it is
// below the current viewport will align the top line of the frame exactly
// with the bottom of the window. This is fine, BUT, the popup event causes
// the control to be re-focused which does this exact call to
// ScrollContentIntoView, which has a one-pixel disagreement of whether the
// frame is actually in view. The result is that the frame is aligned with
// the top of the window, but the menu is still at the bottom.
//
// Doing this call first forces the frame to be in view, eliminating the
// problem. The only difference in the result is that if your cursor is in
// an edit box below the current view, you'll get the edit box aligned with
// the top of the window. This is arguably better behavior anyway.
rv = MOZ_KnownLive(mPresShell)
->ScrollContentIntoView(
content,
ScrollAxis(WhereToScroll::Nearest, WhenToScroll::IfNotVisible),
ScrollAxis(WhereToScroll::Nearest, WhenToScroll::IfNotVisible),
ScrollFlags::ScrollOverflowHidden);
NS_ENSURE_SUCCESS(rv, false);
frame = content->GetPrimaryFrame();
NS_WARNING_ASSERTION(frame, "No frame for focused content?");
}
// Actually scroll the selection (ie caret) into view. Note that this must
// be synchronous since we will be checking the caret position on the screen.
//
// Be easy about errors, and just don't scroll in those cases. Better to have
// the correct menu at a weird place than the wrong menu.
// After ScrollSelectionIntoView(), the pending notifications might be
// flushed and PresShell/PresContext/Frames may be dead. See bug 418470.
nsCOMPtr<nsISelectionController> selCon;
if (frame) {
frame->GetSelectionController(GetPresContext(), getter_AddRefs(selCon));
} else {
selCon = static_cast<nsISelectionController*>(mPresShell);
}
if (selCon) {
rv = selCon->ScrollSelectionIntoView(
SelectionType::eNormal, nsISelectionController::SELECTION_FOCUS_REGION,
SelectionScrollMode::SyncFlush);
NS_ENSURE_SUCCESS(rv, false);
}
nsPresContext* presContext = GetPresContext();
// get caret position relative to the closest view
nsRect caretCoords;
nsIFrame* caretFrame = caret->GetGeometry(&caretCoords);
if (!caretFrame) {
return false;
}
nsPoint viewOffset;
nsView* view = caretFrame->GetClosestView(&viewOffset);
if (!view) {
return false;
}
// and then get the caret coords relative to the event widget
if (aEventWidget) {
viewOffset += view->GetOffsetToWidget(aEventWidget);
}
caretCoords.MoveBy(viewOffset);
// caret coordinates are in app units, convert to pixels
aTargetPt.x =
presContext->AppUnitsToDevPixels(caretCoords.x + caretCoords.width);
aTargetPt.y =
presContext->AppUnitsToDevPixels(caretCoords.y + caretCoords.height);
// make sure rounding doesn't return a pixel which is outside the caret
// (e.g. one line lower)
aTargetPt.y -= 1;
return true;
}
void PresShell::EventHandler::GetCurrentItemAndPositionForElement(
Element* aFocusedElement, nsIContent** aTargetToUse,
LayoutDeviceIntPoint& aTargetPt, nsIWidget* aRootWidget) {
nsCOMPtr<nsIContent> focusedContent = aFocusedElement;
MOZ_KnownLive(mPresShell)
->ScrollContentIntoView(focusedContent, ScrollAxis(), ScrollAxis(),
ScrollFlags::ScrollOverflowHidden);
nsPresContext* presContext = GetPresContext();
bool istree = false, checkLineHeight = true;
nscoord extraTreeY = 0;
// Set the position to just underneath the current item for multi-select
// lists or just underneath the selected item for single-select lists. If
// the element is not a list, or there is no selection, leave the position
// as is.
nsCOMPtr<Element> item;
nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelect =
aFocusedElement->AsXULMultiSelectControl();
if (multiSelect) {
checkLineHeight = false;
int32_t currentIndex;
multiSelect->GetCurrentIndex(¤tIndex);
if (currentIndex >= 0) {
RefPtr<XULTreeElement> tree = XULTreeElement::FromNode(focusedContent);
// Tree view special case (tree items have no frames)
// Get the focused row and add its coordinates, which are already in
// pixels
// XXX Boris, should we create a new interface so that this doesn't
// need to know about trees? Something like nsINodelessChildCreator
// which could provide the current focus coordinates?
if (tree) {
tree->EnsureRowIsVisible(currentIndex);
int32_t firstVisibleRow = tree->GetFirstVisibleRow();
int32_t rowHeight = tree->RowHeight();
extraTreeY += nsPresContext::CSSPixelsToAppUnits(
(currentIndex - firstVisibleRow + 1) * rowHeight);
istree = true;
RefPtr<nsTreeColumns> cols = tree->GetColumns();
if (cols) {
nsTreeColumn* col = cols->GetFirstColumn();
if (col) {
RefPtr<Element> colElement = col->Element();
nsIFrame* frame = colElement->GetPrimaryFrame();
if (frame) {
extraTreeY += frame->GetSize().height;
}
}
}
} else {
multiSelect->GetCurrentItem(getter_AddRefs(item));
}
}
} else {
// don't check menulists as the selected item will be inside a popup.
nsCOMPtr<nsIDOMXULMenuListElement> menulist =
aFocusedElement->AsXULMenuList();
if (!menulist) {
nsCOMPtr<nsIDOMXULSelectControlElement> select =
aFocusedElement->AsXULSelectControl();
if (select) {
checkLineHeight = false;
select->GetSelectedItem(getter_AddRefs(item));
}
}
}
if (item) {
focusedContent = item;
}
nsIFrame* frame = focusedContent->GetPrimaryFrame();
if (frame) {
NS_ASSERTION(
frame->PresContext() == GetPresContext(),
"handling event for focused content that is not in our document?");
nsPoint frameOrigin(0, 0);
// Get the frame's origin within its view
nsView* view = frame->GetClosestView(&frameOrigin);
NS_ASSERTION(view, "No view for frame");
// View's origin relative the widget
if (aRootWidget) {
frameOrigin += view->GetOffsetToWidget(aRootWidget);
}
// Start context menu down and to the right from top left of frame
// use the lineheight. This is a good distance to move the context
// menu away from the top left corner of the frame. If we always
// used the frame height, the context menu could end up far away,
// for example when we're focused on linked images.
// On the other hand, we want to use the frame height if it's less
// than the current line height, so that the context menu appears
// associated with the correct frame.
nscoord extra = 0;
if (!istree) {
extra = frame->GetSize().height;
if (checkLineHeight) {
ScrollContainerFrame* scrollContainerFrame =
nsLayoutUtils::GetNearestScrollContainerFrame(
frame, nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN |
nsLayoutUtils::SCROLLABLE_FIXEDPOS_FINDS_ROOT);
if (scrollContainerFrame) {
nsSize scrollAmount = scrollContainerFrame->GetLineScrollAmount();
int32_t APD = presContext->AppUnitsPerDevPixel();
int32_t scrollAPD =
scrollContainerFrame->PresContext()->AppUnitsPerDevPixel();
scrollAmount = scrollAmount.ScaleToOtherAppUnits(scrollAPD, APD);
if (extra > scrollAmount.height) {
extra = scrollAmount.height;
}
}
}
}
aTargetPt.x = presContext->AppUnitsToDevPixels(frameOrigin.x);
aTargetPt.y =
presContext->AppUnitsToDevPixels(frameOrigin.y + extra + extraTreeY);
}
NS_IF_ADDREF(*aTargetToUse = focusedContent);
}
bool PresShell::ShouldIgnoreInvalidation() {
return mPaintingSuppressed || !mIsActive || mIsNeverPainting;
}
void PresShell::WillPaint() {
// Check the simplest things first. In particular, it's important to
// check mIsActive before making any of the more expensive calls such
// as GetRootPresContext, for the case of a browser with a large
// number of tabs.
// Don't bother doing anything if some viewmanager in our tree is painting
// while we still have painting suppressed or we are not active.
if (!mIsActive || mPaintingSuppressed || !IsVisible()) {
return;
}
nsRootPresContext* rootPresContext = mPresContext->GetRootPresContext();
if (!rootPresContext) {
// In some edge cases, such as when we don't have a root frame yet,
// we can't find the root prescontext. There's nothing to do in that
// case.
return;
}
rootPresContext->FlushWillPaintObservers();
if (mIsDestroying) {
return;
}
// Process reflows, if we have them, to reduce flicker due to invalidates and
// reflow being interspersed. Note that we _do_ allow this to be
// interruptible; if we can't do all the reflows it's better to flicker a bit
// than to freeze up.
FlushPendingNotifications(ChangesToFlush(FlushType::InterruptibleLayout,
/* aFlushAnimations = */ false,
/* aUpdateRelevancy = */ false));
}
void PresShell::DidPaintWindow() {
nsRootPresContext* rootPresContext = mPresContext->GetRootPresContext();
if (rootPresContext != mPresContext) {
// This could be a popup's presshell. No point in notifying XPConnect
// about compositing of popups.
return;
}
if (!mHasReceivedPaintMessage) {
mHasReceivedPaintMessage = true;
nsCOMPtr<nsIObserverService> obsvc = services::GetObserverService();
if (obsvc && mDocument) {
nsPIDOMWindowOuter* window = mDocument->GetWindow();
if (window && nsGlobalWindowOuter::Cast(window)->IsChromeWindow()) {
obsvc->NotifyObservers(window, "widget-first-paint", nullptr);
}
}
}
}
bool PresShell::IsVisible() const {
if (!mIsActive || !mViewManager) {
return false;
}
nsView* view = mViewManager->GetRootView();
if (!view) {
return true;
}
// inner view of subdoc frame
view = view->GetParent();
if (!view) {
return true;
}
// subdoc view
view = view->GetParent();
if (!view) {
return true;
}
nsIFrame* frame = view->GetFrame();
if (!frame) {
return true;
}
return frame->IsVisibleConsideringAncestors(
nsIFrame::VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY);
}
void PresShell::SuppressDisplayport(bool aEnabled) {
if (aEnabled) {
mActiveSuppressDisplayport++;
} else if (mActiveSuppressDisplayport > 0) {
bool isSuppressed = IsDisplayportSuppressed();
mActiveSuppressDisplayport--;
if (isSuppressed && !IsDisplayportSuppressed()) {
// We unsuppressed the displayport, trigger a paint
if (nsIFrame* rootFrame = mFrameConstructor->GetRootFrame()) {
rootFrame->SchedulePaint();
}
}
}
}
static bool sDisplayPortSuppressionRespected = true;
void PresShell::RespectDisplayportSuppression(bool aEnabled) {
bool isSuppressed = IsDisplayportSuppressed();
sDisplayPortSuppressionRespected = aEnabled;
if (isSuppressed && !IsDisplayportSuppressed()) {
// We unsuppressed the displayport, trigger a paint
if (nsIFrame* rootFrame = mFrameConstructor->GetRootFrame()) {
rootFrame->SchedulePaint();
}
}
}
bool PresShell::IsDisplayportSuppressed() {
return sDisplayPortSuppressionRespected && mActiveSuppressDisplayport > 0;
}
static CallState FreezeSubDocument(Document& aDocument) {
if (PresShell* presShell = aDocument.GetPresShell()) {
presShell->Freeze();
}
return CallState::Continue;
}
void PresShell::Freeze(bool aIncludeSubDocuments) {
mUpdateApproximateFrameVisibilityEvent.Revoke();
MaybeReleaseCapturingContent();
if (mCaret) {
SetCaretEnabled(false);
}
mPaintingSuppressed = true;
if (aIncludeSubDocuments && mDocument) {
mDocument->EnumerateSubDocuments(FreezeSubDocument);
}
nsPresContext* presContext = GetPresContext();
if (presContext) {
presContext->DisableInteractionTimeRecording();
if (presContext->RefreshDriver()->GetPresContext() == presContext) {
presContext->RefreshDriver()->Freeze();
}
if (nsPresContext* rootPresContext = presContext->GetRootPresContext()) {
rootPresContext->ResetUserInputEventsAllowed();
}
}
mFrozen = true;
if (mDocument) {
UpdateImageLockingState();
}
}
void PresShell::FireOrClearDelayedEvents(bool aFireEvents) {
mNoDelayedMouseEvents = false;
mNoDelayedKeyEvents = false;
if (!aFireEvents) {
mDelayedEvents.Clear();
return;
}
if (mDocument) {
RefPtr<Document> doc = mDocument;
while (!mIsDestroying && mDelayedEvents.Length() &&
!doc->EventHandlingSuppressed()) {
UniquePtr<DelayedEvent> ev = std::move(mDelayedEvents[0]);
mDelayedEvents.RemoveElementAt(0);
if (ev->IsKeyPressEvent() && mIsLastKeyDownCanceled) {
continue;
}
ev->Dispatch();
}
if (!doc->EventHandlingSuppressed()) {
mDelayedEvents.Clear();
}
}
}
void PresShell::Thaw(bool aIncludeSubDocuments) {
nsPresContext* presContext = GetPresContext();
if (presContext &&
presContext->RefreshDriver()->GetPresContext() == presContext) {
presContext->RefreshDriver()->Thaw();
}
if (aIncludeSubDocuments && mDocument) {
mDocument->EnumerateSubDocuments([](Document& aSubDoc) {
if (PresShell* presShell = aSubDoc.GetPresShell()) {
presShell->Thaw();
}
return CallState::Continue;
});
}
// Get the activeness of our presshell, as this might have changed
// while we were in the bfcache
ActivenessMaybeChanged();
// We're now unfrozen
mFrozen = false;
UpdateImageLockingState();
UnsuppressPainting();
// In case the above UnsuppressPainting call didn't start the
// refresh driver, we manually start the refresh driver to
// ensure nsPresContext::MaybeIncreaseMeasuredTicksSinceLoading
// can be called for user input events handling.
if (presContext && presContext->IsRoot()) {
if (!presContext->RefreshDriver()->HasPendingTick()) {
presContext->RefreshDriver()->InitializeTimer();
}
}
}
//--------------------------------------------------------
// Start of protected and private methods on the PresShell
//--------------------------------------------------------
void PresShell::WillCauseReflow() {
nsContentUtils::AddScriptBlocker();
++mChangeNestCount;
}
void PresShell::DidCauseReflow() {
NS_ASSERTION(mChangeNestCount != 0, "Unexpected call to DidCauseReflow()");
--mChangeNestCount;
nsContentUtils::RemoveScriptBlocker();
}
void PresShell::WillDoReflow() {
mDocument->FlushUserFontSet();
mPresContext->FlushCounterStyles();
mPresContext->FlushFontFeatureValues();
mPresContext->FlushFontPaletteValues();
mLastReflowStart = GetPerformanceNowUnclamped();
}
void PresShell::DidDoReflow(bool aInterruptible) {
MOZ_ASSERT(mPendingDidDoReflow);
if (!nsContentUtils::IsSafeToRunScript()) {
// If we're reflowing while script-blocked (e.g. from container query
// updates), defer our reflow callbacks until the end of our next layout
// flush.
SetNeedLayoutFlush();
return;
}
auto clearPendingDidDoReflow =
MakeScopeExit([&] { mPendingDidDoReflow = false; });
mHiddenContentInForcedLayout.Clear();
HandlePostedReflowCallbacks(aInterruptible);
if (mIsDestroying) {
return;
}
{
nsAutoScriptBlocker scriptBlocker;
AutoAssertNoFlush noReentrantFlush(*this);
if (nsCOMPtr<nsIDocShell> docShell = mPresContext->GetDocShell()) {
DOMHighResTimeStamp now = GetPerformanceNowUnclamped();
docShell->NotifyReflowObservers(aInterruptible, mLastReflowStart, now);
}
if (StaticPrefs::layout_reflow_synthMouseMove()) {
SynthesizeMouseMove(false);
}
mPresContext->NotifyMissingFonts();
}
if (mIsDestroying) {
return;
}
if (mDirtyRoots.IsEmpty()) {
// We only unsuppress painting if we're out of reflows. It's pointless to
// do so if reflows are still pending, since reflows are just going to
// thrash the frames around some more. By waiting we avoid an overeager
// "jitter" effect.
if (mShouldUnsuppressPainting) {
mShouldUnsuppressPainting = false;
UnsuppressAndInvalidate();
}
} else {
// If any new reflow commands were enqueued during the reflow (or we didn't
// reflow everything because we were interrupted), schedule another reflow
// event to process them.
//
// Note that we want to do this after DidDoReflow(), since that method can
// change whether there are dirty roots around by flushing, and there's no
// point in posting a reflow event just to have the flush revoke it.
EnsureLayoutFlush();
}
}
DOMHighResTimeStamp PresShell::GetPerformanceNowUnclamped() {
DOMHighResTimeStamp now = 0;
if (nsPIDOMWindowInner* window = mDocument->GetInnerWindow()) {
Performance* perf = window->GetPerformance();
if (perf) {
now = perf->NowUnclamped();
}
}
return now;
}
bool PresShell::DoReflow(nsIFrame* target, bool aInterruptible,
OverflowChangedTracker* aOverflowTracker) {
[[maybe_unused]] nsIURI* uri = mDocument->GetDocumentURI();
AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING_RELEVANT_FOR_JS(
"Reflow", LAYOUT_Reflow, uri ? uri->GetSpecOrDefault() : "N/A"_ns);
PerfStats::AutoMetricRecording<PerfStats::Metric::Reflowing> autoRecording;
gfxTextPerfMetrics* tp = mPresContext->GetTextPerfMetrics();
TimeStamp timeStart;
if (tp) {
tp->Accumulate();
tp->reflowCount++;
timeStart = TimeStamp::Now();
}
// set up a cache that saves all nodes contained in each selection,
// allowing a fast lookup in `nsTextFrame::IsFrameSelected()`.
// This cache only lives throughout this reflow call.
SelectionNodeCache cache(*this);
// Schedule a paint, but don't actually mark this frame as changed for
// retained DL building purposes. If any child frames get moved, then
// they will schedule paint again. We could probaby skip this, and just
// schedule a similar paint when a frame is deleted.
target->SchedulePaint(nsIFrame::PAINT_DEFAULT, false);
Maybe<uint64_t> innerWindowID;
if (auto* window = mDocument->GetInnerWindow()) {
innerWindowID = Some(window->WindowID());
}
AutoProfilerTracing tracingLayoutFlush(
"Paint", aInterruptible ? "Reflow (interruptible)" : "Reflow (sync)",
geckoprofiler::category::LAYOUT, std::move(mReflowCause), innerWindowID);
mReflowCause = nullptr;
FlushPendingScrollAnchorSelections();
const bool isRoot = target == mFrameConstructor->GetRootFrame();
MOZ_ASSERT(isRoot || aOverflowTracker,
"caller must provide overflow tracker when reflowing "
"non-root frames");
// CreateReferenceRenderingContext can return nullptr
UniquePtr<gfxContext> rcx(CreateReferenceRenderingContext());
#ifdef DEBUG
mCurrentReflowRoot = target;
#endif
// If the target frame is the root of the frame hierarchy, then
// use all the available space. If it's simply a `reflow root',
// then use the target frame's size as the available space.
WritingMode wm = target->GetWritingMode();
LogicalSize size(wm);
if (isRoot) {
size = LogicalSize(wm, mPresContext->GetVisibleArea().Size());
} else {
size = target->GetLogicalSize();
}
OverflowAreas oldOverflow; // initialized and used only when !isRoot
if (!isRoot) {
oldOverflow = target->GetOverflowAreas();
}
NS_ASSERTION(!target->GetNextInFlow() && !target->GetPrevInFlow(),
"reflow roots should never split");
// Don't pass size directly to the reflow input, since a
// constrained height implies page/column breaking.
LogicalSize reflowSize(wm, size.ISize(wm), NS_UNCONSTRAINEDSIZE);
ReflowInput reflowInput(mPresContext, target, rcx.get(), reflowSize,
ReflowInput::InitFlag::CallerWillInit);
if (isRoot) {
reflowInput.Init(mPresContext);
} else {
// Initialize reflow input with current used border and padding,
// in case this was set specially by the parent frame when the reflow root
// was reflowed by its parent.
reflowInput.Init(mPresContext, Nothing(),
Some(target->GetLogicalUsedBorder(wm)),
Some(target->GetLogicalUsedPadding(wm)));
}
// fix the computed height
NS_ASSERTION(reflowInput.ComputedPhysicalMargin() == nsMargin(0, 0, 0, 0),
"reflow input should not set margin for reflow roots");
if (size.BSize(wm) != NS_UNCONSTRAINEDSIZE) {
nscoord computedBSize =
size.BSize(wm) -
reflowInput.ComputedLogicalBorderPadding(wm).BStartEnd(wm);
computedBSize = std::max(computedBSize, 0);
reflowInput.SetComputedBSize(computedBSize);
}
NS_ASSERTION(
reflowInput.ComputedISize() ==
size.ISize(wm) -
reflowInput.ComputedLogicalBorderPadding(wm).IStartEnd(wm),
"reflow input computed incorrect inline size");
mPresContext->ReflowStarted(aInterruptible);
mIsReflowing = true;
nsReflowStatus status;
ReflowOutput desiredSize(reflowInput);
target->Reflow(mPresContext, desiredSize, reflowInput, status);
// If an incremental reflow is initiated at a frame other than the
// root frame, then its desired size had better not change! If it's
// initiated at the root, then the size better not change unless its
// height was unconstrained to start with.
nsRect boundsRelativeToTarget =
nsRect(0, 0, desiredSize.Width(), desiredSize.Height());
const bool isBSizeLimitReflow =
isRoot && size.BSize(wm) == NS_UNCONSTRAINEDSIZE;
NS_ASSERTION(isBSizeLimitReflow || desiredSize.Size(wm) == size,
"non-root frame's desired size changed during an "
"incremental reflow");
NS_ASSERTION(status.IsEmpty(), "reflow roots should never split");
target->SetSize(boundsRelativeToTarget.Size());
// Always use boundsRelativeToTarget here, not desiredSize.InkOverflowRect(),
// because for root frames (where they could be different, since root frames
// are allowed to have overflow) the root view bounds need to match the
// viewport bounds; the view manager "window dimensions" code depends on it.
if (target->HasView()) {
nsContainerFrame::SyncFrameViewAfterReflow(
mPresContext, target, target->GetView(), boundsRelativeToTarget);
}
target->DidReflow(mPresContext, nullptr);
if (target->IsInScrollAnchorChain()) {
ScrollAnchorContainer* container = ScrollAnchorContainer::FindFor(target);
PostPendingScrollAnchorAdjustment(container);
}
if (MOZ_UNLIKELY(isBSizeLimitReflow)) {
mPresContext->SetVisibleArea(boundsRelativeToTarget);
}
#ifdef DEBUG
mCurrentReflowRoot = nullptr;
#endif
if (!isRoot && oldOverflow != target->GetOverflowAreas()) {
// The overflow area changed. Propagate this change to ancestors.
aOverflowTracker->AddFrame(target->GetParent(),
OverflowChangedTracker::CHILDREN_CHANGED);
}
NS_ASSERTION(
mPresContext->HasPendingInterrupt() || mFramesToDirty.Count() == 0,
"Why do we need to dirty anything if not interrupted?");
mIsReflowing = false;
bool interrupted = mPresContext->HasPendingInterrupt();
if (interrupted) {
// Make sure target gets reflowed again.
for (const auto& key : mFramesToDirty) {
// Mark frames dirty until target frame.
for (nsIFrame* f = key; f && !f->IsSubtreeDirty(); f = f->GetParent()) {
f->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
if (f->IsFlexItem()) {
nsFlexContainerFrame::MarkCachedFlexMeasurementsDirty(f);
}
if (f == target) {
break;
}
}
}
NS_ASSERTION(target->IsSubtreeDirty(), "Why is the target not dirty?");
mDirtyRoots.Add(target);
SetNeedLayoutFlush();
// Clear mFramesToDirty after we've done the target->IsSubtreeDirty()
// assertion so that if it fails it's easier to see what's going on.
#ifdef NOISY_INTERRUPTIBLE_REFLOW
printf("mFramesToDirty.Count() == %u\n", mFramesToDirty.Count());
#endif /* NOISY_INTERRUPTIBLE_REFLOW */
mFramesToDirty.Clear();
// Any FlushPendingNotifications with interruptible reflows
// should be suppressed now. We don't want to do extra reflow work
// before our reflow event happens.
mWasLastReflowInterrupted = true;
EnsureLayoutFlush();
}
// dump text perf metrics for reflows with significant text processing
if (tp) {
if (tp->current.numChars > 100) {
TimeDuration reflowTime = TimeStamp::Now() - timeStart;
LogTextPerfStats(tp, this, tp->current, reflowTime.ToMilliseconds(),
eLog_reflow, nullptr);
}
tp->Accumulate();
}
return !interrupted;
}
#ifdef DEBUG
void PresShell::DoVerifyReflow() {
if (GetVerifyReflowEnable()) {
// First synchronously render what we have so far so that we can
// see it.
nsView* rootView = mViewManager->GetRootView();
mViewManager->InvalidateView(rootView);
FlushPendingNotifications(FlushType::Layout);
mInVerifyReflow = true;
bool ok = VerifyIncrementalReflow();
mInVerifyReflow = false;
if (VerifyReflowFlags::All & gVerifyReflowFlags) {
printf("ProcessReflowCommands: finished (%s)\n", ok ? "ok" : "failed");
}
if (!mDirtyRoots.IsEmpty()) {
printf("XXX yikes! reflow commands queued during verify-reflow\n");
}
}
}
#endif
// used with Telemetry metrics
#define NS_LONG_REFLOW_TIME_MS 5000
bool PresShell::ProcessReflowCommands(bool aInterruptible) {
if (mDirtyRoots.IsEmpty() && !mShouldUnsuppressPainting &&
!mPendingDidDoReflow) {
// Nothing to do; bail out
return true;
}
const bool wasProcessingReflowCommands = mProcessingReflowCommands;
auto restoreProcessingReflowCommands = MakeScopeExit(
[&] { mProcessingReflowCommands = wasProcessingReflowCommands; });
mProcessingReflowCommands = true;
auto timerStart = mozilla::TimeStamp::Now();
bool interrupted = false;
if (!mDirtyRoots.IsEmpty()) {
#ifdef DEBUG
if (VerifyReflowFlags::DumpCommands & gVerifyReflowFlags) {
printf("ProcessReflowCommands: begin incremental reflow\n");
}
#endif
// If reflow is interruptible, then make a note of our deadline.
const PRIntervalTime deadline =
aInterruptible
? PR_IntervalNow() + PR_MicrosecondsToInterval(gMaxRCProcessingTime)
: (PRIntervalTime)0;
// Scope for the reflow entry point
nsAutoScriptBlocker scriptBlocker;
WillDoReflow();
AUTO_LAYOUT_PHASE_ENTRY_POINT(GetPresContext(), Reflow);
nsViewManager::AutoDisableRefresh refreshBlocker(mViewManager);
OverflowChangedTracker overflowTracker;
do {
// Send an incremental reflow notification to the target frame.
nsIFrame* target = mDirtyRoots.PopShallowestRoot();
if (!target->IsSubtreeDirty()) {
// It's not dirty anymore, which probably means the notification
// was posted in the middle of a reflow (perhaps with a reflow
// root in the middle). Don't do anything.
continue;
}
interrupted = !DoReflow(target, aInterruptible, &overflowTracker);
// Keep going until we're out of reflow commands, or we've run
// past our deadline, or we're interrupted.
} while (!interrupted && !mDirtyRoots.IsEmpty() &&
(!aInterruptible || PR_IntervalNow() < deadline));
interrupted = !mDirtyRoots.IsEmpty();
overflowTracker.Flush();
if (!interrupted) {
// We didn't get interrupted. Go ahead and perform scroll anchor
// adjustments.
FlushPendingScrollAnchorAdjustments();
}
mPendingDidDoReflow = true;
}
// Exiting the scriptblocker might have killed us. If we were processing
// scroll commands, let the outermost call deal with it.
if (!mIsDestroying && mPendingDidDoReflow && !wasProcessingReflowCommands) {
DidDoReflow(aInterruptible);
}
#ifdef DEBUG
if (VerifyReflowFlags::DumpCommands & gVerifyReflowFlags) {
printf("\nPresShell::ProcessReflowCommands() finished: this=%p\n",
(void*)this);
}
DoVerifyReflow();
#endif
{
TimeDuration elapsed = TimeStamp::Now() - timerStart;
int32_t intElapsed = int32_t(elapsed.ToMilliseconds());
if (intElapsed > NS_LONG_REFLOW_TIME_MS) {
glean::layout::long_reflow_interruptible
.EnumGet(aInterruptible
? glean::layout::LongReflowInterruptibleLabel::eTrue
: glean::layout::LongReflowInterruptibleLabel::eFalse)
.Add();
}
}
return !interrupted;
}
bool PresShell::DoFlushLayout(bool aInterruptible) {
mFrameConstructor->RecalcQuotesAndCounters();
return ProcessReflowCommands(aInterruptible);
}
void PresShell::WindowSizeMoveDone() {
if (mPresContext) {
EventStateManager::ClearGlobalActiveContent(nullptr);
ClearMouseCapture();
}
}
NS_IMETHODIMP
PresShell::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
if (mIsDestroying) {
NS_WARNING("our observers should have been unregistered by now");
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, "memory-pressure")) {
if (!AssumeAllFramesVisible() &&
mPresContext->IsRootContentDocumentInProcess()) {
DoUpdateApproximateFrameVisibility(/* aRemoveOnly = */ true);
}
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, NS_WIDGET_WAKE_OBSERVER_TOPIC)) {
mLastOSWake = TimeStamp::Now();
return NS_OK;
}
// For parent process, user may expect the UI is interactable after a
// tab (previously opened page or home page) has restored.
if (!nsCRT::strcmp(aTopic, "sessionstore-one-or-no-tab-restored")) {
MOZ_ASSERT(XRE_IsParentProcess());
sProcessInteractable = true;
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
os->RemoveObserver(this, "sessionstore-one-or-no-tab-restored");
}
return NS_OK;
}
if (!nsCRT::strcmp(aTopic, "font-info-updated")) {
// See how gfxPlatform::ForceGlobalReflow encodes this.
bool needsReframe = aData && !!aData[0];
mPresContext->ForceReflowForFontInfoUpdate(needsReframe);
return NS_OK;
}
// The "look-and-feel-changed" notification for JS observers will be
// dispatched HandleGlobalThemeChange once LookAndFeel caches are cleared.
if (!nsCRT::strcmp(aTopic, "internal-look-and-feel-changed")) {
// See how LookAndFeel::NotifyChangedAllWindows encodes this.
auto kind = widget::ThemeChangeKind(aData[0]);
mPresContext->ThemeChanged(kind);
return NS_OK;
}
NS_WARNING("unrecognized topic in PresShell::Observe");
return NS_ERROR_FAILURE;
}
bool PresShell::AddRefreshObserver(nsARefreshObserver* aObserver,
FlushType aFlushType,
const char* aObserverDescription) {
nsPresContext* presContext = GetPresContext();
if (MOZ_UNLIKELY(!presContext)) {
return false;
}
presContext->RefreshDriver()->AddRefreshObserver(aObserver, aFlushType,
aObserverDescription);
return true;
}
bool PresShell::RemoveRefreshObserver(nsARefreshObserver* aObserver,
FlushType aFlushType) {
nsPresContext* presContext = GetPresContext();
return presContext && presContext->RefreshDriver()->RemoveRefreshObserver(
aObserver, aFlushType);
}
bool PresShell::AddPostRefreshObserver(nsAPostRefreshObserver* aObserver) {
nsPresContext* presContext = GetPresContext();
if (!presContext) {
return false;
}
presContext->RefreshDriver()->AddPostRefreshObserver(aObserver);
return true;
}
bool PresShell::RemovePostRefreshObserver(nsAPostRefreshObserver* aObserver) {
nsPresContext* presContext = GetPresContext();
if (!presContext) {
return false;
}
presContext->RefreshDriver()->RemovePostRefreshObserver(aObserver);
return true;
}
void PresShell::ScheduleFlush() {
if (MOZ_UNLIKELY(IsDestroying()) ||
MOZ_UNLIKELY(mDocument->GetBFCacheEntry())) {
return;
}
mPresContext->RefreshDriver()->ScheduleRenderingPhase(RenderingPhase::Layout);
}
//------------------------------------------------------
// End of protected and private methods on the PresShell
//------------------------------------------------------
//------------------------------------------------------------------
//-- Delayed event Classes Impls
//------------------------------------------------------------------
PresShell::DelayedInputEvent::DelayedInputEvent()
: DelayedEvent(), mEvent(nullptr) {}
PresShell::DelayedInputEvent::~DelayedInputEvent() { delete mEvent; }
void PresShell::DelayedInputEvent::Dispatch() {
if (!mEvent || !mEvent->mWidget) {
return;
}
nsCOMPtr<nsIWidget> widget = mEvent->mWidget;
nsEventStatus status;
widget->DispatchEvent(mEvent, status);
}
PresShell::DelayedMouseEvent::DelayedMouseEvent(WidgetMouseEvent* aEvent) {
MOZ_DIAGNOSTIC_ASSERT(aEvent->IsTrusted());
WidgetMouseEvent* mouseEvent =
new WidgetMouseEvent(true, aEvent->mMessage, aEvent->mWidget,
aEvent->mReason, aEvent->mContextMenuTrigger);
mouseEvent->AssignMouseEventData(*aEvent, false);
mEvent = mouseEvent;
}
PresShell::DelayedPointerEvent::DelayedPointerEvent(
WidgetPointerEvent* aEvent) {
MOZ_DIAGNOSTIC_ASSERT(aEvent->IsTrusted());
MOZ_ASSERT(aEvent->mMessage == eContextMenu);
WidgetPointerEvent* pointerEvent = new WidgetPointerEvent(
true, aEvent->mMessage, aEvent->mWidget, aEvent->mContextMenuTrigger);
pointerEvent->AssignPointerEventData(*aEvent, false);
mEvent = pointerEvent;
}
PresShell::DelayedKeyEvent::DelayedKeyEvent(WidgetKeyboardEvent* aEvent) {
MOZ_DIAGNOSTIC_ASSERT(aEvent->IsTrusted());
WidgetKeyboardEvent* keyEvent =
new WidgetKeyboardEvent(true, aEvent->mMessage, aEvent->mWidget);
keyEvent->AssignKeyEventData(*aEvent, false);
keyEvent->mFlags.mIsSynthesizedForTests =
aEvent->mFlags.mIsSynthesizedForTests;
keyEvent->mFlags.mIsSuppressedOrDelayed = true;
mEvent = keyEvent;
}
bool PresShell::DelayedKeyEvent::IsKeyPressEvent() {
return mEvent->mMessage == eKeyPress;
}
// Start of DEBUG only code
#ifdef DEBUG
static void LogVerifyMessage(nsIFrame* k1, nsIFrame* k2, const char* aMsg) {
nsAutoString n1, n2;
if (k1) {
k1->GetFrameName(n1);
} else {
n1.AssignLiteral(u"(null)");
}
if (k2) {
k2->GetFrameName(n2);
} else {
n2.AssignLiteral(u"(null)");
}
printf("verifyreflow: %s %p != %s %p %s\n",
NS_LossyConvertUTF16toASCII(n1).get(), (void*)k1,
NS_LossyConvertUTF16toASCII(n2).get(), (void*)k2, aMsg);
}
static void LogVerifyMessage(nsIFrame* k1, nsIFrame* k2, const char* aMsg,
const nsRect& r1, const nsRect& r2) {
printf("VerifyReflow Error:\n");
nsAutoString name;
if (k1) {
k1->GetFrameName(name);
printf(" %s %p ", NS_LossyConvertUTF16toASCII(name).get(), (void*)k1);
}
printf("{%d, %d, %d, %d} != \n", r1.x, r1.y, r1.width, r1.height);
if (k2) {
k2->GetFrameName(name);
printf(" %s %p ", NS_LossyConvertUTF16toASCII(name).get(), (void*)k2);
}
printf("{%d, %d, %d, %d}\n %s\n", r2.x, r2.y, r2.width, r2.height, aMsg);
}
static void LogVerifyMessage(nsIFrame* k1, nsIFrame* k2, const char* aMsg,
const nsIntRect& r1, const nsIntRect& r2) {
printf("VerifyReflow Error:\n");
nsAutoString name;
if (k1) {
k1->GetFrameName(name);
printf(" %s %p ", NS_LossyConvertUTF16toASCII(name).get(), (void*)k1);
}
printf("{%d, %d, %d, %d} != \n", r1.x, r1.y, r1.width, r1.height);
if (k2) {
k2->GetFrameName(name);
printf(" %s %p ", NS_LossyConvertUTF16toASCII(name).get(), (void*)k2);
}
printf("{%d, %d, %d, %d}\n %s\n", r2.x, r2.y, r2.width, r2.height, aMsg);
}
static bool CompareTrees(nsPresContext* aFirstPresContext,
nsIFrame* aFirstFrame,
nsPresContext* aSecondPresContext,
nsIFrame* aSecondFrame) {
if (!aFirstPresContext || !aFirstFrame || !aSecondPresContext ||
!aSecondFrame)
return true;
// XXX Evil hack to reduce false positives; I can't seem to figure
// out how to flush scrollbar changes correctly
// if (aFirstFrame->IsScrollbarFrame())
// return true;
bool ok = true;
const auto& childLists1 = aFirstFrame->ChildLists();
const auto& childLists2 = aSecondFrame->ChildLists();
auto iterLists1 = childLists1.begin();
auto iterLists2 = childLists2.begin();
do {
const nsFrameList& kids1 = iterLists1 != childLists1.end()
? iterLists1->mList
: nsFrameList::EmptyList();
const nsFrameList& kids2 = iterLists2 != childLists2.end()
? iterLists2->mList
: nsFrameList::EmptyList();
int32_t l1 = kids1.GetLength();
int32_t l2 = kids2.GetLength();
if (l1 != l2) {
ok = false;
LogVerifyMessage(kids1.FirstChild(), kids2.FirstChild(),
"child counts don't match: ");
printf("%d != %d\n", l1, l2);
if (!(VerifyReflowFlags::All & gVerifyReflowFlags)) {
break;
}
}
LayoutDeviceIntRect r1, r2;
nsView* v1;
nsView* v2;
for (auto kids1Iter = kids1.begin(), kids2Iter = kids2.begin();;
++kids1Iter, ++kids2Iter) {
nsIFrame* k1 = *kids1Iter;
nsIFrame* k2 = *kids2Iter;
if (((nullptr == k1) && (nullptr != k2)) ||
((nullptr != k1) && (nullptr == k2))) {
ok = false;
LogVerifyMessage(k1, k2, "child lists are different\n");
break;
} else if (nullptr != k1) {
// Verify that the frames are the same size
if (!k1->GetRect().IsEqualInterior(k2->GetRect())) {
ok = false;
LogVerifyMessage(k1, k2, "(frame rects)", k1->GetRect(),
k2->GetRect());
}
// Make sure either both have views or neither have views; if they
// do have views, make sure the views are the same size. If the
// views have widgets, make sure they both do or neither does. If
// they do, make sure the widgets are the same size.
v1 = k1->GetView();
v2 = k2->GetView();
if (((nullptr == v1) && (nullptr != v2)) ||
((nullptr != v1) && (nullptr == v2))) {
ok = false;
LogVerifyMessage(k1, k2, "child views are not matched\n");
} else if (nullptr != v1) {
if (!v1->GetBounds().IsEqualInterior(v2->GetBounds())) {
LogVerifyMessage(k1, k2, "(view rects)", v1->GetBounds(),
v2->GetBounds());
}
nsIWidget* w1 = v1->GetWidget();
nsIWidget* w2 = v2->GetWidget();
if (((nullptr == w1) && (nullptr != w2)) ||
((nullptr != w1) && (nullptr == w2))) {
ok = false;
LogVerifyMessage(k1, k2, "child widgets are not matched\n");
} else if (nullptr != w1) {
r1 = w1->GetBounds();
r2 = w2->GetBounds();
if (!r1.IsEqualEdges(r2)) {
LogVerifyMessage(k1, k2, "(widget rects)", r1.ToUnknownRect(),
r2.ToUnknownRect());
}
}
}
if (!ok && !(VerifyReflowFlags::All & gVerifyReflowFlags)) {
break;
}
// XXX Should perhaps compare their float managers.
// Compare the sub-trees too
if (!CompareTrees(aFirstPresContext, k1, aSecondPresContext, k2)) {
ok = false;
if (!(VerifyReflowFlags::All & gVerifyReflowFlags)) {
break;
}
}
} else {
break;
}
}
if (!ok && (!(VerifyReflowFlags::All & gVerifyReflowFlags))) {
break;
}
++iterLists1;
++iterLists2;
const bool lists1Done = iterLists1 == childLists1.end();
const bool lists2Done = iterLists2 == childLists2.end();
if (lists1Done != lists2Done ||
(!lists1Done && iterLists1->mID != iterLists2->mID)) {
if (!(VerifyReflowFlags::All & gVerifyReflowFlags)) {
ok = false;
}
LogVerifyMessage(kids1.FirstChild(), kids2.FirstChild(),
"child list names are not matched: ");
fprintf(stdout, "%s != %s\n",
!lists1Done ? ChildListName(iterLists1->mID) : "(null)",
!lists2Done ? ChildListName(iterLists2->mID) : "(null)");
break;
}
} while (ok && iterLists1 != childLists1.end());
return ok;
}
#endif
#if 0
static nsIFrame*
FindTopFrame(nsIFrame* aRoot)
{
if (aRoot) {
nsIContent* content = aRoot->GetContent();
if (content) {
nsAtom* tag;
content->GetTag(tag);
if (nullptr != tag) {
NS_RELEASE(tag);
return aRoot;
}
}
// Try one of the children
for (nsIFrame* kid : aRoot->PrincipalChildList()) {
nsIFrame* result = FindTopFrame(kid);
if (nullptr != result) {
return result;
}
}
}
return nullptr;
}
#endif
#ifdef DEBUG
// After an incremental reflow, we verify the correctness by doing a
// full reflow into a fresh frame tree.
bool PresShell::VerifyIncrementalReflow() {
if (VerifyReflowFlags::Noisy & gVerifyReflowFlags) {
printf("Building Verification Tree...\n");
}
// Create a presentation context to view the new frame tree
auto cx = MakeRefPtr<nsRootPresContext>(
mDocument, mPresContext->IsPaginated()
? nsPresContext::eContext_PrintPreview
: nsPresContext::eContext_Galley);
nsDeviceContext* dc = mPresContext->DeviceContext();
nsresult rv = cx->Init(dc);
NS_ENSURE_SUCCESS(rv, false);
// Get our scrolling preference
nsView* rootView = mViewManager->GetRootView();
NS_ENSURE_TRUE(rootView->HasWidget(), false);
nsIWidget* parentWidget = rootView->GetWidget();
// Create a new view manager.
auto vm = MakeRefPtr<nsViewManager>();
rv = vm->Init(dc);
NS_ENSURE_SUCCESS(rv, false);
// Create a child window of the parent that is our "root view/window"
// Create a view
nsRect tbounds = mPresContext->GetVisibleArea();
nsView* view = vm->CreateView(tbounds, nullptr);
NS_ENSURE_TRUE(view, false);
// now create the widget for the view
rv = view->CreateWidget(parentWidget, true);
NS_ENSURE_SUCCESS(rv, false);
// Setup hierarchical relationship in view manager
vm->SetRootView(view);
// Make the new presentation context the same size as our
// presentation context.
cx->SetVisibleArea(mPresContext->GetVisibleArea());
RefPtr<PresShell> presShell = mDocument->CreatePresShell(cx, vm);
NS_ENSURE_TRUE(presShell, false);
// Note that after we create the shell, we must make sure to destroy it
presShell->SetVerifyReflowEnable(
false); // turn off verify reflow while we're
// reflowing the test frame tree
vm->SetPresShell(presShell);
{
nsAutoCauseReflowNotifier crNotifier(this);
presShell->Initialize();
}
presShell->FlushPendingNotifications(FlushType::Layout);
presShell->SetVerifyReflowEnable(
true); // turn on verify reflow again now that
// we're done reflowing the test frame tree
// Force the non-primary presshell to unsuppress; it doesn't want to normally
// because it thinks it's hidden
presShell->mPaintingSuppressed = false;
if (VerifyReflowFlags::Noisy & gVerifyReflowFlags) {
printf("Verification Tree built, comparing...\n");
}
// Now that the document has been reflowed, use its frame tree to
// compare against our frame tree.
nsIFrame* root1 = mFrameConstructor->GetRootFrame();
nsIFrame* root2 = presShell->GetRootFrame();
bool ok = CompareTrees(mPresContext, root1, cx, root2);
if (!ok && (VerifyReflowFlags::Noisy & gVerifyReflowFlags)) {
printf("Verify reflow failed, primary tree:\n");
root1->List(stdout);
printf("Verification tree:\n");
root2->List(stdout);
}
# if 0
// Sample code for dumping page to png
// XXX Needs to be made more flexible
if (!ok) {
nsString stra;
static int num = 0;
stra.AppendLiteral("C:\\mozilla\\mozilla\\debug\\filea");
stra.AppendInt(num);
stra.AppendLiteral(".png");
gfxUtils::WriteAsPNG(presShell, stra);
nsString strb;
strb.AppendLiteral("C:\\mozilla\\mozilla\\debug\\fileb");
strb.AppendInt(num);
strb.AppendLiteral(".png");
gfxUtils::WriteAsPNG(presShell, strb);
++num;
}
# endif
presShell->EndObservingDocument();
presShell->Destroy();
if (VerifyReflowFlags::Noisy & gVerifyReflowFlags) {
printf("Finished Verifying Reflow...\n");
}
return ok;
}
// Layout debugging hooks
void PresShell::ListComputedStyles(FILE* out, int32_t aIndent) {
nsIFrame* rootFrame = GetRootFrame();
if (rootFrame) {
rootFrame->Style()->List(out, aIndent);
}
// The root element's frame's ComputedStyle is the root of a separate tree.
Element* rootElement = mDocument->GetRootElement();
if (rootElement) {
nsIFrame* rootElementFrame = rootElement->GetPrimaryFrame();
if (rootElementFrame) {
rootElementFrame->Style()->List(out, aIndent);
}
}
}
#endif
#if defined(DEBUG) || defined(MOZ_LAYOUT_DEBUGGER)
void PresShell::ListStyleSheets(FILE* out, int32_t aIndent) {
auto ListStyleSheetsAtOrigin = [this, out, aIndent](StyleOrigin origin) {
int32_t sheetCount = StyleSet()->SheetCount(origin);
for (int32_t i = 0; i < sheetCount; ++i) {
StyleSet()->SheetAt(origin, i)->List(out, aIndent);
}
};
ListStyleSheetsAtOrigin(StyleOrigin::UserAgent);
ListStyleSheetsAtOrigin(StyleOrigin::User);
ListStyleSheetsAtOrigin(StyleOrigin::Author);
}
#endif
//=============================================================
//=============================================================
//-- Debug Reflow Counts
//=============================================================
//=============================================================
#ifdef MOZ_REFLOW_PERF
//-------------------------------------------------------------
void PresShell::DumpReflows() {
if (mReflowCountMgr) {
nsAutoCString uriStr;
if (mDocument) {
nsIURI* uri = mDocument->GetDocumentURI();
if (uri) {
uri->GetPathQueryRef(uriStr);
}
}
mReflowCountMgr->DisplayTotals(uriStr.get());
mReflowCountMgr->DisplayHTMLTotals(uriStr.get());
mReflowCountMgr->DisplayDiffsInTotals();
}
}
//-------------------------------------------------------------
void PresShell::CountReflows(const char* aName, nsIFrame* aFrame) {
if (mReflowCountMgr) {
mReflowCountMgr->Add(aName, aFrame);
}
}
//-------------------------------------------------------------
void PresShell::PaintCount(const char* aName, gfxContext* aRenderingContext,
nsPresContext* aPresContext, nsIFrame* aFrame,
const nsPoint& aOffset, uint32_t aColor) {
if (mReflowCountMgr) {
mReflowCountMgr->PaintCount(aName, aRenderingContext, aPresContext, aFrame,
aOffset, aColor);
}
}
//-------------------------------------------------------------
void PresShell::SetPaintFrameCount(bool aPaintFrameCounts) {
if (mReflowCountMgr) {
mReflowCountMgr->SetPaintFrameCounts(aPaintFrameCounts);
}
}
bool PresShell::IsPaintingFrameCounts() {
if (mReflowCountMgr) return mReflowCountMgr->IsPaintingFrameCounts();
return false;
}
//------------------------------------------------------------------
//-- Reflow Counter Classes Impls
//------------------------------------------------------------------
//------------------------------------------------------------------
ReflowCounter::ReflowCounter(ReflowCountMgr* aMgr) : mMgr(aMgr) {
ClearTotals();
SetTotalsCache();
}
//------------------------------------------------------------------
ReflowCounter::~ReflowCounter() = default;
//------------------------------------------------------------------
void ReflowCounter::ClearTotals() { mTotal = 0; }
//------------------------------------------------------------------
void ReflowCounter::SetTotalsCache() { mCacheTotal = mTotal; }
//------------------------------------------------------------------
void ReflowCounter::CalcDiffInTotals() { mCacheTotal = mTotal - mCacheTotal; }
//------------------------------------------------------------------
void ReflowCounter::DisplayTotals(const char* aStr) {
DisplayTotals(mTotal, aStr ? aStr : "Totals");
}
//------------------------------------------------------------------
void ReflowCounter::DisplayDiffTotals(const char* aStr) {
DisplayTotals(mCacheTotal, aStr ? aStr : "Diff Totals");
}
//------------------------------------------------------------------
void ReflowCounter::DisplayHTMLTotals(const char* aStr) {
DisplayHTMLTotals(mTotal, aStr ? aStr : "Totals");
}
//------------------------------------------------------------------
void ReflowCounter::DisplayTotals(uint32_t aTotal, const char* aTitle) {
// figure total
if (aTotal == 0) {
return;
}
ReflowCounter* gTots = (ReflowCounter*)mMgr->LookUp(kGrandTotalsStr);
printf("%25s\t", aTitle);
printf("%d\t", aTotal);
if (gTots != this && aTotal > 0) {
gTots->Add(aTotal);
}
}
//------------------------------------------------------------------
void ReflowCounter::DisplayHTMLTotals(uint32_t aTotal, const char* aTitle) {
if (aTotal == 0) {
return;
}
ReflowCounter* gTots = (ReflowCounter*)mMgr->LookUp(kGrandTotalsStr);
FILE* fd = mMgr->GetOutFile();
if (!fd) {
return;
}
fprintf(fd, "<tr><td><center>%s</center></td>", aTitle);
fprintf(fd, "<td><center>%d</center></td></tr>\n", aTotal);
if (gTots != this && aTotal > 0) {
gTots->Add(aTotal);
}
}
//------------------------------------------------------------------
//-- ReflowCountMgr
//------------------------------------------------------------------
# define KEY_BUF_SIZE_FOR_PTR \
24 // adequate char[] buffer to sprintf a pointer
ReflowCountMgr::ReflowCountMgr() : mCounts(10), mIndiFrameCounts(10) {
mCycledOnce = false;
mDumpFrameCounts = false;
mDumpFrameByFrameCounts = false;
mPaintFrameByFrameCounts = false;
}
//------------------------------------------------------------------
ReflowCountMgr::~ReflowCountMgr() = default;
//------------------------------------------------------------------
ReflowCounter* ReflowCountMgr::LookUp(const char* aName) {
return mCounts.Get(aName);
}
//------------------------------------------------------------------
void ReflowCountMgr::Add(const char* aName, nsIFrame* aFrame) {
NS_ASSERTION(aName != nullptr, "Name shouldn't be null!");
if (mDumpFrameCounts) {
auto* const counter = mCounts.GetOrInsertNew(aName, this);
counter->Add();
}
if ((mDumpFrameByFrameCounts || mPaintFrameByFrameCounts) &&
aFrame != nullptr) {
char key[KEY_BUF_SIZE_FOR_PTR];
SprintfLiteral(key, "%p", (void*)aFrame);
auto* const counter =
mIndiFrameCounts
.LookupOrInsertWith(key,
[&aName, &aFrame, this]() {
auto counter =
MakeUnique<IndiReflowCounter>(this);
counter->mFrame = aFrame;
counter->mName.AssignASCII(aName);
return counter;
})
.get();
// this eliminates extra counts from super classes
if (counter && counter->mName.EqualsASCII(aName)) {
counter->mCount++;
counter->mCounter.Add(1);
}
}
}
//------------------------------------------------------------------
void ReflowCountMgr::PaintCount(const char* aName,
gfxContext* aRenderingContext,
nsPresContext* aPresContext, nsIFrame* aFrame,
const nsPoint& aOffset, uint32_t aColor) {
if (mPaintFrameByFrameCounts && aFrame != nullptr) {
char key[KEY_BUF_SIZE_FOR_PTR];
SprintfLiteral(key, "%p", (void*)aFrame);
IndiReflowCounter* counter = mIndiFrameCounts.Get(key);
if (counter != nullptr && counter->mName.EqualsASCII(aName)) {
DrawTarget* drawTarget = aRenderingContext->GetDrawTarget();
int32_t appUnitsPerDevPixel = aPresContext->AppUnitsPerDevPixel();
aRenderingContext->Save();
gfxPoint devPixelOffset =
nsLayoutUtils::PointToGfxPoint(aOffset, appUnitsPerDevPixel);
aRenderingContext->SetMatrixDouble(
aRenderingContext->CurrentMatrixDouble().PreTranslate(
devPixelOffset));
// We don't care about the document language or user fonts here;
// just get a default Latin font.
nsFont font(StyleGenericFontFamily::Serif, Length::FromPixels(11));
nsFontMetrics::Params params;
params.language = nsGkAtoms::x_western;
params.textPerf = aPresContext->GetTextPerfMetrics();
params.featureValueLookup = aPresContext->GetFontFeatureValuesLookup();
RefPtr<nsFontMetrics> fm = aPresContext->GetMetricsFor(font, params);
char buf[16];
int len = SprintfLiteral(buf, "%d", counter->mCount);
nscoord x = 0, y = fm->MaxAscent();
nscoord width, height = fm->MaxHeight();
fm->SetTextRunRTL(false);
width = fm->GetWidth(buf, len, drawTarget);
sRGBColor color;
sRGBColor color2;
if (aColor != 0) {
color = sRGBColor::FromABGR(aColor);
color2 = sRGBColor(0.f, 0.f, 0.f);
} else {
gfx::Float rc = 0.f, gc = 0.f, bc = 0.f;
if (counter->mCount < 5) {
rc = 1.f;
gc = 1.f;
} else if (counter->mCount < 11) {
gc = 1.f;
} else {
rc = 1.f;
}
color = sRGBColor(rc, gc, bc);
color2 = sRGBColor(rc / 2, gc / 2, bc / 2);
}
nsRect rect(0, 0, width + 15, height + 15);
Rect devPxRect =
NSRectToSnappedRect(rect, appUnitsPerDevPixel, *drawTarget);
ColorPattern black(ToDeviceColor(sRGBColor::OpaqueBlack()));
drawTarget->FillRect(devPxRect, black);
aRenderingContext->SetColor(color2);
fm->DrawString(buf, len, x + 15, y + 15, aRenderingContext);
aRenderingContext->SetColor(color);
fm->DrawString(buf, len, x, y, aRenderingContext);
aRenderingContext->Restore();
}
}
}
//------------------------------------------------------------------
void ReflowCountMgr::DoGrandTotals() {
mCounts.WithEntryHandle(kGrandTotalsStr, [this](auto&& entry) {
if (!entry) {
entry.Insert(MakeUnique<ReflowCounter>(this));
} else {
entry.Data()->ClearTotals();
}
});
printf("\t\t\t\tTotal\n");
for (uint32_t i = 0; i < 78; i++) {
printf("-");
}
printf("\n");
for (const auto& entry : mCounts) {
entry.GetData()->DisplayTotals(entry.GetKey());
}
}
static void RecurseIndiTotals(
nsPresContext* aPresContext,
nsClassHashtable<nsCharPtrHashKey, IndiReflowCounter>& aHT,
nsIFrame* aParentFrame, int32_t aLevel) {
if (aParentFrame == nullptr) {
return;
}
char key[KEY_BUF_SIZE_FOR_PTR];
SprintfLiteral(key, "%p", (void*)aParentFrame);
IndiReflowCounter* counter = aHT.Get(key);
if (counter) {
counter->mHasBeenOutput = true;
char* name = ToNewCString(counter->mName);
for (int32_t i = 0; i < aLevel; i++) printf(" ");
printf("%s - %p [%d][", name, (void*)aParentFrame, counter->mCount);
printf("%d", counter->mCounter.GetTotal());
printf("]\n");
free(name);
}
for (nsIFrame* child : aParentFrame->PrincipalChildList()) {
RecurseIndiTotals(aPresContext, aHT, child, aLevel + 1);
}
}
//------------------------------------------------------------------
void ReflowCountMgr::DoIndiTotalsTree() {
printf("\n------------------------------------------------\n");
printf("-- Individual Frame Counts\n");
printf("------------------------------------------------\n");
if (mPresShell) {
nsIFrame* rootFrame = mPresShell->GetRootFrame();
RecurseIndiTotals(mPresContext, mIndiFrameCounts, rootFrame, 0);
printf("------------------------------------------------\n");
printf("-- Individual Counts of Frames not in Root Tree\n");
printf("------------------------------------------------\n");
for (const auto& counter : mIndiFrameCounts.Values()) {
if (!counter->mHasBeenOutput) {
char* name = ToNewCString(counter->mName);
printf("%s - %p [%d][", name, (void*)counter->mFrame,
counter->mCount);
printf("%d", counter->mCounter.GetTotal());
printf("]\n");
free(name);
}
}
}
}
//------------------------------------------------------------------
void ReflowCountMgr::DoGrandHTMLTotals() {
mCounts.WithEntryHandle(kGrandTotalsStr, [this](auto&& entry) {
if (!entry) {
entry.Insert(MakeUnique<ReflowCounter>(this));
} else {
entry.Data()->ClearTotals();
}
});
static const char* title[] = {"Class", "Reflows"};
fprintf(mFD, "<tr>");
for (uint32_t i = 0; i < std::size(title); i++) {
fprintf(mFD, "<td><center><b>%s<b></center></td>", title[i]);
}
fprintf(mFD, "</tr>\n");
for (const auto& entry : mCounts) {
entry.GetData()->DisplayHTMLTotals(entry.GetKey());
}
}
//------------------------------------
void ReflowCountMgr::DisplayTotals(const char* aStr) {
if (mDumpFrameCounts) {
DoGrandTotals();
}
if (mDumpFrameByFrameCounts) {
DoIndiTotalsTree();
}
}
//------------------------------------
void ReflowCountMgr::DisplayHTMLTotals(const char* aStr) {
# ifdef WIN32x // XXX NOT XP!
char name[1024];
char* sptr = strrchr(aStr, '/');
if (sptr) {
sptr++;
strcpy(name, sptr);
char* eptr = strrchr(name, '.');
if (eptr) {
*eptr = 0;
}
strcat(name, "_stats.html");
}
mFD = fopen(name, "w");
if (mFD) {
fprintf(mFD, "<html><head><title>Reflow Stats</title></head><body>\n");
const char* title = aStr ? aStr : "No name";
fprintf(mFD,
"<center><b>%s</b><br><table border=1 "
"style=\"background-color:#e0e0e0\">",
title);
DoGrandHTMLTotals();
fprintf(mFD, "</center></table>\n");
fprintf(mFD, "</body></html>\n");
fclose(mFD);
mFD = nullptr;
}
# endif // not XP!
}
//------------------------------------------------------------------
void ReflowCountMgr::ClearTotals() {
for (const auto& data : mCounts.Values()) {
data->ClearTotals();
}
}
//------------------------------------------------------------------
void ReflowCountMgr::ClearGrandTotals() {
mCounts.WithEntryHandle(kGrandTotalsStr, [&](auto&& entry) {
if (!entry) {
entry.Insert(MakeUnique<ReflowCounter>(this));
} else {
entry.Data()->ClearTotals();
entry.Data()->SetTotalsCache();
}
});
}
//------------------------------------------------------------------
void ReflowCountMgr::DisplayDiffsInTotals() {
if (mCycledOnce) {
printf("Differences\n");
for (int32_t i = 0; i < 78; i++) {
printf("-");
}
printf("\n");
ClearGrandTotals();
}
for (const auto& entry : mCounts) {
if (mCycledOnce) {
entry.GetData()->CalcDiffInTotals();
entry.GetData()->DisplayDiffTotals(entry.GetKey());
}
entry.GetData()->SetTotalsCache();
}
mCycledOnce = true;
}
#endif // MOZ_REFLOW_PERF
nsIFrame* PresShell::GetAbsoluteContainingBlock(nsIFrame* aFrame) {
return FrameConstructor()->GetAbsoluteContainingBlock(
aFrame, nsCSSFrameConstructor::ABS_POS);
}
nsIFrame* PresShell::GetAnchorPosAnchor(
const nsAtom* aName, const nsIFrame* aPositionedFrame) const {
MOZ_ASSERT(aName);
if (const auto& entry = mAnchorPosAnchors.Lookup(aName)) {
return AnchorPositioningUtils::FindFirstAcceptableAnchor(aPositionedFrame,
entry.Data());
}
return nullptr;
}
void PresShell::AddAnchorPosAnchor(const nsAtom* aName, nsIFrame* aFrame) {
MOZ_ASSERT(aName);
auto& entry = mAnchorPosAnchors.LookupOrInsertWith(
aName, []() { return nsTArray<nsIFrame*>(); });
if (entry.IsEmpty()) {
entry.AppendElement(aFrame);
return;
}
struct FrameTreeComparator {
nsIFrame* mFrame;
int32_t operator()(nsIFrame* aOther) const {
return nsLayoutUtils::CompareTreePosition(aOther, mFrame, nullptr);
}
};
FrameTreeComparator cmp{aFrame};
size_t matchOrInsertionIdx = entry.Length();
// If the same element is already in the array,
// someone forgot to call RemoveAnchorPosAnchor.
if (BinarySearchIf(entry, 0, entry.Length(), cmp, &matchOrInsertionIdx)) {
MOZ_ASSERT_UNREACHABLE("Anchor added already");
return;
}
*entry.InsertElementAt(matchOrInsertionIdx) = aFrame;
}
void PresShell::RemoveAnchorPosAnchor(const nsAtom* aName, nsIFrame* aFrame) {
MOZ_ASSERT(aName);
auto entry = mAnchorPosAnchors.Lookup(aName);
if (!entry) {
return; // Nothing to remove.
}
auto& anchorArray = entry.Data();
// XXX: Once the implementation is more complete,
// we should probably assert here that anchorArray
// is not empty and aFrame is in it.
anchorArray.RemoveElement(aFrame);
if (anchorArray.IsEmpty()) {
entry.Remove();
}
}
void PresShell::ActivenessMaybeChanged() {
if (!mDocument) {
return;
}
SetIsActive(ComputeActiveness());
}
// A PresShell being active means that it is visible (or close to be visible, if
// the front-end is warming it). That means that when it is active we always
// tick its refresh driver at full speed if needed.
//
// Image documents behave specially in the sense that they are always "active"
// and never "in the active tab". However these documents tick manually so
// there's not much to worry about there.
bool PresShell::ComputeActiveness() const {
MOZ_LOG(gLog, LogLevel::Debug,
("PresShell::ComputeActiveness(%s, %d)\n",
mDocument->GetDocumentURI()
? mDocument->GetDocumentURI()->GetSpecOrDefault().get()
: "(no uri)",
mIsActive));
Document* doc = mDocument;
if (doc->IsBeingUsedAsImage()) {
// Documents used as an image can remain active. They do not tick their
// refresh driver if not painted, and they can't run script or such so they
// can't really observe much else.
//
// Image docs can be displayed in multiple docs at the same time so the "in
// active tab" bool doesn't make much sense for them.
return true;
}
if (Document* displayDoc = doc->GetDisplayDocument()) {
// Ok, we're an external resource document -- we need to use our display
// document's docshell to determine "IsActive" status, since we lack
// a browsing context of our own.
MOZ_ASSERT(!doc->GetBrowsingContext(),
"external resource doc shouldn't have its own BC");
doc = displayDoc;
}
BrowsingContext* bc = doc->GetBrowsingContext();
const bool inActiveTab = bc && bc->IsActive();
MOZ_LOG(gLog, LogLevel::Debug,
(" > BrowsingContext %p active: %d", bc, inActiveTab));
if (StaticPrefs::layout_testing_top_level_always_active() && bc &&
bc->IsTop()) {
MOZ_LOG(gLog, LogLevel::Debug, (" > Activeness overridden by pref"));
return true;
}
Document* root = nsContentUtils::GetInProcessSubtreeRootDocument(doc);
if (auto* browserChild = BrowserChild::GetFrom(root->GetDocShell())) {
// We might want to activate a tab even though the browsing-context is not
// active if the BrowserChild is considered visible. This serves two
// purposes:
//
// * For top-level tabs, we use this for tab warming. The browsing-context
// might still be inactive, but we want to activate the pres shell and
// the refresh driver.
//
// * For oop iframes, we do want to throttle them if they're not visible.
//
// TODO(emilio): Consider unifying the in-process vs. fission iframe
// throttling code (in-process throttling for non-visible iframes lives
// right now in Document::ShouldThrottleFrameRequests(), but that only
// throttles rAF).
if (!browserChild->IsVisible()) {
MOZ_LOG(gLog, LogLevel::Debug,
(" > BrowserChild %p is not visible", browserChild));
return false;
}
// If the browser is visible but just due to be preserving layers
// artificially, we do want to fall back to the browsing context activeness
// instead. Otherwise we do want to be active for the use cases above.
if (!browserChild->IsPreservingLayers()) {
MOZ_LOG(gLog, LogLevel::Debug,
(" > BrowserChild %p is visible and not preserving layers",
browserChild));
return true;
}
MOZ_LOG(
gLog, LogLevel::Debug,
(" > BrowserChild %p is visible and preserving layers", browserChild));
}
return inActiveTab;
}
void PresShell::SetIsActive(bool aIsActive) {
MOZ_ASSERT(mDocument, "should only be called with a document");
const bool activityChanged = mIsActive != aIsActive;
mIsActive = aIsActive;
nsPresContext* presContext = GetPresContext();
if (presContext &&
presContext->RefreshDriver()->GetPresContext() == presContext) {
presContext->RefreshDriver()->SetActivity(aIsActive);
}
if (activityChanged) {
// Propagate state-change to my resource documents' PresShells and other
// subdocuments.
//
// Note that it is fine to not propagate to fission iframes. Those will
// become active / inactive as needed as a result of they getting painted /
// not painted eventually.
auto recurse = [aIsActive](Document& aSubDoc) {
if (PresShell* presShell = aSubDoc.GetPresShell()) {
presShell->SetIsActive(aIsActive);
}
return CallState::Continue;
};
mDocument->EnumerateExternalResources(recurse);
mDocument->EnumerateSubDocuments(recurse);
}
UpdateImageLockingState();
if (activityChanged) {
#if defined(MOZ_WIDGET_ANDROID)
if (!aIsActive && presContext &&
presContext->IsRootContentDocumentCrossProcess()) {
// Reset the dynamic toolbar offset state.
presContext->UpdateDynamicToolbarOffset(0);
}
#endif
}
if (aIsActive) {
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
accService->PresShellActivated(this);
}
#endif
if (nsIFrame* rootFrame = GetRootFrame()) {
rootFrame->SchedulePaint();
}
}
}
MobileViewportManager* PresShell::GetMobileViewportManager() const {
return mMobileViewportManager;
}
Maybe<MobileViewportManager::ManagerType> UseMobileViewportManager(
PresShell* aPresShell, Document* aDocument) {
// If we're not using APZ, we won't be able to zoom, so there is no
// point in having an MVM.
if (nsPresContext* presContext = aPresShell->GetPresContext()) {
if (nsIWidget* widget = presContext->GetNearestWidget()) {
if (!widget->AsyncPanZoomEnabled()) {
return Nothing();
}
}
}
if (nsLayoutUtils::ShouldHandleMetaViewport(aDocument)) {
return Some(MobileViewportManager::ManagerType::VisualAndMetaViewport);
}
if (nsLayoutUtils::AllowZoomingForDocument(aDocument)) {
return Some(MobileViewportManager::ManagerType::VisualViewportOnly);
}
return Nothing();
}
void PresShell::MaybeRecreateMobileViewportManager(bool aAfterInitialization) {
// Determine if we require a MobileViewportManager, and what kind if so. We
// need one any time we allow resolution zooming for a document, and any time
// we want to obey <meta name="viewport"> tags for it.
Maybe<MobileViewportManager::ManagerType> mvmType =
UseMobileViewportManager(this, mDocument);
if (mvmType.isNothing() && !mMobileViewportManager) {
// We don't need one and don't have it. So we're done.
return;
}
if (mvmType && mMobileViewportManager &&
*mvmType == mMobileViewportManager->GetManagerType()) {
// We need one and we have one of the correct type, so we're done.
return;
}
if (!mPresContext->IsRootContentDocumentCrossProcess()) {
MOZ_ASSERT(!mMobileViewportManager, "We never create MVMs for subframes");
return;
}
if (mMobileViewportManager) {
// We have one, but we need to either destroy it completely to replace it
// with another one of the correct type. So either way, let's destroy the
// one we have.
mMobileViewportManager->Destroy();
mMobileViewportManager = nullptr;
mMVMContext = nullptr;
ResetVisualViewportSize();
}
if (mvmType) {
// Let's create the MVM of the type that we need. At this point we shouldn't
// have one.
MOZ_ASSERT(!mMobileViewportManager);
mMVMContext = new GeckoMVMContext(mDocument, this);
mMobileViewportManager = new MobileViewportManager(mMVMContext, *mvmType);
if (MOZ_UNLIKELY(
MOZ_LOG_TEST(MobileViewportManager::gLog, LogLevel::Debug))) {
nsIURI* uri = mDocument->GetDocumentURI();
MOZ_LOG(
MobileViewportManager::gLog, LogLevel::Debug,
("Created MVM %p (type %d) for URI %s", mMobileViewportManager.get(),
(int)*mvmType, uri ? uri->GetSpecOrDefault().get() : "(null)"));
}
if (BrowserChild* browserChild = BrowserChild::GetFrom(this)) {
mMobileViewportManager->UpdateKeyboardHeight(
browserChild->GetKeyboardHeight());
}
}
if (aAfterInitialization) {
// Setting the initial viewport will trigger a reflow.
if (mMobileViewportManager) {
mMobileViewportManager->SetInitialViewport();
} else {
// Force a reflow to our correct view manager size.
ForceResizeReflowWithCurrentDimensions();
}
// After we clear out the MVM and the MVMContext, also reset the
// resolution to 1.
SetResolutionAndScaleTo(1.0f, ResolutionChangeOrigin::MainThreadRestore);
}
}
bool PresShell::UsesMobileViewportSizing() const {
return mMobileViewportManager &&
nsLayoutUtils::ShouldHandleMetaViewport(mDocument);
}
/*
* Determines the current image locking state. Called when one of the
* dependent factors changes.
*/
void PresShell::UpdateImageLockingState() {
// We're locked if we're both thawed and active.
const bool locked = !mFrozen && mIsActive;
auto* tracker = mDocument->ImageTracker();
if (locked == tracker->GetLockingState()) {
return;
}
tracker->SetLockingState(locked);
if (locked) {
// Request decodes for visible image frames; we want to start decoding as
// quickly as possible when we get foregrounded to minimize flashing.
for (const auto& key : mApproximatelyVisibleFrames) {
if (nsImageFrame* imageFrame = do_QueryFrame(key)) {
imageFrame->MaybeDecodeForPredictedSize();
}
}
}
}
PresShell* PresShell::GetRootPresShell() const {
if (mPresContext) {
nsPresContext* rootPresContext = mPresContext->GetRootPresContext();
if (rootPresContext) {
return rootPresContext->PresShell();
}
}
return nullptr;
}
void PresShell::AddSizeOfIncludingThis(nsWindowSizes& aSizes) const {
MallocSizeOf mallocSizeOf = aSizes.mState.mMallocSizeOf;
mFrameArena.AddSizeOfExcludingThis(aSizes, Arena::ArenaKind::PresShell);
aSizes.mLayoutPresShellSize += mallocSizeOf(this);
if (mCaret) {
aSizes.mLayoutPresShellSize += mCaret->SizeOfIncludingThis(mallocSizeOf);
}
aSizes.mLayoutPresShellSize +=
mApproximatelyVisibleFrames.ShallowSizeOfExcludingThis(mallocSizeOf) +
mFramesToDirty.ShallowSizeOfExcludingThis(mallocSizeOf) +
mPendingScrollAnchorSelection.ShallowSizeOfExcludingThis(mallocSizeOf) +
mPendingScrollAnchorAdjustment.ShallowSizeOfExcludingThis(mallocSizeOf);
aSizes.mLayoutTextRunsSize += SizeOfTextRuns(mallocSizeOf);
aSizes.mLayoutPresContextSize +=
mPresContext->SizeOfIncludingThis(mallocSizeOf);
mFrameConstructor->AddSizeOfIncludingThis(aSizes);
}
size_t PresShell::SizeOfTextRuns(MallocSizeOf aMallocSizeOf) const {
nsIFrame* rootFrame = mFrameConstructor->GetRootFrame();
if (!rootFrame) {
return 0;
}
// clear the TEXT_RUN_MEMORY_ACCOUNTED flags
nsLayoutUtils::SizeOfTextRunsForFrames(rootFrame, nullptr,
/* clear = */ true);
// collect the total memory in use for textruns
return nsLayoutUtils::SizeOfTextRunsForFrames(rootFrame, aMallocSizeOf,
/* clear = */ false);
}
void PresShell::MarkFixedFramesForReflow(IntrinsicDirty aIntrinsicDirty) {
nsIFrame* rootFrame = mFrameConstructor->GetRootFrame();
if (rootFrame) {
const nsFrameList& childList =
rootFrame->GetChildList(FrameChildListID::Fixed);
for (nsIFrame* childFrame : childList) {
FrameNeedsReflow(childFrame, aIntrinsicDirty, NS_FRAME_IS_DIRTY);
}
}
}
void PresShell::MarkStickyFramesForReflow() {
ScrollContainerFrame* sc = GetRootScrollContainerFrame();
if (!sc) {
return;
}
StickyScrollContainer* ssc =
StickyScrollContainer::GetStickyScrollContainerForScrollFrame(sc);
if (!ssc) {
return;
}
ssc->MarkFramesForReflow();
}
static void AppendSubtree(nsIDocShell* aDocShell,
nsTArray<nsCOMPtr<nsIDocumentViewer>>& aArray) {
if (nsCOMPtr<nsIDocumentViewer> viewer = aDocShell->GetDocViewer()) {
aArray.AppendElement(viewer);
}
int32_t n = aDocShell->GetInProcessChildCount();
for (int32_t i = 0; i < n; i++) {
nsCOMPtr<nsIDocShellTreeItem> childItem;
aDocShell->GetInProcessChildAt(i, getter_AddRefs(childItem));
if (childItem) {
nsCOMPtr<nsIDocShell> child(do_QueryInterface(childItem));
AppendSubtree(child, aArray);
}
}
}
void PresShell::MaybeReflowForInflationScreenSizeChange() {
nsPresContext* pc = GetPresContext();
const bool fontInflationWasEnabled = FontSizeInflationEnabled();
RecomputeFontSizeInflationEnabled();
bool changed = false;
if (FontSizeInflationEnabled() && FontSizeInflationMinTwips() != 0) {
pc->ScreenSizeInchesForFontInflation(&changed);
}
changed = changed || fontInflationWasEnabled != FontSizeInflationEnabled();
if (!changed) {
return;
}
if (nsCOMPtr<nsIDocShell> docShell = pc->GetDocShell()) {
nsTArray<nsCOMPtr<nsIDocumentViewer>> array;
AppendSubtree(docShell, array);
for (uint32_t i = 0, iEnd = array.Length(); i < iEnd; ++i) {
nsCOMPtr<nsIDocumentViewer> viewer = array[i];
if (RefPtr<PresShell> descendantPresShell = viewer->GetPresShell()) {
nsIFrame* rootFrame = descendantPresShell->GetRootFrame();
if (rootFrame) {
descendantPresShell->FrameNeedsReflow(
rootFrame, IntrinsicDirty::FrameAncestorsAndDescendants,
NS_FRAME_IS_DIRTY);
}
}
}
}
}
void PresShell::CompleteChangeToVisualViewportSize() {
// This can get called during reflow, if the caller wants to get the latest
// visual viewport size after scrollbars have been added/removed. In such a
// case, we don't need to mark things as dirty because the things that we
// would mark dirty either just got updated (the root scrollframe's
// scrollbars), or will be laid out later during this reflow cycle (fixed-pos
// items). Callers that update the visual viewport during a reflow are
// responsible for maintaining these invariants.
if (!mIsReflowing) {
if (ScrollContainerFrame* sf = GetRootScrollContainerFrame()) {
sf->MarkScrollbarsDirtyForReflow();
}
MarkFixedFramesForReflow(IntrinsicDirty::None);
}
MaybeReflowForInflationScreenSizeChange();
if (auto* window = nsGlobalWindowInner::Cast(mDocument->GetInnerWindow())) {
window->VisualViewport()->PostResizeEvent();
}
}
void PresShell::SetVisualViewportSize(nscoord aWidth, nscoord aHeight) {
MOZ_ASSERT(aWidth >= 0.0 && aHeight >= 0.0);
if (!mVisualViewportSizeSet || mVisualViewportSize.width != aWidth ||
mVisualViewportSize.height != aHeight) {
mVisualViewportSizeSet = true;
mVisualViewportSize.width = aWidth;
mVisualViewportSize.height = aHeight;
CompleteChangeToVisualViewportSize();
}
}
void PresShell::ResetVisualViewportSize() {
if (mVisualViewportSizeSet) {
mVisualViewportSizeSet = false;
mVisualViewportSize.width = 0;
mVisualViewportSize.height = 0;
CompleteChangeToVisualViewportSize();
}
}
bool PresShell::SetVisualViewportOffset(const nsPoint& aScrollOffset,
const nsPoint& aPrevLayoutScrollPos) {
nsPoint newOffset = aScrollOffset;
ScrollContainerFrame* rootScrollContainerFrame =
GetRootScrollContainerFrame();
if (rootScrollContainerFrame) {
// See the comment in ScrollContainerFrame::Reflow above the call to
// SetVisualViewportOffset for why we need to do this.
nsRect scrollRange =
rootScrollContainerFrame->GetScrollRangeForUserInputEvents();
if (!scrollRange.Contains(newOffset)) {
newOffset.x = std::min(newOffset.x, scrollRange.XMost());
newOffset.x = std::max(newOffset.x, scrollRange.x);
newOffset.y = std::min(newOffset.y, scrollRange.YMost());
newOffset.y = std::max(newOffset.y, scrollRange.y);
}
}
// Careful here not to call GetVisualViewportOffset to get the previous visual
// viewport offset because if mVisualViewportOffset is nothing then we'll get
// the layout scroll position directly from the scroll frame and it has likely
// already been updated.
nsPoint prevOffset = aPrevLayoutScrollPos;
if (mVisualViewportOffset.isSome()) {
prevOffset = *mVisualViewportOffset;
}
if (prevOffset == newOffset) {
return false;
}
mVisualViewportOffset = Some(newOffset);
if (auto* window = nsGlobalWindowInner::Cast(mDocument->GetInnerWindow())) {
window->VisualViewport()->PostScrollEvent(prevOffset, aPrevLayoutScrollPos);
}
if (IsVisualViewportSizeSet() && rootScrollContainerFrame) {
rootScrollContainerFrame->Anchor()->UserScrolled();
}
if (gfxPlatform::UseDesktopZoomingScrollbars()) {
if (rootScrollContainerFrame) {
rootScrollContainerFrame->UpdateScrollbarPosition();
}
}
return true;
}
void PresShell::ResetVisualViewportOffset() { mVisualViewportOffset.reset(); }
void PresShell::RefreshViewportSize() {
if (mMobileViewportManager) {
mMobileViewportManager->RefreshViewportSize(false);
}
}
void PresShell::ScrollToVisual(const nsPoint& aVisualViewportOffset,
FrameMetrics::ScrollOffsetUpdateType aUpdateType,
ScrollMode aMode) {
MOZ_ASSERT(aMode == ScrollMode::Instant || aMode == ScrollMode::SmoothMsd);
if (aMode == ScrollMode::SmoothMsd) {
if (ScrollContainerFrame* sf = GetRootScrollContainerFrame()) {
if (sf->SmoothScrollVisual(aVisualViewportOffset, aUpdateType)) {
return;
}
}
}
// If the caller asked for instant scroll, or if we failed
// to do a smooth scroll, do an instant scroll.
SetPendingVisualScrollUpdate(aVisualViewportOffset, aUpdateType);
}
void PresShell::SetPendingVisualScrollUpdate(
const nsPoint& aVisualViewportOffset,
FrameMetrics::ScrollOffsetUpdateType aUpdateType) {
mPendingVisualScrollUpdate =
Some(VisualScrollUpdate{aVisualViewportOffset, aUpdateType});
// The pending update is picked up during the next paint.
// Schedule a paint to make sure one will happen.
if (nsIFrame* rootFrame = GetRootFrame()) {
rootFrame->SchedulePaint();
}
}
void PresShell::ClearPendingVisualScrollUpdate() {
if (mPendingVisualScrollUpdate && mPendingVisualScrollUpdate->mAcknowledged) {
mPendingVisualScrollUpdate = mozilla::Nothing();
}
}
void PresShell::AcknowledgePendingVisualScrollUpdate() {
MOZ_ASSERT(mPendingVisualScrollUpdate);
mPendingVisualScrollUpdate->mAcknowledged = true;
}
nsPoint PresShell::GetVisualViewportOffsetRelativeToLayoutViewport() const {
return GetVisualViewportOffset() - GetLayoutViewportOffset();
}
nsPoint PresShell::GetLayoutViewportOffset() const {
nsPoint result;
if (ScrollContainerFrame* sf = GetRootScrollContainerFrame()) {
result = sf->GetScrollPosition();
}
return result;
}
nsSize PresShell::GetLayoutViewportSize() const {
nsSize result;
if (ScrollContainerFrame* sf = GetRootScrollContainerFrame()) {
result = sf->GetScrollPortRect().Size();
}
return result;
}
nsSize PresShell::GetVisualViewportSizeUpdatedByDynamicToolbar() const {
NS_ASSERTION(mVisualViewportSizeSet,
"asking for visual viewport size when its not set?");
if (!mMobileViewportManager) {
return mVisualViewportSize;
}
MOZ_ASSERT(GetDynamicToolbarState() == DynamicToolbarState::InTransition ||
GetDynamicToolbarState() == DynamicToolbarState::Collapsed);
nsSize sizeUpdatedByDynamicToolbar =
mMobileViewportManager->GetVisualViewportSizeUpdatedByDynamicToolbar();
return sizeUpdatedByDynamicToolbar == nsSize() ? mVisualViewportSize
: sizeUpdatedByDynamicToolbar;
}
void PresShell::RecomputeFontSizeInflationEnabled() {
mFontSizeInflationEnabled = DetermineFontSizeInflationState();
}
bool PresShell::DetermineFontSizeInflationState() {
MOZ_ASSERT(mPresContext, "our pres context should not be null");
if (mPresContext->IsChrome()) {
return false;
}
if (FontSizeInflationEmPerLine() == 0 && FontSizeInflationMinTwips() == 0) {
return false;
}
// Force-enabling font inflation always trumps the heuristics here.
if (!FontSizeInflationForceEnabled()) {
if (BrowserChild* tab = BrowserChild::GetFrom(this)) {
// We're in a child process. Cancel inflation if we're not
// async-pan zoomed.
if (!tab->AsyncPanZoomEnabled()) {
return false;
}
} else if (XRE_IsParentProcess()) {
// We're in the master process. Cancel inflation if it's been
// explicitly disabled.
if (FontSizeInflationDisabledInMasterProcess()) {
return false;
}
}
}
Maybe<LayoutDeviceIntSize> displaySize;
// The MVM already caches the top-level content viewer size and is therefore
// the fastest way of getting that data.
if (mPresContext->IsRootContentDocumentCrossProcess()) {
if (mMobileViewportManager) {
displaySize = Some(mMobileViewportManager->DisplaySize());
}
} else if (PresShell* rootPresShell = GetRootPresShell()) {
// With any luck, we can get at the root content document without any cross-
// process shenanigans.
if (auto mvm = rootPresShell->GetMobileViewportManager()) {
displaySize = Some(mvm->DisplaySize());
}
}
if (!displaySize) {
// Unfortunately, it looks like the root content document lives in a
// different process. For consistency's sake it would be best to always use
// the content viewer size of the root content document, but it's not worth
// the effort, because this only makes a difference in the case of pages
// with an explicitly sized viewport (neither "width=device-width" nor a
// completely missing viewport tag) being loaded within a frame, which is
// hopefully a relatively exotic case.
// More to the point, these viewport size and zoom-based calculations don't
// really make sense for frames anyway, so instead of creating a way to
// access the content viewer size of the top level document cross-process,
// we probably rather want frames to simply inherit the font inflation state
// of their top-level parent and should therefore invest any time spent on
// getting things to work cross-process into that (bug 1724311).
// Until we get around to that though, we just use the content viewer size
// of however high we can get within the same process.
// (This also serves as a fallback code path if the MVM isn't available,
// e.g. when debugging in non-e10s mode on Desktop.)
nsPresContext* topContext =
mPresContext->GetInProcessRootContentDocumentPresContext();
LayoutDeviceIntSize result;
if (!nsLayoutUtils::GetDocumentViewerSize(topContext, result)) {
return false;
}
displaySize = Some(result);
}
ScreenIntSize screenSize = ViewAs<ScreenPixel>(
displaySize.value(),
PixelCastJustification::LayoutDeviceIsScreenForBounds);
nsViewportInfo vInf = GetDocument()->GetViewportInfo(screenSize);
CSSToScreenScale defaultScale =
mPresContext->CSSToDevPixelScale() * LayoutDeviceToScreenScale(1.0);
if (vInf.GetDefaultZoom() >= defaultScale || vInf.IsAutoSizeEnabled()) {
return false;
}
return true;
}
static nsIWidget* GetPresContextContainerWidget(nsPresContext* aPresContext) {
nsCOMPtr<nsISupports> container = aPresContext->Document()->GetContainer();
nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(container);
if (!baseWindow) {
return nullptr;
}
nsCOMPtr<nsIWidget> mainWidget;
baseWindow->GetMainWidget(getter_AddRefs(mainWidget));
return mainWidget;
}
static bool IsTopLevelWidget(nsIWidget* aWidget) {
using WindowType = mozilla::widget::WindowType;
auto windowType = aWidget->GetWindowType();
return windowType == WindowType::TopLevel ||
windowType == WindowType::Dialog || windowType == WindowType::Popup;
}
PresShell::WindowSizeConstraints PresShell::GetWindowSizeConstraints() {
nsSize minSize(0, 0);
nsSize maxSize(NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE);
nsIFrame* rootFrame = FrameConstructor()->GetRootElementStyleFrame();
if (!rootFrame || !mPresContext) {
return {minSize, maxSize};
}
const auto* pos = rootFrame->StylePosition();
const auto anchorResolutionParams =
AnchorPosResolutionParams::From(rootFrame);
if (const auto styleMinWidth =
pos->GetMinWidth(anchorResolutionParams.mPosition);
styleMinWidth->ConvertsToLength()) {
minSize.width = styleMinWidth->ToLength();
}
if (const auto styleMinHeight =
pos->GetMinHeight(anchorResolutionParams.mPosition);
styleMinHeight->ConvertsToLength()) {
minSize.height = styleMinHeight->ToLength();
}
if (const auto maxWidth = pos->GetMaxWidth(anchorResolutionParams.mPosition);
maxWidth->ConvertsToLength()) {
maxSize.width = maxWidth->ToLength();
}
if (const auto maxHeight =
pos->GetMaxHeight(anchorResolutionParams.mPosition);
maxHeight->ConvertsToLength()) {
maxSize.height = maxHeight->ToLength();
}
return {minSize, maxSize};
}
void PresShell::SyncWindowProperties(bool aSync) {
if (XRE_IsContentProcess()) {
return;
}
nsView* view = mViewManager->GetRootView();
if (!view || !view->HasWidget()) {
return;
}
RefPtr pc = mPresContext;
if (!pc) {
return;
}
nsCOMPtr<nsIWidget> windowWidget = GetPresContextContainerWidget(pc);
if (!windowWidget || !IsTopLevelWidget(windowWidget)) {
return;
}
if (!aSync) {
view->SetNeedsWindowPropertiesSync();
return;
}
nsIFrame* rootFrame = FrameConstructor()->GetRootElementStyleFrame();
if (!rootFrame) {
return;
}
// Apply color scheme to the top level window widget.
windowWidget->SetColorScheme(
Some(LookAndFeel::ColorSchemeForFrame(rootFrame)));
AutoWeakFrame weak(rootFrame);
auto* canvas = GetCanvasFrame();
windowWidget->SetTransparencyMode(nsLayoutUtils::GetFrameTransparency(
canvas ? canvas : rootFrame, rootFrame));
if (!weak.IsAlive()) {
return;
}
const auto& constraints = GetWindowSizeConstraints();
nsContainerFrame::SetSizeConstraints(pc, windowWidget, constraints.mMinSize,
constraints.mMaxSize);
}
nsresult PresShell::HasRuleProcessorUsedByMultipleStyleSets(uint32_t aSheetType,
bool* aRetVal) {
*aRetVal = false;
return NS_OK;
}
void PresShell::NotifyStyleSheetServiceSheetAdded(StyleSheet* aSheet,
uint32_t aSheetType) {
switch (aSheetType) {
case nsIStyleSheetService::AGENT_SHEET:
AddAgentSheet(aSheet);
break;
case nsIStyleSheetService::USER_SHEET:
AddUserSheet(aSheet);
break;
case nsIStyleSheetService::AUTHOR_SHEET:
AddAuthorSheet(aSheet);
break;
default:
MOZ_ASSERT_UNREACHABLE("unexpected aSheetType value");
break;
}
}
void PresShell::NotifyStyleSheetServiceSheetRemoved(StyleSheet* aSheet,
uint32_t aSheetType) {
StyleSet()->RemoveStyleSheet(*aSheet);
mDocument->ApplicableStylesChanged();
}
Result<nsIContent*, nsresult> PresShell::EventHandler::GetOverrideClickTarget(
WidgetGUIEvent* aGUIEvent, nsIFrame* aFrameForPresShell,
nsIContent* aPointerCapturingContent) {
if (aGUIEvent->mMessage != eMouseUp) {
return nullptr;
}
// If aFrameForPresShell has already been reframed before this is called,
// we cannot keep handling aGUIEvent.
auto overrideClickTargetOrError = [&]() -> Result<nsIContent*, nsresult> {
if (PointerEventHandler::ShouldDispatchClickEventOnCapturingElement() &&
aPointerCapturingContent) {
return aGUIEvent->AsMouseEvent()->mInputSource ==
MouseEvent_Binding::MOZ_SOURCE_TOUCH
// If the event is a compatibility mouse event of Touch Events,
// `click` event target should be the element capturing the
// touch (Note that eTouchStart caused implicit pointer capture
// by default when the web app does not use the pointer capture
// API). However, if the web app released the pointer capture,
// the target should be the closest common ancestor of
// ePointerDown and ePointerUp. These things will be handled
// by EventStateManager::SetClickCount(). Therefore, we should
// not override the click event target for a single tap here.
? nullptr
// On the other hand, we want to use the pointer capturing
// element as the target of `click` event caused by other input
// devices.
: aPointerCapturingContent;
}
if (MOZ_UNLIKELY(!aFrameForPresShell)) {
return Err(NS_ERROR_FAILURE);
}
MOZ_ASSERT(aGUIEvent->mClass == eMouseEventClass);
WidgetMouseEvent* mouseEvent = aGUIEvent->AsMouseEvent();
uint32_t flags = 0;
RelativeTo relativeTo{aFrameForPresShell};
nsPoint eventPoint =
nsLayoutUtils::GetEventCoordinatesRelativeTo(aGUIEvent, relativeTo);
if (mouseEvent->mIgnoreRootScrollFrame) {
flags |= INPUT_IGNORE_ROOT_SCROLL_FRAME;
}
nsIFrame* target =
FindFrameTargetedByInputEvent(aGUIEvent, relativeTo, eventPoint, flags);
if (!target) {
return nullptr;
}
return target->GetContent();
}();
if (MOZ_UNLIKELY(overrideClickTargetOrError.isErr())) {
return overrideClickTargetOrError;
}
return overrideClickTargetOrError.inspect()
? overrideClickTargetOrError.inspect()
->GetInclusiveFlattenedTreeAncestorElement()
: nullptr;
}
/******************************************************************************
* PresShell::EventHandler::EventTargetData
******************************************************************************/
void PresShell::EventHandler::EventTargetData::SetFrameAndComputePresShell(
nsIFrame* aFrameToHandleEvent) {
if (aFrameToHandleEvent) {
mFrame = aFrameToHandleEvent;
mPresShell = aFrameToHandleEvent->PresShell();
} else {
mFrame = nullptr;
mPresShell = nullptr;
}
}
void PresShell::EventHandler::EventTargetData::
SetFrameAndComputePresShellAndContent(nsIFrame* aFrameToHandleEvent,
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aFrameToHandleEvent);
MOZ_ASSERT(aGUIEvent);
SetFrameAndComputePresShell(aFrameToHandleEvent);
SetContentForEventFromFrame(aGUIEvent);
}
void PresShell::EventHandler::EventTargetData::SetContentForEventFromFrame(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(mFrame);
mContent = mFrame->GetContentForEvent(aGUIEvent);
AssertIfEventTargetContentAndFrameContentMismatch(aGUIEvent);
}
nsIContent* PresShell::EventHandler::EventTargetData::GetFrameContent() const {
return mFrame ? mFrame->GetContent() : nullptr;
}
void PresShell::EventHandler::EventTargetData::
AssertIfEventTargetContentAndFrameContentMismatch(
const WidgetGUIEvent* aGUIEvent) const {
#ifdef DEBUG
if (!mContent || !mFrame || !mFrame->GetContent()) {
return;
}
// If we know the event, we can compute the target correctly.
if (aGUIEvent) {
MOZ_ASSERT(mContent == mFrame->GetContentForEvent(aGUIEvent));
return;
}
// Otherwise, we can check only whether mContent is an inclusive ancestor
// element or not.
if (!mContent->IsElement()) {
MOZ_ASSERT(mContent == mFrame->GetContent());
return;
}
const Element* const closestInclusiveAncestorElement =
mFrame->GetContent()->GetInclusiveFlattenedTreeAncestorElement();
if (closestInclusiveAncestorElement == mContent) {
return;
}
if (closestInclusiveAncestorElement->IsInNativeAnonymousSubtree() &&
(mContent == closestInclusiveAncestorElement
->FindFirstNonChromeOnlyAccessContent())) {
return;
}
NS_WARNING(nsPrintfCString("mContent=%s", ToString(*mContent).c_str()).get());
NS_WARNING(nsPrintfCString("mFrame->GetContent()=%s",
ToString(*mFrame->GetContent()).c_str())
.get());
MOZ_ASSERT(mContent == mFrame->GetContent());
#endif // #ifdef DEBUG
}
bool PresShell::EventHandler::EventTargetData::MaybeRetargetToActiveDocument(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(mFrame);
MOZ_ASSERT(mPresShell);
MOZ_ASSERT(!mContent, "Doesn't support to retarget the content");
EventStateManager* activeESM =
EventStateManager::GetActiveEventStateManager();
if (!activeESM) {
return false;
}
if (aGUIEvent->mClass != ePointerEventClass &&
!aGUIEvent->HasMouseEventMessage()) {
return false;
}
if (activeESM == GetEventStateManager()) {
return false;
}
if (aGUIEvent->ShouldIgnoreCapturingContent()) {
return false;
}
nsPresContext* activePresContext = activeESM->GetPresContext();
if (!activePresContext) {
return false;
}
PresShell* activePresShell = activePresContext->GetPresShell();
if (!activePresShell) {
return false;
}
// Note, currently for backwards compatibility we don't forward mouse events
// to the active document when mouse is over some subdocument.
if (!nsContentUtils::ContentIsCrossDocDescendantOf(
activePresShell->GetDocument(), GetDocument())) {
return false;
}
SetFrameAndComputePresShell(activePresShell->GetRootFrame());
return true;
}
bool PresShell::EventHandler::EventTargetData::ComputeElementFromFrame(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
MOZ_ASSERT(aGUIEvent->IsUsingCoordinates());
MOZ_ASSERT(mPresShell);
MOZ_ASSERT(mFrame);
SetContentForEventFromFrame(aGUIEvent);
// If there is no content for this frame, target it anyway. Some frames can
// be targeted but do not have content, particularly windows with scrolling
// off.
if (!mContent) {
return true;
}
// Bug 103055, bug 185889: mouse events apply to *elements*, not all nodes.
// Thus we get the nearest element parent here.
// XXX we leave the frame the same even if we find an element parent, so that
// the text frame will receive the event (selection and friends are the ones
// who care about that anyway)
//
// We use weak pointers because during this tight loop, the node
// will *not* go away. And this happens on every mousemove.
mContent = mContent->GetInclusiveFlattenedTreeAncestorElement();
// If we found an element, target it. Otherwise, target *nothing*.
return !!mContent;
}
void PresShell::EventHandler::EventTargetData::UpdateWheelEventTarget(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
if (aGUIEvent->mMessage != eWheel) {
return;
}
// If dom.event.wheel-event-groups.enabled is not set or the stored
// event target is removed, we will not get a event target frame from the
// wheel transaction here.
nsIFrame* groupFrame = WheelTransaction::GetEventTargetFrame();
if (!groupFrame) {
return;
}
// If dom.event.wheel-event-groups.enabled is set and whe have a stored
// event target from the wheel transaction, override the event target.
SetFrameAndComputePresShellAndContent(groupFrame, aGUIEvent);
}
void PresShell::EventHandler::EventTargetData::UpdateTouchEventTarget(
WidgetGUIEvent* aGUIEvent) {
MOZ_ASSERT(aGUIEvent);
if (aGUIEvent->mClass != eTouchEventClass) {
return;
}
if (aGUIEvent->mMessage == eTouchStart) {
WidgetTouchEvent* touchEvent = aGUIEvent->AsTouchEvent();
nsIFrame* newFrame =
TouchManager::SuppressInvalidPointsAndGetTargetedFrame(touchEvent);
if (!newFrame) {
return;
}
SetFrameAndComputePresShellAndContent(newFrame, aGUIEvent);
return;
}
PresShell* newPresShell = PresShell::GetShellForTouchEvent(aGUIEvent);
if (!newPresShell) {
return; // XXX Why don't we stop handling the event in this case?
}
// Touch events (except touchstart) are dispatching to the captured
// element. Get correct shell from it.
mPresShell = newPresShell;
}
void PresShell::EndPaint() {
ClearPendingVisualScrollUpdate();
if (mDocument) {
mDocument->EnumerateSubDocuments([](Document& aSubDoc) {
if (PresShell* presShell = aSubDoc.GetPresShell()) {
presShell->EndPaint();
}
return CallState::Continue;
});
if (nsPresContext* presContext = GetPresContext()) {
if (PerformanceMainThread* perf =
presContext->GetPerformanceMainThread()) {
perf->FinalizeLCPEntriesForText();
}
}
}
}
bool PresShell::GetZoomableByAPZ() const {
return mZoomConstraintsClient && mZoomConstraintsClient->GetAllowZoom();
}
bool PresShell::ReflowForHiddenContentIfNeeded() {
if (mHiddenContentInForcedLayout.IsEmpty()) {
return false;
}
mDocument->FlushPendingNotifications(FlushType::Layout);
mHiddenContentInForcedLayout.Clear();
return true;
}
void PresShell::UpdateHiddenContentInForcedLayout(nsIFrame* aFrame) {
if (!aFrame || !aFrame->IsSubtreeDirty()) {
return;
}
nsIFrame* topmostFrameWithContentHidden = nullptr;
for (nsIFrame* cur = aFrame->GetInFlowParent(); cur;
cur = cur->GetInFlowParent()) {
if (cur->HidesContent()) {
topmostFrameWithContentHidden = cur;
mHiddenContentInForcedLayout.Insert(cur->GetContent());
}
}
if (mHiddenContentInForcedLayout.IsEmpty()) {
return;
}
// Queue and immediately flush a reflow for this node.
MOZ_ASSERT(topmostFrameWithContentHidden);
FrameNeedsReflow(topmostFrameWithContentHidden, IntrinsicDirty::None,
NS_FRAME_IS_DIRTY);
}
void PresShell::EnsureReflowIfFrameHasHiddenContent(nsIFrame* aFrame) {
MOZ_ASSERT(mHiddenContentInForcedLayout.IsEmpty());
UpdateHiddenContentInForcedLayout(aFrame);
ReflowForHiddenContentIfNeeded();
}
bool PresShell::IsForcingLayoutForHiddenContent(const nsIFrame* aFrame) const {
return mHiddenContentInForcedLayout.Contains(aFrame->GetContent());
}
void PresShell::UpdateRelevancyOfContentVisibilityAutoFrames() {
if (mContentVisibilityRelevancyToUpdate.isEmpty()) {
return;
}
for (nsIFrame* frame : mContentVisibilityAutoFrames) {
frame->UpdateIsRelevantContent(mContentVisibilityRelevancyToUpdate);
}
if (nsPresContext* presContext = GetPresContext()) {
presContext->UpdateHiddenByContentVisibilityForAnimationsIfNeeded();
}
mContentVisibilityRelevancyToUpdate.clear();
}
void PresShell::ScheduleContentRelevancyUpdate(ContentRelevancyReason aReason) {
if (MOZ_UNLIKELY(mIsDestroying)) {
return;
}
mContentVisibilityRelevancyToUpdate += aReason;
EnsureLayoutFlush();
}
PresShell::ProximityToViewportResult PresShell::DetermineProximityToViewport() {
ProximityToViewportResult result;
if (mContentVisibilityAutoFrames.IsEmpty()) {
return result;
}
auto margin = LengthPercentage::FromPercentage(
StaticPrefs::layout_css_content_visibility_relevant_content_margin() /
100.0f);
auto rootMargin = StyleRect<LengthPercentage>::WithAllSides(margin);
auto input = DOMIntersectionObserver::ComputeInput(
*mDocument, /* aRoot = */ nullptr, &rootMargin, nullptr);
for (nsIFrame* frame : mContentVisibilityAutoFrames) {
auto* element = frame->GetContent()->AsElement();
result.mAnyScrollIntoViewFlag |=
element->TemporarilyVisibleForScrolledIntoViewDescendant();
// 14.2.3.1
Maybe<bool> oldVisibility = element->GetVisibleForContentVisibility();
bool checkForInitialDetermination =
oldVisibility.isNothing() &&
(element->GetContentRelevancy().isNothing() ||
element->GetContentRelevancy()->isEmpty());
// 14.2.3.2
bool intersects =
DOMIntersectionObserver::Intersect(
input, *element, DOMIntersectionObserver::BoxToUse::OverflowClip,
DOMIntersectionObserver::IsForProximityToViewport::Yes)
.Intersects();
element->SetVisibleForContentVisibility(intersects);
// 14.2.3.3
if (checkForInitialDetermination && intersects) {
// Initial determination happens sync, otherwise on the next rendering
// opportunity.
frame->UpdateIsRelevantContent(ContentRelevancyReason::Visible);
result.mHadInitialDetermination = true;
} else if (oldVisibility.isNothing() || *oldVisibility != intersects) {
ScheduleContentRelevancyUpdate(ContentRelevancyReason::Visible);
}
}
if (nsPresContext* presContext = GetPresContext()) {
presContext->UpdateHiddenByContentVisibilityForAnimationsIfNeeded();
}
return result;
}
void PresShell::ClearTemporarilyVisibleForScrolledIntoViewDescendantFlags()
const {
for (nsIFrame* frame : mContentVisibilityAutoFrames) {
frame->GetContent()
->AsElement()
->SetTemporarilyVisibleForScrolledIntoViewDescendant(false);
}
}
void PresShell::UpdateContentRelevancyImmediately(
ContentRelevancyReason aReason) {
if (MOZ_UNLIKELY(mIsDestroying)) {
return;
}
mContentVisibilityRelevancyToUpdate += aReason;
EnsureLayoutFlush();
UpdateRelevancyOfContentVisibilityAutoFrames();
}
|