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
|
/*
* Copyright (C) 2009-2020 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "RenderLayerCompositor.h"
#include "AsyncScrollingCoordinator.h"
#include "BorderData.h"
#include "BorderShape.h"
#include "CSSPropertyNames.h"
#include "CanvasRenderingContext.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "FullscreenManager.h"
#include "GraphicsLayer.h"
#include "HTMLCanvasElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLNames.h"
#include "HitTestResult.h"
#include "InspectorInstrumentation.h"
#include "KeyframeEffectStack.h"
#include "LayerAncestorClippingStack.h"
#include "LayerOverlapMap.h"
#include "LocalFrame.h"
#include "LocalFrameView.h"
#include "Logging.h"
#include "NodeList.h"
#include "OffsetRotation.h"
#include "Page.h"
#include "PageOverlayController.h"
#include "PathOperation.h"
#include "RemoteFrame.h"
#include "RenderBoxInlines.h"
#include "RenderElementInlines.h"
#include "RenderEmbeddedObject.h"
#include "RenderFragmentedFlow.h"
#include "RenderGeometryMap.h"
#include "RenderIFrame.h"
#include "RenderImage.h"
#include "RenderLayerBacking.h"
#include "RenderLayerInlines.h"
#include "RenderLayerScrollableArea.h"
#include "RenderObjectInlines.h"
#include "RenderStyleInlines.h"
#include "RenderVideo.h"
#include "RenderView.h"
#include "RenderViewTransitionCapture.h"
#include "RotateTransformOperation.h"
#include "SVGGraphicsElement.h"
#include "ScaleTransformOperation.h"
#include "ScrollingConstraints.h"
#include "Settings.h"
#include "TiledBacking.h"
#include "TransformState.h"
#include "TranslateTransformOperation.h"
#include "ViewTransition.h"
#include "WillChangeData.h"
#include <wtf/HexNumber.h>
#include <wtf/MemoryPressureHandler.h>
#include <wtf/ObjectIdentifier.h>
#include <wtf/Scope.h>
#include <wtf/SetForScope.h>
#include <wtf/SystemTracing.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/CString.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/TextStream.h>
#if PLATFORM(IOS_FAMILY)
#include "LegacyTileCache.h"
#include "RenderScrollbar.h"
#endif
#if PLATFORM(MAC)
#include "LocalDefaultSystemAppearance.h"
#endif
#if ENABLE(TREE_DEBUGGING)
#include "RenderTreeAsText.h"
#endif
#if ENABLE(MODEL_ELEMENT)
#include "RenderModel.h"
#endif
#if !PLATFORM(MAC) && !PLATFORM(IOS_FAMILY) && !PLATFORM(GTK) && !PLATFORM(WPE)
#define USE_COMPOSITING_FOR_SMALL_CANVASES 1
#endif
namespace WebCore {
#if PLATFORM(IOS_FAMILY)
WTF_MAKE_TZONE_ALLOCATED_IMPL(LegacyWebKitScrollingLayerCoordinator);
#endif
WTF_MAKE_TZONE_ALLOCATED_IMPL(RenderLayerCompositor);
#if !USE(COMPOSITING_FOR_SMALL_CANVASES)
static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
#endif
using namespace HTMLNames;
struct ScrollingTreeState {
Markable<ScrollingNodeID> parentNodeID;
bool hasParent { false };
size_t nextChildIndex { 0 };
bool needSynchronousScrollingReasonsUpdate { false };
};
struct RenderLayerCompositor::OverlapExtent {
LayoutRect bounds;
LayerOverlapMap::LayerAndBoundsVector clippingScopes;
bool extentComputed { false };
bool hasTransformAnimation { false };
bool animationCausesExtentUncertainty { false };
bool clippingScopesComputed { false };
bool knownToBeHaveExtentUncertainty() const { return extentComputed && animationCausesExtentUncertainty; }
};
struct RenderLayerCompositor::CompositingState {
CompositingState(RenderLayer* compAncestor, bool testOverlap = true)
: compositingAncestor(compAncestor)
, testingOverlap(testOverlap)
{
}
CompositingState stateForPaintOrderChildren(RenderLayer& layer) const
{
UNUSED_PARAM(layer);
CompositingState childState(compositingAncestor);
if (layer.isStackingContext())
childState.stackingContextAncestor = &layer;
else
childState.stackingContextAncestor = stackingContextAncestor;
childState.backingSharingAncestor = backingSharingAncestor;
childState.subtreeIsCompositing = false;
childState.testingOverlap = testingOverlap;
childState.fullPaintOrderTraversalRequired = fullPaintOrderTraversalRequired;
childState.descendantsRequireCompositingUpdate = descendantsRequireCompositingUpdate;
childState.ancestorHasTransformAnimation = ancestorHasTransformAnimation;
childState.ancestorAllowsBackingStoreDetachingForFixed = ancestorAllowsBackingStoreDetachingForFixed;
childState.hasCompositedNonContainedDescendants = false;
childState.hasNotIsolatedCompositedBlendingDescendants = false; // FIXME: should this only be reset for stacking contexts?
childState.hasBackdropFilterDescendantsWithoutRoot = false;
#if !LOG_DISABLED
childState.depth = depth + 1;
#endif
return childState;
}
void updateWithDescendantStateAndLayer(const CompositingState& childState, const RenderLayer& layer, const RenderLayer* ancestorLayer, const OverlapExtent& layerExtent, bool isUnchangedSubtree = false)
{
// Subsequent layers in the parent stacking context also need to composite.
subtreeIsCompositing |= childState.subtreeIsCompositing | layer.isComposited();
if (!isUnchangedSubtree)
fullPaintOrderTraversalRequired |= childState.fullPaintOrderTraversalRequired;
// Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
// Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
// we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
auto canReenableOverlapTesting = [&layer] {
return layer.isComposited() && RenderLayerCompositor::clipsCompositingDescendants(layer);
};
if ((!childState.testingOverlap && !canReenableOverlapTesting()) || layerExtent.knownToBeHaveExtentUncertainty())
testingOverlap = false;
auto computeHasCompositedNonContainedDescendants = [&] {
if (hasCompositedNonContainedDescendants)
return true;
if (!ancestorLayer)
return false;
if (!layer.isComposited())
return false;
if (!layer.renderer().isOutOfFlowPositioned())
return false;
if (layer.ancestorLayerIsInContainingBlockChain(*ancestorLayer))
return false;
return true;
};
hasCompositedNonContainedDescendants = computeHasCompositedNonContainedDescendants();
if ((layer.isComposited() && layer.hasBlendMode()) || (layer.hasNotIsolatedCompositedBlendingDescendants() && !layer.isolatesCompositedBlending()))
hasNotIsolatedCompositedBlendingDescendants = true;
if ((layer.isComposited() && layer.hasBackdropFilter()) || (layer.hasBackdropFilterDescendantsWithoutRoot() && !layer.isBackdropRoot()))
hasBackdropFilterDescendantsWithoutRoot = true;
#if HAVE(CORE_MATERIAL)
if (layer.isComposited() && layer.hasAppleVisualEffectRequiringBackdropFilter())
hasBackdropFilterDescendantsWithoutRoot = true;
#endif
}
bool hasNonRootCompositedAncestor() const
{
return compositingAncestor && !compositingAncestor->isRenderViewLayer();
}
RenderLayer* compositingAncestor;
RenderLayer* backingSharingAncestor { nullptr };
RenderLayer* stackingContextAncestor { nullptr };
bool subtreeIsCompositing { false };
bool testingOverlap { true };
bool fullPaintOrderTraversalRequired { false };
bool descendantsRequireCompositingUpdate { false };
bool ancestorHasTransformAnimation { false };
bool ancestorAllowsBackingStoreDetachingForFixed { false };
bool hasCompositedNonContainedDescendants { false };
bool hasNotIsolatedCompositedBlendingDescendants { false };
bool hasBackdropFilterDescendantsWithoutRoot { false };
#if !LOG_DISABLED
unsigned depth { 0 };
#endif
};
struct RenderLayerCompositor::UpdateBackingTraversalState {
UpdateBackingTraversalState(RenderLayer* compAncestor = nullptr, Vector<RenderLayer*>* clippedLayers = nullptr, Vector<RenderLayer*>* overflowScrollers = nullptr)
: compositingAncestor(compAncestor)
, layersClippedByScrollers(clippedLayers)
, overflowScrollLayers(overflowScrollers)
{
}
UpdateBackingTraversalState stateForDescendants() const
{
UpdateBackingTraversalState state(compositingAncestor, layersClippedByScrollers, overflowScrollLayers);
#if !LOG_DISABLED
state.depth = depth + 1;
#endif
return state;
}
RenderLayer* compositingAncestor;
// List of layers in the current stacking context that are clipped by ancestor scrollers.
Vector<RenderLayer*>* layersClippedByScrollers;
// List of layers with composited overflow:scroll.
Vector<RenderLayer*>* overflowScrollLayers;
#if !LOG_DISABLED
unsigned depth { 0 };
#endif
};
/*
Backing sharing is used to reduce memory use by allowing multiple RenderLayers (normally siblings) which share the same
stacking context ancestor to render into the same compositing layer. This has to be done in a way that preserves back-to-front
paint order. The common case where this kicks in is a non-stacking context overflow:scroll with position:relative descendants.
When we've determined that a layer can be composited, it becomes a candidate for backing sharing (i.e. layers later
in paint order, with the same stacking context ancestor, might be able to paint into it).
We maintain multiple backing provider candidates in order to have backing sharing work with sibling or nested
overflow scrollers. When traversing layers that might be able to share with these providers, this is essentially
a bucketing process. There are three cases to consider here:
1. Sibling scrollers that don't overlap:
In this case we can simply add later layers to the appropriate scroller (using scrolling scope to find the right one),
since we know that we're traversing those layers in paint order and the scrollers don't overlap. Aswe assign layers to
one or other candidate, paint order will be preserved. This is supported.
2. Sibling scrollers that overlap:
Here we can have layers share with the on-top scroller, but have to ensure that layers scrolled by the below scroller
correctly overlap the border/background of the on-top scroller (i.e. they can't use sharing). So we can only do sharing
with the last scroller. This is not currently supported.
3. Nested scrollers:
Similar to overlapping scrollers, we have to ensure that we add to the right provider (looking a scrolling scope),
and don't break overlap with the nested scroller. This is not currently supported.
We also track additional backing sharing providers that aren't clipped scrollers. These cannot be added to, since that could expand the bounds of the resulting layer.
They are tracked so we can check them for overlap, and continue to add to the scroller backing sharing providers if the new content doesn't overlap.
To debug sharing behavior, enable the "Compositing" log channel and look for the P/p in the hierarchy output.
*/
enum class BackingSharingSequenceIdentifierType { };
using BackingSharingSequenceIdentifier = ObjectIdentifier<BackingSharingSequenceIdentifierType>;
struct RenderLayerCompositor::BackingSharingSnapshot {
BackingSharingSequenceIdentifier sequenceIdentifier;
size_t providerCount { 0 };
};
class RenderLayerCompositor::BackingSharingState {
WTF_MAKE_NONCOPYABLE(BackingSharingState);
public:
BackingSharingState(bool allowOverlappingProviders)
: m_allowOverlappingProviders(allowOverlappingProviders)
{ }
struct Provider {
SingleThreadWeakPtr<RenderLayer> providerLayer;
SingleThreadWeakListHashSet<RenderLayer> sharingLayers;
LayoutRect absoluteBounds;
};
auto& backingProviderCandidates() { return m_backingProviderCandidates; }
const RenderLayer* firstProviderCandidateLayer() const
{
return !m_backingProviderCandidates.isEmpty() ? m_backingProviderCandidates.first().providerLayer.get() : nullptr;
}
RenderLayer* backingSharingStackingContext() const { return m_backingSharingStackingContext; }
Provider* backingProviderCandidateForLayer(const RenderLayer&, const RenderLayerCompositor&, LayerOverlapMap&, OverlapExtent&);
Provider* existingBackingProviderCandidateForLayer(const RenderLayer&);
Provider* backingProviderForLayer(const RenderLayer&);
// Add a layer that would repaint into a layer in m_backingSharingLayers.
// That repaint has to wait until we've set the provider's backing-sharing layers.
void addLayerNeedingRepaint(RenderLayer& layer)
{
m_layersPendingRepaint.add(layer);
}
void addBackingSharingCandidate(RenderLayer& candidateLayer, LayoutRect candidateAbsoluteBounds, RenderLayer& candidateStackingContext, const std::optional<BackingSharingSnapshot>&);
bool isAdditionalProviderCandidate(RenderLayer&, LayoutRect candidateAbsoluteBounds, RenderLayer* stackingContextAncestor) const;
void startBackingSharingSequence(RenderLayer& candidateLayer, LayoutRect candidateAbsoluteBounds, RenderLayer& candidateStackingContext);
void endBackingSharingSequence(RenderLayer&);
std::optional<BackingSharingSnapshot> snapshot() const
{
if (!m_backingSharingStackingContext)
return std::nullopt;
return BackingSharingSnapshot { m_sequenceIdentifier, m_backingProviderCandidates.size() };
}
BackingSharingSequenceIdentifier sequenceIdentifier() const { return m_sequenceIdentifier; }
private:
void layerWillBeComposited(RenderLayer&);
void issuePendingRepaints();
Vector<Provider> m_backingProviderCandidates;
RenderLayer* m_backingSharingStackingContext { nullptr };
BackingSharingSequenceIdentifier m_sequenceIdentifier { BackingSharingSequenceIdentifier::generate() };
SingleThreadWeakHashSet<RenderLayer> m_layersPendingRepaint;
bool m_allowOverlappingProviders { false };
};
WTF::TextStream& operator<<(WTF::TextStream&, const RenderLayerCompositor::BackingSharingState::Provider&);
void RenderLayerCompositor::BackingSharingState::startBackingSharingSequence(RenderLayer& candidateLayer, LayoutRect candidateAbsoluteBounds, RenderLayer& candidateStackingContext)
{
ASSERT(!m_backingSharingStackingContext);
ASSERT(m_backingProviderCandidates.isEmpty());
m_backingProviderCandidates.append({ &candidateLayer, { }, candidateAbsoluteBounds });
m_backingSharingStackingContext = &candidateStackingContext;
}
void RenderLayerCompositor::BackingSharingState::addBackingSharingCandidate(RenderLayer& candidateLayer, LayoutRect candidateAbsoluteBounds, RenderLayer& candidateStackingContext, const std::optional<BackingSharingSnapshot>& backingSharingSnapshot)
{
ASSERT_UNUSED(candidateStackingContext, m_backingSharingStackingContext == &candidateStackingContext);
ASSERT(!m_backingProviderCandidates.containsIf([&](auto& candidate) { return candidate.providerLayer == &candidateLayer; }));
// Inserts candidateLayer into the provider list in z-order, using the state snapshot that
// was taken before any descendant layers were traversed.
if (!backingSharingSnapshot || m_sequenceIdentifier != backingSharingSnapshot->sequenceIdentifier) {
// If a new sharing sequence has been started since the snapshot was taken, then this candidate
// will be before any of the current ones in z-order (which must have been added by descendants of this layer).
m_backingProviderCandidates.insert(0, { &candidateLayer, { }, candidateAbsoluteBounds });
} else
// Otherwise insert it at the position captured in the snapshot
m_backingProviderCandidates.insert(backingSharingSnapshot->providerCount, { &candidateLayer, { }, candidateAbsoluteBounds });
}
void RenderLayerCompositor::BackingSharingState::endBackingSharingSequence(RenderLayer& endLayer)
{
ASSERT(m_backingSharingStackingContext);
auto candidates = std::exchange(m_backingProviderCandidates, { });
for (auto& candidate : candidates) {
candidate.sharingLayers.remove(endLayer);
candidate.providerLayer->backing()->setBackingSharingLayers(WTFMove(candidate.sharingLayers));
}
m_backingSharingStackingContext = nullptr;
m_sequenceIdentifier = BackingSharingSequenceIdentifier::generate();
issuePendingRepaints();
}
auto RenderLayerCompositor::BackingSharingState::backingProviderCandidateForLayer(const RenderLayer& layer, const RenderLayerCompositor& compositor, LayerOverlapMap& overlapMap, OverlapExtent& overlap) -> Provider*
{
if (layer.hasReflection())
return nullptr;
if (!m_allowOverlappingProviders) {
for (auto& candidate : m_backingProviderCandidates) {
auto& providerLayer = *candidate.providerLayer;
if (layer.ancestorLayerIsInContainingBlockChain(providerLayer))
return &candidate;
}
return nullptr;
}
if (m_backingProviderCandidates.isEmpty())
return nullptr;
LOG_WITH_STREAM(Compositing, stream << "Looking for backing provider candidate for " << &layer);
// First, find the frontmost provider that is an ancestor in the containing block chain.
auto candidateIndex = m_backingProviderCandidates.reverseFindIf([&](auto& provider) {
auto& providerLayer = *provider.providerLayer;
if (&layer == &providerLayer) {
LOG_WITH_STREAM(Compositing, stream << "Rejected subject layer " << &providerLayer);
return false;
}
if (!layer.ancestorLayerIsInContainingBlockChain(providerLayer)) {
LOG_WITH_STREAM(Compositing, stream << "Rejected non-containing block ancestor " << &providerLayer);
return false;
}
LOG_WITH_STREAM(Compositing, stream << "Found candidate " << &providerLayer);
return true;
});
if (candidateIndex == notFound)
return nullptr;
auto& candidate = m_backingProviderCandidates[candidateIndex];
// Only allow adding to providers that clip their descendants, unless there's only a single provider.
// Unclipped providers in-front are tracked for overlap testing only.
// FIXME: We could accumulate the union of the overlap bounds for a provider and its sharing layers to avoid this restriction.
if (m_backingProviderCandidates.size() > 1 && !candidate.providerLayer->canUseCompositedScrolling())
return nullptr;
if (candidateIndex == m_backingProviderCandidates.size() - 1) {
// No other provider is in front of the candidate, so no need to check for overlap.
return &candidate;
}
auto& providerLayer = *candidate.providerLayer;
LayoutRect overlapBounds = candidate.absoluteBounds;
if (CheckedPtr scrollableArea = providerLayer.scrollableArea(); scrollableArea && providerLayer.canUseCompositedScrolling() && scrollableArea->hasScrollableHorizontalOverflow() != scrollableArea->hasScrollableVerticalOverflow()) {
// If the provider uses composited scrolling but only supports scrolling
// in one axis, we can use the clipped overlap bounds in the other axis,
// when checking for overlap.
auto clippedOverlapBounds = compositor.computeClippedOverlapBounds(overlapMap, layer, overlap);
LOG_WITH_STREAM(Compositing, stream << "Candidate provider supports composited scrolling in a single axis; using layer bounds in opposite axis: clippedOverlapBounds(" << clippedOverlapBounds << ")");
if (scrollableArea->hasScrollableHorizontalOverflow()) {
overlapBounds.setY(clippedOverlapBounds.y());
overlapBounds.setHeight(clippedOverlapBounds.height());
} else {
overlapBounds.setX(clippedOverlapBounds.x());
overlapBounds.setWidth(clippedOverlapBounds.width());
}
}
LOG_WITH_STREAM(Compositing, stream << "Provider: composited scroll(" << providerLayer.canUseCompositedScrolling() << ") scrollableArea(" << providerLayer.scrollableArea() << ") horizontalOverflow(" << (providerLayer.scrollableArea() && providerLayer.scrollableArea()->hasScrollableHorizontalOverflow()) << ") verticalOverflow(" << (providerLayer.scrollableArea() && providerLayer.scrollableArea()->hasScrollableVerticalOverflow()) << ")" << " overlapBounds(" << overlapBounds << ")");
// Check if any of the other candidates that are in front of the selected provider will
// overlap the bounds of the layer to be added.
for (auto& provider : m_backingProviderCandidates.subspan(candidateIndex + 1)) {
LOG_WITH_STREAM(Compositing, stream << "Considering " << provider.providerLayer << " with bounds " << provider.absoluteBounds);
if (overlapBounds.intersects(provider.absoluteBounds)) {
LOG_WITH_STREAM(Compositing, stream << "Aborting due to overlap");
return nullptr;
}
}
return &candidate;
}
auto RenderLayerCompositor::BackingSharingState::existingBackingProviderCandidateForLayer(const RenderLayer& layer) -> Provider*
{
ASSERT(layer.paintsIntoProvidedBacking());
for (auto& candidate : m_backingProviderCandidates) {
if (layer.backingProviderLayer() == candidate.providerLayer.get())
return &candidate;
}
return nullptr;
}
auto RenderLayerCompositor::BackingSharingState::backingProviderForLayer(const RenderLayer& layer) -> Provider*
{
for (auto& candidate : m_backingProviderCandidates) {
if (candidate.sharingLayers.contains(layer))
return &candidate;
}
return nullptr;
}
bool RenderLayerCompositor::BackingSharingState::isAdditionalProviderCandidate(RenderLayer& candidateLayer, LayoutRect candidateAbsoluteBounds, RenderLayer* stackingContextAncestor) const
{
ASSERT(!m_backingProviderCandidates.isEmpty());
if (!stackingContextAncestor || stackingContextAncestor != m_backingSharingStackingContext)
return false;
if (!m_allowOverlappingProviders) {
// Only allow multiple providers for overflow scroll, which we know clips its descendants.
if (!(m_backingProviderCandidates[0].providerLayer->canUseCompositedScrolling() && candidateLayer.canUseCompositedScrolling()))
return false;
// Disallow overlap between backing providers.
for (auto& candidate : m_backingProviderCandidates) {
if (candidateAbsoluteBounds.intersects(candidate.absoluteBounds))
return false;
}
return true;
}
if (!m_backingProviderCandidates[0].providerLayer->canUseCompositedScrolling())
return false;
if (m_backingProviderCandidates.size() >= 10)
return false;
return true;
}
void RenderLayerCompositor::BackingSharingState::issuePendingRepaints()
{
for (auto& layer : m_layersPendingRepaint) {
LOG_WITH_STREAM(Compositing, stream << "Issuing postponed repaint of layer " << &layer);
layer.compositingStatusChanged(LayoutUpToDate::Yes);
layer.compositor().repaintOnCompositingChange(layer);
}
m_layersPendingRepaint.clear();
}
#if !LOG_DISABLED || ENABLE(TREE_DEBUGGING)
static inline bool compositingLogEnabled()
{
return LogCompositing.state == WTFLogChannelState::On;
}
static inline bool layersLogEnabled()
{
return LogLayers.state == WTFLogChannelState::On;
}
#endif
static constexpr Seconds conservativeCompositingPolicyHysteresisDuration { 2_s };
RenderLayerCompositor::RenderLayerCompositor(RenderView& renderView)
: m_renderView(renderView)
, m_updateCompositingLayersTimer(*this, &RenderLayerCompositor::updateCompositingLayersTimerFired)
, m_updateRenderingTimer(*this, &RenderLayerCompositor::scheduleRenderingUpdate)
, m_compositingPolicyHysteresis([](PAL::HysteresisState) { }, conservativeCompositingPolicyHysteresisDuration)
{
#if PLATFORM(IOS_FAMILY)
if (m_renderView.frameView().platformWidget())
m_legacyScrollingLayerCoordinator = makeUnique<LegacyWebKitScrollingLayerCoordinator>(page().chrome().client(), isRootFrameCompositor());
#endif
}
RenderLayerCompositor::~RenderLayerCompositor()
{
// Take care that the owned GraphicsLayers are deleted first as their destructors may call back here.
GraphicsLayer::unparentAndClear(m_rootContentsLayer);
GraphicsLayer::unparentAndClear(m_clipLayer);
GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
#if HAVE(RUBBER_BANDING)
GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
GraphicsLayer::unparentAndClear(m_contentShadowLayer);
GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
GraphicsLayer::unparentAndClear(m_layerForHeader);
GraphicsLayer::unparentAndClear(m_layerForFooter);
#endif
ASSERT(m_rootLayerAttachment == RootLayerUnattached);
}
void RenderLayerCompositor::enableCompositingMode(bool enable /* = true */)
{
if (enable != m_compositing) {
m_compositing = enable;
if (m_compositing) {
ensureRootLayer();
notifyIFramesOfCompositingChange();
} else
destroyRootLayer();
m_renderView.layer()->setNeedsPostLayoutCompositingUpdate();
}
}
void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
{
Ref settings = m_renderView.settings();
bool hasAcceleratedCompositing = settings->acceleratedCompositingEnabled();
// We allow the chrome to override the settings, in case the page is rendered
// on a chrome that doesn't allow accelerated compositing.
if (hasAcceleratedCompositing) {
m_compositingTriggers = page().chrome().client().allowedCompositingTriggers();
hasAcceleratedCompositing = m_compositingTriggers;
}
bool showDebugBorders = settings->showDebugBorders();
bool showRepaintCounter = settings->showRepaintCounter();
bool acceleratedDrawingEnabled = settings->acceleratedDrawingEnabled();
// forceCompositingMode for subframes can only be computed after layout.
bool forceCompositingMode = m_forceCompositingMode;
if (isRootFrameCompositor())
forceCompositingMode = m_renderView.settings().forceCompositingMode() && hasAcceleratedCompositing;
if (hasAcceleratedCompositing != m_hasAcceleratedCompositing || showDebugBorders != m_showDebugBorders || showRepaintCounter != m_showRepaintCounter || forceCompositingMode != m_forceCompositingMode) {
if (auto* rootLayer = m_renderView.layer()) {
rootLayer->setNeedsCompositingConfigurationUpdate();
rootLayer->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
}
}
bool debugBordersChanged = m_showDebugBorders != showDebugBorders;
m_hasAcceleratedCompositing = hasAcceleratedCompositing;
m_forceCompositingMode = forceCompositingMode;
m_showDebugBorders = showDebugBorders;
m_showRepaintCounter = showRepaintCounter;
m_acceleratedDrawingEnabled = acceleratedDrawingEnabled;
if (debugBordersChanged) {
if (m_layerForHorizontalScrollbar)
m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
if (m_layerForVerticalScrollbar)
m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
if (m_layerForScrollCorner)
m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
}
if (updateCompositingPolicy())
rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
}
void RenderLayerCompositor::cacheAcceleratedCompositingFlagsAfterLayout()
{
cacheAcceleratedCompositingFlags();
if (isRootFrameCompositor())
return;
RequiresCompositingData queryData;
bool forceCompositingMode = m_hasAcceleratedCompositing && m_renderView.settings().forceCompositingMode() && requiresCompositingForScrollableFrame(queryData);
if (forceCompositingMode != m_forceCompositingMode) {
m_forceCompositingMode = forceCompositingMode;
rootRenderLayer().setDescendantsNeedCompositingRequirementsTraversal();
}
}
bool RenderLayerCompositor::updateCompositingPolicy()
{
if (!usesCompositing())
return false;
auto currentPolicy = m_compositingPolicy;
if (page().compositingPolicyOverride()) {
m_compositingPolicy = page().compositingPolicyOverride().value();
return m_compositingPolicy != currentPolicy;
}
if (!canUpdateCompositingPolicy())
return false;
const auto isCurrentlyUnderMemoryPressureOrWarning = [] {
return MemoryPressureHandler::singleton().isUnderMemoryPressure() || MemoryPressureHandler::singleton().isUnderMemoryWarning();
};
static auto cachedMemoryPolicy = WTF::MemoryUsagePolicy::Unrestricted;
bool nowUnderMemoryPressure = isCurrentlyUnderMemoryPressureOrWarning();
static bool cachedIsUnderMemoryPressureOrWarning = nowUnderMemoryPressure;
if (cachedIsUnderMemoryPressureOrWarning != nowUnderMemoryPressure) {
cachedMemoryPolicy = MemoryPressureHandler::singleton().currentMemoryUsagePolicy();
cachedIsUnderMemoryPressureOrWarning = nowUnderMemoryPressure;
}
m_compositingPolicy = cachedMemoryPolicy == WTF::MemoryUsagePolicy::Unrestricted ? CompositingPolicy::Normal : CompositingPolicy::Conservative;
bool didChangePolicy = currentPolicy != m_compositingPolicy;
if (didChangePolicy && m_compositingPolicy == CompositingPolicy::Conservative)
m_compositingPolicyHysteresis.impulse();
return didChangePolicy;
}
bool RenderLayerCompositor::canUpdateCompositingPolicy() const
{
return m_compositingPolicyHysteresis.state() == PAL::HysteresisState::Stopped;
}
bool RenderLayerCompositor::canRender3DTransforms() const
{
return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
}
void RenderLayerCompositor::willRecalcStyle()
{
cacheAcceleratedCompositingFlags();
}
bool RenderLayerCompositor::didRecalcStyleWithNoPendingLayout()
{
return updateCompositingLayers(CompositingUpdateType::AfterStyleChange);
}
void RenderLayerCompositor::customPositionForVisibleRectComputation(const GraphicsLayer* graphicsLayer, FloatPoint& position) const
{
if (graphicsLayer != m_scrolledContentsLayer.get())
return;
FloatPoint scrollPosition = -position;
Ref frameView = m_renderView.frameView();
if (frameView->scrollBehaviorForFixedElements() == ScrollBehaviorForFixedElements::StickToDocumentBounds)
scrollPosition = frameView->constrainScrollPositionForOverhang(roundedIntPoint(scrollPosition));
position = -scrollPosition;
}
bool RenderLayerCompositor::shouldDumpPropertyForLayer(const GraphicsLayer* layer, ASCIILiteral propertyName, OptionSet<LayerTreeAsTextOptions>) const
{
if (propertyName == "anchorPoint"_s)
return layer->anchorPoint() != FloatPoint3D(0.5f, 0.5f, 0);
return true;
}
bool RenderLayerCompositor::backdropRootIsOpaque(const GraphicsLayer* layer) const
{
if (layer != rootGraphicsLayer())
return false;
return !viewHasTransparentBackground();
}
void RenderLayerCompositor::notifyFlushRequired(const GraphicsLayer*)
{
scheduleRenderingUpdate();
}
void RenderLayerCompositor::scheduleRenderingUpdate()
{
ASSERT(!m_flushingLayers);
protectedPage()->scheduleRenderingUpdate(RenderingUpdateStep::LayerFlush);
}
static inline ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusionForVisibleRect()
{
#if USE(COORDINATED_GRAPHICS)
return ScrollableArea::VisibleContentRectIncludesScrollbars::Yes;
#else
return ScrollableArea::VisibleContentRectIncludesScrollbars::No;
#endif
}
FloatRect RenderLayerCompositor::visibleRectForLayerFlushing() const
{
const Ref frameView = m_renderView.frameView();
#if PLATFORM(IOS_FAMILY)
return frameView->exposedContentRect();
#else
// Having a m_scrolledContentsLayer indicates that we're doing scrolling via GraphicsLayers.
FloatRect visibleRect = m_scrolledContentsLayer ? FloatRect({ }, frameView->sizeForVisibleContent(scrollbarInclusionForVisibleRect())) : frameView->visibleContentRect();
if (auto exposedRect = frameView->viewExposedRect())
visibleRect.intersect(*exposedRect);
return visibleRect;
#endif
}
void RenderLayerCompositor::flushPendingLayerChanges(bool isFlushRoot)
{
// LocalFrameView::flushCompositingStateIncludingSubframes() flushes each subframe,
// but GraphicsLayer::flushCompositingState() will cross frame boundaries
// if the GraphicsLayers are connected (the RootLayerAttachedViaEnclosingFrame case).
// As long as we're not the root of the flush, we can bail.
if (!isFlushRoot && rootLayerAttachment() == RootLayerAttachedViaEnclosingFrame)
return;
if (rootLayerAttachment() == RootLayerUnattached) {
m_shouldFlushOnReattach = true;
return;
}
ASSERT(!m_flushingLayers);
{
SetForScope flushingLayersScope(m_flushingLayers, true);
if (RefPtr rootLayer = rootGraphicsLayer()) {
#if ENABLE(ASYNC_SCROLLING) && ENABLE(SCROLLING_THREAD)
LayerTreeHitTestLocker layerLocker(scrollingCoordinator());
#endif
FloatRect visibleRect = visibleRectForLayerFlushing();
LOG_WITH_STREAM(Compositing, stream << "\nRenderLayerCompositor " << this << " flushPendingLayerChanges (is root " << isFlushRoot << ") visible rect " << visibleRect);
rootLayer->flushCompositingState(visibleRect);
}
ASSERT(m_flushingLayers);
#if ENABLE(TREE_DEBUGGING)
if (layersLogEnabled()) {
LOG(Layers, "RenderLayerCompositor::flushPendingLayerChanges");
showGraphicsLayerTree(rootGraphicsLayer());
}
#endif
}
#if PLATFORM(IOS_FAMILY)
updateScrollCoordinatedLayersAfterFlushIncludingSubframes();
if (isFlushRoot)
page().chrome().client().didFlushCompositingLayers();
#endif
++m_layerFlushCount;
}
void RenderLayerCompositor::setRenderingIsSuppressed(bool suppressed)
{
if (auto* rootLayer = rootGraphicsLayer())
rootLayer->setRenderingIsSuppressedIncludingDescendants(suppressed);
}
#if PLATFORM(IOS_FAMILY)
void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlushIncludingSubframes()
{
updateScrollCoordinatedLayersAfterFlush();
auto& frame = m_renderView.frameView().frame();
for (auto* subframe = frame.tree().firstChild(); subframe; subframe = subframe->tree().traverseNext(&frame)) {
auto* localFrame = dynamicDowncast<LocalFrame>(subframe);
if (!localFrame)
continue;
auto* view = localFrame->contentRenderer();
if (!view)
continue;
view->compositor().updateScrollCoordinatedLayersAfterFlush();
}
}
void RenderLayerCompositor::updateScrollCoordinatedLayersAfterFlush()
{
if (m_legacyScrollingLayerCoordinator) {
m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
}
}
#endif
void RenderLayerCompositor::didChangePlatformLayerForLayer(RenderLayer& layer, const GraphicsLayer*)
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
if (!scrollingCoordinator)
return;
auto* backing = layer.backing();
if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling))
updateScrollingNodeLayers(*nodeID, layer, *scrollingCoordinator);
if (auto* clippingStack = layer.backing()->ancestorClippingStack())
clippingStack->updateScrollingNodeLayers(*scrollingCoordinator);
if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::ViewportConstrained))
scrollingCoordinator->setNodeLayers(*nodeID, { backing->viewportAnchorLayer() });
if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
scrollingCoordinator->setNodeLayers(*nodeID, { backing->graphicsLayer() });
if (auto nodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Positioning))
scrollingCoordinator->setNodeLayers(*nodeID, { backing->graphicsLayer() });
}
void RenderLayerCompositor::didPaintBacking(RenderLayerBacking*)
{
Ref frameView = m_renderView.frameView();
frameView->setLastPaintTime(MonotonicTime::now());
if (frameView->milestonesPendingPaint())
frameView->firePaintRelatedMilestonesIfNeeded();
}
void RenderLayerCompositor::didChangeVisibleRect()
{
RefPtr rootLayer = rootGraphicsLayer();
if (!rootLayer)
return;
FloatRect visibleRect = visibleRectForLayerFlushing();
bool requiresFlush = rootLayer->visibleRectChangeRequiresFlush(visibleRect);
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor::didChangeVisibleRect " << visibleRect << " requiresFlush " << requiresFlush);
if (requiresFlush)
scheduleRenderingUpdate();
}
void RenderLayerCompositor::notifySubsequentFlushRequired(const GraphicsLayer*)
{
if (!m_updateRenderingTimer.isActive())
m_updateRenderingTimer.startOneShot(0_s);
}
void RenderLayerCompositor::layerTiledBackingUsageChanged(const GraphicsLayer* graphicsLayer, bool usingTiledBacking)
{
if (usingTiledBacking) {
++m_layersWithTiledBackingCount;
graphicsLayer->tiledBacking()->setIsInWindow(page().isInWindow());
} else {
ASSERT(m_layersWithTiledBackingCount > 0);
--m_layersWithTiledBackingCount;
}
}
void RenderLayerCompositor::scheduleCompositingLayerUpdate()
{
if (!m_updateCompositingLayersTimer.isActive())
m_updateCompositingLayersTimer.startOneShot(0_s);
}
void RenderLayerCompositor::updateCompositingLayersTimerFired()
{
updateCompositingLayers(CompositingUpdateType::AfterLayout);
}
void RenderLayerCompositor::cancelCompositingLayerUpdate()
{
m_updateCompositingLayersTimer.stop();
}
template<typename ApplyFunctionType>
void RenderLayerCompositor::applyToCompositedLayerIncludingDescendants(RenderLayer& layer, const ApplyFunctionType& function)
{
if (layer.isComposited())
function(layer);
for (auto* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
applyToCompositedLayerIncludingDescendants(*childLayer, function);
}
void RenderLayerCompositor::updateEventRegionsRecursive(RenderLayer& layer)
{
#if ENABLE(ASYNC_SCROLLING)
if (layer.isComposited())
layer.backing()->updateEventRegion();
if (!layer.hasDescendantNeedingEventRegionUpdate())
return;
for (auto* childLayer = layer.firstChild(); childLayer; childLayer = childLayer->nextSibling())
updateEventRegionsRecursive(*childLayer);
layer.clearHasDescendantNeedingEventRegionUpdate();
#else
UNUSED_PARAM(layer);
#endif
}
void RenderLayerCompositor::updateEventRegions()
{
updateEventRegionsRecursive(*m_renderView.layer());
m_renderView.setNeedsEventRegionUpdateForNonCompositedFrame(false);
}
static std::optional<ScrollingNodeID> frameHostingNodeForFrame(LocalFrame& frame)
{
if (!frame.document() || !frame.view())
return { };
// Find the frame's enclosing layer in our render tree.
RefPtr ownerElement = frame.protectedDocument()->ownerElement();
if (!ownerElement)
return { };
RefPtr widgetRenderer = dynamicDowncast<RenderWidget>(ownerElement->renderer());
if (!widgetRenderer)
return { };
if (!widgetRenderer->hasLayer() || !widgetRenderer->layer()->isComposited()) {
LOG(Scrolling, "frameHostingNodeForFrame: frame renderer has no layer or is not composited.");
return { };
}
if (auto frameHostingNodeID = widgetRenderer->layer()->backing()->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting))
return frameHostingNodeID;
return { };
}
// Returns true on a successful update.
bool RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
{
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " [" << m_renderView.frameView() << "] updateCompositingLayers " << updateType << " contentLayersCount " << m_contentLayersCount);
TraceScope tracingScope(CompositingUpdateStart, CompositingUpdateEnd);
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabled())
showPaintOrderTree(m_renderView.layer());
#endif
if (updateType == CompositingUpdateType::AfterStyleChange || updateType == CompositingUpdateType::AfterLayout)
cacheAcceleratedCompositingFlagsAfterLayout(); // Some flags (e.g. forceCompositingMode) depend on layout.
m_updateCompositingLayersTimer.stop();
ASSERT(m_renderView.document().backForwardCacheState() == Document::NotInBackForwardCache
|| m_renderView.document().backForwardCacheState() == Document::AboutToEnterBackForwardCache);
// Compositing layers will be updated in Document::setVisualUpdatesAllowed(bool) if suppressed here.
if (!m_renderView.document().visualUpdatesAllowed())
return false;
// Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
// This happens when m_updateCompositingLayersTimer fires before layout is updated.
if (m_renderView.needsLayout()) {
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " updateCompositingLayers " << updateType << " - m_renderView.needsLayout, bailing ");
return false;
}
if (!m_compositing && (m_forceCompositingMode || (isRootFrameCompositor() && page().pageOverlayController().overlayCount())))
enableCompositingMode(true);
bool isPageScroll = !updateRoot || updateRoot == &rootRenderLayer();
updateRoot = &rootRenderLayer();
if (updateType == CompositingUpdateType::OnScroll || updateType == CompositingUpdateType::OnCompositedScroll) {
// We only get here if we didn't scroll on the scrolling thread, so this update needs to re-position viewport-constrained layers.
if (m_renderView.settings().acceleratedCompositingForFixedPositionEnabled() && isPageScroll) {
if (auto* viewportConstrainedObjects = m_renderView.frameView().viewportConstrainedObjects()) {
for (auto& renderer : *viewportConstrainedObjects) {
if (auto* layer = renderer.layer())
layer->setNeedsCompositingGeometryUpdate();
}
}
}
// Scrolling can affect overlap. FIXME: avoid for page scrolling.
updateRoot->setDescendantsNeedCompositingRequirementsTraversal();
}
if (updateType == CompositingUpdateType::AfterLayout) {
// Ensure that post-layout updates push new scroll position and viewport rects onto the root node.
rootRenderLayer().setNeedsScrollingTreeUpdate();
}
if (!updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() && !m_compositing) {
LOG_WITH_STREAM(Compositing, stream << " no compositing work to do");
return true;
}
if (!updateRoot->needsAnyCompositingTraversal()) {
LOG_WITH_STREAM(Compositing, stream << " updateRoot has no dirty child and doesn't need update");
return true;
}
++m_compositingUpdateCount;
#if !LOG_DISABLED
MonotonicTime startTime;
if (compositingLogEnabled()) {
++m_rootLayerUpdateCount;
startTime = MonotonicTime::now();
}
if (compositingLogEnabled()) {
m_obligateCompositedLayerCount = 0;
m_secondaryCompositedLayerCount = 0;
m_obligatoryBackingStoreBytes = 0;
m_secondaryBackingStoreBytes = 0;
auto& frame = m_renderView.frameView().frame();
bool isRootFrame = isRootFrameCompositor();
LOG_WITH_STREAM(Compositing, stream << "\nUpdate " << m_rootLayerUpdateCount << " of " << (isRootFrame ? "root frame"_s : makeString("frame "_s, frame.frameID().object().toUInt64())) << " - compositing policy is " << m_compositingPolicy);
}
#endif
// FIXME: optimize root-only update.
if (updateRoot->hasDescendantNeedingCompositingRequirementsTraversal() || updateRoot->needsCompositingRequirementsTraversal()) {
auto& rootLayer = rootRenderLayer();
CompositingState compositingState(updateRoot);
BackingSharingState backingSharingState(m_renderView.settings().overlappingBackingStoreProvidersEnabled());
LayerOverlapMap overlapMap(rootLayer);
computeCompositingRequirements(nullptr, rootLayer, overlapMap, compositingState, backingSharingState);
}
LOG(Compositing, "\nRenderLayerCompositor::updateCompositingLayers - mid");
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabled())
showPaintOrderTree(m_renderView.layer());
#endif
if (updateRoot->hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || updateRoot->needsUpdateBackingOrHierarchyTraversal()) {
ASSERT(m_layersWithUnresolvedRelations.isEmptyIgnoringNullReferences());
ScrollingTreeState scrollingTreeState;
scrollingTreeState.hasParent = true;
if (!m_renderView.frame().isMainFrame()) {
scrollingTreeState.parentNodeID = frameHostingNodeForFrame(m_renderView.protectedFrame());
scrollingTreeState.hasParent = !!scrollingTreeState.parentNodeID;
}
RefPtr scrollingCoordinator = this->scrollingCoordinator();
bool hadSubscrollers = scrollingCoordinator ? scrollingCoordinator->hasSubscrollers(m_renderView.frame().rootFrame().frameID()) : false;
UpdateBackingTraversalState traversalState;
Vector<Ref<GraphicsLayer>> childList;
updateBackingAndHierarchy(*updateRoot, childList, traversalState, scrollingTreeState);
if (scrollingTreeState.needSynchronousScrollingReasonsUpdate)
updateSynchronousScrollingNodes();
// Host the document layer in the RenderView's root layer.
appendDocumentOverlayLayers(childList);
// Even when childList is empty, don't drop out of compositing mode if there are
// composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
if (childList.isEmpty() && !needsCompositingForContentOrOverlays())
destroyRootLayer();
else if (RefPtr rootContentsLayer = m_rootContentsLayer)
rootContentsLayer->setChildren(WTFMove(childList));
if (scrollingCoordinator && scrollingCoordinator->hasSubscrollers(m_renderView.frame().rootFrame().frameID()) != hadSubscrollers)
invalidateEventRegionForAllFrames();
resolveScrollingTreeRelationships();
}
#if !LOG_DISABLED
if (compositingLogEnabled()) {
MonotonicTime endTime = MonotonicTime::now();
LOG(Compositing, "Total layers primary secondary obligatory backing (KB) secondary backing(KB) total backing (KB) update time (ms)\n");
LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, (endTime - startTime).milliseconds());
}
#endif
// FIXME: Only do if dirty.
updateRootLayerPosition();
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabled()) {
LOG(Compositing, "RenderLayerCompositor::updateCompositingLayers - post");
showPaintOrderTree(m_renderView.layer());
}
#endif
InspectorInstrumentation::layerTreeDidChange(protectedPage().ptr());
if (m_renderView.needsRepaintHackAfterCompositingLayerUpdateForDebugOverlaysOnly()) {
m_renderView.repaintRootContents();
m_renderView.setNeedsRepaintHackAfterCompositingLayerUpdateForDebugOverlaysOnly(false);
}
if (m_scrolledContentsLayer)
updateOverflowControlsLayers();
return true;
}
// Unchanged leaf compositing layers that clip their descendants can skip descendant
// traversal, since their descendants can't contribute any new overlap to the map.
static bool canSkipComputeCompositingRequirementsForSubtree(const RenderLayer& layer, bool willBeComposited)
{
if (layer.needsCompositingRequirementsTraversal() || layer.hasDescendantNeedingCompositingRequirementsTraversal())
return false;
if (!layer.isComposited() || !willBeComposited || layer.hasCompositingDescendant() || !layer.isStackingContext())
return false;
return layer.renderer().hasNonVisibleOverflow();
}
bool RenderLayerCompositor::allowBackingStoreDetachingForFixedPosition(RenderLayer& layer, const LayoutRect& absoluteBounds)
{
ASSERT_UNUSED(layer, layer.behavesAsFixed());
// We'll allow detaching if the layer is outside the layout viewport. Fixed layers inside
// the layout viewport can be revealed by async scrolling, so we want to pin their backing store.
Ref frameView = m_renderView.frameView();
LayoutRect fixedLayoutRect;
if (frameView->useFixedLayout())
fixedLayoutRect = m_renderView.unscaledDocumentRect();
else
fixedLayoutRect = frameView->rectForFixedPositionLayout();
bool allowDetaching = !fixedLayoutRect.intersects(absoluteBounds);
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor (layer " << &layer << ") allowsBackingStoreDetaching - absoluteBounds " << absoluteBounds << " layoutViewportRect " << fixedLayoutRect << ", allowDetaching " << allowDetaching);
return allowDetaching;
}
void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState)
{
#if !LOG_DISABLED
unsigned treeDepth = compositingState.depth;
#else
unsigned treeDepth = 0;
#endif
layer.updateDescendantDependentFlags();
layer.updateLayerListsIfNeeded();
if (!layer.hasDescendantNeedingCompositingRequirementsTraversal()
&& !layer.needsCompositingRequirementsTraversal()
&& !compositingState.fullPaintOrderTraversalRequired
&& !compositingState.descendantsRequireCompositingUpdate) {
traverseUnchangedSubtree(ancestorLayer, layer, overlapMap, compositingState, backingSharingState);
return;
}
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(treeDepth * 2, ' ') << &layer << " computeCompositingRequirements (backing provider candidates " << backingSharingState.backingProviderCandidates() << ")");
// FIXME: maybe we can avoid updating all remaining layers in paint order.
compositingState.fullPaintOrderTraversalRequired |= layer.needsCompositingRequirementsTraversal();
compositingState.descendantsRequireCompositingUpdate |= layer.descendantsNeedCompositingRequirementsTraversal();
// We updated compositing for direct reasons in layerStyleChanged(). Here, check for compositing that can only be evaluated after layout.
RequiresCompositingData queryData;
bool willBeComposited = layer.isComposited();
bool becameCompositedAfterDescendantTraversal = false;
IndirectCompositingReason compositingReason = compositingState.subtreeIsCompositing ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None;
if (layer.needsPostLayoutCompositingUpdate() || compositingState.fullPaintOrderTraversalRequired || compositingState.descendantsRequireCompositingUpdate) {
layer.setIndirectCompositingReason(IndirectCompositingReason::None);
willBeComposited = needsToBeComposited(layer, queryData);
}
compositingState.fullPaintOrderTraversalRequired |= layer.subsequentLayersNeedCompositingRequirementsTraversal();
OverlapExtent layerExtent;
// Use the fact that we're composited as a hint to check for an animating transform.
// FIXME: Maybe needsToBeComposited() should return a bitmask of reasons, to avoid the need to recompute things.
if (willBeComposited && !layer.isRenderViewLayer())
layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
bool respectTransforms = !layerExtent.hasTransformAnimation;
overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
bool layerPaintsIntoProvidedBacking = false;
if (!willBeComposited && compositingState.subtreeIsCompositing && canBeComposited(layer)) {
if (auto* provider = backingSharingState.backingProviderCandidateForLayer(layer, *this, overlapMap, layerExtent)) {
provider->sharingLayers.add(layer);
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(treeDepth * 2, ' ') << " " << &layer << " can share with " << backingSharingState.backingProviderCandidates());
compositingReason = IndirectCompositingReason::None;
layerPaintsIntoProvidedBacking = true;
}
}
// If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
if (!willBeComposited && !layerPaintsIntoProvidedBacking && !overlapMap.isEmpty() && compositingState.testingOverlap) {
// If we're testing for overlap, we only need to composite if we overlap something that is already composited.
if (layerOverlaps(overlapMap, layer, layerExtent))
compositingReason = IndirectCompositingReason::Overlap;
else
compositingReason = IndirectCompositingReason::None;
}
#if ENABLE(VIDEO)
// Video is special. It's the only RenderLayer type that can both have
// RenderLayer children and whose children can't use its backing to render
// into. These children (the controls) always need to be promoted into their
// own layers to draw on top of the accelerated video.
if (compositingState.compositingAncestor && compositingState.compositingAncestor->renderer().isRenderVideo())
compositingReason = IndirectCompositingReason::Overlap;
#endif
if (compositingReason != IndirectCompositingReason::None)
layer.setIndirectCompositingReason(compositingReason);
// Check if the computed indirect reason will force the layer to become composited.
if (!willBeComposited && layer.mustCompositeForIndirectReasons() && canBeComposited(layer)) {
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(treeDepth * 2, ' ') << "layer " << &layer << " compositing for indirect reason " << layer.indirectCompositingReason() << " (was sharing: " << layerPaintsIntoProvidedBacking << ")");
willBeComposited = true;
layerPaintsIntoProvidedBacking = false;
}
// The children of this layer don't need to composite, unless there is
// a compositing layer among them, so start by inheriting the compositing
// ancestor with subtreeIsCompositing set to false.
CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
bool didPushOverlapContainer = false;
auto layerWillComposite = [&] {
// This layer is going to be composited, so children can safely ignore the fact that there's an
// animation running behind this layer, meaning they can rely on the overlap map testing again.
currentState.testingOverlap = true;
// This layer now acts as the ancestor for kids.
currentState.compositingAncestor = &layer;
// Compositing turns off backing sharing.
currentState.backingSharingAncestor = nullptr;
if (layerPaintsIntoProvidedBacking) {
layerPaintsIntoProvidedBacking = false;
// layerPaintsIntoProvidedBacking was only true for layers that would otherwise composite because of overlap. If we can
// no longer share, put this this indirect reason back on the layer so that requiresOwnBackingStore() sees it.
layer.setIndirectCompositingReason(IndirectCompositingReason::Overlap);
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(treeDepth * 2, ' ') << "layer " << &layer << " was sharing, now will composite");
} else {
if (!didPushOverlapContainer) {
overlapMap.pushCompositingContainer(layer);
didPushOverlapContainer = true;
LOG_WITH_STREAM(CompositingOverlap, stream << TextStream::Repeat(treeDepth * 2, ' ') << "layer " << &layer << " will composite, pushed container " << overlapMap);
}
}
willBeComposited = true;
};
// Unless we leave the containing block chain, or have an animated transform,
// then we can continue to use the inherited backing store attachment.
bool allowsBackingStoreDetachingForFixed = false;
if (currentState.ancestorAllowsBackingStoreDetachingForFixed && ancestorLayer && layer.ancestorLayerIsInContainingBlockChain(*ancestorLayer) && !layerExtent.hasTransformAnimation)
allowsBackingStoreDetachingForFixed = true;
auto layerWillCompositePostDescendants = [&] {
layerWillComposite();
currentState.subtreeIsCompositing = true;
becameCompositedAfterDescendantTraversal = true;
if (layer.behavesAsFixed())
allowsBackingStoreDetachingForFixed = allowBackingStoreDetachingForFixedPosition(layer, layerExtent.bounds);
};
if (willBeComposited) {
layerWillComposite();
computeExtent(overlapMap, layer, layerExtent);
currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
if (!allowsBackingStoreDetachingForFixed && layer.behavesAsFixed())
currentState.ancestorAllowsBackingStoreDetachingForFixed = allowsBackingStoreDetachingForFixed = allowBackingStoreDetachingForFixedPosition(layer, layerExtent.bounds);
// Too hard to compute animated bounds if both us and some ancestor is animating transform.
layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
} else if (layerPaintsIntoProvidedBacking) {
currentState.backingSharingAncestor = &layer;
overlapMap.pushCompositingContainer(layer);
didPushOverlapContainer = true;
LOG_WITH_STREAM(CompositingOverlap, stream << TextStream::Repeat(treeDepth * 2, ' ') << "layer " << &layer << " will share, pushed container " << overlapMap);
}
auto backingSharingSnapshot = updateBackingSharingBeforeDescendantTraversal(backingSharingState, treeDepth, overlapMap, layer, layerExtent, willBeComposited, compositingState.stackingContextAncestor);
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(layer);
#endif
bool descendantsAddedToOverlap = currentState.hasNonRootCompositedAncestor();
if (!canSkipComputeCompositingRequirementsForSubtree(layer, willBeComposited)) {
if (layer.hasNegativeZOrderLayers()) {
// Speculatively push this layer onto the overlap map.
bool didSpeculativelyPushOverlapContainer = false;
if (!didPushOverlapContainer) {
overlapMap.pushSpeculativeCompositingContainer(layer);
didPushOverlapContainer = true;
didSpeculativelyPushOverlapContainer = true;
}
for (auto* childLayer : layer.negativeZOrderLayers()) {
computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState);
// If we have to make a layer for this child, make one now so we can have a contents layer
// (since we need to ensure that the -ve z-order child renders underneath our contents).
if (!willBeComposited && currentState.subtreeIsCompositing) {
layer.setIndirectCompositingReason(IndirectCompositingReason::BackgroundLayer);
layerWillComposite();
overlapMap.confirmSpeculativeCompositingContainer();
}
}
if (didSpeculativelyPushOverlapContainer) {
if (overlapMap.maybePopSpeculativeCompositingContainer())
didPushOverlapContainer = false;
else if (!willBeComposited) {
layer.setIndirectCompositingReason(IndirectCompositingReason::BackgroundLayer);
layerWillComposite();
}
}
}
for (auto* childLayer : layer.normalFlowLayers())
computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState);
for (auto* childLayer : layer.positiveZOrderLayers())
computeCompositingRequirements(&layer, *childLayer, overlapMap, currentState, backingSharingState);
// Set the flag to say that this layer has compositing children.
layer.setHasCompositingDescendant(currentState.subtreeIsCompositing);
layer.setHasCompositedNonContainedDescendants(currentState.hasCompositedNonContainedDescendants);
}
// If we just entered compositing mode, the root will have become composited (as long as accelerated compositing is enabled).
if (layer.isRenderViewLayer()) {
if (usesCompositing() && m_hasAcceleratedCompositing)
willBeComposited = true;
}
bool isolatedCompositedBlending = layer.isolatesCompositedBlending();
layer.setHasNotIsolatedCompositedBlendingDescendants(currentState.hasNotIsolatedCompositedBlendingDescendants);
if (layer.isolatesCompositedBlending() != isolatedCompositedBlending) {
// isolatedCompositedBlending affects the result of clippedByAncestor().
layer.setChildrenNeedCompositingGeometryUpdate();
}
ASSERT(!layer.hasNotIsolatedCompositedBlendingDescendants() || layer.hasNotIsolatedBlendingDescendants());
bool isBackdropRoot = layer.isBackdropRoot();
layer.setHasBackdropFilterDescendantsWithoutRoot(currentState.hasBackdropFilterDescendantsWithoutRoot);
if (layer.isBackdropRoot() != isBackdropRoot)
layer.setNeedsCompositingConfigurationUpdate();
// Now check for reasons to become composited that depend on the state of descendant layers.
if (!willBeComposited && canBeComposited(layer)) {
layer.update3DTransformedDescendantStatus();
auto indirectReason = computeIndirectCompositingReason(layer, currentState.subtreeIsCompositing, layer.has3DTransformedDescendant(), layerPaintsIntoProvidedBacking);
if (indirectReason != IndirectCompositingReason::None) {
layer.setIndirectCompositingReason(indirectReason);
layerWillCompositePostDescendants();
}
}
if (layer.reflectionLayer()) {
// FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
layer.reflectionLayer()->setIndirectCompositingReason(willBeComposited ? IndirectCompositingReason::Stacking : IndirectCompositingReason::None);
}
// If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
// to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
// if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
RequiresCompositingData rootLayerQueryData;
if (layer.isRenderViewLayer() && !currentState.subtreeIsCompositing && !requiresCompositingLayer(layer, rootLayerQueryData) && !m_forceCompositingMode && !needsCompositingForContentOrOverlays()) {
// Don't drop out of compositing on iOS, because we may flash. See <rdar://problem/8348337>.
#if !PLATFORM(IOS_FAMILY)
enableCompositingMode(false);
willBeComposited = false;
#endif
}
ASSERT(willBeComposited == needsToBeComposited(layer, queryData));
// Create or destroy backing here. However, we can't update geometry because layers above us may become composited
// during post-order traversal (e.g. for clipping).
bool needsCompositingStatusUpdate = false;
if (updateBacking(layer, queryData, &backingSharingState, willBeComposited ? BackingRequired::Yes : BackingRequired::No)) {
layer.setNeedsCompositingLayerConnection();
// Child layers need to get a geometry update to recompute their position.
layer.setChildrenNeedCompositingGeometryUpdate();
// The composited bounds of enclosing layers depends on which descendants are composited, so they need a geometry update.
layer.setNeedsCompositingGeometryUpdateOnAncestors();
// This layer and all of its descendants have cached repaints rects that are relative to
// the repaint container, so change when compositing changes; we need to update them here,
// as long as shared backing isn't going to change our repaint container.
if (willBeComposited || !layerRepaintTargetsBackingSharingLayer(layer, backingSharingState))
needsCompositingStatusUpdate = true;
}
// Update layer state bits.
if (layer.reflectionLayer() && updateLayerCompositingState(*layer.reflectionLayer(), &layer, queryData, backingSharingState))
layer.setNeedsCompositingLayerConnection();
// FIXME: clarify needsCompositingPaintOrderChildrenUpdate. If a composited layer gets a new ancestor, it needs geometry computations.
if (layer.needsCompositingPaintOrderChildrenUpdate()) {
layer.setChildrenNeedCompositingGeometryUpdate();
layer.setNeedsCompositingLayerConnection();
}
layer.clearCompositingRequirementsTraversalState();
// Compute state passed to the caller.
compositingState.updateWithDescendantStateAndLayer(currentState, layer, ancestorLayer, layerExtent);
updateBackingSharingAfterDescendantTraversal(backingSharingState, treeDepth, overlapMap, layer, layerExtent, compositingState.stackingContextAncestor, backingSharingSnapshot);
// Update the cached repaint rects now that we've finished updating backing
// sharing state on descendants
if (needsCompositingStatusUpdate) {
layer.compositingStatusChanged(queryData.layoutUpToDate);
if (!layer.isComposited()) {
if (layerRepaintTargetsBackingSharingLayer(layer, backingSharingState))
backingSharingState.addLayerNeedingRepaint(layer);
else
repaintOnCompositingChange(layer);
}
}
bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap, becameCompositedAfterDescendantTraversal && !descendantsAddedToOverlap);
if (layer.isComposited())
layer.backing()->updateAllowsBackingStoreDetaching(allowsBackingStoreDetachingForFixed);
overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(treeDepth * 2, ' ') << &layer << " computeCompositingRequirements - willBeComposited " << willBeComposited << " (backing provider candidates " << backingSharingState.backingProviderCandidates() << ")");
}
// We have to traverse unchanged layers to fill in the overlap map.
void RenderLayerCompositor::traverseUnchangedSubtree(RenderLayer* ancestorLayer, RenderLayer& layer, LayerOverlapMap& overlapMap, CompositingState& compositingState, BackingSharingState& backingSharingState)
{
#if !LOG_DISABLED
unsigned treeDepth = compositingState.depth;
#else
unsigned treeDepth = 0;
#endif
layer.updateDescendantDependentFlags();
layer.updateLayerListsIfNeeded();
ASSERT(!compositingState.fullPaintOrderTraversalRequired);
ASSERT(!layer.hasDescendantNeedingCompositingRequirementsTraversal());
ASSERT(!layer.needsCompositingRequirementsTraversal());
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(treeDepth * 2, ' ') << &layer << (layer.isNormalFlowOnly() ? " n" : " s") << " traverseUnchangedSubtree");
bool layerIsComposited = layer.isComposited();
bool layerPaintsIntoProvidedBacking = false;
bool didPushOverlapContainer = false;
OverlapExtent layerExtent;
if (layerIsComposited && !layer.isRenderViewLayer())
layerExtent.hasTransformAnimation = isRunningTransformAnimation(layer.renderer());
bool respectTransforms = !layerExtent.hasTransformAnimation;
overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer, respectTransforms);
// If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map
if (!layerIsComposited && !overlapMap.isEmpty() && compositingState.testingOverlap)
computeExtent(overlapMap, layer, layerExtent);
if (layer.paintsIntoProvidedBacking()) {
auto* provider = backingSharingState.existingBackingProviderCandidateForLayer(layer);
ASSERT_WITH_SECURITY_IMPLICATION(provider);
ASSERT_WITH_SECURITY_IMPLICATION(provider == backingSharingState.backingProviderCandidateForLayer(layer, *this, overlapMap, layerExtent));
provider->sharingLayers.add(layer);
layerPaintsIntoProvidedBacking = true;
}
CompositingState currentState = compositingState.stateForPaintOrderChildren(layer);
if (layerIsComposited) {
// This layer is going to be composited, so children can safely ignore the fact that there's an
// animation running behind this layer, meaning they can rely on the overlap map testing again.
currentState.testingOverlap = true;
// This layer now acts as the ancestor for kids.
currentState.compositingAncestor = &layer;
currentState.backingSharingAncestor = nullptr;
overlapMap.pushCompositingContainer(layer);
didPushOverlapContainer = true;
LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will composite, pushed container " << overlapMap);
computeExtent(overlapMap, layer, layerExtent);
currentState.ancestorHasTransformAnimation |= layerExtent.hasTransformAnimation;
// Too hard to compute animated bounds if both us and some ancestor is animating transform.
layerExtent.animationCausesExtentUncertainty |= layerExtent.hasTransformAnimation && compositingState.ancestorHasTransformAnimation;
} else if (layerPaintsIntoProvidedBacking) {
overlapMap.pushCompositingContainer(layer);
currentState.backingSharingAncestor = &layer;
didPushOverlapContainer = true;
LOG_WITH_STREAM(CompositingOverlap, stream << "unchangedSubtree: layer " << &layer << " will share, pushed container " << overlapMap);
}
auto backingSharingSnapshot = updateBackingSharingBeforeDescendantTraversal(backingSharingState, treeDepth, overlapMap, layer, layerExtent, layerIsComposited, compositingState.stackingContextAncestor);
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(layer);
#endif
if (!canSkipComputeCompositingRequirementsForSubtree(layer, layerIsComposited)) {
for (auto* childLayer : layer.negativeZOrderLayers()) {
traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState);
if (currentState.subtreeIsCompositing)
ASSERT(layerIsComposited);
}
for (auto* childLayer : layer.normalFlowLayers())
traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState);
for (auto* childLayer : layer.positiveZOrderLayers())
traverseUnchangedSubtree(&layer, *childLayer, overlapMap, currentState, backingSharingState);
// Set the flag to say that this layer has compositing children.
ASSERT(layer.hasCompositingDescendant() == currentState.subtreeIsCompositing);
ASSERT_IMPLIES(canBeComposited(layer) && clipsCompositingDescendants(layer), layerIsComposited);
}
ASSERT(!currentState.fullPaintOrderTraversalRequired);
compositingState.updateWithDescendantStateAndLayer(currentState, layer, ancestorLayer, layerExtent, true);
updateBackingSharingAfterDescendantTraversal(backingSharingState, treeDepth, overlapMap, layer, layerExtent, compositingState.stackingContextAncestor, backingSharingSnapshot);
bool layerContributesToOverlap = (currentState.compositingAncestor && !currentState.compositingAncestor->isRenderViewLayer()) || currentState.backingSharingAncestor;
updateOverlapMap(overlapMap, layer, layerExtent, didPushOverlapContainer, layerContributesToOverlap);
overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
ASSERT(!layer.needsCompositingRequirementsTraversal());
}
void RenderLayerCompositor::collectViewTransitionNewContentLayers(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childList)
{
if (layer.renderer().style().pseudoElementType() != PseudoId::ViewTransitionNew || !layer.hasVisibleContent())
return;
if (!downcast<RenderViewTransitionCapture>(layer.renderer()).canUseExistingLayers())
return;
RefPtr activeViewTransition = layer.renderer().protectedDocument()->activeViewTransition();
if (!activeViewTransition)
return;
auto* capturedElement = activeViewTransition->namedElements().find(layer.renderer().style().pseudoElementNameArgument());
if (!capturedElement)
return;
auto newStyleable = capturedElement->newElement.styleable();
if (!newStyleable)
return;
auto* capturedRenderer = newStyleable->renderer();
if (!capturedRenderer || !capturedRenderer->hasLayer())
return;
if (capturedRenderer->isDocumentElementRenderer()) {
capturedRenderer = &capturedRenderer->view();
ASSERT(capturedRenderer->hasLayer());
}
auto& modelObject = downcast<RenderLayerModelObject>(*capturedRenderer);
if (RenderLayerBacking* backing = modelObject.layer()->backing())
childList.append(Ref { *backing->childForSuperlayersExcludingViewTransitions() });
}
void RenderLayerCompositor::updateBackingAndHierarchy(RenderLayer& layer, Vector<Ref<GraphicsLayer>>& childLayersOfEnclosingLayer, UpdateBackingTraversalState& traversalState, ScrollingTreeState& scrollingTreeState, OptionSet<UpdateLevel> updateLevel)
{
layer.updateDescendantDependentFlags();
layer.updateLayerListsIfNeeded();
bool layerNeedsUpdate = !updateLevel.isEmpty();
if (layer.descendantsNeedUpdateBackingAndHierarchyTraversal())
updateLevel.add(UpdateLevel::AllDescendants);
ScrollingTreeState scrollingStateForDescendants = scrollingTreeState;
UpdateBackingTraversalState traversalStateForDescendants = traversalState.stateForDescendants();
Vector<RenderLayer*> layersClippedByScrollers;
Vector<RenderLayer*> compositedOverflowScrollLayers;
if (layer.needsScrollingTreeUpdate())
scrollingTreeState.needSynchronousScrollingReasonsUpdate = true;
auto* layerBacking = layer.backing();
if (layerBacking) {
updateLevel.remove(UpdateLevel::CompositedChildren);
// We updated the composited bounds in RenderLayerBacking::updateAfterLayout(), but it may have changed
// based on which descendants are now composited.
if (layerBacking->updateCompositedBounds()) {
layer.setNeedsCompositingGeometryUpdate();
// Our geometry can affect descendants.
updateLevel.add(UpdateLevel::CompositedChildren);
}
if (layerNeedsUpdate || layer.needsCompositingConfigurationUpdate()) {
if (layerBacking->updateConfiguration(traversalState.compositingAncestor)) {
layerNeedsUpdate = true; // We also need to update geometry.
layer.setNeedsCompositingLayerConnection();
}
layerBacking->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
}
OptionSet<ScrollingNodeChangeFlags> scrollingNodeChanges = { ScrollingNodeChangeFlags::Layer };
if (layerNeedsUpdate || layer.needsCompositingGeometryUpdate()) {
layerBacking->updateGeometry(traversalState.compositingAncestor);
scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
} else if (layer.needsScrollingTreeUpdate())
scrollingNodeChanges.add(ScrollingNodeChangeFlags::LayerGeometry);
if (auto* reflection = layer.reflectionLayer()) {
if (auto* reflectionBacking = reflection->backing()) {
reflectionBacking->updateCompositedBounds();
reflectionBacking->updateGeometry(&layer);
reflectionBacking->updateAfterDescendants();
}
}
if (!layer.parent())
updateRootLayerPosition();
// FIXME: do based on dirty flags. Need to do this for changes of geometry, configuration and hierarchy.
// Need to be careful to do the right thing when a scroll-coordinated layer loses a scroll-coordinated ancestor.
scrollingStateForDescendants.parentNodeID = updateScrollCoordinationForLayer(layer, traversalState.compositingAncestor, scrollingTreeState, scrollingNodeChanges);
scrollingStateForDescendants.hasParent = true;
scrollingStateForDescendants.nextChildIndex = 0;
traversalStateForDescendants.compositingAncestor = &layer;
traversalStateForDescendants.layersClippedByScrollers = &layersClippedByScrollers;
traversalStateForDescendants.overflowScrollLayers = &compositedOverflowScrollLayers;
#if !LOG_DISABLED
logLayerInfo(layer, "updateBackingAndHierarchy"_s, traversalState.depth);
#endif
}
if (layer.childrenNeedCompositingGeometryUpdate())
updateLevel.add(UpdateLevel::CompositedChildren);
// If this layer has backing, then we are collecting its children, otherwise appending
// to the compositing child list of an enclosing layer.
Vector<Ref<GraphicsLayer>> layerChildren;
auto& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
bool requireDescendantTraversal = layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal()
|| (layer.hasCompositingDescendant() && (!layerBacking || layer.needsCompositingLayerConnection() || !updateLevel.isEmpty()));
bool requiresChildRebuild = layerBacking && layer.needsCompositingLayerConnection() && !layer.hasCompositingDescendant();
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(layer);
#endif
auto appendForegroundLayerIfNecessary = [&] {
// If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
if (layer.negativeZOrderLayers().size()) {
if (layerBacking && layerBacking->foregroundLayer())
childList.append(Ref { *layerBacking->foregroundLayer() });
}
};
if (requireDescendantTraversal) {
for (auto* renderLayer : layer.negativeZOrderLayers())
updateBackingAndHierarchy(*renderLayer, childList, traversalStateForDescendants, scrollingStateForDescendants, updateLevel);
appendForegroundLayerIfNecessary();
for (auto* renderLayer : layer.normalFlowLayers())
updateBackingAndHierarchy(*renderLayer, childList, traversalStateForDescendants, scrollingStateForDescendants, updateLevel);
for (auto* renderLayer : layer.positiveZOrderLayers())
updateBackingAndHierarchy(*renderLayer, childList, traversalStateForDescendants, scrollingStateForDescendants, updateLevel);
// Pass needSynchronousScrollingReasonsUpdate back up.
scrollingTreeState.needSynchronousScrollingReasonsUpdate |= scrollingStateForDescendants.needSynchronousScrollingReasonsUpdate;
if (scrollingTreeState.parentNodeID == scrollingStateForDescendants.parentNodeID)
scrollingTreeState.nextChildIndex = scrollingStateForDescendants.nextChildIndex;
} else if (requiresChildRebuild)
appendForegroundLayerIfNecessary();
if (layerBacking) {
if (requireDescendantTraversal || requiresChildRebuild) {
WidgetLayerAttachment widgetLayerAttachment;
if (auto* renderWidget = dynamicDowncast<RenderWidget>(layer.renderer()))
widgetLayerAttachment = attachWidgetContentLayersIfNecessary(*renderWidget);
collectViewTransitionNewContentLayers(layer, childList);
if (!widgetLayerAttachment.widgetLayersAttachedAsChildren) {
// If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
// Otherwise, the overflow control layers are normal children.
if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
if (RefPtr overflowControlLayer = layerBacking->overflowControlsContainer())
layerChildren.append(*overflowControlLayer);
}
adjustOverflowScrollbarContainerLayers(layer, compositedOverflowScrollLayers, layersClippedByScrollers, layerChildren);
RefPtr { layerBacking->parentForSublayers() }->setChildren(WTFMove(layerChildren));
}
}
// Layers that are captured in a view transition get manually parented to their pseudo in collectViewTransitionNewContentLayers.
// The view transition root (when the document element is captured) gets parented in RenderLayerBacking::childForSuperlayers.
bool skipAddToEnclosing = layer.renderer().capturedInViewTransition() && !layer.renderer().isDocumentElementRenderer();
if (layer.renderer().isViewTransitionRoot() && layer.renderer().protectedDocument()->activeViewTransitionCapturedDocumentElement())
skipAddToEnclosing = true;
if (!skipAddToEnclosing)
childLayersOfEnclosingLayer.append(Ref { *layerBacking->childForSuperlayers() });
if (layerBacking->hasAncestorClippingLayers() && layerBacking->ancestorClippingStack()->hasAnyScrollingLayers())
traversalState.layersClippedByScrollers->append(&layer);
if (layer.hasCompositedScrollableOverflow())
traversalState.overflowScrollLayers->append(&layer);
layerBacking->updateAfterDescendants();
}
layer.clearUpdateBackingOrHierarchyTraversalState();
}
std::optional<RenderLayerCompositor::BackingSharingSnapshot> RenderLayerCompositor::updateBackingSharingBeforeDescendantTraversal(BackingSharingState& sharingState, unsigned depth, const LayerOverlapMap& overlapMap, RenderLayer& layer, OverlapExtent& layerExtent, bool willBeComposited, RenderLayer* stackingContextAncestor)
{
UNUSED_PARAM(depth);
layer.setBackingProviderLayer(nullptr);
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(depth * 2, ' ') << &layer << " updateBackingSharingBeforeDescendantTraversal - will be composited " << willBeComposited);
auto shouldEndSharingSequence = [&] {
if (!sharingState.backingSharingStackingContext())
return false;
if (!willBeComposited)
return false;
// If this layer is composited, we can only continue the sequence if it's a new provider candidate.
computeExtent(overlapMap, layer, layerExtent);
return !sharingState.isAdditionalProviderCandidate(layer, layerExtent.bounds, stackingContextAncestor);
}();
// A layer that composites resets backing-sharing, since subsequent layers need to composite to overlap it.
if (shouldEndSharingSequence) {
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(depth * 2, ' ') << " - ending sharing sequence on " << sharingState.backingProviderCandidates());
sharingState.endBackingSharingSequence(layer);
}
return sharingState.snapshot();
}
void RenderLayerCompositor::updateBackingSharingAfterDescendantTraversal(BackingSharingState& sharingState, unsigned depth, const LayerOverlapMap& overlapMap, RenderLayer& layer, OverlapExtent& layerExtent, RenderLayer* stackingContextAncestor, const std::optional<BackingSharingSnapshot>& backingSharingSnapshot)
{
UNUSED_PARAM(depth);
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(depth * 2, ' ') << &layer << " updateBackingSharingAfterDescendantTraversal for layer - is composited " << layer.isComposited() << " has composited descendant " << layer.hasCompositingDescendant());
if (layer.isComposited()) {
// If this layer is being composited, clean up sharing-related state.
layer.disconnectFromBackingProviderLayer();
for (auto& candidate : sharingState.backingProviderCandidates())
candidate.sharingLayers.remove(layer);
}
// Backing sharing is constrained to layers in the same stacking context.
if (&layer == sharingState.backingSharingStackingContext()) {
ASSERT(!sharingState.backingProviderCandidates().containsIf([&](auto& candidate) { return candidate.providerLayer == &layer; }));
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(depth * 2, ' ') << " - end of stacking context for backing provider " << sharingState.backingProviderCandidates());
sharingState.endBackingSharingSequence(layer);
if (layer.isComposited())
layer.backing()->clearBackingSharingLayers();
return;
}
if (!layer.isComposited())
return;
if (!stackingContextAncestor)
return;
bool canBeBackingProvider = !layer.hasCompositingDescendant();
if (canBeBackingProvider) {
if (!sharingState.backingSharingStackingContext()) {
computeExtent(overlapMap, layer, layerExtent);
sharingState.startBackingSharingSequence(layer, layerExtent.bounds, *stackingContextAncestor);
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(depth * 2, ' ') << " - started sharing sequence with provider candidate " << &layer);
return;
}
computeExtent(overlapMap, layer, layerExtent);
if (sharingState.isAdditionalProviderCandidate(layer, layerExtent.bounds, stackingContextAncestor)) {
sharingState.addBackingSharingCandidate(layer, layerExtent.bounds, *stackingContextAncestor, backingSharingSnapshot);
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(depth * 2, ' ') << " - added additional provider candidate " << &layer);
return;
}
}
layer.backing()->clearBackingSharingLayers();
LOG_WITH_STREAM(Compositing, stream << TextStream::Repeat(depth * 2, ' ') << " - is composited; maybe ending existing backing sequence with candidates " << sharingState.backingProviderCandidates() << " stacking context " << sharingState.backingSharingStackingContext());
// A layer that composites resets backing-sharing, since subsequent layers need to composite to overlap it. If a descendant didn't already end the sharing sequence that was current when processing of this layer started, end it now.
if (backingSharingSnapshot && backingSharingSnapshot->sequenceIdentifier == sharingState.sequenceIdentifier())
sharingState.endBackingSharingSequence(layer);
}
// Finds the set of overflow:scroll layers whose overflow controls hosting layer needs to be reparented,
// to ensure that the scrollbars show on top of positioned content inside the scroller.
void RenderLayerCompositor::adjustOverflowScrollbarContainerLayers(RenderLayer& stackingContextLayer, const Vector<RenderLayer*>& overflowScrollLayers, const Vector<RenderLayer*>& layersClippedByScrollers, Vector<Ref<GraphicsLayer>>& layerChildren)
{
if (layersClippedByScrollers.isEmpty())
return;
UncheckedKeyHashMap<CheckedPtr<RenderLayer>, CheckedPtr<RenderLayer>> overflowScrollToLastContainedLayerMap;
for (auto* clippedLayer : layersClippedByScrollers) {
auto* clippingStack = clippedLayer->backing()->ancestorClippingStack();
for (const auto& stackEntry : clippingStack->stack()) {
if (!stackEntry.clipData.isOverflowScroll)
continue;
if (auto* layer = stackEntry.clipData.clippingLayer.get())
overflowScrollToLastContainedLayerMap.set(layer, clippedLayer);
}
}
for (auto* overflowScrollingLayer : overflowScrollLayers) {
auto it = overflowScrollToLastContainedLayerMap.find(overflowScrollingLayer);
if (it == overflowScrollToLastContainedLayerMap.end())
continue;
CheckedPtr lastContainedDescendant = it->value;
if (!lastContainedDescendant || !lastContainedDescendant->isComposited())
continue;
auto* lastContainedDescendantBacking = lastContainedDescendant->backing();
auto* overflowBacking = overflowScrollingLayer->backing();
if (!overflowBacking)
continue;
RefPtr overflowContainerLayer = overflowBacking->overflowControlsContainer();
if (!overflowContainerLayer)
continue;
overflowContainerLayer->removeFromParent();
if (overflowBacking->hasAncestorClippingLayers())
overflowBacking->ensureOverflowControlsHostLayerAncestorClippingStack(&stackingContextLayer);
if (auto* overflowControlsAncestorClippingStack = overflowBacking->overflowControlsHostLayerAncestorClippingStack()) {
RefPtr { overflowControlsAncestorClippingStack->lastLayer() }->setChildren({ Ref { *overflowContainerLayer } });
overflowContainerLayer = overflowControlsAncestorClippingStack->firstLayer();
}
RefPtr lastDescendantGraphicsLayer = lastContainedDescendantBacking->childForSuperlayers();
RefPtr overflowScrollerGraphicsLayer = overflowBacking->childForSuperlayers();
std::optional<size_t> lastDescendantLayerIndex;
std::optional<size_t> scrollerLayerIndex;
for (size_t i = 0; i < layerChildren.size(); ++i) {
const RefPtr graphicsLayer = layerChildren[i].ptr();
if (graphicsLayer == lastDescendantGraphicsLayer)
lastDescendantLayerIndex = i;
else if (graphicsLayer == overflowScrollerGraphicsLayer)
scrollerLayerIndex = i;
}
if (lastDescendantLayerIndex && scrollerLayerIndex) {
auto insertionIndex = std::max(lastDescendantLayerIndex.value() + 1, scrollerLayerIndex.value() + 1);
LOG_WITH_STREAM(Compositing, stream << "Moving overflow controls layer for " << *overflowScrollingLayer << " to appear after " << *lastContainedDescendant);
layerChildren.insert(insertionIndex, *overflowContainerLayer);
}
overflowBacking->adjustOverflowControlsPositionRelativeToAncestor(stackingContextLayer);
}
}
void RenderLayerCompositor::appendDocumentOverlayLayers(Vector<Ref<GraphicsLayer>>& childList)
{
if (!isRootFrameCompositor() || !m_compositing)
return;
if (!page().pageOverlayController().hasDocumentOverlays())
return;
Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
childList.append(WTFMove(overlayHost));
}
bool RenderLayerCompositor::needsCompositingForContentOrOverlays() const
{
return m_contentLayersCount + page().pageOverlayController().overlayCount();
}
void RenderLayerCompositor::layerBecameComposited(const RenderLayer& layer)
{
if (&layer != m_renderView.layer())
++m_contentLayersCount;
}
void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer& layer)
{
// Inform the inspector that the given RenderLayer was destroyed.
// FIXME: "destroyed" is a misnomer.
InspectorInstrumentation::renderLayerDestroyed(protectedPage().ptr(), layer);
if (&layer != m_renderView.layer()) {
ASSERT(m_contentLayersCount > 0);
--m_contentLayersCount;
}
}
#if !LOG_DISABLED
void RenderLayerCompositor::logLayerInfo(const RenderLayer& layer, ASCIILiteral phase, int depth)
{
if (!compositingLogEnabled())
return;
auto* backing = layer.backing();
RequiresCompositingData queryData;
if (requiresCompositingLayer(layer, queryData) || layer.isRenderViewLayer()) {
++m_obligateCompositedLayerCount;
m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
} else {
++m_secondaryCompositedLayerCount;
m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
}
LayoutRect absoluteBounds = backing->compositedBounds();
absoluteBounds.move(layer.offsetFromAncestor(m_renderView.layer()));
StringBuilder logString;
logString.append(pad(' ', 12 + depth * 2, hex(reinterpret_cast<uintptr_t>(&layer), Lowercase)), " id "_s, backing->graphicsLayer()->primaryLayerID() ? backing->graphicsLayer()->primaryLayerID()->object().toUInt64() : 0, " ("_s, absoluteBounds.x().toFloat(), ',', absoluteBounds.y().toFloat(), '-', absoluteBounds.maxX().toFloat(), ',', absoluteBounds.maxY().toFloat(), ") "_s, FormattedNumber::fixedWidth(backing->backingStoreMemoryEstimate() / 1024, 2), "KB"_s);
if (!layer.renderer().style().hasAutoUsedZIndex())
logString.append(" z-index: "_s, layer.renderer().style().usedZIndex());
logString.append(" ("_s, logOneReasonForCompositing(layer), ") "_s);
if (backing->graphicsLayer()->contentsOpaque() || backing->paintsIntoCompositedAncestor() || backing->foregroundLayer() || backing->backgroundLayer()) {
logString.append('[');
auto prefix = ""_s;
if (backing->graphicsLayer()->contentsOpaque()) {
logString.append("opaque"_s);
prefix = ", "_s;
}
if (backing->paintsIntoCompositedAncestor()) {
logString.append(prefix, "paints into ancestor"_s);
prefix = ", "_s;
}
if (backing->foregroundLayer() || backing->backgroundLayer()) {
if (backing->foregroundLayer() && backing->backgroundLayer()) {
logString.append(prefix, "+foreground+background"_s);
prefix = ", "_s;
} else if (backing->foregroundLayer()) {
logString.append(prefix, "+foreground"_s);
prefix = ", "_s;
} else {
logString.append(prefix, "+background"_s);
prefix = ", "_s;
}
}
logString.append("] "_s);
}
logString.append(layer.name(), " - "_s, phase);
LOG(Compositing, "%s", logString.toString().utf8().data());
}
#endif
static bool clippingChanged(const RenderStyle& oldStyle, const RenderStyle& newStyle)
{
return oldStyle.overflowX() != newStyle.overflowX() || oldStyle.overflowY() != newStyle.overflowY()
|| oldStyle.hasClip() != newStyle.hasClip() || oldStyle.clip() != newStyle.clip();
}
static bool styleAffectsLayerGeometry(const RenderStyle& style)
{
return style.hasClip() || style.clipPath() || style.hasBorderRadius();
}
static bool recompositeChangeRequiresGeometryUpdate(const RenderStyle& oldStyle, const RenderStyle& newStyle)
{
return oldStyle.transform() != newStyle.transform()
|| oldStyle.translate() != newStyle.translate()
|| oldStyle.scale() != newStyle.scale()
|| oldStyle.rotate() != newStyle.rotate()
|| oldStyle.transformBox() != newStyle.transformBox()
|| oldStyle.transformOriginX() != newStyle.transformOriginX()
|| oldStyle.transformOriginY() != newStyle.transformOriginY()
|| oldStyle.transformOriginZ() != newStyle.transformOriginZ()
|| oldStyle.usedTransformStyle3D() != newStyle.usedTransformStyle3D()
|| oldStyle.perspective() != newStyle.perspective()
|| oldStyle.perspectiveOriginX() != newStyle.perspectiveOriginX()
|| oldStyle.perspectiveOriginY() != newStyle.perspectiveOriginY()
|| oldStyle.backfaceVisibility() != newStyle.backfaceVisibility()
|| !arePointingToEqualData(oldStyle.offsetPath(), newStyle.offsetPath())
|| oldStyle.offsetAnchor() != newStyle.offsetAnchor()
|| oldStyle.offsetPosition() != newStyle.offsetPosition()
|| oldStyle.offsetDistance() != newStyle.offsetDistance()
|| oldStyle.offsetRotate() != newStyle.offsetRotate()
|| !arePointingToEqualData(oldStyle.clipPath(), newStyle.clipPath())
|| oldStyle.overscrollBehaviorX() != newStyle.overscrollBehaviorX()
|| oldStyle.overscrollBehaviorY() != newStyle.overscrollBehaviorY();
}
static bool recompositeChangeRequiresChildrenGeometryUpdate(const RenderStyle& oldStyle, const RenderStyle& newStyle)
{
return oldStyle.hasPerspective() != newStyle.hasPerspective()
|| oldStyle.usedTransformStyle3D() != newStyle.usedTransformStyle3D();
}
void RenderLayerCompositor::layerGainedCompositedScrollableOverflow(RenderLayer& layer)
{
RequiresCompositingData queryData;
queryData.layoutUpToDate = LayoutUpToDate::No;
bool layerChanged = updateBacking(layer, queryData, nullptr, BackingRequired::Yes);
if (layerChanged) {
layer.compositingStatusChanged(queryData.layoutUpToDate);
if (!layer.isComposited())
repaintOnCompositingChange(layer);
layer.setChildrenNeedCompositingGeometryUpdate();
layer.setNeedsCompositingLayerConnection();
layer.setSubsequentLayersNeedCompositingRequirementsTraversal();
// Ancestor layers that composited for indirect reasons (things listed in styleChangeMayAffectIndirectCompositingReasons()) need to get updated.
// This could be optimized by only setting this flag on layers with the relevant styles.
layer.setNeedsPostLayoutCompositingUpdateOnAncestors();
}
auto* backing = layer.backing();
if (!backing)
return;
backing->updateConfigurationAfterStyleChange();
}
void RenderLayerCompositor::layerStyleChanged(StyleDifference diff, RenderLayer& layer, const RenderStyle* oldStyle)
{
if (diff == StyleDifference::Equal)
return;
// Create or destroy backing here so that code that runs during layout can reliably use isComposited() (though this
// is only true for layers composited for direct reasons).
// Also, it allows us to avoid a tree walk in updateCompositingLayers() when no layer changed its compositing state.
RequiresCompositingData queryData;
queryData.layoutUpToDate = LayoutUpToDate::No;
bool layerChanged = updateBacking(layer, queryData);
if (layerChanged) {
layer.compositingStatusChanged(queryData.layoutUpToDate);
if (!layer.isComposited())
repaintOnCompositingChange(layer);
layer.setChildrenNeedCompositingGeometryUpdate();
layer.setNeedsCompositingLayerConnection();
layer.setSubsequentLayersNeedCompositingRequirementsTraversal();
// Ancestor layers that composited for indirect reasons (things listed in styleChangeMayAffectIndirectCompositingReasons()) need to get updated.
// This could be optimized by only setting this flag on layers with the relevant styles.
layer.setNeedsPostLayoutCompositingUpdateOnAncestors();
}
layer.setIntrinsicallyComposited(queryData.intrinsic);
if (queryData.reevaluateAfterLayout)
layer.setNeedsPostLayoutCompositingUpdate();
const auto& newStyle = layer.renderer().style();
if (hasContentCompositingLayers()) {
if (diff >= StyleDifference::LayoutPositionedMovementOnly) {
layer.setNeedsPostLayoutCompositingUpdate();
layer.setNeedsCompositingGeometryUpdate();
}
if (diff >= StyleDifference::Layout) {
// FIXME: only set flags here if we know we have a composited descendant, but we might not know at this point.
if (oldStyle && clippingChanged(*oldStyle, newStyle)) {
if (layer.isStackingContext()) {
layer.setNeedsPostLayoutCompositingUpdate(); // Layer needs to become composited if it has composited descendants.
layer.setNeedsCompositingConfigurationUpdate(); // If already composited, layer needs to create/destroy clipping layer.
layer.setChildrenNeedCompositingGeometryUpdate(); // Clipping layers on this layer affect descendant layer geometry.
} else {
// Descendant (in containing block order) compositing layers need to re-evaluate their clipping,
// but they might be siblings in z-order so go up to our stacking context.
if (auto* stackingContext = layer.stackingContext())
stackingContext->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
}
}
// This ensures that the viewport anchor layer will be updated when updating compositing layers upon style change
auto styleChangeAffectsAnchorLayer = [](const RenderStyle* oldStyle, const RenderStyle& newStyle) {
if (!oldStyle)
return false;
return oldStyle->hasViewportConstrainedPosition() != newStyle.hasViewportConstrainedPosition();
};
if (styleChangeAffectsAnchorLayer(oldStyle, newStyle))
layer.setNeedsCompositingConfigurationUpdate();
// These properties trigger compositing if some descendant is composited.
if (oldStyle && styleChangeMayAffectIndirectCompositingReasons(*oldStyle, newStyle))
layer.setNeedsPostLayoutCompositingUpdate();
layer.setNeedsCompositingGeometryUpdate();
}
}
if (diff >= StyleDifference::Repaint && oldStyle) {
// This ensures that we update border-radius clips on layers that are descendants in containing-block order but not paint order. This is necessary even when
// the current layer is not composited.
bool changeAffectsClippingOfNonPaintOrderDescendants = !layer.isStackingContext() && layer.renderer().hasNonVisibleOverflow() && oldStyle->border() != newStyle.border();
if (changeAffectsClippingOfNonPaintOrderDescendants) {
if (auto* parent = layer.paintOrderParent())
parent->setChildrenNeedCompositingGeometryUpdate();
}
}
auto* backing = layer.backing();
if (!backing)
return;
#if HAVE(CORE_ANIMATION_SEPARATED_LAYERS)
auto styleChangeAffectsSeparatedProperties = [](const RenderStyle* oldStyle, const RenderStyle& newStyle) {
if (!oldStyle)
return newStyle.usedTransformStyle3D() == TransformStyle3D::Separated;
return oldStyle->usedTransformStyle3D() != newStyle.usedTransformStyle3D()
&& (oldStyle->usedTransformStyle3D() == TransformStyle3D::Separated
|| newStyle.usedTransformStyle3D() == TransformStyle3D::Separated);
};
// We need a full compositing configuration update since this also impacts the clipping strategy.
if (styleChangeAffectsSeparatedProperties(oldStyle, newStyle))
layer.setNeedsCompositingConfigurationUpdate();
#endif
backing->updateConfigurationAfterStyleChange();
if (diff >= StyleDifference::Repaint) {
// Visibility change may affect geometry of the enclosing composited layer.
if (oldStyle && oldStyle->usedVisibility() != newStyle.usedVisibility())
layer.setNeedsCompositingGeometryUpdate();
// We'll get a diff of Repaint when things like clip-path change; these might affect layer or inner-layer geometry.
if (layer.isComposited() && oldStyle) {
if (styleAffectsLayerGeometry(*oldStyle) || styleAffectsLayerGeometry(newStyle))
layer.setNeedsCompositingGeometryUpdate();
}
// image rendering mode can determine whether we use device pixel ratio for the backing store.
if (oldStyle && oldStyle->imageRendering() != newStyle.imageRendering())
layer.setNeedsCompositingConfigurationUpdate();
}
if (diff >= StyleDifference::RecompositeLayer) {
if (layer.isComposited()) {
bool hitTestingStateChanged = oldStyle && (oldStyle->usedPointerEvents() != newStyle.usedPointerEvents());
if (is<RenderWidget>(layer.renderer()) || hitTestingStateChanged) {
// For RenderWidgets this is necessary to get iframe layers hooked up in response to scheduleInvalidateStyleAndLayerComposition().
layer.setNeedsCompositingConfigurationUpdate();
}
// If we're changing to/from 0 opacity, then we need to reconfigure the layer since we try to
// skip backing store allocation for opacity:0.
if (oldStyle && oldStyle->opacity() != newStyle.opacity() && (!oldStyle->opacity() || !newStyle.opacity()))
layer.setNeedsCompositingConfigurationUpdate();
}
if (oldStyle && recompositeChangeRequiresGeometryUpdate(*oldStyle, newStyle)) {
// FIXME: transform changes really need to trigger layout. See RenderElement::adjustStyleDifference().
layer.setNeedsPostLayoutCompositingUpdate();
layer.setNeedsCompositingGeometryUpdate();
}
if (oldStyle && recompositeChangeRequiresChildrenGeometryUpdate(*oldStyle, newStyle))
layer.setChildrenNeedCompositingGeometryUpdate();
}
}
void RenderLayerCompositor::establishesTopLayerWillChangeForLayer(RenderLayer& layer)
{
clearBackingProviderSequencesInStackingContextOfLayer(layer);
}
// This is a recursive walk similar to RenderLayer::collectLayers().
static void clearBackingSharingWithinStackingContext(RenderLayer& stackingContextRoot, RenderLayer& curLayer)
{
if (curLayer.establishesTopLayer())
return;
if (&curLayer != &stackingContextRoot && curLayer.isStackingContext())
return;
for (auto* child = curLayer.firstChild(); child; child = child->nextSibling()) {
if (child->isComposited())
child->backing()->clearBackingSharingLayers();
if (!curLayer.isReflectionLayer(*child))
clearBackingSharingWithinStackingContext(stackingContextRoot, *child);
}
}
void RenderLayerCompositor::clearBackingProviderSequencesInStackingContextOfLayer(RenderLayer& layer)
{
// We can't rely on z-order lists to be up-to-date here. For fullscreen, we may already have done a style update which dirties them.
if (auto* stackingContextLayer = layer.stackingContext())
clearBackingSharingWithinStackingContext(*stackingContextLayer, *stackingContextLayer);
}
// FIXME: remove and never ask questions about reflection layers.
static RenderLayerModelObject& rendererForCompositingTests(const RenderLayer& layer)
{
auto* renderer = &layer.renderer();
// The compositing state of a reflection should match that of its reflected layer.
if (layer.isReflection())
renderer = downcast<RenderLayerModelObject>(renderer->parent()); // The RenderReplica's parent is the object being reflected.
return *renderer;
}
void RenderLayerCompositor::updateRootContentLayerClipping()
{
RefPtr { m_rootContentsLayer }->setMasksToBounds(!m_renderView.settings().backgroundShouldExtendBeyondPage());
}
bool RenderLayerCompositor::updateBacking(RenderLayer& layer, RequiresCompositingData& queryData, BackingSharingState* backingSharingState, BackingRequired backingRequired)
{
bool layerChanged = false;
if (backingRequired == BackingRequired::Unknown)
backingRequired = needsToBeComposited(layer, queryData) ? BackingRequired::Yes : BackingRequired::No;
else {
// Need to fetch viewportConstrainedNotCompositedReason, but without doing all the work that needsToBeComposited does.
requiresCompositingForPosition(rendererForCompositingTests(layer), layer, queryData);
}
auto repaintTargetsSharedBacking = [&](RenderLayer& layer) {
return backingSharingState && layerRepaintTargetsBackingSharingLayer(layer, *backingSharingState);
};
auto repaintLayer = [&](RenderLayer& layer) {
if (repaintTargetsSharedBacking(layer)) {
LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " needs to repaint into potential backing-sharing layer, postponing repaint");
backingSharingState->addLayerNeedingRepaint(layer);
} else
repaintOnCompositingChange(layer);
};
if (backingRequired == BackingRequired::Yes) {
// If we need to repaint, do so before making backing and disconnecting from the backing provider layer.
if (!layer.backing())
repaintLayer(layer);
layer.disconnectFromBackingProviderLayer();
enableCompositingMode();
if (!layer.backing()) {
layer.ensureBacking();
if (layer.isRenderViewLayer() && useCoordinatedScrollingForLayer(layer)) {
Ref frameView = m_renderView.frameView();
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(frameView);
#if HAVE(RUBBER_BANDING)
updateLayerForHeader(frameView->headerHeight());
updateLayerForFooter(frameView->footerHeight());
#endif
updateRootContentLayerClipping();
if (auto* tiledBacking = layer.backing()->tiledBacking())
tiledBacking->setObscuredContentInsets(frameView->obscuredContentInsets());
}
layer.setNeedsCompositingGeometryUpdate();
layer.setNeedsCompositingConfigurationUpdate();
layer.setNeedsCompositingPaintOrderChildrenUpdate();
layerChanged = true;
}
} else {
if (layer.backing()) {
// If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
// its replica GraphicsLayer. In practice this should never happen because reflectee and reflection
// are both either composited, or not composited.
if (layer.isReflection()) {
auto* sourceLayer = downcast<RenderLayerModelObject>(*layer.renderer().parent()).layer();
if (auto* backing = sourceLayer->backing()) {
ASSERT(backing->graphicsLayer()->replicaLayer() == layer.backing()->graphicsLayer());
RefPtr { backing->graphicsLayer() }->setReplicatedByLayer(nullptr);
}
}
layer.clearBacking();
layerChanged = true;
// If we need to repaint, do so now that we've removed the backing.
repaintLayer(layer);
}
}
#if ENABLE(VIDEO)
if (layerChanged) {
if (CheckedPtr renderVideo = dynamicDowncast<RenderVideo>(layer.renderer())) {
// If it's a video, give the media player a chance to hook up to the layer.
renderVideo->acceleratedRenderingStateChanged();
}
}
#endif
if (layerChanged) {
if (RefPtr renderWidget = dynamicDowncast<RenderWidget>(layer.renderer())) {
auto* innerCompositor = frameContentsCompositor(*renderWidget);
if (innerCompositor && innerCompositor->usesCompositing())
innerCompositor->updateRootLayerAttachment();
}
}
if (layerChanged)
layer.clearClipRectsIncludingDescendants(PaintingClipRects);
// If a fixed position layer gained/lost a backing or the reason not compositing it changed,
// the scrolling coordinator needs to recalculate whether it can do fast scrolling.
if (layer.renderer().isFixedPositioned()) {
if (layer.viewportConstrainedNotCompositedReason() != queryData.nonCompositedForPositionReason && !queryData.reevaluateAfterLayout) {
layer.setViewportConstrainedNotCompositedReason(queryData.nonCompositedForPositionReason);
layerChanged = true;
}
if (layerChanged) {
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView.protectedFrameView());
}
} else
layer.setViewportConstrainedNotCompositedReason(RenderLayer::NoNotCompositedReason);
if (layer.backing())
layer.backing()->updateDebugIndicators(m_showDebugBorders, m_showRepaintCounter);
return layerChanged;
}
bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer& layer, const RenderLayer* compositingAncestor, RequiresCompositingData& queryData, BackingSharingState& backingSharingState)
{
bool layerChanged = updateBacking(layer, queryData, &backingSharingState);
if (layerChanged) {
layer.compositingStatusChanged(queryData.layoutUpToDate);
if (!layer.isComposited())
repaintOnCompositingChange(layer);
}
// See if we need content or clipping layers. Methods called here should assume
// that the compositing state of descendant layers has not been updated yet.
if (layer.backing() && layer.backing()->updateConfiguration(compositingAncestor))
layerChanged = true;
return layerChanged;
}
void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer& layer)
{
// If the renderer is not attached yet, no need to repaint.
if (&layer.renderer() != &m_renderView && !layer.renderer().parent())
return;
CheckedPtr repaintContainer = layer.renderer().containerForRepaint().renderer;
if (!repaintContainer)
repaintContainer = &m_renderView;
layer.repaintIncludingNonCompositingDescendants(repaintContainer.get());
if (repaintContainer == &m_renderView) {
// The contents of this layer may be moving between the window
// and a GraphicsLayer, so we need to make sure the window system
// synchronizes those changes on the screen.
m_renderView.protectedFrameView()->setNeedsOneShotDrawingSynchronization();
}
}
// This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer& layer, const LayoutRect& rect)
{
auto* compositedAncestor = layer.enclosingCompositingLayerForRepaint(ExcludeSelf).layer;
if (!compositedAncestor)
return;
ASSERT(compositedAncestor->backing());
LayoutRect repaintRect = rect;
repaintRect.move(layer.offsetFromAncestor(compositedAncestor));
compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
// The contents of this layer may be moving from a GraphicsLayer to the window,
// so we need to make sure the window system synchronizes those changes on the screen.
if (compositedAncestor->isRenderViewLayer())
m_renderView.protectedFrameView()->setNeedsOneShotDrawingSynchronization();
}
void RenderLayerCompositor::layerWillBeRemoved(RenderLayer& parent, RenderLayer& child)
{
if (parent.renderer().renderTreeBeingDestroyed())
return;
if (child.isComposited())
repaintInCompositedAncestor(child, child.backing()->compositedBounds()); // FIXME: do via dirty bits?
else if (child.paintsIntoProvidedBacking()) {
auto* backingProviderLayer = child.backingProviderLayer();
// FIXME: Optimize this repaint.
backingProviderLayer->setBackingNeedsRepaint();
backingProviderLayer->backing()->removeBackingSharingLayer(child);
} else
return;
child.setNeedsCompositingLayerConnection();
}
RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer& layer) const
{
for (auto* parent = layer.parent(); parent; parent = parent->parent()) {
if (parent->isStackingContext())
return nullptr;
if (parent->renderer().hasClipOrNonVisibleOverflow())
return parent;
}
return nullptr;
}
void RenderLayerCompositor::computeExtent(const LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
{
if (extent.extentComputed)
return;
LayoutRect layerBounds;
if (extent.hasTransformAnimation)
extent.animationCausesExtentUncertainty = !layer.getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(layerBounds);
else
layerBounds = layer.overlapBounds();
// In the animating transform case, we avoid double-accounting for the transform because
// we told pushMappingsToAncestor() to ignore transforms earlier.
extent.bounds = enclosingLayoutRect(overlapMap.geometryMap().absoluteRect(layerBounds));
// Empty rects never intersect, but we need them to for the purposes of overlap testing.
if (extent.bounds.isEmpty())
extent.bounds.setSize(LayoutSize(1, 1));
RenderLayerModelObject& renderer = layer.renderer();
if (renderer.isFixedPositioned() && renderer.container() == &m_renderView) {
// Because fixed elements get moved around without re-computing overlap, we have to compute an overlap
// rect that covers all the locations that the fixed element could move to.
// FIXME: need to handle sticky too.
extent.bounds = m_renderView.protectedFrameView()->fixedScrollableAreaBoundsInflatedForScrolling(extent.bounds);
}
extent.extentComputed = true;
}
enum class AncestorTraversal { Continue, Stop };
// This is a simplified version of containing block walking that only handles absolute and fixed position.
template <typename Function>
static AncestorTraversal traverseAncestorLayers(const RenderLayer& layer, Function&& function)
{
auto positioningBehavior = layer.renderer().style().position();
RenderLayer* nextPaintOrderParent = layer.paintOrderParent();
for (const auto* ancestorLayer = layer.parent(); ancestorLayer; ancestorLayer = ancestorLayer->parent()) {
bool inContainingBlockChain = true;
switch (positioningBehavior) {
case PositionType::Static:
case PositionType::Relative:
case PositionType::Sticky:
break;
case PositionType::Absolute:
inContainingBlockChain = ancestorLayer->renderer().canContainAbsolutelyPositionedObjects();
break;
case PositionType::Fixed:
inContainingBlockChain = ancestorLayer->renderer().canContainFixedPositionObjects();
break;
}
if (function(*ancestorLayer, inContainingBlockChain, ancestorLayer == nextPaintOrderParent) == AncestorTraversal::Stop)
return AncestorTraversal::Stop;
if (inContainingBlockChain)
positioningBehavior = ancestorLayer->renderer().style().position();
if (ancestorLayer == nextPaintOrderParent)
nextPaintOrderParent = ancestorLayer->paintOrderParent();
}
return AncestorTraversal::Continue;
}
void RenderLayerCompositor::computeClippingScopes(const RenderLayer& layer, OverlapExtent& extent) const
{
if (extent.clippingScopesComputed)
return;
// FIXME: constrain the scopes (by composited stacking context ancestor I think).
auto populateEnclosingClippingScopes = [](const RenderLayer& layer, const RenderLayer& rootLayer, LayerOverlapMap::LayerAndBoundsVector& clippingScopes) {
auto createsClippingScope = [](const RenderLayer& layer) {
return layer.hasCompositedScrollableOverflow();
};
clippingScopes.append({ const_cast<RenderLayer&>(rootLayer), { } });
if (!layer.hasCompositedScrollingAncestor())
return;
traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool inContainingBlockChain, bool) {
if (inContainingBlockChain && createsClippingScope(ancestorLayer)) {
LayoutRect clipRect;
if (CheckedPtr box = dynamicDowncast<RenderBox>(ancestorLayer.renderer())) {
// FIXME: This is expensive. Broken with transforms.
LayoutPoint offsetFromRoot = ancestorLayer.convertToLayerCoords(&rootLayer, { });
clipRect = box->overflowClipRect(offsetFromRoot);
}
LayerOverlapMap::LayerAndBounds layerAndBounds { const_cast<RenderLayer&>(ancestorLayer), clipRect };
clippingScopes.insert(1, layerAndBounds); // Order is roots to leaves.
}
return AncestorTraversal::Continue;
});
};
populateEnclosingClippingScopes(layer, rootRenderLayer(), extent.clippingScopes);
extent.clippingScopesComputed = true;
}
LayoutRect RenderLayerCompositor::computeClippedOverlapBounds(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
{
computeExtent(overlapMap, layer, extent);
computeClippingScopes(layer, extent);
LayoutRect clipRect;
if (layer.hasCompositedScrollingAncestor()) {
// Compute a clip up to the composited scrolling ancestor, then convert it to absolute coordinates.
auto& scrollingScope = extent.clippingScopes.last();
auto& scopeLayer = scrollingScope.layer;
clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&scopeLayer, TemporaryClipRects, { })).rect();
if (!clipRect.isInfinite())
clipRect.setLocation(scopeLayer.convertToLayerCoords(&rootRenderLayer(), clipRect.location()));
} else
clipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(&rootRenderLayer(), AbsoluteClipRects)).rect(); // FIXME: Incorrect for CSS regions.
auto clippedBounds = extent.bounds;
if (!clipRect.isInfinite()) {
// With delegated page scaling, pageScaleFactor() is not applied by RenderView, so we should not scale here.
if (!page().delegatesScaling())
clipRect.scale(pageScaleFactor());
clippedBounds.intersect(clipRect);
}
return clippedBounds;
}
void RenderLayerCompositor::addToOverlapMap(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
{
if (layer.isRenderViewLayer())
return;
auto clippedBounds = computeClippedOverlapBounds(overlapMap, layer, extent);
computeClippingScopes(layer, extent);
overlapMap.add(layer, clippedBounds, extent.clippingScopes);
}
void RenderLayerCompositor::addDescendantsToOverlapMapRecursive(LayerOverlapMap& overlapMap, const RenderLayer& layer, const RenderLayer* ancestorLayer) const
{
if (!canBeComposited(layer))
return;
// A null ancestorLayer is an indication that 'layer' has already been pushed.
if (ancestorLayer) {
overlapMap.geometryMap().pushMappingsToAncestor(&layer, ancestorLayer);
OverlapExtent layerExtent;
addToOverlapMap(overlapMap, layer, layerExtent);
}
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
#endif
for (auto* renderLayer : layer.negativeZOrderLayers())
addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
for (auto* renderLayer : layer.normalFlowLayers())
addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
for (auto* renderLayer : layer.positiveZOrderLayers())
addDescendantsToOverlapMapRecursive(overlapMap, *renderLayer, &layer);
if (ancestorLayer)
overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
}
void RenderLayerCompositor::updateOverlapMap(LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& layerExtent, bool didPushContainer, bool addLayerToOverlap, bool addDescendantsToOverlap) const
{
if (addLayerToOverlap)
addToOverlapMap(overlapMap, layer, layerExtent);
if (addDescendantsToOverlap) {
// If this is the first non-root layer to composite, we need to add all the descendants we already traversed to the overlap map.
addDescendantsToOverlapMapRecursive(overlapMap, layer);
LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " composited post descendant traversal, added recursive " << overlapMap);
}
if (didPushContainer) {
overlapMap.popCompositingContainer(layer);
LOG_WITH_STREAM(CompositingOverlap, stream << "layer " << &layer << " is composited or shared, popped container " << overlapMap);
}
}
bool RenderLayerCompositor::layerOverlaps(const LayerOverlapMap& overlapMap, const RenderLayer& layer, OverlapExtent& extent) const
{
computeExtent(overlapMap, layer, extent);
computeClippingScopes(layer, extent);
return overlapMap.overlapsLayers(layer, extent.bounds, extent.clippingScopes);
}
#if ENABLE(VIDEO)
bool RenderLayerCompositor::canAccelerateVideoRendering(RenderVideo& video) const
{
if (!m_hasAcceleratedCompositing)
return false;
return video.supportsAcceleratedRendering();
}
#endif
void RenderLayerCompositor::frameViewDidChangeLocation(const IntPoint& contentsOffset)
{
if (m_overflowControlsHostLayer)
m_overflowControlsHostLayer->setPosition(contentsOffset);
}
void RenderLayerCompositor::frameViewDidChangeSize()
{
if (auto* layer = m_renderView.layer())
layer->setNeedsCompositingGeometryUpdate();
if (m_scrolledContentsLayer) {
updateScrollLayerClipping();
frameViewDidScroll();
updateOverflowControlsLayers();
#if HAVE(RUBBER_BANDING)
updateSizeAndPositionForOverhangAreaLayer();
#endif
}
}
void RenderLayerCompositor::widgetDidChangeSize(RenderWidget& widget)
{
if (!widget.hasLayer())
return;
auto& layer = *widget.layer();
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " widgetDidChangeSize (layer " << &layer << ")");
// Widget size affects answer to requiresCompositingForFrame() so we need to trigger
// a compositing update.
layer.setNeedsPostLayoutCompositingUpdate();
scheduleCompositingLayerUpdate();
if (layer.isComposited())
layer.backing()->updateAfterWidgetResize();
}
bool RenderLayerCompositor::hasCoordinatedScrolling() const
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
return scrollingCoordinator && scrollingCoordinator->coordinatesScrollingForFrameView(m_renderView.protectedFrameView());
}
void RenderLayerCompositor::updateScrollLayerPosition()
{
ASSERT(!hasCoordinatedScrolling());
ASSERT(m_scrolledContentsLayer);
Ref frameView = m_renderView.frameView();
IntPoint scrollPosition = frameView->scrollPosition();
// We use scroll position here because the root content layer is offset to account for scrollOrigin (see LocalFrameView::positionForRootContentLayer).
m_scrolledContentsLayer->setPosition(FloatPoint(-scrollPosition.x(), -scrollPosition.y()));
if (RefPtr fixedBackgroundLayer = fixedRootBackgroundLayer())
fixedBackgroundLayer->setPosition(frameView->scrollPositionForFixedPosition());
}
void RenderLayerCompositor::updateScrollLayerClipping()
{
RefPtr layerForClipping = this->layerForClipping();
if (!layerForClipping)
return;
auto layerSize = m_renderView.protectedFrameView()->sizeForVisibleContent();
layerForClipping->setSize(layerSize);
layerForClipping->setPosition(positionForClipLayer());
#if ENABLE(SCROLLING_THREAD)
if (layerForClipping == m_clipLayer) {
EventRegion eventRegion;
auto eventRegionContext = eventRegion.makeContext();
eventRegionContext.unite(FloatRoundedRect(FloatRect({ }, layerSize)), m_renderView, RenderStyle::defaultStyle());
#if ENABLE(INTERACTION_REGIONS_IN_EVENT_REGION)
eventRegionContext.copyInteractionRegionsToEventRegion(m_renderView.settings().interactionRegionMinimumCornerRadius());
#endif
RefPtr { m_clipLayer }->setEventRegion(WTFMove(eventRegion));
}
#endif
}
FloatPoint RenderLayerCompositor::positionForClipLayer() const
{
Ref frameView = m_renderView.frameView();
auto clipLayerPosition = LocalFrameView::positionForInsetClipLayer(frameView->scrollPosition(), frameView->obscuredContentInsets());
return FloatPoint(frameView->insetForLeftScrollbarSpace() + clipLayerPosition.x(), clipLayerPosition.y());
}
void RenderLayerCompositor::frameViewDidScroll()
{
if (!m_scrolledContentsLayer)
return;
// If there's a scrolling coordinator that manages scrolling for this frame view,
// it will also manage updating the scroll layer position.
if (hasCoordinatedScrolling()) {
// We have to schedule a flush in order for the main TiledBacking to update its tile coverage.
scheduleRenderingUpdate();
return;
}
updateScrollLayerPosition();
}
void RenderLayerCompositor::frameViewDidAddOrRemoveScrollbars()
{
updateOverflowControlsLayers();
}
void RenderLayerCompositor::frameViewDidLayout()
{
if (auto* renderViewBacking = m_renderView.layer()->backing())
renderViewBacking->adjustTiledBackingCoverage();
}
void RenderLayerCompositor::rootLayerConfigurationChanged()
{
auto* renderViewBacking = m_renderView.layer()->backing();
if (renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking()) {
m_renderView.layer()->setNeedsCompositingConfigurationUpdate();
scheduleCompositingLayerUpdate();
}
}
void RenderLayerCompositor::updateCompositingForLayerTreeAsTextDump()
{
Ref frameView = m_renderView.frameView();
frameView->updateLayoutAndStyleIfNeededRecursive(LayoutOptions::UpdateCompositingLayers);
updateEventRegions();
for (RefPtr child = frameView->frame().tree().firstRenderedChild(); child; child = child->tree().traverseNextRendered()) {
RefPtr localChild = dynamicDowncast<LocalFrame>(child);
if (!localChild)
continue;
if (auto* renderer = localChild->contentRenderer())
renderer->compositor().updateEventRegions();
}
updateCompositingLayers(CompositingUpdateType::AfterLayout);
if (!m_rootContentsLayer)
return;
flushPendingLayerChanges(true);
// We need to trigger an update because the flushPendingLayerChanges() will have pushed changes to platform layers,
// which may cause painting to happen in the current runloop.
protectedPage()->triggerRenderingUpdateForTesting();
}
String RenderLayerCompositor::layerTreeAsText(OptionSet<LayerTreeAsTextOptions> options, uint32_t baseIndent)
{
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " layerTreeAsText");
updateCompositingForLayerTreeAsTextDump();
// Exclude any implicitly created layers that wrap the root contents layer, unless the caller explicitly requested the true root to be included.
RefPtr dumpRootLayer = (options & LayerTreeAsTextOptions::IncludeRootLayers) ? rootGraphicsLayer() : m_rootContentsLayer;
if (!dumpRootLayer)
return String();
// We skip dumping the scroll and clip layers to keep layerTreeAsText output
// similar between platforms.
String layerTreeText = dumpRootLayer->layerTreeAsText(options, baseIndent);
// Dump an empty layer tree only if the only composited layer is the main frame's tiled backing,
// so that tests expecting us to drop out of accelerated compositing when there are no layers succeed.
if (!hasContentCompositingLayers() && documentUsesTiledBacking() && !(options & LayerTreeAsTextOptions::IncludeTileCaches) && !(options & LayerTreeAsTextOptions::IncludeRootLayerProperties))
layerTreeText = emptyString();
// The true root layer is not included in the dump, so if we want to report
// its repaint rects, they must be included here.
if (options & LayerTreeAsTextOptions::IncludeRepaintRects)
return makeString(m_renderView.protectedFrameView()->trackedRepaintRectsAsText(), layerTreeText);
return layerTreeText;
}
std::optional<String> RenderLayerCompositor::platformLayerTreeAsText(Element& element, OptionSet<PlatformLayerTreeAsTextFlags> flags)
{
LOG_WITH_STREAM(Compositing, stream << "RenderLayerCompositor " << this << " platformLayerTreeAsText");
updateCompositingForLayerTreeAsTextDump();
if (!element.renderer() || !element.renderer()->hasLayer())
return std::nullopt;
auto& layerModelObject = downcast<RenderLayerModelObject>(*element.renderer());
if (!layerModelObject.layer()->isComposited())
return std::nullopt;
auto* backing = layerModelObject.layer()->backing();
return backing->graphicsLayer()->platformLayerTreeAsText(flags);
}
static RenderView* frameContentsRenderView(RenderWidget& renderer)
{
if (RefPtr contentDocument = renderer.protectedFrameOwnerElement()->contentDocument())
return contentDocument->renderView();
return nullptr;
}
RenderLayerCompositor* RenderLayerCompositor::frameContentsCompositor(RenderWidget& renderer)
{
if (auto* view = frameContentsRenderView(renderer))
return &view->compositor();
return nullptr;
}
auto RenderLayerCompositor::attachWidgetContentLayersIfNecessary(RenderWidget& renderer) -> WidgetLayerAttachment
{
auto* layer = renderer.layer();
if (!layer->isComposited())
return { false, false };
auto* backing = layer->backing();
RefPtr hostingLayer = backing->parentForSublayers();
bool isVisible = renderer.style().usedVisibility() == Visibility::Visible;
auto addContentsLayerChildIfNecessary = [&](GraphicsLayer& contentsLayer, bool isVisible) -> bool {
if (isVisible && hostingLayer->children().size() == 1 && hostingLayer->children()[0].ptr() == &contentsLayer)
return false;
if (!isVisible && hostingLayer->children().isEmpty())
return false;
hostingLayer->removeAllChildren();
if (isVisible)
hostingLayer->addChild(contentsLayer);
return true;
};
WidgetLayerAttachment result;
if (isCompositedPlugin(renderer)) {
if (RefPtr contentsLayer = backing->layerForContents()) {
result.widgetLayersAttachedAsChildren = isVisible;
result.layerHierarchyChanged = addContentsLayerChildIfNecessary(*contentsLayer, isVisible);
if (!isLayerForPluginWithScrollCoordinatedContents(*layer))
return result;
RefPtr scrollingCoordinator = this->scrollingCoordinator();
if (!scrollingCoordinator)
return result;
auto pluginHostingNodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::PluginHosting);
if (!pluginHostingNodeID)
return result;
CheckedPtr renderEmbeddedObject = dynamicDowncast<RenderEmbeddedObject>(renderer);
renderEmbeddedObject->willAttachScrollingNode();
if (auto pluginScrollingNodeID = renderEmbeddedObject->scrollingNodeID()) {
if (isVisible) {
scrollingCoordinator->insertNode(m_renderView.protectedFrameView()->frame().rootFrame().frameID(), ScrollingNodeType::PluginScrolling, *pluginScrollingNodeID, *pluginHostingNodeID, 0);
renderEmbeddedObject->didAttachScrollingNode();
} else
scrollingCoordinator->unparentNode(*pluginScrollingNodeID);
}
return result;
}
}
auto* innerCompositor = frameContentsCompositor(renderer);
if (!innerCompositor || !innerCompositor->usesCompositing() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
return result;
result.widgetLayersAttachedAsChildren = isVisible;
if (RefPtr iframeRootLayer = innerCompositor->rootGraphicsLayer())
result.layerHierarchyChanged = addContentsLayerChildIfNecessary(*iframeRootLayer, isVisible);
if (auto frameHostingNodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::FrameHosting)) {
RefPtr scrollingCoordinator = this->scrollingCoordinator();
if (!scrollingCoordinator)
return result;
auto* contentsRenderView = frameContentsRenderView(renderer);
if (auto frameRootScrollingNodeID = contentsRenderView->protectedFrameView()->scrollingNodeID()) {
if (isVisible)
scrollingCoordinator->insertNode(m_renderView.protectedFrameView()->frame().rootFrame().frameID(), ScrollingNodeType::Subframe, *frameRootScrollingNodeID, *frameHostingNodeID, 0);
else
scrollingCoordinator->unparentNode(*frameRootScrollingNodeID);
}
}
return result;
}
void RenderLayerCompositor::repaintCompositedLayers()
{
recursiveRepaintLayer(rootRenderLayer());
}
void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer& layer)
{
layer.updateLayerListsIfNeeded();
// FIXME: This method does not work correctly with transforms.
if (layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor())
layer.setBackingNeedsRepaint();
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(layer);
#endif
if (layer.hasCompositingDescendant()) {
for (auto* renderLayer : layer.negativeZOrderLayers())
recursiveRepaintLayer(*renderLayer);
for (auto* renderLayer : layer.positiveZOrderLayers())
recursiveRepaintLayer(*renderLayer);
}
for (auto* renderLayer : layer.normalFlowLayers())
recursiveRepaintLayer(*renderLayer);
}
bool RenderLayerCompositor::layerRepaintTargetsBackingSharingLayer(RenderLayer& layer, BackingSharingState& sharingState) const
{
if (sharingState.backingProviderCandidates().isEmpty())
return false;
for (const auto* currLayer = &layer; currLayer; currLayer = currLayer->paintOrderParent()) {
if (compositedWithOwnBackingStore(*currLayer))
return false;
if (currLayer->paintsIntoProvidedBacking())
return false;
if (sharingState.backingProviderForLayer(*currLayer))
return true;
}
return false;
}
RenderLayer& RenderLayerCompositor::rootRenderLayer() const
{
return *m_renderView.layer();
}
GraphicsLayer* RenderLayerCompositor::rootGraphicsLayer() const
{
if (m_overflowControlsHostLayer)
return m_overflowControlsHostLayer.get();
return m_rootContentsLayer.get();
}
void RenderLayerCompositor::setIsInWindow(bool isInWindow)
{
LOG(Compositing, "RenderLayerCompositor %p setIsInWindow %d", this, isInWindow);
if (!usesCompositing())
return;
if (RefPtr rootLayer = rootGraphicsLayer()) {
GraphicsLayer::traverse(*rootLayer, [isInWindow](GraphicsLayer& layer) {
layer.setIsInWindow(isInWindow);
});
}
if (isInWindow) {
if (m_rootLayerAttachment != RootLayerUnattached)
return;
RootLayerAttachment attachment = isRootFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
attachRootLayer(attachment);
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator) {
m_legacyScrollingLayerCoordinator->registerAllViewportConstrainedLayers(*this);
m_legacyScrollingLayerCoordinator->registerAllScrollingLayers();
}
#endif
} else {
if (m_rootLayerAttachment == RootLayerUnattached)
return;
detachRootLayer();
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator) {
m_legacyScrollingLayerCoordinator->unregisterAllViewportConstrainedLayers();
m_legacyScrollingLayerCoordinator->unregisterAllScrollingLayers();
}
#endif
}
}
void RenderLayerCompositor::invalidateEventRegionForAllFrames()
{
for (RefPtr frame = &page().mainFrame(); frame; frame = frame->tree().traverseNext()) {
RefPtr localFrame = dynamicDowncast<LocalFrame>(frame);
if (!localFrame)
continue;
if (auto* view = localFrame->contentRenderer())
view->compositor().invalidateEventRegionForAllLayers();
}
}
void RenderLayerCompositor::invalidateEventRegionForAllLayers()
{
applyToCompositedLayerIncludingDescendants(*m_renderView.layer(), [](auto& layer) {
layer.invalidateEventRegion(RenderLayer::EventRegionInvalidationReason::SettingDidChange);
});
}
void RenderLayerCompositor::clearBackingForAllLayers()
{
applyToCompositedLayerIncludingDescendants(*m_renderView.layer(), [](auto& layer) { layer.clearBacking(); });
}
void RenderLayerCompositor::updateRootLayerPosition()
{
if (RefPtr rootContentsLayer = m_rootContentsLayer) {
Ref frameView = m_renderView.frameView();
rootContentsLayer->setSize(frameView->contentsSize());
rootContentsLayer->setPosition(frameView->positionForRootContentLayer());
rootContentsLayer->setAnchorPoint(FloatPoint3D());
}
updateScrollLayerClipping();
#if HAVE(RUBBER_BANDING)
if (m_contentShadowLayer && m_rootContentsLayer) {
m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
RefPtr { m_contentShadowLayer }->setSize(m_rootContentsLayer->size());
}
updateLayerForTopOverhangArea(m_layerForTopOverhangArea != nullptr);
updateLayerForBottomOverhangArea(m_layerForBottomOverhangArea != nullptr);
updateLayerForHeader(m_layerForHeader != nullptr);
updateLayerForFooter(m_layerForFooter != nullptr);
#endif
}
bool RenderLayerCompositor::has3DContent() const
{
return layerHas3DContent(rootRenderLayer());
}
bool RenderLayerCompositor::needsToBeComposited(const RenderLayer& layer, RequiresCompositingData& queryData) const
{
if (!canBeComposited(layer))
return false;
return requiresCompositingLayer(layer, queryData) || layer.mustCompositeForIndirectReasons() || (usesCompositing() && layer.isRenderViewLayer());
}
// Note: this specifies whether the RL needs a compositing layer for intrinsic reasons.
// Use needsToBeComposited() to determine if a RL actually needs a compositing layer.
// FIXME: is clipsCompositingDescendants() an intrinsic reason?
bool RenderLayerCompositor::requiresCompositingLayer(const RenderLayer& layer, RequiresCompositingData& queryData) const
{
auto& renderer = rendererForCompositingTests(layer);
if (!renderer.layer()) {
ASSERT_NOT_REACHED();
return false;
}
// The root layer always has a compositing layer, but it may not have backing.
if (requiresCompositingForTransform(renderer)
|| requiresCompositingForAnimation(renderer)
|| requiresCompositingForPosition(renderer, *renderer.layer(), queryData)
|| requiresCompositingForCanvas(renderer)
|| requiresCompositingForFilters(renderer)
|| requiresCompositingForWillChange(renderer)
|| requiresCompositingForBackfaceVisibility(renderer)
|| requiresCompositingForViewTransition(renderer)
|| requiresCompositingForVideo(renderer)
|| requiresCompositingForModel(renderer)
|| requiresCompositingForFrame(renderer, queryData)
|| requiresCompositingForPlugin(renderer, queryData)
|| requiresCompositingForOverflowScrolling(*renderer.layer(), queryData)
|| requiresCompositingForAnchorPositioning(*renderer.layer())) {
queryData.intrinsic = true;
return true;
}
return false;
}
bool RenderLayerCompositor::canBeComposited(const RenderLayer& layer) const
{
if (m_hasAcceleratedCompositing && layer.isSelfPaintingLayer()) {
if (layer.renderer().isSkippedContent())
return false;
if (!layer.isInsideFragmentedFlow())
return true;
// CSS Regions flow threads do not need to be composited as we use composited RenderFragmentContainers
// to render the background of the RenderFragmentedFlow.
if (layer.isRenderFragmentedFlow())
return false;
return true;
}
return false;
}
#if ENABLE(FULLSCREEN_API)
enum class FullScreenDescendant { Yes, No, NotApplicable };
static FullScreenDescendant isDescendantOfFullScreenLayer(const RenderLayer& layer)
{
CheckedPtr manager = layer.renderer().document().fullscreenManagerIfExists();
if (!manager)
return FullScreenDescendant::NotApplicable;
RefPtr fullScreenElement = manager->fullscreenElement();
if (!fullScreenElement)
return FullScreenDescendant::NotApplicable;
auto* fullScreenRenderer = dynamicDowncast<RenderLayerModelObject>(fullScreenElement->renderer());
if (!fullScreenRenderer)
return FullScreenDescendant::NotApplicable;
auto* fullScreenLayer = fullScreenRenderer->layer();
if (!fullScreenLayer)
return FullScreenDescendant::NotApplicable;
auto backdropRenderer = fullScreenRenderer->backdropRenderer();
if (backdropRenderer && backdropRenderer.get() == &layer.renderer())
return FullScreenDescendant::Yes;
return layer.isDescendantOf(*fullScreenLayer) ? FullScreenDescendant::Yes : FullScreenDescendant::No;
}
#endif
bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer& layer, const RenderLayer* compositingAncestorLayer, const LayoutRect& layerCompositedBoundsInAncestor, const LayoutRect& ancestorCompositedBounds) const
{
auto& renderer = layer.renderer();
if (compositingAncestorLayer
&& !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
|| compositingAncestorLayer->backing()->paintsIntoWindow()
|| compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
return true;
RequiresCompositingData queryData;
if (layer.isRenderViewLayer()
|| layer.transform() // note: excludes perspective and transformStyle3D.
|| requiresCompositingForAnimation(renderer)
|| requiresCompositingForPosition(renderer, layer, queryData)
|| requiresCompositingForCanvas(renderer)
|| requiresCompositingForFilters(renderer)
|| requiresCompositingForWillChange(renderer)
|| requiresCompositingForBackfaceVisibility(renderer)
|| requiresCompositingForViewTransition(renderer)
|| requiresCompositingForVideo(renderer)
|| requiresCompositingForModel(renderer)
|| requiresCompositingForFrame(renderer, queryData)
|| requiresCompositingForPlugin(renderer, queryData)
|| requiresCompositingForOverflowScrolling(layer, queryData)
|| requiresCompositingForAnchorPositioning(layer)
|| needsContentsCompositingLayer(layer)
|| renderer.isTransparent()
|| renderer.hasMask()
|| renderer.hasReflection()
|| renderer.hasFilter()
#if HAVE(CORE_MATERIAL)
|| renderer.hasAppleVisualEffect()
#endif
|| renderer.hasBackdropFilter())
return true;
if (layer.isComposited() && layer.backing()->hasBackingSharingLayers())
return true;
// FIXME: We really need to keep track of the ancestor layer that has its own backing store.
if (!ancestorCompositedBounds.contains(layerCompositedBoundsInAncestor))
return true;
if (layer.mustCompositeForIndirectReasons()) {
IndirectCompositingReason reason = layer.indirectCompositingReason();
return reason == IndirectCompositingReason::Overlap
|| reason == IndirectCompositingReason::OverflowScrollPositioning
|| reason == IndirectCompositingReason::Stacking
|| reason == IndirectCompositingReason::BackgroundLayer
|| reason == IndirectCompositingReason::GraphicalEffect
|| reason == IndirectCompositingReason::Preserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
}
return false;
}
OptionSet<CompositingReason> RenderLayerCompositor::reasonsForCompositing(const RenderLayer& layer) const
{
OptionSet<CompositingReason> reasons;
if (!layer.isComposited())
return reasons;
RequiresCompositingData queryData;
auto& renderer = rendererForCompositingTests(layer);
if (requiresCompositingForTransform(renderer))
reasons.add(CompositingReason::Transform3D);
if (requiresCompositingForVideo(renderer))
reasons.add(CompositingReason::Video);
else if (requiresCompositingForCanvas(renderer))
reasons.add(CompositingReason::Canvas);
else if (requiresCompositingForModel(renderer))
reasons.add(CompositingReason::Model);
else if (requiresCompositingForPlugin(renderer, queryData))
reasons.add(CompositingReason::Plugin);
else if (requiresCompositingForFrame(renderer, queryData))
reasons.add(CompositingReason::IFrame);
if ((canRender3DTransforms() && renderer.style().backfaceVisibility() == BackfaceVisibility::Hidden))
reasons.add(CompositingReason::BackfaceVisibilityHidden);
if (requiresCompositingForAnimation(renderer))
reasons.add(CompositingReason::Animation);
if (requiresCompositingForFilters(renderer))
reasons.add(CompositingReason::Filters);
if (requiresCompositingForWillChange(renderer))
reasons.add(CompositingReason::WillChange);
if (requiresCompositingForPosition(renderer, *renderer.layer(), queryData))
reasons.add(renderer.isFixedPositioned() ? CompositingReason::PositionFixed : CompositingReason::PositionSticky);
if (requiresCompositingForOverflowScrolling(*renderer.layer(), queryData))
reasons.add(CompositingReason::OverflowScrolling);
if (requiresCompositingForAnchorPositioning(*renderer.layer()))
reasons.add(CompositingReason::AnchorPositioning);
switch (renderer.layer()->indirectCompositingReason()) {
case IndirectCompositingReason::None:
break;
case IndirectCompositingReason::Clipping:
reasons.add(CompositingReason::ClipsCompositingDescendants);
break;
case IndirectCompositingReason::Stacking:
reasons.add(CompositingReason::Stacking);
break;
case IndirectCompositingReason::OverflowScrollPositioning:
reasons.add(CompositingReason::OverflowScrollPositioning);
break;
case IndirectCompositingReason::Overlap:
reasons.add(CompositingReason::Overlap);
break;
case IndirectCompositingReason::BackgroundLayer:
reasons.add(CompositingReason::NegativeZIndexChildren);
break;
case IndirectCompositingReason::GraphicalEffect:
if (renderer.isTransformed())
reasons.add(CompositingReason::TransformWithCompositedDescendants);
if (renderer.isTransparent())
reasons.add(CompositingReason::OpacityWithCompositedDescendants);
if (renderer.hasMask())
reasons.add(CompositingReason::MaskWithCompositedDescendants);
if (renderer.hasReflection())
reasons.add(CompositingReason::ReflectionWithCompositedDescendants);
if (renderer.hasFilter() || renderer.hasBackdropFilter())
reasons.add(CompositingReason::FilterWithCompositedDescendants);
#if HAVE(CORE_MATERIAL)
if (renderer.hasAppleVisualEffect())
reasons.add(CompositingReason::FilterWithCompositedDescendants);
#endif
if (layer.isBackdropRoot())
reasons.add(CompositingReason::BackdropRoot);
if (layer.isolatesCompositedBlending())
reasons.add(CompositingReason::IsolatesCompositedBlendingDescendants);
if (layer.hasBlendMode())
reasons.add(CompositingReason::BlendingWithCompositedDescendants);
if (renderer.hasClipPath())
reasons.add(CompositingReason::ClipsCompositingDescendants);
break;
case IndirectCompositingReason::Perspective:
reasons.add(CompositingReason::Perspective);
break;
case IndirectCompositingReason::Preserve3D:
reasons.add(CompositingReason::Preserve3D);
break;
}
if (usesCompositing() && renderer.layer()->isRenderViewLayer())
reasons.add(CompositingReason::Root);
return reasons;
}
static ASCIILiteral compositingReasonToString(CompositingReason reason)
{
switch (reason) {
case CompositingReason::Transform3D: return "3D transform"_s;
case CompositingReason::Video: return "video"_s;
case CompositingReason::Canvas: return "canvas"_s;
case CompositingReason::Plugin: return "plugin"_s;
case CompositingReason::IFrame: return "iframe"_s;
case CompositingReason::BackfaceVisibilityHidden: return "backface-visibility: hidden"_s;
case CompositingReason::ClipsCompositingDescendants: return "clips compositing descendants"_s;
case CompositingReason::Animation: return "animation"_s;
case CompositingReason::Filters: return "filters"_s;
case CompositingReason::PositionFixed: return "position: fixed"_s;
case CompositingReason::PositionSticky: return "position: sticky"_s;
case CompositingReason::OverflowScrolling: return "async overflow scrolling"_s;
case CompositingReason::Stacking: return "stacking"_s;
case CompositingReason::Overlap: return "overlap"_s;
case CompositingReason::OverflowScrollPositioning: return "overflow scroll positioning"_s;
case CompositingReason::NegativeZIndexChildren: return "negative z-index children"_s;
case CompositingReason::TransformWithCompositedDescendants: return "transform with composited descendants"_s;
case CompositingReason::OpacityWithCompositedDescendants: return "opacity with composited descendants"_s;
case CompositingReason::MaskWithCompositedDescendants: return "mask with composited descendants"_s;
case CompositingReason::ReflectionWithCompositedDescendants: return "reflection with composited descendants"_s;
case CompositingReason::FilterWithCompositedDescendants: return "filter with composited descendants"_s;
case CompositingReason::BlendingWithCompositedDescendants: return "blending with composited descendants"_s;
case CompositingReason::IsolatesCompositedBlendingDescendants: return "isolates composited blending descendants"_s;
case CompositingReason::Perspective: return "perspective"_s;
case CompositingReason::Preserve3D: return "preserve-3d"_s;
case CompositingReason::WillChange: return "will-change"_s;
case CompositingReason::Root: return "root"_s;
case CompositingReason::Model: return "model"_s;
case CompositingReason::BackdropRoot: return "backdrop root"_s;
case CompositingReason::AnchorPositioning: return "anchor positioning"_s;
}
return ""_s;
}
#if !LOG_DISABLED
ASCIILiteral RenderLayerCompositor::logOneReasonForCompositing(const RenderLayer& layer)
{
for (auto reason : reasonsForCompositing(layer))
return compositingReasonToString(reason);
return ""_s;
}
#endif
static bool canUseDescendantClippingLayer(const RenderLayer& layer)
{
if (layer.isolatesCompositedBlending())
return false;
// We can only use the "descendant clipping layer" strategy when the clip rect is entirely within
// the border box, because of interactions with border-radius clipping and compositing.
if (auto* renderer = layer.renderBox(); renderer && renderer->hasClip()) {
auto borderBoxRect = renderer->borderBoxRect();
auto clipRect = renderer->clipRect({ });
bool clipRectInsideBorderRect = intersection(borderBoxRect, clipRect) == clipRect;
return clipRectInsideBorderRect;
}
return true;
}
// Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
// up to the enclosing compositing ancestor. This is required because compositing layers are parented
// according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
// Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
// but a sibling in the z-order hierarchy.
// FIXME: can we do this without a tree walk?
bool RenderLayerCompositor::clippedByAncestor(RenderLayer& layer, const RenderLayer* compositingAncestor) const
{
ASSERT(layer.isComposited());
if (!compositingAncestor)
return false;
if (layer.renderer().capturedInViewTransition())
return false;
// If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
// so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
// and layer. The exception is when the compositingAncestor isolates composited blending children,
// in this case it is not allowed to clipsCompositingDescendants() and each of its children
// will be clippedByAncestor()s, including the compositingAncestor.
auto* computeClipRoot = compositingAncestor;
if (canUseDescendantClippingLayer(*compositingAncestor)) {
computeClipRoot = nullptr;
auto* parent = &layer;
while (parent) {
auto* next = parent->parent();
if (next == compositingAncestor) {
computeClipRoot = parent;
break;
}
parent = next;
}
if (!computeClipRoot || computeClipRoot == &layer)
return false;
}
auto backgroundClipRect = layer.backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, TemporaryClipRects));
return !backgroundClipRect.isInfinite(); // FIXME: Incorrect for CSS regions.
}
bool RenderLayerCompositor::updateAncestorClippingStack(const RenderLayer& layer, const RenderLayer* compositingAncestor) const
{
ASSERT(layer.isComposited());
auto clippingStack = computeAncestorClippingStack(layer, compositingAncestor);
return layer.backing()->updateAncestorClippingStack(WTFMove(clippingStack));
}
Vector<CompositedClipData> RenderLayerCompositor::computeAncestorClippingStack(const RenderLayer& layer, const RenderLayer* compositingAncestor) const
{
// On first pass in WK1, the root may not have become composited yet.
if (!compositingAncestor)
return { };
// We'll start by building a child-to-ancestors stack.
Vector<CompositedClipData> newStack;
// Walk up the containing block chain to composited ancestor, prepending an entry to the clip stack for:
// * each composited scrolling layer
// * each set of RenderLayers which contribute a clip.
bool haveNonScrollableClippingIntermediateLayer = false;
const RenderLayer* currentClippedLayer = &layer;
auto pushNonScrollableClip = [&](const RenderLayer& clippedLayer, const RenderLayer& clippingRoot, ShouldRespectOverflowClip respectClip = IgnoreOverflowClip) {
// Use IgnoreOverflowClip to ignore overflow contributed by clippingRoot (which may be a scroller).
OptionSet<RenderLayer::ClipRectsOption> options;
if (respectClip == RespectOverflowClip)
options.add(RenderLayer::ClipRectsOption::RespectOverflowClip);
auto backgroundClip = clippedLayer.backgroundClipRect(RenderLayer::ClipRectsContext(&clippingRoot, TemporaryClipRects, options));
ASSERT(!backgroundClip.affectedByRadius());
auto clipRect = backgroundClip.rect();
if (clipRect.isInfinite())
return;
auto infiniteRect = LayoutRect::infiniteRect();
auto renderableInfiniteRect = [] {
// Return a infinite-like rect whose values are such that, when converted to float pixel values, they can reasonably represent device pixels.
return LayoutRect(LayoutUnit::nearlyMin() / 32, LayoutUnit::nearlyMin() / 32, LayoutUnit::nearlyMax() / 16, LayoutUnit::nearlyMax() / 16);
}();
if (clipRect.width() == infiniteRect.width()) {
clipRect.setX(renderableInfiniteRect.x());
clipRect.setWidth(renderableInfiniteRect.width());
}
if (clipRect.height() == infiniteRect.height()) {
clipRect.setY(renderableInfiniteRect.y());
clipRect.setHeight(renderableInfiniteRect.height());
}
auto offset = layer.convertToLayerCoords(&clippingRoot, { }, RenderLayer::AdjustForColumns);
clipRect.moveBy(-offset);
CompositedClipData clipData { const_cast<RenderLayer*>(&clippedLayer), RoundedRect { clipRect }, false };
newStack.insert(0, WTFMove(clipData));
};
// Surprisingly, the deprecated CSS "clip" property on abspos ancestors of fixedpos elements clips them <https://github.com/w3c/csswg-drafts/issues/8336>.
bool checkAbsoluteAncestorForClip = layer.renderer().isFixedPositioned();
traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool /*isPaintOrderAncestor*/) {
if (&ancestorLayer == compositingAncestor) {
bool canUseDescendantClip = canUseDescendantClippingLayer(ancestorLayer);
if (haveNonScrollableClippingIntermediateLayer)
pushNonScrollableClip(*currentClippedLayer, ancestorLayer, !canUseDescendantClip ? RespectOverflowClip : IgnoreOverflowClip);
else if (!canUseDescendantClip && newStack.isEmpty())
pushNonScrollableClip(*currentClippedLayer, ancestorLayer, RespectOverflowClip);
return AncestorTraversal::Stop;
}
auto ancestorLayerMayClip = [&]() {
if (checkAbsoluteAncestorForClip && ancestorLayer.renderer().hasClip())
return true;
return isContainingBlockChain && ancestorLayer.renderer().hasClipOrNonVisibleOverflow();
};
if (ancestorLayerMayClip()) {
auto* box = ancestorLayer.renderBox();
if (!box)
return AncestorTraversal::Continue;
if (ancestorLayer.hasCompositedScrollableOverflow()) {
if (haveNonScrollableClippingIntermediateLayer) {
pushNonScrollableClip(*currentClippedLayer, ancestorLayer);
haveNonScrollableClippingIntermediateLayer = false;
}
auto clipRoundedRect = parentRelativeScrollableRect(ancestorLayer, &ancestorLayer);
auto offset = layer.convertToLayerCoords(&ancestorLayer, { }, RenderLayer::AdjustForColumns);
clipRoundedRect.moveBy(-offset);
CompositedClipData clipData { const_cast<RenderLayer*>(&ancestorLayer), clipRoundedRect, true };
newStack.insert(0, WTFMove(clipData));
currentClippedLayer = &ancestorLayer;
} else if (box->hasNonVisibleOverflow() && box->style().hasBorderRadius()) {
if (haveNonScrollableClippingIntermediateLayer) {
pushNonScrollableClip(*currentClippedLayer, ancestorLayer);
haveNonScrollableClippingIntermediateLayer = false;
}
auto borderShape = BorderShape::shapeForBorderRect(box->style(), box->borderBoxRect());
auto clipRoundedRect = borderShape.deprecatedInnerRoundedRect();
auto offset = layer.convertToLayerCoords(&ancestorLayer, { }, RenderLayer::AdjustForColumns);
auto rect = clipRoundedRect.rect();
rect.moveBy(-offset);
clipRoundedRect.setRect(rect);
CompositedClipData clipData { const_cast<RenderLayer*>(&ancestorLayer), clipRoundedRect, false };
newStack.insert(0, WTFMove(clipData));
currentClippedLayer = &ancestorLayer;
} else
haveNonScrollableClippingIntermediateLayer = true;
}
return AncestorTraversal::Continue;
});
return newStack;
}
// Note that this returns the ScrollingNodeID of the scroller this layer is embedded in, not the layer's own ScrollingNodeID if it has one.
std::optional<ScrollingNodeID> RenderLayerCompositor::asyncScrollableContainerNodeID(const RenderObject& renderer)
{
auto* enclosingLayer = renderer.enclosingLayer();
if (!enclosingLayer)
return std::nullopt;
auto layerScrollingNodeID = [](const RenderLayer& layer) -> std::optional<ScrollingNodeID> {
if (layer.isComposited())
return layer.backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
return std::nullopt;
};
// If the renderer is inside the layer, we care about the layer's scrollability. Otherwise, we let traverseAncestorLayers look at ancestors.
if (!renderer.hasLayer()) {
if (auto scrollingNodeID = layerScrollingNodeID(*enclosingLayer))
return scrollingNodeID;
}
std::optional<ScrollingNodeID> containerScrollingNodeID;
traverseAncestorLayers(*enclosingLayer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool /*isPaintOrderAncestor*/) {
if (isContainingBlockChain && ancestorLayer.hasCompositedScrollableOverflow()) {
containerScrollingNodeID = layerScrollingNodeID(ancestorLayer);
return AncestorTraversal::Stop;
}
return AncestorTraversal::Continue;
});
return containerScrollingNodeID;
}
bool RenderLayerCompositor::hasCompositedWidgetContents(const RenderObject& renderer)
{
auto* renderWidget = dynamicDowncast<RenderWidget>(renderer);
if (!renderWidget)
return false;
return renderWidget->requiresAcceleratedCompositing();
}
bool RenderLayerCompositor::isCompositedPlugin(const RenderObject& renderer)
{
auto* renderEmbeddedObject = dynamicDowncast<RenderEmbeddedObject>(renderer);
if (!renderEmbeddedObject)
return false;
return renderEmbeddedObject->requiresAcceleratedCompositing();
}
#if HAVE(CORE_ANIMATION_SEPARATED_LAYERS)
bool RenderLayerCompositor::isSeparated(const RenderObject& renderer)
{
return renderer.style().usedTransformStyle3D() == TransformStyle3D::Separated;
}
#endif
// Return true if the given layer is a stacking context and has compositing child
// layers that it needs to clip. In this case we insert a clipping GraphicsLayer
// into the hierarchy between this layer and its children in the z-order hierarchy.
bool RenderLayerCompositor::clipsCompositingDescendants(const RenderLayer& layer)
{
if (!(layer.hasCompositingDescendant() && layer.renderer().hasClipOrNonVisibleOverflow()))
return false;
if (layer.hasCompositedNonContainedDescendants())
return false;
return canUseDescendantClippingLayer(layer);
}
bool RenderLayerCompositor::requiresCompositingForAnimation(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
return false;
if (auto styleable = Styleable::fromRenderer(renderer)) {
if (styleable->hasRunningAcceleratedAnimations())
return true;
if (auto* effectsStack = styleable->keyframeEffectStack()) {
return (effectsStack->isCurrentlyAffectingProperty(CSSPropertyOpacity)
&& (usesCompositing() || (m_compositingTriggers & ChromeClient::AnimatedOpacityTrigger)))
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyFilter)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyBackdropFilter)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyWebkitBackdropFilter)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyTranslate)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyScale)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyRotate)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyTransform)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyOffsetAnchor)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyOffsetDistance)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyOffsetPath)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyOffsetPosition)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyOffsetRotate);
}
}
return false;
}
static bool styleHas3DTransformOperation(const RenderStyle& style)
{
return style.transform().has3DOperation()
|| (style.translate() && style.translate()->is3DOperation())
|| (style.scale() && style.scale()->is3DOperation())
|| (style.rotate() && style.rotate()->is3DOperation());
}
static bool styleTransformOperationsAreRepresentableIn2D(const RenderStyle& style)
{
return style.transform().isRepresentableIn2D()
&& (!style.translate() || style.translate()->isRepresentableIn2D())
&& (!style.scale() || style.scale()->isRepresentableIn2D())
&& (!style.rotate() || style.rotate()->isRepresentableIn2D());
}
bool RenderLayerCompositor::requiresCompositingForTransform(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
return false;
// Note that we ask the renderer if it has a transform, because the style may have transforms,
// but the renderer may be an inline that doesn't suppport them.
if (!renderer.isTransformed())
return false;
auto compositingPolicy = m_compositingPolicy;
#if !USE(COMPOSITING_FOR_SMALL_CANVASES)
if (RefPtr canvas = dynamicDowncast<HTMLCanvasElement>(renderer.element())) {
auto canvasArea = canvas->size().area<RecordOverflow>();
if (!canvasArea.hasOverflowed() && canvasArea < canvasAreaThresholdRequiringCompositing)
compositingPolicy = CompositingPolicy::Conservative;
}
#endif
switch (compositingPolicy) {
case CompositingPolicy::Normal:
return styleHas3DTransformOperation(renderer.style());
case CompositingPolicy::Conservative:
// Continue to allow pages to avoid the very slow software filter path.
if (styleHas3DTransformOperation(renderer.style()) && renderer.hasFilter())
return true;
return styleTransformOperationsAreRepresentableIn2D(renderer.style()) ? false : true;
}
return false;
}
bool RenderLayerCompositor::requiresCompositingForBackfaceVisibility(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::ThreeDTransformTrigger))
return false;
if (renderer.style().backfaceVisibility() != BackfaceVisibility::Hidden)
return false;
if (renderer.layer()->has3DTransformedAncestor())
return true;
// FIXME: workaround for webkit.org/b/132801
auto* stackingContext = renderer.layer()->stackingContext();
if (stackingContext && stackingContext->renderer().style().preserves3D())
return true;
return false;
}
bool RenderLayerCompositor::requiresCompositingForViewTransition(RenderLayerModelObject& renderer) const
{
return renderer.effectiveCapturedInViewTransition() || renderer.isRenderViewTransitionCapture();
}
bool RenderLayerCompositor::requiresCompositingForVideo(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::VideoTrigger))
return false;
#if ENABLE(VIDEO)
CheckedPtr video = dynamicDowncast<RenderVideo>(renderer);
if (!video)
return false;
if ((video->requiresImmediateCompositing() || video->shouldDisplayVideo()) && canAccelerateVideoRendering(*video))
return true;
#else
UNUSED_PARAM(renderer);
#endif
return false;
}
bool RenderLayerCompositor::requiresCompositingForCanvas(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::CanvasTrigger))
return false;
if (!renderer.isRenderHTMLCanvas())
return false;
bool isCanvasLargeEnoughToForceCompositing = true;
#if !USE(COMPOSITING_FOR_SMALL_CANVASES)
RefPtr canvas = downcast<HTMLCanvasElement>(renderer.element());
auto canvasArea = canvas->size().area<RecordOverflow>();
isCanvasLargeEnoughToForceCompositing = !canvasArea.hasOverflowed() && canvasArea >= canvasAreaThresholdRequiringCompositing;
#endif
CanvasCompositingStrategy compositingStrategy = canvasCompositingStrategy(renderer);
if (compositingStrategy == CanvasAsLayerContents)
return true;
if (m_compositingPolicy == CompositingPolicy::Normal)
return compositingStrategy == CanvasPaintedToLayer && isCanvasLargeEnoughToForceCompositing;
return false;
}
bool RenderLayerCompositor::requiresCompositingForFilters(RenderLayerModelObject& renderer) const
{
if (renderer.hasBackdropFilter())
return true;
#if HAVE(CORE_MATERIAL)
if (renderer.hasAppleVisualEffect())
return true;
#endif
if (!(m_compositingTriggers & ChromeClient::FilterTrigger))
return false;
return renderer.hasFilter();
}
bool RenderLayerCompositor::requiresCompositingForWillChange(RenderLayerModelObject& renderer) const
{
if (!renderer.style().willChange() || !renderer.style().willChange()->canTriggerCompositing())
return false;
#if ENABLE(FULLSCREEN_API)
// FIXME: does this require layout?
if (renderer.layer() && isDescendantOfFullScreenLayer(*renderer.layer()) == FullScreenDescendant::No)
return false;
#endif
#if !PLATFORM(MAC)
// Ugly workaround for rdar://71881767. Undo when webkit.org/b/222092 and webkit.org/b/222132 are fixed.
if (m_compositingPolicy == CompositingPolicy::Conservative)
return false;
#endif
if (is<RenderBox>(renderer))
return true;
return renderer.style().willChange()->canTriggerCompositingOnInline();
}
bool RenderLayerCompositor::requiresCompositingForModel(RenderLayerModelObject& renderer) const
{
#if ENABLE(MODEL_ELEMENT)
if (is<RenderModel>(renderer))
return true;
#else
UNUSED_PARAM(renderer);
#endif
return false;
}
bool RenderLayerCompositor::requiresCompositingForPlugin(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
{
if (!(m_compositingTriggers & ChromeClient::PluginTrigger))
return false;
if (!isCompositedPlugin(renderer))
return false;
auto& pluginRenderer = downcast<RenderWidget>(renderer);
if (pluginRenderer.style().usedVisibility() != Visibility::Visible)
return false;
// If we can't reliably know the size of the plugin yet, don't change compositing state.
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return pluginRenderer.isComposited();
}
// Don't go into compositing mode if height or width are zero, or size is 1x1.
IntRect contentBox = snappedIntRect(pluginRenderer.contentBoxRect());
return (contentBox.height() * contentBox.width() > 1);
}
bool RenderLayerCompositor::requiresCompositingForFrame(RenderLayerModelObject& renderer, RequiresCompositingData& queryData) const
{
RefPtr frameRenderer = dynamicDowncast<RenderWidget>(renderer);
if (!frameRenderer)
return false;
if (frameRenderer->style().usedVisibility() != Visibility::Visible)
return false;
if (!frameRenderer->requiresAcceleratedCompositing())
return false;
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return frameRenderer->isComposited();
}
// Don't go into compositing mode if height or width are zero.
return !snappedIntRect(frameRenderer->contentBoxRect()).isEmpty();
}
bool RenderLayerCompositor::requiresCompositingForScrollableFrame(RequiresCompositingData& queryData) const
{
if (isRootFrameCompositor())
return false;
#if PLATFORM(COCOA) || USE(COORDINATED_GRAPHICS)
if (!m_renderView.settings().asyncFrameScrollingEnabled())
return false;
#endif
if (!(m_compositingTriggers & ChromeClient::ScrollableNonMainFrameTrigger))
return false;
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return m_renderView.isComposited();
}
return m_renderView.protectedFrameView()->isScrollable();
}
bool RenderLayerCompositor::requiresCompositingForPosition(RenderLayerModelObject& renderer, const RenderLayer& layer, RequiresCompositingData& queryData) const
{
// position:fixed elements that create their own stacking context (e.g. have an explicit z-index,
// opacity, transform) can get their own composited layer. A stacking context is required otherwise
// z-index and clipping will be broken.
if (!renderer.isPositioned())
return false;
#if ENABLE(FULLSCREEN_API)
if (isDescendantOfFullScreenLayer(layer) == FullScreenDescendant::No)
return false;
#endif
auto position = renderer.style().position();
bool isFixed = renderer.isFixedPositioned();
if (isFixed && !layer.isStackingContext())
return false;
bool isSticky = renderer.isInFlowPositioned() && position == PositionType::Sticky;
if (!isFixed && !isSticky)
return false;
// FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
if (!m_renderView.settings().acceleratedCompositingForFixedPositionEnabled())
return false;
if (isSticky)
return isAsyncScrollableStickyLayer(layer);
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return layer.isComposited();
}
auto container = renderer.container();
ASSERT(container);
// Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
// They will stay fixed wrt the container rather than the enclosing frame.
if (container != &m_renderView) {
queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNonViewContainer;
return false;
}
bool paintsContent = layer.isVisuallyNonEmpty() || layer.hasVisibleDescendant();
if (!paintsContent) {
queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForNoVisibleContent;
return false;
}
bool intersectsViewport = fixedLayerIntersectsViewport(layer);
if (!intersectsViewport) {
queryData.nonCompositedForPositionReason = RenderLayer::NotCompositedForBoundsOutOfView;
LOG_WITH_STREAM(Compositing, stream << "Layer " << &layer << " is outside the viewport");
return false;
}
return true;
}
bool RenderLayerCompositor::requiresCompositingForOverflowScrolling(const RenderLayer& layer, RequiresCompositingData& queryData) const
{
if (!layer.canUseCompositedScrolling())
return false;
if (queryData.layoutUpToDate == LayoutUpToDate::No) {
queryData.reevaluateAfterLayout = true;
return layer.isComposited();
}
const_cast<RenderLayer&>(layer).computeHasCompositedScrollableOverflow(LayoutUpToDate::Yes);
return layer.hasCompositedScrollableOverflow();
}
bool RenderLayerCompositor::requiresCompositingForAnchorPositioning(const RenderLayer& layer) const
{
return !!layer.snapshottedScrollOffsetForAnchorPositioning();
}
IndirectCompositingReason RenderLayerCompositor::computeIndirectCompositingReason(const RenderLayer& layer, bool hasCompositedDescendants, bool has3DTransformedDescendants, bool paintsIntoProvidedBacking) const
{
// When a layer has composited descendants, some effects, like 2d transforms, filters, masks etc must be implemented
// via compositing so that they also apply to those composited descendants.
auto& renderer = layer.renderer();
if (hasCompositedDescendants && (layer.isolatesCompositedBlending() || layer.isBackdropRoot() || layer.transform() || renderer.createsGroup() || renderer.hasReflection()))
return IndirectCompositingReason::GraphicalEffect;
// A layer with preserve-3d or perspective only needs to be composited if there are descendant layers that
// will be affected by the preserve-3d or perspective.
if (has3DTransformedDescendants) {
if (renderer.style().preserves3D())
return IndirectCompositingReason::Preserve3D;
if (renderer.style().hasPerspective())
return IndirectCompositingReason::Perspective;
}
// If this layer scrolls independently from the layer that it would paint into, it needs to get composited.
if (!paintsIntoProvidedBacking && layer.hasCompositedScrollingAncestor()) {
auto* paintDestination = layer.paintOrderParent();
if (paintDestination && layerScrollBehahaviorRelativeToCompositedAncestor(layer, *paintDestination) != ScrollPositioningBehavior::None)
return IndirectCompositingReason::OverflowScrollPositioning;
}
// Check for clipping last; if compositing just for clipping, the layer doesn't need its own backing store.
if (hasCompositedDescendants && clipsCompositingDescendants(layer))
return IndirectCompositingReason::Clipping;
return IndirectCompositingReason::None;
}
bool RenderLayerCompositor::styleChangeMayAffectIndirectCompositingReasons(const RenderStyle& oldStyle, const RenderStyle& newStyle)
{
if (RenderElement::createsGroupForStyle(newStyle) != RenderElement::createsGroupForStyle(oldStyle))
return true;
if (newStyle.isolation() != oldStyle.isolation())
return true;
if (newStyle.hasTransform() != oldStyle.hasTransform())
return true;
if (newStyle.boxReflect() != oldStyle.boxReflect())
return true;
if (newStyle.usedTransformStyle3D() != oldStyle.usedTransformStyle3D())
return true;
if (newStyle.hasPerspective() != oldStyle.hasPerspective())
return true;
return false;
}
bool RenderLayerCompositor::isAsyncScrollableStickyLayer(const RenderLayer& layer, const RenderLayer** enclosingAcceleratedOverflowLayer) const
{
ASSERT(layer.renderer().isStickilyPositioned());
auto* enclosingOverflowLayer = layer.enclosingOverflowClipLayer(ExcludeSelf);
if (enclosingOverflowLayer && enclosingOverflowLayer->hasCompositedScrollableOverflow()) {
if (enclosingAcceleratedOverflowLayer)
*enclosingAcceleratedOverflowLayer = enclosingOverflowLayer;
return true;
}
// If the layer is inside normal overflow, it's not async-scrollable.
if (enclosingOverflowLayer)
return false;
// No overflow ancestor, so see if the frame supports async scrolling.
if (hasCoordinatedScrolling())
return true;
#if PLATFORM(IOS_FAMILY)
// iOS WK1 has fixed/sticky support in the main frame via WebFixedPositionContent.
return isMainFrameCompositor();
#else
return false;
#endif
}
bool RenderLayerCompositor::isViewportConstrainedFixedOrStickyLayer(const RenderLayer& layer) const
{
if (layer.renderer().isStickilyPositioned())
return isAsyncScrollableStickyLayer(layer);
if (!(layer.renderer().isFixedPositioned() && layer.behavesAsFixed()))
return false;
for (auto* ancestor = layer.parent(); ancestor; ancestor = ancestor->parent()) {
if (ancestor->hasCompositedScrollableOverflow())
return true;
if (ancestor->isStackingContext() && ancestor->isComposited() && ancestor->renderer().isFixedPositioned())
return false;
}
return true;
}
bool RenderLayerCompositor::fixedLayerIntersectsViewport(const RenderLayer& layer) const
{
ASSERT(layer.renderer().isFixedPositioned());
// Fixed position elements that are invisible in the current view don't get their own layer.
// FIXME: We shouldn't have to check useFixedLayout() here; one of the viewport rects needs to give the correct answer.
LayoutRect viewBounds;
Ref frameView = m_renderView.frameView();
if (frameView->useFixedLayout())
viewBounds = m_renderView.unscaledDocumentRect();
else
viewBounds = frameView->rectForFixedPositionLayout();
LayoutRect layerBounds = layer.calculateLayerBounds(&layer, LayoutSize(), { RenderLayer::UseLocalClipRectIfPossible, RenderLayer::IncludeFilterOutsets, RenderLayer::UseFragmentBoxesExcludingCompositing,
RenderLayer::ExcludeHiddenDescendants, RenderLayer::DontConstrainForMask, RenderLayer::IncludeCompositedDescendants });
// Map to m_renderView to ignore page scale.
FloatRect absoluteBounds = layer.renderer().localToContainerQuad(FloatRect(layerBounds), &m_renderView).boundingBox();
return viewBounds.intersects(enclosingIntRect(absoluteBounds));
}
bool RenderLayerCompositor::useCoordinatedScrollingForLayer(const RenderLayer& layer) const
{
if (layer.isRenderViewLayer() && hasCoordinatedScrolling())
return true;
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
return scrollingCoordinator->coordinatesScrollingForOverflowLayer(layer);
return false;
}
ScrollPositioningBehavior RenderLayerCompositor::layerScrollBehahaviorRelativeToCompositedAncestor(const RenderLayer& layer, const RenderLayer& compositedAncestor)
{
if (!layer.hasCompositedScrollingAncestor())
return ScrollPositioningBehavior::None;
auto needsMovesNode = [&] {
bool result = false;
traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool /* isPaintOrderAncestor */) {
if (&ancestorLayer == &compositedAncestor)
return AncestorTraversal::Stop;
if (isContainingBlockChain && ancestorLayer.hasCompositedScrollableOverflow()) {
result = true;
return AncestorTraversal::Stop;
}
return AncestorTraversal::Continue;
});
return result;
};
if (needsMovesNode())
return ScrollPositioningBehavior::Moves;
if (layer.boxScrollingScope() != compositedAncestor.contentsScrollingScope())
return ScrollPositioningBehavior::Stationary;
return ScrollPositioningBehavior::None;
}
static void collectStationaryLayerRelatedOverflowNodes(const RenderLayer& layer, const RenderLayer&, Vector<ScrollingNodeID>& scrollingNodes)
{
ASSERT(layer.isComposited());
auto appendOverflowLayerNodeID = [&scrollingNodes] (const RenderLayer& overflowLayer) {
ASSERT(overflowLayer.isComposited());
if (overflowLayer.isComposited()) {
if (auto scrollingNodeID = overflowLayer.backing()->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling)) {
scrollingNodes.append(*scrollingNodeID);
return;
}
}
LOG(Scrolling, "Layer %p isn't composited or doesn't have scrolling node ID yet", &overflowLayer);
};
// Collect all the composited scrollers which affect the position of this layer relative to its compositing ancestor (which might be inside the scroller or the scroller itself).
bool seenPaintOrderAncestor = false;
traverseAncestorLayers(layer, [&](const RenderLayer& ancestorLayer, bool isContainingBlockChain, bool isPaintOrderAncestor) {
seenPaintOrderAncestor |= isPaintOrderAncestor;
if (isContainingBlockChain && isPaintOrderAncestor)
return AncestorTraversal::Stop;
if (seenPaintOrderAncestor && !isContainingBlockChain && ancestorLayer.hasCompositedScrollableOverflow())
appendOverflowLayerNodeID(ancestorLayer);
return AncestorTraversal::Continue;
});
}
ScrollPositioningBehavior RenderLayerCompositor::computeCoordinatedPositioningForLayer(const RenderLayer& layer, const RenderLayer* compositedAncestor) const
{
if (layer.isRenderViewLayer())
return ScrollPositioningBehavior::None;
if (layer.renderer().isFixedPositioned() && layer.behavesAsFixed())
return ScrollPositioningBehavior::None;
if (!layer.hasCompositedScrollingAncestor())
return ScrollPositioningBehavior::None;
RefPtr scrollingCoordinator = this->scrollingCoordinator();
if (!scrollingCoordinator)
return ScrollPositioningBehavior::None;
if (!compositedAncestor) {
ASSERT_NOT_REACHED();
return ScrollPositioningBehavior::None;
}
return layerScrollBehahaviorRelativeToCompositedAncestor(layer, *compositedAncestor);
}
static Vector<ScrollingNodeID> collectRelatedCoordinatedScrollingNodes(const RenderLayer& layer, ScrollPositioningBehavior positioningBehavior)
{
Vector<ScrollingNodeID> overflowNodeIDs;
switch (positioningBehavior) {
case ScrollPositioningBehavior::Stationary: {
auto* compositedAncestor = layer.ancestorCompositingLayer();
if (!compositedAncestor)
return overflowNodeIDs;
collectStationaryLayerRelatedOverflowNodes(layer, *compositedAncestor, overflowNodeIDs);
break;
}
case ScrollPositioningBehavior::Moves:
case ScrollPositioningBehavior::None:
ASSERT_NOT_REACHED();
break;
}
return overflowNodeIDs;
}
bool RenderLayerCompositor::isLayerForIFrameWithScrollCoordinatedContents(const RenderLayer& layer) const
{
auto* renderWidget = dynamicDowncast<RenderWidget>(layer.renderer());
if (!renderWidget)
return false;
RefPtr frame = renderWidget->frameOwnerElement().contentFrame();
if (frame && is<RemoteFrame>(frame))
return renderWidget->hasLayer() && renderWidget->layer()->isComposited();
RefPtr contentDocument = renderWidget->protectedFrameOwnerElement()->contentDocument();
if (!contentDocument)
return false;
auto* view = contentDocument->renderView();
if (!view)
return false;
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
return scrollingCoordinator->coordinatesScrollingForFrameView(view->protectedFrameView());
return false;
}
bool RenderLayerCompositor::isLayerForPluginWithScrollCoordinatedContents(const RenderLayer& layer) const
{
CheckedPtr renderEmbeddedObject = dynamicDowncast<RenderEmbeddedObject>(layer.renderer());
if (!renderEmbeddedObject)
return false;
return renderEmbeddedObject->usesAsyncScrolling();
}
bool RenderLayerCompositor::isRunningTransformAnimation(RenderLayerModelObject& renderer) const
{
if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
return false;
if (auto styleable = Styleable::fromRenderer(renderer)) {
if (auto* effectsStack = styleable->keyframeEffectStack())
return effectsStack->isCurrentlyAffectingProperty(CSSPropertyTransform)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyRotate)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyScale)
|| effectsStack->isCurrentlyAffectingProperty(CSSPropertyTranslate);
}
return false;
}
// If an element has composited negative z-index children, those children render in front of the
// layer background, so we need an extra 'contents' layer for the foreground of the layer object.
bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer& layer) const
{
for (auto* layer : layer.negativeZOrderLayers()) {
if (layer->isComposited() || layer->hasCompositingDescendant())
return true;
}
return false;
}
bool RenderLayerCompositor::requiresScrollLayer(RootLayerAttachment attachment) const
{
Ref frameView = m_renderView.frameView();
// This applies when the application UI handles scrolling, in which case RenderLayerCompositor doesn't need to manage it.
if (frameView->delegatedScrollingMode() == DelegatedScrollingMode::DelegatedToNativeScrollView && isMainFrameCompositor())
return false;
// We need to handle our own scrolling if we're:
return !m_renderView.protectedFrameView()->platformWidget() // viewless (i.e. non-Mac, or Mac in WebKit2)
|| attachment == RootLayerAttachedViaEnclosingFrame; // a composited frame on Mac
}
void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip, const Color& backgroundColor)
{
if (!scrollbar)
return;
context.save();
const IntRect& scrollbarRect = scrollbar->frameRect();
context.translate(-scrollbarRect.location());
IntRect transformedClip = clip;
transformedClip.moveBy(scrollbarRect.location());
#if HAVE(RUBBER_BANDING)
UNUSED_PARAM(backgroundColor);
#else
if (!scrollbar->isOverlayScrollbar() && backgroundColor.isVisible())
context.fillRect(transformedClip, backgroundColor);
#endif
scrollbar->paint(context, transformedClip);
context.restore();
}
void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, const FloatRect& clip, OptionSet<GraphicsLayerPaintBehavior>)
{
#if PLATFORM(MAC)
LocalDefaultSystemAppearance localAppearance(m_renderView.useDarkAppearance());
#endif
IntRect pixelSnappedRectForIntegralPositionedItems = snappedIntRect(LayoutRect(clip));
if (graphicsLayer == layerForHorizontalScrollbar())
paintScrollbar(RefPtr { m_renderView.frameView().horizontalScrollbar() }.get(), context, pixelSnappedRectForIntegralPositionedItems, m_viewBackgroundColor);
else if (graphicsLayer == layerForVerticalScrollbar())
paintScrollbar(RefPtr { m_renderView.frameView().verticalScrollbar() }.get(), context, pixelSnappedRectForIntegralPositionedItems, m_viewBackgroundColor);
else if (graphicsLayer == layerForScrollCorner()) {
Ref frameView = m_renderView.frameView();
const IntRect& scrollCorner = frameView->scrollCornerRect();
context.save();
context.translate(-scrollCorner.location());
IntRect transformedClip = pixelSnappedRectForIntegralPositionedItems;
transformedClip.moveBy(scrollCorner.location());
frameView->paintScrollCorner(context, transformedClip);
context.restore();
}
}
bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
{
auto* renderViewBacking = m_renderView.layer()->backing();
return renderViewBacking && renderViewBacking->isFrameLayerWithTiledBacking();
}
bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer& layer) const
{
if (!layer.isRenderViewLayer())
return false;
if (m_renderView.settings().fixedBackgroundsPaintRelativeToDocument())
return false;
return supportsFixedRootBackgroundCompositing() && m_renderView.rootBackgroundIsEntirelyFixed();
}
GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
{
// Get the fixed root background from the RenderView layer's backing.
auto* viewLayer = m_renderView.layer();
if (!viewLayer)
return nullptr;
if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
return viewLayer->backing()->backgroundLayer();
return nullptr;
}
void RenderLayerCompositor::resetTrackedRepaintRects()
{
if (RefPtr rootLayer = rootGraphicsLayer()) {
GraphicsLayer::traverse(*rootLayer, [](GraphicsLayer& layer) {
layer.resetTrackedRepaints();
});
}
}
float RenderLayerCompositor::deviceScaleFactor() const
{
return page().deviceScaleFactor();
}
float RenderLayerCompositor::pageScaleFactor() const
{
return page().pageScaleFactor();
}
float RenderLayerCompositor::zoomedOutPageScaleFactor() const
{
return page().zoomedOutPageScaleFactor();
}
float RenderLayerCompositor::contentsScaleMultiplierForNewTiles(const GraphicsLayer*) const
{
#if PLATFORM(IOS_FAMILY)
RefPtr<LegacyTileCache> tileCache;
RefPtr localMainFrame = page().localMainFrame();
if (auto* frameView = localMainFrame ? localMainFrame->view() : nullptr)
tileCache = frameView->legacyTileCache();
if (!tileCache)
return 1;
return tileCache->tileControllerShouldUseLowScaleTiles() ? 0.125 : 1;
#else
return 1;
#endif
}
bool RenderLayerCompositor::documentUsesTiledBacking() const
{
auto* layer = m_renderView.layer();
if (!layer)
return false;
auto* backing = layer->backing();
if (!backing)
return false;
return backing->isFrameLayerWithTiledBacking();
}
bool RenderLayerCompositor::isRootFrameCompositor() const
{
return m_renderView.protectedFrameView()->frame().isRootFrame();
}
bool RenderLayerCompositor::isMainFrameCompositor() const
{
return m_renderView.protectedFrameView()->frame().isMainFrame();
}
bool RenderLayerCompositor::shouldCompositeOverflowControls() const
{
Ref frameView = m_renderView.frameView();
if (!frameView->managesScrollbars())
return false;
if (documentUsesTiledBacking())
return true;
if (m_overflowControlsHostLayer && isRootFrameCompositor())
return true;
#if !USE(COORDINATED_GRAPHICS)
if (!frameView->hasOverlayScrollbars())
return false;
#endif
return true;
}
bool RenderLayerCompositor::requiresHorizontalScrollbarLayer() const
{
return shouldCompositeOverflowControls() && m_renderView.frameView().horizontalScrollbar();
}
bool RenderLayerCompositor::requiresVerticalScrollbarLayer() const
{
return shouldCompositeOverflowControls() && m_renderView.frameView().verticalScrollbar();
}
bool RenderLayerCompositor::requiresScrollCornerLayer() const
{
return shouldCompositeOverflowControls() && m_renderView.protectedFrameView()->isScrollCornerVisible();
}
#if HAVE(RUBBER_BANDING)
bool RenderLayerCompositor::requiresOverhangAreasLayer() const
{
if (!isMainFrameCompositor())
return false;
// We do want a layer if we're using tiled drawing and can scroll.
Ref frameView = m_renderView.frameView();
if (documentUsesTiledBacking() && frameView->hasOpaqueBackground() && !frameView->prohibitsScrolling())
return true;
return false;
}
bool RenderLayerCompositor::requiresContentShadowLayer() const
{
if (!isMainFrameCompositor())
return false;
#if PLATFORM(COCOA)
if (viewHasTransparentBackground())
return false;
// If the background is going to extend, then it doesn't make sense to have a shadow layer.
if (m_renderView.settings().backgroundShouldExtendBeyondPage())
return false;
// On Mac, we want a content shadow layer if we're using tiled drawing and can scroll.
if (documentUsesTiledBacking() && !m_renderView.frameView().prohibitsScrolling())
return true;
#endif
return false;
}
GraphicsLayer* RenderLayerCompositor::updateLayerForTopOverhangArea(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
if (!wantsLayer) {
GraphicsLayer::unparentAndClear(m_layerForTopOverhangArea);
return nullptr;
}
if (!m_layerForTopOverhangArea) {
m_layerForTopOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForTopOverhangArea->setName(MAKE_STATIC_STRING_IMPL("top overhang"));
RefPtr { m_scrolledContentsLayer }->addChildBelow(*m_layerForTopOverhangArea, m_rootContentsLayer.get());
}
return m_layerForTopOverhangArea.get();
}
GraphicsLayer* RenderLayerCompositor::updateLayerForBottomOverhangArea(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
if (!wantsLayer) {
GraphicsLayer::unparentAndClear(m_layerForBottomOverhangArea);
return nullptr;
}
if (!m_layerForBottomOverhangArea) {
m_layerForBottomOverhangArea = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForBottomOverhangArea->setName(MAKE_STATIC_STRING_IMPL("bottom overhang"));
RefPtr { m_scrolledContentsLayer }->addChildBelow(*m_layerForBottomOverhangArea, m_rootContentsLayer.get());
}
Ref frameView = m_renderView.frameView();
m_layerForBottomOverhangArea->setPosition(FloatPoint(0, m_rootContentsLayer->size().height() + frameView->headerHeight()
+ frameView->footerHeight() + frameView->obscuredContentInsets().top()));
return m_layerForBottomOverhangArea.get();
}
GraphicsLayer* RenderLayerCompositor::updateLayerForHeader(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
if (!wantsLayer) {
if (m_layerForHeader) {
GraphicsLayer::unparentAndClear(m_layerForHeader);
// The ScrollingTree knows about the header layer, and the position of the root layer is affected
// by the header layer, so if we remove the header, we need to tell the scrolling tree.
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(m_renderView.protectedFrameView());
}
return nullptr;
}
if (!m_layerForHeader) {
m_layerForHeader = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForHeader->setName(MAKE_STATIC_STRING_IMPL("header"));
RefPtr { m_scrolledContentsLayer }->addChildAbove(*m_layerForHeader, m_rootContentsLayer.get());
}
Ref frameView = m_renderView.frameView();
m_layerForHeader->setPosition(FloatPoint(0,
LocalFrameView::yPositionForHeaderLayer(frameView->scrollPosition(), frameView->obscuredContentInsets().top())));
m_layerForHeader->setAnchorPoint(FloatPoint3D());
RefPtr { m_layerForHeader }->setSize(FloatSize(frameView->visibleWidth(), frameView->headerHeight()));
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(frameView);
page().chrome().client().didAddHeaderLayer(*m_layerForHeader);
return m_layerForHeader.get();
}
GraphicsLayer* RenderLayerCompositor::updateLayerForFooter(bool wantsLayer)
{
if (!isMainFrameCompositor())
return nullptr;
Ref frameView = m_renderView.frameView();
if (!wantsLayer) {
if (m_layerForFooter) {
GraphicsLayer::unparentAndClear(m_layerForFooter);
// The ScrollingTree knows about the footer layer, and the total scrollable size is affected
// by the footer layer, so if we remove the footer, we need to tell the scrolling tree.
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(frameView);
}
return nullptr;
}
if (!m_layerForFooter) {
m_layerForFooter = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForFooter->setName(MAKE_STATIC_STRING_IMPL("footer"));
RefPtr { m_scrolledContentsLayer }->addChildAbove(*m_layerForFooter, m_rootContentsLayer.get());
}
float totalContentHeight = m_rootContentsLayer->size().height() + frameView->headerHeight() + frameView->footerHeight();
m_layerForFooter->setPosition(FloatPoint(0, LocalFrameView::yPositionForFooterLayer(frameView->scrollPosition(),
frameView->obscuredContentInsets().top(), totalContentHeight, frameView->footerHeight())));
m_layerForFooter->setAnchorPoint(FloatPoint3D());
RefPtr { m_layerForFooter }->setSize(FloatSize(frameView->visibleWidth(), frameView->footerHeight()));
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(frameView);
page().chrome().client().didAddFooterLayer(*m_layerForFooter);
return m_layerForFooter.get();
}
void RenderLayerCompositor::updateLayerForOverhangAreasBackgroundColor()
{
if (!m_layerForOverhangAreas)
return;
Color backgroundColor;
if (m_renderView.settings().backgroundShouldExtendBeyondPage()) {
backgroundColor = ([&] {
if (auto underPageBackgroundColorOverride = protectedPage()->underPageBackgroundColorOverride(); underPageBackgroundColorOverride.isValid())
return underPageBackgroundColorOverride;
return m_rootExtendedBackgroundColor;
})();
RefPtr { m_layerForOverhangAreas }->setBackgroundColor(backgroundColor);
}
}
#endif // HAVE(RUBBER_BANDING)
bool RenderLayerCompositor::viewNeedsToInvalidateEventRegionOfEnclosingCompositingLayerForRepaint() const
{
// Event regions are only updated on compositing layers. Non-composited layers must
// delegate to their enclosing compositing layer for repaint to update the event region
// for elements inside them.
return !m_renderView.isComposited();
}
bool RenderLayerCompositor::viewHasTransparentBackground(Color* backgroundColor) const
{
Ref frameView = m_renderView.frameView();
if (frameView->isTransparent()) {
if (backgroundColor)
*backgroundColor = Color(); // Return an invalid color.
return true;
}
Color documentBackgroundColor = frameView->documentBackgroundColor();
if (!documentBackgroundColor.isValid())
documentBackgroundColor = frameView->baseBackgroundColor();
ASSERT(documentBackgroundColor.isValid());
if (backgroundColor)
*backgroundColor = documentBackgroundColor;
return !documentBackgroundColor.isOpaque();
}
// We can't rely on getting layerStyleChanged() for a style change that affects the root background, because the style change may
// be on the body which has no RenderLayer.
void RenderLayerCompositor::rootOrBodyStyleChanged(RenderElement& renderer, const RenderStyle* oldStyle)
{
if (!usesCompositing())
return;
Color oldBackgroundColor;
if (oldStyle)
oldBackgroundColor = oldStyle->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
if (oldBackgroundColor != renderer.style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor))
rootBackgroundColorOrTransparencyChanged();
bool hadFixedBackground = oldStyle && oldStyle->hasEntirelyFixedBackground();
if (hadFixedBackground != renderer.style().hasEntirelyFixedBackground())
rootLayerConfigurationChanged();
if (oldStyle && (oldStyle->overscrollBehaviorX() != renderer.style().overscrollBehaviorX() || oldStyle->overscrollBehaviorY() != renderer.style().overscrollBehaviorY())) {
if (auto* layer = m_renderView.layer())
layer->setNeedsCompositingGeometryUpdate();
}
}
void RenderLayerCompositor::setRootElementCapturedInViewTransition(bool captured)
{
if (m_rootElementCapturedInViewTransition == captured)
return;
m_rootElementCapturedInViewTransition = captured;
updateRootContentsLayerBackgroundColor();
}
void RenderLayerCompositor::updateRootContentsLayerBackgroundColor()
{
if (!m_rootContentsLayer)
return;
RefPtr rootContentsLayer = m_rootContentsLayer;
if (m_rootElementCapturedInViewTransition)
rootContentsLayer->setBackgroundColor(m_viewBackgroundColor);
else
rootContentsLayer->setBackgroundColor(Color());
}
void RenderLayerCompositor::rootBackgroundColorOrTransparencyChanged()
{
if (!usesCompositing())
return;
Color backgroundColor;
bool isTransparent = viewHasTransparentBackground(&backgroundColor);
Color extendedBackgroundColor = m_renderView.settings().backgroundShouldExtendBeyondPage() ? backgroundColor : Color();
bool transparencyChanged = m_viewBackgroundIsTransparent != isTransparent;
bool backgroundColorChanged = m_viewBackgroundColor != backgroundColor;
bool extendedBackgroundColorChanged = m_rootExtendedBackgroundColor != extendedBackgroundColor;
if (!transparencyChanged && !backgroundColorChanged && !extendedBackgroundColorChanged)
return;
LOG(Compositing, "RenderLayerCompositor %p rootBackgroundColorOrTransparencyChanged. isTransparent=%d", this, isTransparent);
m_viewBackgroundIsTransparent = isTransparent;
m_viewBackgroundColor = backgroundColor;
m_rootExtendedBackgroundColor = extendedBackgroundColor;
if (extendedBackgroundColorChanged) {
page().chrome().client().pageExtendedBackgroundColorDidChange();
#if HAVE(RUBBER_BANDING)
updateLayerForOverhangAreasBackgroundColor();
#endif
updateRootContentsLayerBackgroundColor();
}
rootLayerConfigurationChanged();
}
#if HAVE(RUBBER_BANDING)
void RenderLayerCompositor::updateSizeAndPositionForOverhangAreaLayer()
{
if (!m_layerForOverhangAreas)
return;
Ref frameView = m_renderView.frameView();
auto obscuredContentInsets = frameView->obscuredContentInsets();
IntSize overhangAreaSize = frameView->frameRect().size();
overhangAreaSize.contract(obscuredContentInsets.left(), obscuredContentInsets.top());
overhangAreaSize.clampNegativeToZero();
RefPtr { m_layerForOverhangAreas }->setSize(overhangAreaSize);
m_layerForOverhangAreas->setPosition({ obscuredContentInsets.left(), obscuredContentInsets.top() });
}
#endif
void RenderLayerCompositor::updateOverflowControlsLayers()
{
#if HAVE(RUBBER_BANDING)
if (requiresOverhangAreasLayer()) {
if (!m_layerForOverhangAreas) {
m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForOverhangAreas->setName(MAKE_STATIC_STRING_IMPL("overhang areas"));
RefPtr { m_layerForOverhangAreas }->setDrawsContent(false);
updateSizeAndPositionForOverhangAreaLayer();
m_layerForOverhangAreas->setAnchorPoint(FloatPoint3D());
updateLayerForOverhangAreasBackgroundColor();
// We want the overhang areas layer to be positioned below the frame contents,
// so insert it below the clip layer.
RefPtr { m_overflowControlsHostLayer }->addChildBelow(*m_layerForOverhangAreas, RefPtr { layerForClipping() }.get());
}
} else
GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
if (requiresContentShadowLayer()) {
if (!m_contentShadowLayer) {
m_contentShadowLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_contentShadowLayer->setName(MAKE_STATIC_STRING_IMPL("content shadow"));
RefPtr { m_contentShadowLayer }->setSize(m_rootContentsLayer->size());
m_contentShadowLayer->setPosition(m_rootContentsLayer->position());
m_contentShadowLayer->setAnchorPoint(FloatPoint3D());
m_contentShadowLayer->setCustomAppearance(GraphicsLayer::CustomAppearance::ScrollingShadow);
RefPtr { m_scrolledContentsLayer }->addChildBelow(*m_contentShadowLayer, m_rootContentsLayer.get());
}
} else
GraphicsLayer::unparentAndClear(m_contentShadowLayer);
#endif
if (requiresHorizontalScrollbarLayer()) {
if (!m_layerForHorizontalScrollbar) {
m_layerForHorizontalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForHorizontalScrollbar->setAllowsBackingStoreDetaching(false);
m_layerForHorizontalScrollbar->setAllowsTiling(false);
m_layerForHorizontalScrollbar->setShowDebugBorder(m_showDebugBorders);
m_layerForHorizontalScrollbar->setName(MAKE_STATIC_STRING_IMPL("horizontal scrollbar container"));
#if USE(CA)
m_layerForHorizontalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
#endif
RefPtr { m_overflowControlsHostLayer }->addChild(*m_layerForHorizontalScrollbar);
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), ScrollbarOrientation::Horizontal);
}
} else if (m_layerForHorizontalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), ScrollbarOrientation::Horizontal);
}
if (requiresVerticalScrollbarLayer()) {
if (!m_layerForVerticalScrollbar) {
m_layerForVerticalScrollbar = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForVerticalScrollbar->setAllowsBackingStoreDetaching(false);
m_layerForVerticalScrollbar->setAllowsTiling(false);
m_layerForVerticalScrollbar->setShowDebugBorder(m_showDebugBorders);
m_layerForVerticalScrollbar->setName(MAKE_STATIC_STRING_IMPL("vertical scrollbar container"));
#if USE(CA)
m_layerForVerticalScrollbar->setAcceleratesDrawing(acceleratedDrawingEnabled());
#endif
RefPtr { m_overflowControlsHostLayer }->addChild(*m_layerForVerticalScrollbar);
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), ScrollbarOrientation::Vertical);
}
} else if (m_layerForVerticalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_renderView.frameView(), ScrollbarOrientation::Vertical);
}
if (requiresScrollCornerLayer()) {
if (!m_layerForScrollCorner) {
m_layerForScrollCorner = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_layerForScrollCorner->setAllowsBackingStoreDetaching(false);
m_layerForScrollCorner->setShowDebugBorder(m_showDebugBorders);
m_layerForScrollCorner->setName(MAKE_STATIC_STRING_IMPL("scroll corner"));
#if USE(CA)
m_layerForScrollCorner->setAcceleratesDrawing(acceleratedDrawingEnabled());
#endif
RefPtr { m_overflowControlsHostLayer }->addChild(*m_layerForScrollCorner);
}
} else
GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
m_renderView.protectedFrameView()->positionScrollbarLayers();
}
void RenderLayerCompositor::ensureRootLayer()
{
RootLayerAttachment expectedAttachment = isRootFrameCompositor() ? RootLayerAttachedViaChromeClient : RootLayerAttachedViaEnclosingFrame;
if (expectedAttachment == m_rootLayerAttachment)
return;
if (!m_rootContentsLayer) {
m_rootContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_rootContentsLayer->setName(MAKE_STATIC_STRING_IMPL("content root"));
IntRect overflowRect = snappedIntRect(m_renderView.layoutOverflowRect());
RefPtr { m_rootContentsLayer }->setSize(FloatSize(overflowRect.maxX(), overflowRect.maxY()));
m_rootContentsLayer->setPosition(FloatPoint());
#if PLATFORM(IOS_FAMILY)
// Page scale is applied above this on iOS, so we'll just say that our root layer applies it.
if (m_renderView.protectedFrameView()->frame().isRootFrame())
m_rootContentsLayer->setAppliesPageScale();
#endif
// Need to clip to prevent transformed content showing outside this frame
updateRootContentLayerClipping();
updateRootContentsLayerBackgroundColor();
}
if (requiresScrollLayer(expectedAttachment)) {
if (!m_overflowControlsHostLayer) {
ASSERT(!m_scrolledContentsLayer);
ASSERT(!m_clipLayer);
// Create a layer to host the clipping layer and the overflow controls layers.
m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
m_overflowControlsHostLayer->setName(MAKE_STATIC_STRING_IMPL("overflow controls host"));
m_scrolledContentsLayer = GraphicsLayer::create(graphicsLayerFactory(), *this, GraphicsLayer::Type::ScrolledContents);
m_scrolledContentsLayer->setName(MAKE_STATIC_STRING_IMPL("frame scrolled contents"));
m_scrolledContentsLayer->setAnchorPoint({ });
#if PLATFORM(IOS_FAMILY)
if (m_renderView.settings().asyncFrameScrollingEnabled()) {
m_scrollContainerLayer = GraphicsLayer::create(graphicsLayerFactory(), *this, GraphicsLayer::Type::ScrollContainer);
m_scrollContainerLayer->setName(MAKE_STATIC_STRING_IMPL("scroll container"));
m_scrollContainerLayer->setMasksToBounds(true);
m_scrollContainerLayer->setAnchorPoint({ });
m_scrollContainerLayer->addChild(*m_scrolledContentsLayer);
m_overflowControlsHostLayer->addChild(*m_scrollContainerLayer);
}
#endif
// FIXME: m_scrollContainerLayer and m_clipLayer have similar roles here, but m_clipLayer has some special positioning to
// account for clipping and top content inset (see LocalFrameView::positionForInsetClipLayer()).
if (!m_scrollContainerLayer) {
m_clipLayer = GraphicsLayer::create(graphicsLayerFactory(), *this);
RefPtr clipLayer = m_clipLayer;
clipLayer->setName(MAKE_STATIC_STRING_IMPL("frame clipping"));
clipLayer->setMasksToBounds(true);
clipLayer->setAnchorPoint({ });
clipLayer->addChild(*m_scrolledContentsLayer);
RefPtr { m_overflowControlsHostLayer }->addChild(*m_clipLayer);
}
RefPtr { m_scrolledContentsLayer }->addChild(*m_rootContentsLayer);
updateScrollLayerClipping();
updateOverflowControlsLayers();
if (hasCoordinatedScrolling())
scheduleRenderingUpdate();
else
updateScrollLayerPosition();
}
} else {
if (m_overflowControlsHostLayer) {
GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
GraphicsLayer::unparentAndClear(m_clipLayer);
GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
}
}
// Check to see if we have to change the attachment
if (m_rootLayerAttachment != RootLayerUnattached)
detachRootLayer();
attachRootLayer(expectedAttachment);
}
void RenderLayerCompositor::destroyRootLayer()
{
if (!m_rootContentsLayer)
return;
detachRootLayer();
#if HAVE(RUBBER_BANDING)
GraphicsLayer::unparentAndClear(m_layerForOverhangAreas);
#endif
Ref frameView = m_renderView.frameView();
if (m_layerForHorizontalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForHorizontalScrollbar);
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(frameView, ScrollbarOrientation::Horizontal);
if (RefPtr horizontalScrollbar = frameView->horizontalScrollbar())
frameView->invalidateScrollbar(*horizontalScrollbar, IntRect(IntPoint(0, 0), horizontalScrollbar->frameRect().size()));
}
if (m_layerForVerticalScrollbar) {
GraphicsLayer::unparentAndClear(m_layerForVerticalScrollbar);
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(frameView, ScrollbarOrientation::Vertical);
if (RefPtr verticalScrollbar = frameView->verticalScrollbar())
frameView->invalidateScrollbar(*verticalScrollbar, IntRect(IntPoint(0, 0), verticalScrollbar->frameRect().size()));
}
if (m_layerForScrollCorner) {
GraphicsLayer::unparentAndClear(m_layerForScrollCorner);
frameView->invalidateScrollCorner(frameView->scrollCornerRect());
}
if (m_overflowControlsHostLayer) {
GraphicsLayer::unparentAndClear(m_overflowControlsHostLayer);
GraphicsLayer::unparentAndClear(m_clipLayer);
GraphicsLayer::unparentAndClear(m_scrollContainerLayer);
GraphicsLayer::unparentAndClear(m_scrolledContentsLayer);
}
ASSERT(!m_scrolledContentsLayer);
GraphicsLayer::unparentAndClear(m_rootContentsLayer);
}
void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
{
if (!m_rootContentsLayer)
return;
LOG(Compositing, "RenderLayerCompositor %p attachRootLayer %d", this, attachment);
switch (attachment) {
case RootLayerUnattached:
ASSERT_NOT_REACHED();
break;
case RootLayerAttachedViaChromeClient: {
page().chrome().client().attachRootGraphicsLayer(m_renderView.protectedFrameView()->protectedFrame(), RefPtr { rootGraphicsLayer() }.get());
break;
}
case RootLayerAttachedViaEnclosingFrame: {
// The layer will get hooked up via RenderLayerBacking::updateConfiguration()
// for the frame's renderer in the parent document.
if (RefPtr ownerElement = m_renderView.protectedDocument()->ownerElement())
ownerElement->scheduleInvalidateStyleAndLayerComposition();
break;
}
}
m_rootLayerAttachment = attachment;
rootLayerAttachmentChanged();
if (m_shouldFlushOnReattach) {
scheduleRenderingUpdate();
m_shouldFlushOnReattach = false;
}
}
void RenderLayerCompositor::detachRootLayer()
{
if (!m_rootContentsLayer || m_rootLayerAttachment == RootLayerUnattached)
return;
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewWillBeDetached(m_renderView.frameView());
switch (m_rootLayerAttachment) {
case RootLayerAttachedViaEnclosingFrame: {
// The layer will get unhooked up via RenderLayerBacking::updateConfiguration()
// for the frame's renderer in the parent document.
if (RefPtr layer = m_overflowControlsHostLayer)
layer->removeFromParent();
else
RefPtr { m_rootContentsLayer }->removeFromParent();
if (RefPtr ownerElement = m_renderView.protectedDocument()->ownerElement())
ownerElement->scheduleInvalidateStyleAndLayerComposition();
if (auto frameRootScrollingNodeID = m_renderView.protectedFrameView()->scrollingNodeID()) {
if (RefPtr scrollingCoordinator = this->scrollingCoordinator()) {
scrollingCoordinator->frameViewWillBeDetached(m_renderView.frameView());
scrollingCoordinator->unparentNode(*frameRootScrollingNodeID);
}
}
break;
}
case RootLayerAttachedViaChromeClient: {
if (RefPtr scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewWillBeDetached(m_renderView.frameView());
page().chrome().client().attachRootGraphicsLayer(m_renderView.protectedFrameView()->protectedFrame(), nullptr);
}
break;
case RootLayerUnattached:
break;
}
m_rootLayerAttachment = RootLayerUnattached;
rootLayerAttachmentChanged();
}
void RenderLayerCompositor::updateRootLayerAttachment()
{
ensureRootLayer();
}
void RenderLayerCompositor::rootLayerAttachmentChanged()
{
// The document-relative page overlay layer (which is pinned to the main frame's layer tree)
// is moved between different RenderLayerCompositors' layer trees, and needs to be
// reattached whenever we swap in a new RenderLayerCompositor.
if (m_rootLayerAttachment == RootLayerUnattached)
return;
// The attachment can affect whether the RenderView layer's paintsIntoWindow() behavior,
// so call updateDrawsContent() to update that.
auto* layer = m_renderView.layer();
if (auto* backing = layer ? layer->backing() : nullptr)
backing->updateDrawsContent();
if (!m_renderView.protectedFrameView()->frame().isMainFrame())
return;
Ref<GraphicsLayer> overlayHost = page().pageOverlayController().layerWithDocumentOverlays();
RefPtr { m_rootContentsLayer }->addChild(WTFMove(overlayHost));
}
void RenderLayerCompositor::notifyIFramesOfCompositingChange()
{
// Compositing affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so
// we need to schedule a style recalc in our parent document.
if (RefPtr ownerElement = m_renderView.protectedDocument()->ownerElement())
ownerElement->scheduleInvalidateStyleAndLayerComposition();
}
bool RenderLayerCompositor::layerHas3DContent(const RenderLayer& layer) const
{
const RenderStyle& style = layer.renderer().style();
if (style.preserves3D() || style.hasPerspective() || styleHas3DTransformOperation(style))
return true;
const_cast<RenderLayer&>(layer).updateLayerListsIfNeeded();
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(layer));
#endif
for (auto* renderLayer : layer.negativeZOrderLayers()) {
if (layerHas3DContent(*renderLayer))
return true;
}
for (auto* renderLayer : layer.positiveZOrderLayers()) {
if (layerHas3DContent(*renderLayer))
return true;
}
for (auto* renderLayer : layer.normalFlowLayers()) {
if (layerHas3DContent(*renderLayer))
return true;
}
return false;
}
void RenderLayerCompositor::deviceOrPageScaleFactorChanged()
{
// Page scale will only be applied at to the RenderView and sublayers, but the device scale factor
// needs to be applied at the level of rootGraphicsLayer().
if (RefPtr rootLayer = rootGraphicsLayer())
rootLayer->noteDeviceOrPageScaleFactorChangedIncludingDescendants();
}
void RenderLayerCompositor::removeFromScrollCoordinatedLayers(RenderLayer& layer)
{
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator)
m_legacyScrollingLayerCoordinator->removeLayer(layer);
#endif
detachScrollCoordinatedLayer(layer, allScrollCoordinationRoles());
}
FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer& layer) const
{
ASSERT(layer.isComposited());
RefPtr anchorLayer = layer.backing()->viewportAnchorLayer();
if (!anchorLayer) {
ASSERT_NOT_REACHED();
return { };
}
FixedPositionViewportConstraints constraints;
constraints.setLayerPositionAtLastLayout(anchorLayer->position());
constraints.setViewportRectAtLastLayout(m_renderView.protectedFrameView()->rectForFixedPositionLayout());
constraints.setAlignmentOffset(anchorLayer->pixelAlignmentOffset());
const RenderStyle& style = layer.renderer().style();
if (!style.left().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
if (!style.right().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
if (!style.top().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
if (!style.bottom().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
// If left and right are auto, use left.
if (style.left().isAuto() && style.right().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
// If top and bottom are auto, use top.
if (style.top().isAuto() && style.bottom().isAuto())
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
return constraints;
}
StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer& layer) const
{
ASSERT(layer.isComposited());
auto& renderer = downcast<RenderBoxModelObject>(layer.renderer());
RefPtr anchorLayer = layer.backing()->viewportAnchorLayer();
if (!anchorLayer) {
ASSERT_NOT_REACHED();
return { };
}
StickyPositionViewportConstraints constraints;
renderer.computeStickyPositionConstraints(constraints, renderer.constrainingRectForStickyPosition());
constraints.setLayerPositionAtLastLayout(anchorLayer->position());
constraints.setStickyOffsetAtLastLayout(renderer.stickyPositionOffset());
constraints.setAlignmentOffset(anchorLayer->pixelAlignmentOffset());
return constraints;
}
static inline ScrollCoordinationRole scrollCoordinationRoleForNodeType(ScrollingNodeType nodeType)
{
switch (nodeType) {
case ScrollingNodeType::MainFrame:
case ScrollingNodeType::Subframe:
case ScrollingNodeType::Overflow:
case ScrollingNodeType::PluginScrolling:
return ScrollCoordinationRole::Scrolling;
case ScrollingNodeType::OverflowProxy:
return ScrollCoordinationRole::ScrollingProxy;
case ScrollingNodeType::FrameHosting:
return ScrollCoordinationRole::FrameHosting;
case ScrollingNodeType::PluginHosting:
return ScrollCoordinationRole::PluginHosting;
case ScrollingNodeType::Fixed:
case ScrollingNodeType::Sticky:
return ScrollCoordinationRole::ViewportConstrained;
case ScrollingNodeType::Positioned:
return ScrollCoordinationRole::Positioning;
}
ASSERT_NOT_REACHED();
return ScrollCoordinationRole::Scrolling;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::attachScrollingNode(RenderLayer& layer, ScrollingNodeType nodeType, ScrollingTreeState& treeState)
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
if (!scrollingCoordinator)
return std::nullopt;
auto* backing = layer.backing();
// Crash logs suggest that backing can be null here, but we don't know how: rdar://problem/18545452.
ASSERT(backing);
if (!backing)
return std::nullopt;
ASSERT(treeState.hasParent || nodeType == ScrollingNodeType::Subframe);
ASSERT_IMPLIES(nodeType == ScrollingNodeType::MainFrame, !treeState.parentNodeID);
ScrollCoordinationRole role = scrollCoordinationRoleForNodeType(nodeType);
auto nodeID = backing->scrollingNodeIDForRole(role);
nodeID = registerScrollingNodeID(*scrollingCoordinator, nodeID, nodeType, treeState);
LOG_WITH_STREAM(ScrollingTree, stream << "RenderLayerCompositor " << this << " attachScrollingNode " << nodeID << " (layer " << backing->graphicsLayer()->primaryLayerID() << ") type " << nodeType << " parent " << treeState.parentNodeID);
if (!nodeID)
return std::nullopt;
backing->setScrollingNodeIDForRole(*nodeID, role);
#if ENABLE(SCROLLING_THREAD)
if (nodeType == ScrollingNodeType::Subframe)
RefPtr { m_clipLayer }->setScrollingNodeID(*nodeID);
#endif
m_scrollingNodeToLayerMap.add(*nodeID, layer);
return nodeID;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::registerScrollingNodeID(ScrollingCoordinator& scrollingCoordinator, std::optional<ScrollingNodeID> nodeID, ScrollingNodeType nodeType, struct ScrollingTreeState& treeState)
{
if (!nodeID)
nodeID = scrollingCoordinator.uniqueScrollingNodeID();
if (nodeType == ScrollingNodeType::Subframe && !treeState.hasParent)
nodeID = scrollingCoordinator.createNode(m_renderView.protectedFrameView()->frame().rootFrame().frameID(), nodeType, *nodeID);
else {
auto newNodeID = scrollingCoordinator.insertNode(m_renderView.protectedFrameView()->frame().rootFrame().frameID(), nodeType, *nodeID, treeState.parentNodeID, treeState.nextChildIndex);
if (newNodeID != nodeID) {
// We'll get a new nodeID if the type changed (and not if the node is new).
scrollingCoordinator.unparentChildrenAndDestroyNode(*nodeID);
m_scrollingNodeToLayerMap.remove(*nodeID);
}
nodeID = newNodeID;
}
ASSERT(nodeID);
if (!nodeID)
return std::nullopt;
++treeState.nextChildIndex;
return nodeID;
}
void RenderLayerCompositor::detachScrollCoordinatedLayerWithRole(RenderLayer& layer, ScrollingCoordinator& scrollingCoordinator, ScrollCoordinationRole role)
{
auto unregisterNode = [&](ScrollingNodeID nodeID) {
auto childNodes = scrollingCoordinator.childrenOfNode(nodeID);
for (auto childNodeID : childNodes) {
if (auto weakLayer = m_scrollingNodeToLayerMap.get(childNodeID))
weakLayer->setNeedsScrollingTreeUpdate();
}
m_scrollingNodeToLayerMap.remove(nodeID);
};
if (role == ScrollCoordinationRole::ScrollingProxy) {
ASSERT(layer.isComposited());
auto* clippingStack = layer.backing()->ancestorClippingStack();
if (!clippingStack)
return;
auto& stack = clippingStack->stack();
for (auto& entry : stack) {
if (entry.overflowScrollProxyNodeID)
unregisterNode(*entry.overflowScrollProxyNodeID);
}
return;
}
if (auto nodeID = layer.backing()->scrollingNodeIDForRole(role))
unregisterNode(*nodeID);
}
void RenderLayerCompositor::detachScrollCoordinatedLayer(RenderLayer& layer, OptionSet<ScrollCoordinationRole> roles)
{
auto* backing = layer.backing();
if (!backing)
return;
RefPtr scrollingCoordinator = this->scrollingCoordinator();
if (!scrollingCoordinator)
return;
if (roles.contains(ScrollCoordinationRole::Scrolling))
detachScrollCoordinatedLayerWithRole(layer, *scrollingCoordinator, ScrollCoordinationRole::Scrolling);
if (roles.contains(ScrollCoordinationRole::ScrollingProxy))
detachScrollCoordinatedLayerWithRole(layer, *scrollingCoordinator, ScrollCoordinationRole::ScrollingProxy);
if (roles.contains(ScrollCoordinationRole::FrameHosting))
detachScrollCoordinatedLayerWithRole(layer, *scrollingCoordinator, ScrollCoordinationRole::FrameHosting);
if (roles.contains(ScrollCoordinationRole::PluginHosting))
detachScrollCoordinatedLayerWithRole(layer, *scrollingCoordinator, ScrollCoordinationRole::PluginHosting);
if (roles.contains(ScrollCoordinationRole::ViewportConstrained))
detachScrollCoordinatedLayerWithRole(layer, *scrollingCoordinator, ScrollCoordinationRole::ViewportConstrained);
if (roles.contains(ScrollCoordinationRole::Positioning))
detachScrollCoordinatedLayerWithRole(layer, *scrollingCoordinator, ScrollCoordinationRole::Positioning);
backing->detachFromScrollingCoordinator(roles);
}
OptionSet<ScrollCoordinationRole> RenderLayerCompositor::coordinatedScrollingRolesForLayer(const RenderLayer& layer, const RenderLayer* compositingAncestor) const
{
OptionSet<ScrollCoordinationRole> coordinationRoles;
if (isViewportConstrainedFixedOrStickyLayer(layer))
coordinationRoles.add(ScrollCoordinationRole::ViewportConstrained);
if (useCoordinatedScrollingForLayer(layer))
coordinationRoles.add(ScrollCoordinationRole::Scrolling);
auto coordinatedPositioning = computeCoordinatedPositioningForLayer(layer, compositingAncestor);
switch (coordinatedPositioning) {
case ScrollPositioningBehavior::Moves:
coordinationRoles.add(ScrollCoordinationRole::ScrollingProxy);
break;
case ScrollPositioningBehavior::Stationary:
coordinationRoles.add(ScrollCoordinationRole::Positioning);
break;
case ScrollPositioningBehavior::None:
break;
}
if (isLayerForIFrameWithScrollCoordinatedContents(layer))
coordinationRoles.add(ScrollCoordinationRole::FrameHosting);
if (isLayerForPluginWithScrollCoordinatedContents(layer))
coordinationRoles.add(ScrollCoordinationRole::PluginHosting);
return coordinationRoles;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::updateScrollCoordinationForLayer(RenderLayer& layer, const RenderLayer* compositingAncestor, ScrollingTreeState& treeState, OptionSet<ScrollingNodeChangeFlags> changes)
{
auto roles = coordinatedScrollingRolesForLayer(layer, compositingAncestor);
#if PLATFORM(IOS_FAMILY)
if (m_legacyScrollingLayerCoordinator) {
if (roles.contains(ScrollCoordinationRole::ViewportConstrained))
m_legacyScrollingLayerCoordinator->addViewportConstrainedLayer(layer);
else
m_legacyScrollingLayerCoordinator->removeViewportConstrainedLayer(layer);
}
#endif
if (!hasCoordinatedScrolling()) {
// If this frame isn't coordinated, it cannot contain any scrolling tree nodes.
return std::nullopt;
}
auto newNodeID = treeState.parentNodeID;
ScrollingTreeState childTreeState;
ScrollingTreeState* currentTreeState = &treeState;
// If there's a positioning node, it's the parent scrolling node for fixed/sticky/scrolling/frame hosting.
if (roles.contains(ScrollCoordinationRole::Positioning)) {
newNodeID = updateScrollingNodeForPositioningRole(layer, compositingAncestor, *currentTreeState, changes);
childTreeState.parentNodeID = newNodeID;
childTreeState.hasParent = true;
currentTreeState = &childTreeState;
} else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::Positioning);
// If there's a scrolling proxy node, it's the parent scrolling node for fixed/sticky/scrolling/frame hosting.
if (roles.contains(ScrollCoordinationRole::ScrollingProxy)) {
newNodeID = updateScrollingNodeForScrollingProxyRole(layer, *currentTreeState, changes);
childTreeState.parentNodeID = newNodeID;
childTreeState.hasParent = true;
currentTreeState = &childTreeState;
} else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::ScrollingProxy);
// If is fixed or sticky, it's the parent scrolling node for scrolling/frame hosting.
if (roles.contains(ScrollCoordinationRole::ViewportConstrained)) {
newNodeID = updateScrollingNodeForViewportConstrainedRole(layer, *currentTreeState, changes);
// ViewportConstrained nodes are the parent of same-layer scrolling nodes, so adjust the ScrollingTreeState.
childTreeState.parentNodeID = newNodeID;
childTreeState.hasParent = true;
currentTreeState = &childTreeState;
} else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::ViewportConstrained);
if (roles.contains(ScrollCoordinationRole::Scrolling))
newNodeID = updateScrollingNodeForScrollingRole(layer, *currentTreeState, changes);
else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::Scrolling);
if (roles.contains(ScrollCoordinationRole::FrameHosting))
newNodeID = updateScrollingNodeForFrameHostingRole(layer, *currentTreeState, changes);
else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::FrameHosting);
if (roles.contains(ScrollCoordinationRole::PluginHosting))
newNodeID = updateScrollingNodeForPluginHostingRole(layer, *currentTreeState, changes);
else
detachScrollCoordinatedLayer(layer, ScrollCoordinationRole::PluginHosting);
return newNodeID;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::updateScrollingNodeForViewportConstrainedRole(RenderLayer& layer, ScrollingTreeState& treeState, OptionSet<ScrollingNodeChangeFlags> changes)
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
auto nodeType = ScrollingNodeType::Fixed;
if (layer.renderer().style().position() == PositionType::Sticky)
nodeType = ScrollingNodeType::Sticky;
else
ASSERT(layer.renderer().isFixedPositioned());
auto newNodeID = attachScrollingNode(layer, nodeType, treeState);
if (!newNodeID) {
ASSERT_NOT_REACHED();
return treeState.parentNodeID;
}
LOG_WITH_STREAM(Compositing, stream << "Registering ViewportConstrained " << nodeType << " node " << newNodeID << " (layer " << layer.backing()->graphicsLayer()->primaryLayerID() << ") as child of " << treeState.parentNodeID);
if (changes & ScrollingNodeChangeFlags::Layer) {
ASSERT(layer.backing()->viewportAnchorLayer());
scrollingCoordinator->setNodeLayers(*newNodeID, { layer.backing()->viewportAnchorLayer() });
}
if (changes & ScrollingNodeChangeFlags::LayerGeometry) {
switch (nodeType) {
case ScrollingNodeType::Fixed:
scrollingCoordinator->setViewportConstraintedNodeConstraints(*newNodeID, computeFixedViewportConstraints(layer));
break;
case ScrollingNodeType::Sticky:
scrollingCoordinator->setViewportConstraintedNodeConstraints(*newNodeID, computeStickyViewportConstraints(layer));
break;
default:
break;
}
}
return newNodeID;
}
RoundedRect RenderLayerCompositor::parentRelativeScrollableRect(const RenderLayer& layer, const RenderLayer* ancestorLayer) const
{
// FIXME: ancestorLayer needs to be always non-null, so should become a reference.
if (!ancestorLayer) {
if (!layer.scrollableArea())
return RoundedRect { LayoutRect { } };
return RoundedRect { LayoutRect({ }, LayoutSize(CheckedPtr { layer.scrollableArea() }->visibleSize())) };
}
RoundedRect scrollableRect(LayoutRect { });
{
CheckedPtr box = dynamicDowncast<RenderBox>(layer.renderer());
if (!box)
return RoundedRect { LayoutRect { } };
scrollableRect = RoundedRect { box->paddingBoxRect() };
if (box->style().hasBorderRadius()) {
auto borderShape = BorderShape::shapeForBorderRect(box->style(), box->borderBoxRect());
scrollableRect = borderShape.deprecatedInnerRoundedRect();
}
}
auto offset = layer.convertToLayerCoords(ancestorLayer, scrollableRect.rect().location()); // FIXME: broken for columns.
auto rect = scrollableRect.rect();
rect.setLocation(offset);
scrollableRect.setRect(rect);
return scrollableRect;
}
void RenderLayerCompositor::updateScrollingNodeLayers(ScrollingNodeID nodeID, RenderLayer& layer, ScrollingCoordinator& scrollingCoordinator)
{
// Plugins handle their own scrolling node layers.
if (isLayerForPluginWithScrollCoordinatedContents(layer))
return;
if (layer.isRenderViewLayer()) {
Ref frameView = m_renderView.frameView();
scrollingCoordinator.setNodeLayers(nodeID, { nullptr,
scrollContainerLayer(), scrolledContentsLayer(),
fixedRootBackgroundLayer(), clipLayer(), rootContentsLayer(),
frameView->layerForHorizontalScrollbar(), frameView->layerForVerticalScrollbar() });
} else {
CheckedPtr scrollableArea = layer.scrollableArea();
ASSERT(scrollableArea);
auto& backing = *layer.backing();
scrollingCoordinator.setNodeLayers(nodeID, { backing.graphicsLayer(),
backing.scrollContainerLayer(), backing.scrolledContentsLayer(),
nullptr, nullptr, nullptr,
scrollableArea->layerForHorizontalScrollbar(), scrollableArea->layerForVerticalScrollbar() });
}
}
std::optional<ScrollingNodeID> RenderLayerCompositor::updateScrollingNodeForScrollingRole(RenderLayer& layer, ScrollingTreeState& treeState, OptionSet<ScrollingNodeChangeFlags> changes)
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
std::optional<ScrollingNodeID> newNodeID;
if (layer.isRenderViewLayer()) {
Ref frameView = m_renderView.frameView();
ASSERT_UNUSED(frameView, scrollingCoordinator->coordinatesScrollingForFrameView(frameView));
newNodeID = attachScrollingNode(*m_renderView.layer(), m_renderView.frame().isMainFrame() ? ScrollingNodeType::MainFrame : ScrollingNodeType::Subframe, treeState);
if (!newNodeID) {
ASSERT_NOT_REACHED();
return treeState.parentNodeID;
}
if (changes & ScrollingNodeChangeFlags::Layer)
updateScrollingNodeLayers(*newNodeID, layer, *scrollingCoordinator);
if (changes & ScrollingNodeChangeFlags::LayerGeometry) {
scrollingCoordinator->setScrollingNodeScrollableAreaGeometry(*newNodeID, frameView);
scrollingCoordinator->setFrameScrollingNodeState(*newNodeID, frameView);
}
page().chrome().client().ensureScrollbarsController(protectedPage(), frameView, true);
} else {
newNodeID = attachScrollingNode(layer, ScrollingNodeType::Overflow, treeState);
if (!newNodeID) {
ASSERT_NOT_REACHED();
return treeState.parentNodeID;
}
// Plugins handle their own scrolling node layers and geometry.
if (isLayerForPluginWithScrollCoordinatedContents(layer))
return newNodeID;
if (changes & ScrollingNodeChangeFlags::Layer)
updateScrollingNodeLayers(*newNodeID, layer, *scrollingCoordinator);
if (changes & ScrollingNodeChangeFlags::LayerGeometry && treeState.hasParent) {
if (CheckedPtr scrollableArea = layer.scrollableArea())
scrollingCoordinator->setScrollingNodeScrollableAreaGeometry(*newNodeID, *scrollableArea);
}
if (CheckedPtr scrollableArea = layer.scrollableArea())
page().chrome().client().ensureScrollbarsController(protectedPage(), *scrollableArea, true);
}
return newNodeID;
}
bool RenderLayerCompositor::setupScrollProxyRelatedOverflowScrollingNode(ScrollingCoordinator& scrollingCoordinator, ScrollingNodeID scrollingProxyNodeID, RenderLayer& overflowScrollingLayer)
{
auto* backing = overflowScrollingLayer.backing();
if (!backing)
return false;
auto overflowScrollNodeID = backing->scrollingNodeIDForRole(ScrollCoordinationRole::Scrolling);
if (!overflowScrollNodeID)
return false;
scrollingCoordinator.setRelatedOverflowScrollingNodes(scrollingProxyNodeID, { *overflowScrollNodeID });
return true;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::updateScrollingNodeForScrollingProxyRole(RenderLayer& layer, ScrollingTreeState& treeState, OptionSet<ScrollingNodeChangeFlags> changes)
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
auto* clippingStack = layer.backing()->ancestorClippingStack();
if (!clippingStack)
return treeState.parentNodeID;
std::optional<ScrollingNodeID> nodeID;
for (auto& entry : clippingStack->stack()) {
if (!entry.clipData.isOverflowScroll)
continue;
nodeID = registerScrollingNodeID(*scrollingCoordinator, entry.overflowScrollProxyNodeID, ScrollingNodeType::OverflowProxy, treeState);
if (!nodeID) {
ASSERT_NOT_REACHED();
return treeState.parentNodeID;
}
entry.overflowScrollProxyNodeID = *nodeID;
#if ENABLE(SCROLLING_THREAD)
if (RefPtr scrollingLayer = entry.scrollingLayer)
scrollingLayer->setScrollingNodeID(*nodeID);
#endif
if (changes & ScrollingNodeChangeFlags::Layer)
scrollingCoordinator->setNodeLayers(*entry.overflowScrollProxyNodeID, { entry.scrollingLayer.get() });
if (changes & ScrollingNodeChangeFlags::LayerGeometry) {
ASSERT(entry.clipData.clippingLayer);
ASSERT(entry.clipData.clippingLayer->isComposited());
if (!setupScrollProxyRelatedOverflowScrollingNode(*scrollingCoordinator, *entry.overflowScrollProxyNodeID, *entry.clipData.clippingLayer))
m_layersWithUnresolvedRelations.add(layer);
}
}
// FIXME: also m_overflowControlsHostLayerAncestorClippingStack
if (!nodeID)
return treeState.parentNodeID;
return nodeID;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::updateScrollingNodeForFrameHostingRole(RenderLayer& layer, ScrollingTreeState& treeState, OptionSet<ScrollingNodeChangeFlags> changes)
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
auto newNodeID = attachScrollingNode(layer, ScrollingNodeType::FrameHosting, treeState);
if (!newNodeID) {
ASSERT_NOT_REACHED();
return treeState.parentNodeID;
}
if (changes & ScrollingNodeChangeFlags::Layer)
scrollingCoordinator->setNodeLayers(*newNodeID, { layer.backing()->graphicsLayer() });
if (auto* renderWidget = dynamicDowncast<RenderWidget>(layer.renderer())) {
if (auto* frame = renderWidget->frameOwnerElement().contentFrame()) {
if (is<RemoteFrame>(frame))
scrollingCoordinator->setLayerHostingContextIdentifierForFrameHostingNode(*newNodeID, dynamicDowncast<RemoteFrame>(frame)->layerHostingContextIdentifier());
}
}
return newNodeID;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::updateScrollingNodeForPluginHostingRole(RenderLayer& layer, ScrollingTreeState& treeState, OptionSet<ScrollingNodeChangeFlags> changes)
{
UNUSED_PARAM(changes);
auto newNodeID = attachScrollingNode(layer, ScrollingNodeType::PluginHosting, treeState);
if (!newNodeID) {
ASSERT_NOT_REACHED();
return treeState.parentNodeID;
}
return newNodeID;
}
std::optional<ScrollingNodeID> RenderLayerCompositor::updateScrollingNodeForPositioningRole(RenderLayer& layer, const RenderLayer* compositingAncestor, ScrollingTreeState& treeState, OptionSet<ScrollingNodeChangeFlags> changes)
{
RefPtr scrollingCoordinator = this->scrollingCoordinator();
auto newNodeID = attachScrollingNode(layer, ScrollingNodeType::Positioned, treeState);
if (!newNodeID) {
ASSERT_NOT_REACHED();
return treeState.parentNodeID;
}
if (changes & ScrollingNodeChangeFlags::Layer) {
auto& backing = *layer.backing();
scrollingCoordinator->setNodeLayers(*newNodeID, { backing.graphicsLayer() });
}
if (changes & ScrollingNodeChangeFlags::LayerGeometry && treeState.hasParent) {
// Would be nice to avoid calling computeCoordinatedPositioningForLayer() again.
auto positioningBehavior = computeCoordinatedPositioningForLayer(layer, compositingAncestor);
auto relatedNodeIDs = collectRelatedCoordinatedScrollingNodes(layer, positioningBehavior);
scrollingCoordinator->setRelatedOverflowScrollingNodes(*newNodeID, WTFMove(relatedNodeIDs));
RefPtr graphicsLayer = layer.backing()->graphicsLayer();
AbsolutePositionConstraints constraints;
constraints.setAlignmentOffset(graphicsLayer->pixelAlignmentOffset());
constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
scrollingCoordinator->setPositionedNodeConstraints(*newNodeID, constraints);
}
return newNodeID;
}
void RenderLayerCompositor::resolveScrollingTreeRelationships()
{
if (m_layersWithUnresolvedRelations.isEmptyIgnoringNullReferences())
return;
RefPtr scrollingCoordinator = this->scrollingCoordinator();
for (auto& layer : m_layersWithUnresolvedRelations) {
LOG_WITH_STREAM(ScrollingTree, stream << "RenderLayerCompositor::resolveScrollingTreeRelationships - resolving relationship for layer " << &layer);
if (!layer.isComposited())
continue;
if (auto* clippingStack = layer.backing()->ancestorClippingStack()) {
for (auto& entry : clippingStack->stack()) {
if (!entry.clipData.isOverflowScroll)
continue;
bool succeeded = setupScrollProxyRelatedOverflowScrollingNode(*scrollingCoordinator, *entry.overflowScrollProxyNodeID, *entry.clipData.clippingLayer);
ASSERT_UNUSED(succeeded, succeeded);
}
}
}
m_layersWithUnresolvedRelations.clear();
}
void RenderLayerCompositor::updateSynchronousScrollingNodes()
{
if (!hasCoordinatedScrolling())
return;
if (m_renderView.settings().fixedBackgroundsPaintRelativeToDocument())
return;
RefPtr scrollingCoordinator = this->scrollingCoordinator();
ASSERT(scrollingCoordinator);
auto rootScrollingNodeID = m_renderView.protectedFrameView()->scrollingNodeID();
UncheckedKeyHashSet<ScrollingNodeID> nodesToClear;
nodesToClear.reserveInitialCapacity(m_scrollingNodeToLayerMap.size());
for (auto key : m_scrollingNodeToLayerMap.keys())
nodesToClear.add(key);
auto clearSynchronousReasonsOnNonRootNodes = [&] {
for (auto nodeID : nodesToClear) {
if (nodeID == rootScrollingNodeID)
continue;
// Harmless to call setSynchronousScrollingReasons on a non-scrolling node.
scrollingCoordinator->setSynchronousScrollingReasons(nodeID, { });
}
};
auto setHasSlowRepaintObjectsSynchronousScrollingReasonOnRootNode = [&](bool hasSlowRepaintObjects) {
if (!rootScrollingNodeID)
return;
// ScrollingCoordinator manages all bits other than HasSlowRepaintObjects, so maintain their current value.
auto reasons = scrollingCoordinator->synchronousScrollingReasons(*rootScrollingNodeID);
reasons.set({ SynchronousScrollingReason::HasSlowRepaintObjects }, hasSlowRepaintObjects);
scrollingCoordinator->setSynchronousScrollingReasons(*rootScrollingNodeID, reasons);
};
auto slowRepaintObjects = m_renderView.frameView().slowRepaintObjects();
if (!slowRepaintObjects) {
setHasSlowRepaintObjectsSynchronousScrollingReasonOnRootNode(false);
clearSynchronousReasonsOnNonRootNodes();
return;
}
auto relevantScrollingScope = [](const RenderObject& renderer, const RenderLayer& layer) {
if (&layer.renderer() == &renderer)
return layer.boxScrollingScope();
return layer.contentsScrollingScope();
};
bool rootHasSlowRepaintObjects = false;
for (auto& renderer : *slowRepaintObjects) {
auto layer = renderer.enclosingLayer();
if (!layer)
continue;
auto scrollingScope = relevantScrollingScope(renderer, *layer);
if (!scrollingScope)
continue;
if (auto enclosingScrollingNodeID = asyncScrollableContainerNodeID(renderer)) {
LOG_WITH_STREAM(Scrolling, stream << "RenderLayerCompositor::updateSynchronousScrollingNodes - node " << enclosingScrollingNodeID << " slow-scrolling because of fixed backgrounds");
ASSERT(enclosingScrollingNodeID != rootScrollingNodeID);
scrollingCoordinator->setSynchronousScrollingReasons(*enclosingScrollingNodeID, { SynchronousScrollingReason::HasSlowRepaintObjects });
nodesToClear.remove(*enclosingScrollingNodeID);
// Although the root scrolling layer does not have a slow repaint object in it directly,
// we need to set some synchronous scrolling reason on it so that
// ScrollingCoordinator::shouldUpdateScrollLayerPositionSynchronously returns an
// appropriate value. (Scrolling itself would be correct without this, since the
// scrolling tree propagates DescendantScrollersHaveSynchronousScrolling bits up the
// tree, but shouldUpdateScrollLayerPositionSynchronously looks at the scrolling state
// tree instead.)
rootHasSlowRepaintObjects = true;
} else if (!layer->behavesAsFixed()) {
LOG_WITH_STREAM(Scrolling, stream << "RenderLayerCompositor::updateSynchronousScrollingNodes - root node slow-scrolling because of fixed backgrounds");
rootHasSlowRepaintObjects = true;
}
}
setHasSlowRepaintObjectsSynchronousScrollingReasonOnRootNode(rootHasSlowRepaintObjects);
clearSynchronousReasonsOnNonRootNodes();
}
ScrollableArea* RenderLayerCompositor::scrollableAreaForScrollingNodeID(std::optional<ScrollingNodeID> nodeID) const
{
if (!nodeID)
return nullptr;
if (*nodeID == m_renderView.protectedFrameView()->scrollingNodeID())
return &m_renderView.frameView();
if (auto weakLayer = m_scrollingNodeToLayerMap.get(*nodeID))
return weakLayer->scrollableArea();
return nullptr;
}
void RenderLayerCompositor::willRemoveScrollingLayerWithBacking(RenderLayer& layer, RenderLayerBacking& backing)
{
if (scrollingCoordinator())
return;
#if PLATFORM(IOS_FAMILY)
ASSERT(m_renderView.document().backForwardCacheState() == Document::NotInBackForwardCache);
if (m_legacyScrollingLayerCoordinator)
m_legacyScrollingLayerCoordinator->removeScrollingLayer(layer, backing);
#else
UNUSED_PARAM(layer);
UNUSED_PARAM(backing);
#endif
}
// FIXME: This should really be called from the updateBackingAndHierarchy.
void RenderLayerCompositor::didAddScrollingLayer(RenderLayer& layer)
{
if (scrollingCoordinator())
return;
#if PLATFORM(IOS_FAMILY)
ASSERT(m_renderView.document().backForwardCacheState() == Document::NotInBackForwardCache);
if (m_legacyScrollingLayerCoordinator)
m_legacyScrollingLayerCoordinator->addScrollingLayer(layer);
#else
UNUSED_PARAM(layer);
#endif
}
ScrollingCoordinator* RenderLayerCompositor::scrollingCoordinator() const
{
RefPtr frame = m_renderView.document().frame();
if (!frame)
return nullptr;
RefPtr page = frame->page();
if (!page)
return nullptr;
return page->scrollingCoordinator();
}
GraphicsLayerFactory* RenderLayerCompositor::graphicsLayerFactory() const
{
return page().chrome().client().graphicsLayerFactory();
}
void RenderLayerCompositor::updateScrollSnapPropertiesWithFrameView(const LocalFrameView& frameView) const
{
if (RefPtr coordinator = scrollingCoordinator())
coordinator->updateScrollSnapPropertiesWithFrameView(frameView);
}
Page& RenderLayerCompositor::page() const
{
return m_renderView.page();
}
Ref<Page> RenderLayerCompositor::protectedPage() const
{
return page();
}
TextStream& operator<<(TextStream& ts, CompositingUpdateType updateType)
{
switch (updateType) {
case CompositingUpdateType::AfterStyleChange: ts << "after style change"; break;
case CompositingUpdateType::AfterLayout: ts << "after layout"; break;
case CompositingUpdateType::OnScroll: ts << "on scroll"; break;
case CompositingUpdateType::OnCompositedScroll: ts << "on composited scroll"; break;
}
return ts;
}
TextStream& operator<<(TextStream& ts, CompositingPolicy compositingPolicy)
{
switch (compositingPolicy) {
case CompositingPolicy::Normal: ts << "normal"; break;
case CompositingPolicy::Conservative: ts << "conservative"; break;
}
return ts;
}
TextStream& operator<<(TextStream& ts, CompositingReason compositingReason)
{
return ts << compositingReasonToString(compositingReason);
}
TextStream& operator<<(TextStream& ts, const RenderLayerCompositor::BackingSharingState::Provider& provider)
{
ts << "provider " << provider.providerLayer.get() << ", sharing layers ";
bool outputComma = false;
for (auto& layer : provider.sharingLayers) {
if (outputComma)
ts << ", ";
ts << &layer;
outputComma = true;
}
return ts;
}
#if PLATFORM(IOS_FAMILY)
typedef HashMap<PlatformLayer*, std::unique_ptr<ViewportConstraints>> LayerMap;
typedef HashMap<PlatformLayer*, PlatformLayer*> StickyContainerMap;
void LegacyWebKitScrollingLayerCoordinator::registerAllViewportConstrainedLayers(RenderLayerCompositor& compositor)
{
if (!m_coordinateViewportConstrainedLayers)
return;
LayerMap layerMap;
StickyContainerMap stickyContainerMap;
for (auto& layer : m_viewportConstrainedLayers) {
ASSERT(layer.isComposited());
std::unique_ptr<ViewportConstraints> constraints;
if (layer.renderer().isStickilyPositioned()) {
constraints = makeUnique<StickyPositionViewportConstraints>(compositor.computeStickyViewportConstraints(layer));
const RenderLayer* enclosingTouchScrollableLayer = nullptr;
if (compositor.isAsyncScrollableStickyLayer(layer, &enclosingTouchScrollableLayer) && enclosingTouchScrollableLayer) {
ASSERT(enclosingTouchScrollableLayer->isComposited());
// what
stickyContainerMap.add(layer.backing()->graphicsLayer()->platformLayer(), enclosingTouchScrollableLayer->backing()->scrollContainerLayer()->platformLayer());
}
} else if (layer.renderer().isFixedPositioned())
constraints = makeUnique<FixedPositionViewportConstraints>(compositor.computeFixedViewportConstraints(layer));
else
continue;
layerMap.add(layer.backing()->graphicsLayer()->platformLayer(), WTFMove(constraints));
}
m_chromeClient.updateViewportConstrainedLayers(layerMap, stickyContainerMap);
}
void LegacyWebKitScrollingLayerCoordinator::unregisterAllViewportConstrainedLayers()
{
if (!m_coordinateViewportConstrainedLayers)
return;
LayerMap layerMap;
m_chromeClient.updateViewportConstrainedLayers(layerMap, { });
}
void LegacyWebKitScrollingLayerCoordinator::updateScrollingLayer(RenderLayer& layer)
{
auto* backing = layer.backing();
ASSERT(backing);
auto* scrollableArea = layer.scrollableArea();
ASSERT(scrollableArea);
bool allowHorizontalScrollbar = scrollableArea->horizontalNativeScrollbarVisibility() != NativeScrollbarVisibility::HiddenByStyle;
bool allowVerticalScrollbar = scrollableArea->verticalNativeScrollbarVisibility() != NativeScrollbarVisibility::HiddenByStyle;
m_chromeClient.addOrUpdateScrollingLayer(layer.renderer().element(), backing->scrollContainerLayer()->platformLayer(), backing->scrolledContentsLayer()->platformLayer(),
scrollableArea->reachableTotalContentsSize(), allowHorizontalScrollbar, allowVerticalScrollbar);
}
void LegacyWebKitScrollingLayerCoordinator::registerAllScrollingLayers()
{
for (auto& layer : m_scrollingLayers)
updateScrollingLayer(layer);
}
void LegacyWebKitScrollingLayerCoordinator::unregisterAllScrollingLayers()
{
for (auto& layer : m_scrollingLayers) {
auto* backing = layer.backing();
ASSERT(backing);
m_chromeClient.removeScrollingLayer(layer.renderer().element(), backing->scrollContainerLayer()->platformLayer(), backing->scrolledContentsLayer()->platformLayer());
}
}
void LegacyWebKitScrollingLayerCoordinator::addScrollingLayer(RenderLayer& layer)
{
m_scrollingLayers.add(layer);
}
void LegacyWebKitScrollingLayerCoordinator::removeScrollingLayer(RenderLayer& layer, RenderLayerBacking& backing)
{
if (m_scrollingLayers.remove(layer)) {
auto* scrollContainerLayer = backing.scrollContainerLayer()->platformLayer();
auto* scrolledContentsLayer = backing.scrolledContentsLayer()->platformLayer();
m_chromeClient.removeScrollingLayer(layer.renderer().element(), scrollContainerLayer, scrolledContentsLayer);
}
}
void LegacyWebKitScrollingLayerCoordinator::removeLayer(RenderLayer& layer)
{
removeScrollingLayer(layer, *layer.backing());
// We'll put the new set of layers to the client via registerAllViewportConstrainedLayers() at flush time.
m_viewportConstrainedLayers.remove(layer);
}
void LegacyWebKitScrollingLayerCoordinator::addViewportConstrainedLayer(RenderLayer& layer)
{
m_viewportConstrainedLayers.add(layer);
}
void LegacyWebKitScrollingLayerCoordinator::removeViewportConstrainedLayer(RenderLayer& layer)
{
m_viewportConstrainedLayers.remove(layer);
}
#endif
} // namespace WebCore
#if ENABLE(TREE_DEBUGGING)
void showGraphicsLayerTreeForCompositor(WebCore::RenderLayerCompositor& compositor)
{
showGraphicsLayerTree(compositor.rootGraphicsLayer());
}
#endif
|