1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758
|
/*
* Copyright (C) 2006-2024 Apple Inc. All rights reserved.
* Copyright (C) 2013-2014 Google Inc. All rights reserved.
* Copyright (C) 2019 Adobe. All rights reserved.
* Copyright (c) 2020, 2021, 2022 Igalia S.L.
*
* Portions are Copyright (C) 1998 Netscape Communications Corporation.
*
* Other contributors:
* Robert O'Callahan <roc+@cs.cmu.edu>
* David Baron <dbaron@fas.harvard.edu>
* Christian Biesinger <cbiesinger@web.de>
* Randall Jesup <rjesup@wgate.com>
* Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
* Josh Soref <timeless@mac.com>
* Boris Zbarsky <bzbarsky@mit.edu>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Alternatively, the contents of this file may be used under the terms
* of either the Mozilla Public License Version 1.1, found at
* http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
* License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
* (the "GPL"), in which case the provisions of the MPL or the GPL are
* applicable instead of those above. If you wish to allow use of your
* version of this file only under the terms of one of those two
* licenses (the MPL or the GPL) and not to allow others to use your
* version of this file under the LGPL, indicate your decision by
* deletingthe provisions above and replace them with the notice and
* other provisions required by the MPL or the GPL, as the case may be.
* If you do not delete the provisions above, a recipient may use your
* version of this file under any of the LGPL, the MPL or the GPL.
*/
#include "config.h"
#include "RenderLayer.h"
#include "AccessibilityRegionContext.h"
#include "BitmapImage.h"
#include "BorderShape.h"
#include "BoxLayoutShape.h"
#include "CSSFilter.h"
#include "CSSPropertyNames.h"
#include "Chrome.h"
#include "DebugPageOverlays.h"
#include "Document.h"
#include "DocumentMarkerController.h"
#include "Editor.h"
#include "Element.h"
#include "ElementInlines.h"
#include "EventHandler.h"
#include "FEColorMatrix.h"
#include "FEMerge.h"
#include "FloatConversion.h"
#include "FloatPoint3D.h"
#include "FloatRect.h"
#include "FloatRoundedRect.h"
#include "FocusController.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "FrameTree.h"
#include "Gradient.h"
#include "GraphicsContext.h"
#include "HTMLFormControlElement.h"
#include "HTMLFrameElement.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLNames.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "HitTestingTransformState.h"
#include "ImageDocument.h"
#include "InspectorInstrumentation.h"
#include "LegacyRenderSVGForeignObject.h"
#include "LegacyRenderSVGResourceClipper.h"
#include "LegacyRenderSVGRoot.h"
#include "LocalFrame.h"
#include "LocalFrameLoaderClient.h"
#include "LocalFrameView.h"
#include "Logging.h"
#include "OverflowEvent.h"
#include "OverlapTestRequestClient.h"
#include "Page.h"
#include "PlatformMouseEvent.h"
#include "ReferencedSVGResources.h"
#include "RenderAncestorIterator.h"
#include "RenderBoxInlines.h"
#include "RenderElementInlines.h"
#include "RenderFlexibleBox.h"
#include "RenderFragmentContainer.h"
#include "RenderFragmentedFlow.h"
#include "RenderHTMLCanvas.h"
#include "RenderImage.h"
#include "RenderInline.h"
#include "RenderIterator.h"
#include "RenderLayerBacking.h"
#include "RenderLayerCompositor.h"
#include "RenderLayerFilters.h"
#include "RenderLayerInlines.h"
#include "RenderLayerScrollableArea.h"
#include "RenderMarquee.h"
#include "RenderMultiColumnFlow.h"
#include "RenderReplica.h"
#include "RenderSVGForeignObject.h"
#include "RenderSVGHiddenContainer.h"
#include "RenderSVGInline.h"
#include "RenderSVGModelObject.h"
#include "RenderSVGResourceClipper.h"
#include "RenderSVGRoot.h"
#include "RenderSVGText.h"
#include "RenderSVGViewportContainer.h"
#include "RenderScrollbar.h"
#include "RenderScrollbarPart.h"
#include "RenderStyleSetters.h"
#include "RenderTableCell.h"
#include "RenderTableRow.h"
#include "RenderText.h"
#include "RenderTheme.h"
#include "RenderTreeAsText.h"
#include "RenderTreeMutationDisallowedScope.h"
#include "RenderView.h"
#include "SVGClipPathElement.h"
#include "SVGNames.h"
#include "ScaleTransformOperation.h"
#include "ScrollAnimator.h"
#include "ScrollSnapOffsetsInfo.h"
#include "Scrollbar.h"
#include "ScrollbarTheme.h"
#include "ScrollingCoordinator.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "SourceGraphic.h"
#include "StyleAttributeMutationScope.h"
#include "StyleProperties.h"
#include "StyleResolver.h"
#include "Styleable.h"
#include "TransformOperationData.h"
#include "TransformationMatrix.h"
#include "TranslateTransformOperation.h"
#include "ViewTransition.h"
#include "WheelEventTestMonitor.h"
#include <stdio.h>
#include <wtf/HexNumber.h>
#include <wtf/MonotonicTime.h>
#include <wtf/StdLibExtras.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/CString.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/TextStream.h>
namespace WebCore {
using namespace HTMLNames;
class ClipRects : public RefCounted<ClipRects> {
WTF_MAKE_TZONE_ALLOCATED_INLINE(ClipRects);
public:
static Ref<ClipRects> create()
{
return adoptRef(*new ClipRects);
}
static Ref<ClipRects> create(const ClipRects& other)
{
return adoptRef(*new ClipRects(other));
}
void reset()
{
m_overflowClipRect.reset();
m_fixedClipRect.reset();
m_posClipRect.reset();
m_fixed = false;
}
const ClipRect& overflowClipRect() const { return m_overflowClipRect; }
void setOverflowClipRect(const ClipRect& clipRect) { m_overflowClipRect = clipRect; }
const ClipRect& fixedClipRect() const { return m_fixedClipRect; }
void setFixedClipRect(const ClipRect& clipRect) { m_fixedClipRect = clipRect; }
const ClipRect& posClipRect() const { return m_posClipRect; }
void setPosClipRect(const ClipRect& clipRect) { m_posClipRect = clipRect; }
bool fixed() const { return m_fixed; }
void setFixed(bool fixed) { m_fixed = fixed; }
void setOverflowClipRectAffectedByRadius() { m_overflowClipRect.setAffectedByRadius(true); }
bool operator==(const ClipRects& other) const
{
return m_overflowClipRect == other.overflowClipRect()
&& m_fixedClipRect == other.fixedClipRect()
&& m_posClipRect == other.posClipRect()
&& m_fixed == other.fixed();
}
ClipRects& operator=(const ClipRects& other)
{
m_overflowClipRect = other.overflowClipRect();
m_fixedClipRect = other.fixedClipRect();
m_posClipRect = other.posClipRect();
m_fixed = other.fixed();
return *this;
}
private:
ClipRects() = default;
ClipRects(const LayoutRect& clipRect)
: m_overflowClipRect(clipRect)
, m_fixedClipRect(clipRect)
, m_posClipRect(clipRect)
{
}
ClipRects(const ClipRects& other)
: RefCounted()
, m_fixed(other.fixed())
, m_overflowClipRect(other.overflowClipRect())
, m_fixedClipRect(other.fixedClipRect())
, m_posClipRect(other.posClipRect())
{
}
bool m_fixed { false };
ClipRect m_overflowClipRect;
ClipRect m_fixedClipRect;
ClipRect m_posClipRect;
};
class ClipRectsCache {
WTF_MAKE_TZONE_ALLOCATED_INLINE(ClipRectsCache);
public:
ClipRectsCache()
{
#if ASSERT_ENABLED
for (int i = 0; i < NumCachedClipRectsTypes; ++i) {
m_clipRectsRoot[i] = nullptr;
}
#endif
}
ClipRects* getClipRects(const RenderLayer::ClipRectsContext& context) const
{
return m_clipRects[getIndex(context.clipRectsType, context.respectOverflowClip())].get();
}
void setClipRects(ClipRectsType clipRectsType, bool respectOverflowClip, RefPtr<ClipRects>&& clipRects)
{
m_clipRects[getIndex(clipRectsType, respectOverflowClip)] = WTFMove(clipRects);
}
#if ASSERT_ENABLED
std::array<const RenderLayer*, NumCachedClipRectsTypes> m_clipRectsRoot;
#endif
private:
unsigned getIndex(ClipRectsType clipRectsType, bool respectOverflowClip) const
{
unsigned index = static_cast<unsigned>(clipRectsType);
if (respectOverflowClip)
index += static_cast<unsigned>(NumCachedClipRectsTypes);
ASSERT_WITH_SECURITY_IMPLICATION(index < NumCachedClipRectsTypes * 2);
return index;
}
std::array<RefPtr<ClipRects>, NumCachedClipRectsTypes * 2> m_clipRects;
};
void makeMatrixRenderable(TransformationMatrix& matrix, bool has3DRendering)
{
if (!has3DRendering)
matrix.makeAffine();
}
#if !LOG_DISABLED
static TextStream& operator<<(TextStream& ts, const ClipRects& clipRects)
{
TextStream::GroupScope scope(ts);
ts << indent << "ClipRects\n";
ts << indent << " overflow : " << clipRects.overflowClipRect() << "\n";
ts << indent << " fixed : " << clipRects.fixedClipRect() << "\n";
ts << indent << " positioned: " << clipRects.posClipRect() << "\n";
return ts;
}
#endif
static ScrollingScope nextScrollingScope()
{
static ScrollingScope currentScope = 0;
return ++currentScope;
}
WTF_MAKE_TZONE_OR_ISO_ALLOCATED_IMPL(RenderLayer);
RenderLayer::RenderLayer(RenderLayerModelObject& renderer)
: m_isRenderViewLayer(renderer.isRenderView())
, m_forcedStackingContext(renderer.isRenderMedia())
, m_isNormalFlowOnly(false)
, m_isCSSStackingContext(false)
, m_canBeBackdropRoot(false)
, m_hasBackdropFilterDescendantsWithoutRoot(false)
, m_isOpportunisticStackingContext(false)
, m_zOrderListsDirty(false)
, m_normalFlowListDirty(true)
, m_hadNegativeZOrderList(false)
, m_inResizeMode(false)
, m_hasSelfPaintingLayerDescendant(false)
, m_hasSelfPaintingLayerDescendantDirty(false)
, m_usedTransparency(false)
, m_paintingInsideReflection(false)
, m_visibleContentStatusDirty(true)
, m_hasVisibleContent(false)
, m_visibleDescendantStatusDirty(false)
, m_hasVisibleDescendant(false)
, m_isFixedIntersectingViewport(false)
, m_behavesAsFixed(false)
, m_3DTransformedDescendantStatusDirty(true)
, m_has3DTransformedDescendant(false)
, m_hasCompositingDescendant(false)
, m_hasCompositedNonContainedDescendants(false)
, m_hasCompositedScrollingAncestor(false)
, m_hasFixedContainingBlockAncestor(false)
, m_hasTransformedAncestor(false)
, m_has3DTransformedAncestor(false)
, m_insideSVGForeignObject(false)
, m_indirectCompositingReason(static_cast<unsigned>(IndirectCompositingReason::None))
, m_viewportConstrainedNotCompositedReason(NoNotCompositedReason)
#if ASSERT_ENABLED
, m_layerListMutationAllowed(true)
#endif
, m_blendMode(static_cast<unsigned>(BlendMode::Normal))
, m_hasNotIsolatedCompositedBlendingDescendants(false)
, m_hasNotIsolatedBlendingDescendants(false)
, m_hasNotIsolatedBlendingDescendantsStatusDirty(false)
, m_renderer(renderer)
{
setIsNormalFlowOnly(shouldBeNormalFlowOnly());
setIsCSSStackingContext(shouldBeCSSStackingContext());
setCanBeBackdropRoot(computeCanBeBackdropRoot());
setNeedsPositionUpdate();
m_isSelfPaintingLayer = shouldBeSelfPaintingLayer();
if (isRenderViewLayer())
m_boxScrollingScope = m_contentsScrollingScope = nextScrollingScope();
auto needsVisibleContentStatusUpdate = [&]() {
if (renderer.firstChild())
return false;
// Leave m_visibleContentStatusDirty = true in any case. The associated renderer needs to be inserted into the
// render tree, before we can determine the visible content status. The visible content status of a SVG renderer
// depends on its ancestors (all children of RenderSVGHiddenContainer are recursively invisible, no matter what).
if (renderer.isSVGLayerAwareRenderer() && renderer.document().settings().layerBasedSVGEngineEnabled())
return false;
// We need the parent to know if we have skipped content or content-visibility root.
if (renderer.style().hasSkippedContent() && !renderer.parent())
return false;
return true;
}();
if (needsVisibleContentStatusUpdate) {
m_visibleContentStatusDirty = false;
m_hasVisibleContent = renderer.style().usedVisibility() == Visibility::Visible;
}
}
RenderLayer::~RenderLayer()
{
if (inResizeMode())
renderer().frame().eventHandler().resizeLayerDestroyed();
if (m_reflection)
removeReflection();
clearLayerScrollableArea();
clearLayerFilters();
// Child layers will be deleted by their corresponding render objects, so
// we don't need to delete them ourselves.
clearBacking(true);
removeClipperClientIfNeeded();
// Layer and all its children should be removed from the tree before destruction.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(renderer().renderTreeBeingDestroyed() || !parent());
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(renderer().renderTreeBeingDestroyed() || !firstChild());
}
RenderLayer::PaintedContentRequest::PaintedContentRequest(const RenderLayer& owningLayer)
{
#if HAVE(SUPPORT_HDR_DISPLAY)
if (owningLayer.page().canDrawHDRContent())
makePaintedHDRContentUnknown();
#else
UNUSED_PARAM(owningLayer);
#endif
}
void RenderLayer::removeClipperClientIfNeeded() const
{
auto& style = renderer().style();
if (RefPtr referenceClipPathOperation = dynamicDowncast<ReferencePathOperation>(style.clipPath())) {
if (auto* clipperRenderer = ReferencedSVGResources::referencedClipperRenderer(renderer().treeScopeForSVGReferences(), *referenceClipPathOperation))
clipperRenderer->removeClientFromCache(renderer());
}
}
void RenderLayer::addChild(RenderLayer& child, RenderLayer* beforeChild)
{
RenderLayer* prevSibling = beforeChild ? beforeChild->previousSibling() : lastChild();
if (prevSibling) {
child.setPreviousSibling(prevSibling);
prevSibling->setNextSibling(&child);
ASSERT(prevSibling != &child);
} else
setFirstChild(&child);
if (beforeChild) {
beforeChild->setPreviousSibling(&child);
child.setNextSibling(beforeChild);
ASSERT(beforeChild != &child);
} else
setLastChild(&child);
child.m_parent = this;
child.setSelfAndDescendantsNeedPositionUpdate();
dirtyPaintOrderListsOnChildChange(child);
child.updateAncestorDependentState();
dirtyAncestorChainVisibleDescendantStatus();
child.updateDescendantDependentFlags();
if (child.isSelfPaintingLayer() || child.hasSelfPaintingLayerDescendant())
setAncestorChainHasSelfPaintingLayerDescendant();
if (compositor().hasContentCompositingLayers())
setDescendantsNeedCompositingRequirementsTraversal();
if (child.hasDescendantNeedingCompositingRequirementsTraversal() || child.needsCompositingRequirementsTraversal())
child.setAncestorsHaveCompositingDirtyFlag(Compositing::HasDescendantNeedingRequirementsTraversal);
if (child.hasDescendantNeedingUpdateBackingOrHierarchyTraversal() || child.needsUpdateBackingOrHierarchyTraversal())
child.setAncestorsHaveCompositingDirtyFlag(Compositing::HasDescendantNeedingBackingOrHierarchyTraversal);
if (child.hasBlendMode() || (child.hasNotIsolatedBlendingDescendants() && !child.isolatesBlending()))
updateAncestorChainHasBlendingDescendants(); // Why not just dirty?
#if ENABLE(ASYNC_SCROLLING)
if (child.hasDescendantNeedingEventRegionUpdate() || (child.isComposited() && child.backing()->needsEventRegionUpdate()))
child.setAncestorsHaveDescendantNeedingEventRegionUpdate();
#endif
}
void RenderLayer::removeChild(RenderLayer& oldChild)
{
if (!renderer().renderTreeBeingDestroyed())
compositor().layerWillBeRemoved(*this, oldChild);
// remove the child
if (oldChild.previousSibling())
oldChild.previousSibling()->setNextSibling(oldChild.nextSibling());
if (oldChild.nextSibling())
oldChild.nextSibling()->setPreviousSibling(oldChild.previousSibling());
if (m_first == &oldChild)
m_first = oldChild.nextSibling();
if (m_last == &oldChild)
m_last = oldChild.previousSibling();
dirtyPaintOrderListsOnChildChange(oldChild);
oldChild.setPreviousSibling(nullptr);
oldChild.setNextSibling(nullptr);
oldChild.m_parent = nullptr;
oldChild.updateDescendantDependentFlags();
if (oldChild.m_hasVisibleContent || oldChild.m_hasVisibleDescendant)
dirtyAncestorChainVisibleDescendantStatus();
if (oldChild.isSelfPaintingLayer() || oldChild.hasSelfPaintingLayerDescendant())
dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
if (compositor().hasContentCompositingLayers())
setDescendantsNeedCompositingRequirementsTraversal();
if (oldChild.hasBlendMode() || (oldChild.hasNotIsolatedBlendingDescendants() && !oldChild.isolatesBlending()))
dirtyAncestorChainHasBlendingDescendants();
if (renderer().style().usedVisibility() != Visibility::Visible)
dirtyVisibleContentStatus();
}
void RenderLayer::dirtyPaintOrderListsOnChildChange(RenderLayer& child)
{
if (child.isNormalFlowOnly())
dirtyNormalFlowList();
if (!child.isNormalFlowOnly() || child.firstChild()) {
// Dirty the z-order list in which we are contained. The stackingContext() can be null in the
// case where we're building up generated content layers. This is ok, since the lists will start
// off dirty in that case anyway.
child.dirtyStackingContextZOrderLists();
}
}
void RenderLayer::insertOnlyThisLayer()
{
if (!m_parent && renderer().parent()) {
// We need to connect ourselves when our renderer() has a parent.
// Find our enclosingLayer and add ourselves.
auto* parentLayer = renderer().layerParent();
if (!parentLayer)
return;
auto* beforeChild = parentLayer->reflectionLayer() != this ? renderer().layerNextSibling(*parentLayer) : nullptr;
parentLayer->addChild(*this, beforeChild);
}
// Remove all descendant layers from the hierarchy and add them to the new position.
for (auto& child : childrenOfType<RenderElement>(renderer()))
child.moveLayers(*this);
// Clear out all the clip rects.
clearClipRectsIncludingDescendants();
}
void RenderLayer::removeOnlyThisLayer()
{
if (!m_parent)
return;
compositor().layerWillBeRemoved(*m_parent, *this);
// Dirty the clip rects.
clearClipRectsIncludingDescendants();
RenderLayer* nextSib = nextSibling();
// Remove the child reflection layer before moving other child layers.
// The reflection layer should not be moved to the parent.
if (auto* reflectionLayer = this->reflectionLayer())
removeChild(*reflectionLayer);
// Now walk our kids and reattach them to our parent.
RenderLayer* current = m_first;
while (current) {
RenderLayer* next = current->nextSibling();
removeChild(*current);
m_parent->addChild(*current, nextSib);
current->setRepaintStatus(RepaintStatus::NeedsFullRepaint);
current = next;
}
// Remove us from the parent.
m_parent->removeChild(*this);
renderer().destroyLayer();
}
static bool canCreateStackingContext(const RenderLayer& layer)
{
auto& renderer = layer.renderer();
return renderer.hasTransformRelatedProperty()
|| renderer.hasClipPath()
|| renderer.hasFilter()
|| renderer.hasMask()
|| renderer.hasBackdropFilter()
#if HAVE(CORE_MATERIAL)
|| renderer.hasAppleVisualEffect()
#endif
|| renderer.hasBlendMode()
|| renderer.isTransparent()
|| renderer.requiresRenderingConsolidationForViewTransition()
|| renderer.isRenderViewTransitionCapture()
|| renderer.isPositioned() // Note that this only creates stacking context in conjunction with explicit z-index.
|| renderer.hasReflection()
|| renderer.style().hasIsolation()
|| renderer.shouldApplyPaintContainment()
|| !renderer.style().hasAutoUsedZIndex()
|| (renderer.style().willChange() && renderer.style().willChange()->canCreateStackingContext())
|| layer.establishesTopLayer();
}
bool RenderLayer::shouldBeNormalFlowOnly() const
{
if (canCreateStackingContext(*this))
return false;
return renderer().hasNonVisibleOverflow()
|| renderer().isRenderHTMLCanvas()
|| renderer().isRenderVideo()
|| renderer().isRenderEmbeddedObject()
|| renderer().isRenderIFrame()
|| (renderer().style().specifiesColumns() && !isRenderViewLayer())
|| renderer().isRenderFragmentedFlow();
}
bool RenderLayer::shouldBeCSSStackingContext() const
{
return !renderer().style().hasAutoUsedZIndex() || renderer().shouldApplyLayoutContainment() || renderer().shouldApplyPaintContainment() || renderer().requiresRenderingConsolidationForViewTransition() || renderer().isRenderViewTransitionCapture() || renderer().isViewTransitionRoot() || isRenderViewLayer();
}
bool RenderLayer::computeCanBeBackdropRoot() const
{
if (!renderer().settings().cssUnprefixedBackdropFilterEnabled())
return false;
// In order to match other impls and not the spec, the document element should
// only be a backdrop root (and be isolated from the base background color) if
// another group rendering effect is present.
// https://github.com/w3c/fxtf-drafts/issues/557
return isRenderViewLayer()
|| renderer().isTransparent()
|| renderer().hasBackdropFilter()
#if HAVE(CORE_MATERIAL)
|| renderer().hasAppleVisualEffect()
#endif
|| renderer().hasClipPath()
|| renderer().hasFilter()
|| renderer().hasBlendMode()
|| renderer().hasMask()
|| (renderer().requiresRenderingConsolidationForViewTransition() && !renderer().isDocumentElementRenderer())
|| (renderer().style().willChange() && renderer().style().willChange()->canBeBackdropRoot());
}
bool RenderLayer::setIsNormalFlowOnly(bool isNormalFlowOnly)
{
if (isNormalFlowOnly == m_isNormalFlowOnly)
return false;
m_isNormalFlowOnly = isNormalFlowOnly;
if (auto* p = parent())
p->dirtyNormalFlowList();
dirtyStackingContextZOrderLists();
return true;
}
void RenderLayer::isStackingContextChanged()
{
dirtyStackingContextZOrderLists();
setSelfAndDescendantsNeedPositionUpdate();
if (isStackingContext())
dirtyZOrderLists();
else
clearZOrderLists();
}
bool RenderLayer::setIsOpportunisticStackingContext(bool isStacking)
{
bool wasStacking = isStackingContext();
m_isOpportunisticStackingContext = isStacking;
if (wasStacking == isStackingContext())
return false;
isStackingContextChanged();
return true;
}
bool RenderLayer::setIsCSSStackingContext(bool isCSSStackingContext)
{
bool wasStacking = isStackingContext();
m_isCSSStackingContext = isCSSStackingContext;
if (wasStacking == isStackingContext())
return false;
isStackingContextChanged();
return true;
}
bool RenderLayer::setCanBeBackdropRoot(bool canBeBackdropRoot)
{
if (m_canBeBackdropRoot == canBeBackdropRoot)
return false;
m_canBeBackdropRoot = canBeBackdropRoot;
return true;
}
RenderLayer* RenderLayer::stackingContext() const
{
auto* layer = parent();
while (layer && !layer->isStackingContext())
layer = layer->parent();
ASSERT(!layer || layer->isStackingContext());
ASSERT_IMPLIES(establishesTopLayer(), !layer || layer == renderer().view().layer());
return layer;
}
void RenderLayer::dirtyZOrderLists()
{
ASSERT(layerListMutationAllowed());
ASSERT(isStackingContext());
if (m_posZOrderList)
m_posZOrderList->clear();
if (m_negZOrderList)
m_negZOrderList->clear();
m_zOrderListsDirty = true;
// FIXME: Ideally, we'd only dirty if the lists changed.
if (hasCompositingDescendant())
setNeedsCompositingPaintOrderChildrenUpdate();
}
void RenderLayer::dirtyStackingContextZOrderLists()
{
if (auto* sc = stackingContext())
sc->dirtyZOrderLists();
}
void RenderLayer::dirtyHiddenStackingContextAncestorZOrderLists()
{
for (auto* sc = stackingContext(); sc; sc = sc->stackingContext()) {
sc->dirtyZOrderLists();
if (sc->hasVisibleContent())
break;
}
}
bool RenderLayer::willCompositeClipPath() const
{
if (!isComposited())
return false;
auto* clipPath = renderer().style().clipPath();
if (!clipPath)
return false;
if (renderer().hasMask())
return false;
return (clipPath->type() != PathOperation::Type::Shape || clipPath->type() == PathOperation::Type::Shape) && GraphicsLayer::supportsLayerType(GraphicsLayer::Type::Shape);
}
void RenderLayer::dirtyNormalFlowList()
{
ASSERT(layerListMutationAllowed());
if (m_normalFlowList)
m_normalFlowList->clear();
m_normalFlowListDirty = true;
if (hasCompositingDescendant())
setNeedsCompositingPaintOrderChildrenUpdate();
}
void RenderLayer::updateNormalFlowList()
{
if (!m_normalFlowListDirty)
return;
ASSERT(layerListMutationAllowed());
for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
// Ignore non-overflow layers and reflections.
if (child->isNormalFlowOnly() && !isReflectionLayer(*child)) {
if (!m_normalFlowList)
m_normalFlowList = makeUnique<Vector<RenderLayer*>>();
m_normalFlowList->append(child);
child->setWasIncludedInZOrderTree();
}
}
if (m_normalFlowList)
m_normalFlowList->shrinkToFit();
m_normalFlowListDirty = false;
}
void RenderLayer::rebuildZOrderLists()
{
ASSERT(layerListMutationAllowed());
ASSERT(isDirtyStackingContext());
OptionSet<Compositing> childDirtyFlags;
rebuildZOrderLists(m_posZOrderList, m_negZOrderList, childDirtyFlags);
m_zOrderListsDirty = false;
bool hasNegativeZOrderList = m_negZOrderList && m_negZOrderList->size();
// Having negative z-order lists affect whether a compositing layer needs a foreground layer.
// Ideally we'd only trigger this when having z-order children changes, but we blow away the old z-order
// lists on dirtying so we don't know the old state.
if (hasNegativeZOrderList != m_hadNegativeZOrderList) {
m_hadNegativeZOrderList = hasNegativeZOrderList;
if (isComposited())
setNeedsCompositingConfigurationUpdate();
}
// Building lists may have added layers with dirty flags, so make sure we propagate dirty bits up the tree.
if (m_compositingDirtyBits.containsAll({ Compositing::DescendantsNeedRequirementsTraversal, Compositing::DescendantsNeedBackingAndHierarchyTraversal }))
return;
if (childDirtyFlags.containsAny(computeCompositingRequirementsFlags()))
setDescendantsNeedCompositingRequirementsTraversal();
if (childDirtyFlags.containsAny(updateBackingOrHierarchyFlags()))
setDescendantsNeedUpdateBackingAndHierarchyTraversal();
}
void RenderLayer::rebuildZOrderLists(std::unique_ptr<Vector<RenderLayer*>>& posZOrderList, std::unique_ptr<Vector<RenderLayer*>>& negZOrderList, OptionSet<Compositing>& accumulatedDirtyFlags)
{
for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
if (!isReflectionLayer(*child))
child->collectLayers(posZOrderList, negZOrderList, accumulatedDirtyFlags);
}
auto compareZIndex = [] (const RenderLayer* first, const RenderLayer* second) -> bool {
return first->zIndex() < second->zIndex();
};
// Sort the two lists.
if (posZOrderList) {
std::stable_sort(posZOrderList->begin(), posZOrderList->end(), compareZIndex);
posZOrderList->shrinkToFit();
}
if (negZOrderList) {
std::stable_sort(negZOrderList->begin(), negZOrderList->end(), compareZIndex);
negZOrderList->shrinkToFit();
}
if (isRenderViewLayer() && renderer().document().hasTopLayerElement()) {
auto topLayerLayers = topLayerRenderLayers(renderer().view());
if (topLayerLayers.size()) {
if (!posZOrderList)
posZOrderList = makeUnique<Vector<RenderLayer*>>();
CheckedPtr<RenderLayer> viewTransitionLayer;
if (posZOrderList->size() && posZOrderList->last()->renderer().style().pseudoElementType() == PseudoId::ViewTransition)
viewTransitionLayer = posZOrderList->takeLast();
posZOrderList->appendVector(topLayerLayers);
if (viewTransitionLayer)
posZOrderList->append(viewTransitionLayer.get());
}
}
}
void RenderLayer::removeSelfFromCompositor()
{
if (parent())
compositor().layerWillBeRemoved(*parent(), *this);
clearBacking();
}
void RenderLayer::removeDescendantsFromCompositor()
{
for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
child->removeSelfFromCompositor();
child->removeDescendantsFromCompositor();
}
}
void RenderLayer::setWasOmittedFromZOrderTree()
{
if (m_wasOmittedFromZOrderTree)
return;
ASSERT(!isNormalFlowOnly());
removeSelfFromCompositor();
// Omitting a stacking context removes the whole subtree, otherwise collectLayers will
// visit and omit/include descendants separately.
if (isStackingContext())
removeDescendantsFromCompositor();
if (compositor().hasContentCompositingLayers() && parent())
parent()->setDescendantsNeedCompositingRequirementsTraversal();
m_wasOmittedFromZOrderTree = true;
}
void RenderLayer::collectLayers(std::unique_ptr<Vector<RenderLayer*>>& positiveZOrderList, std::unique_ptr<Vector<RenderLayer*>>& negativeZOrderList, OptionSet<Compositing>& accumulatedDirtyFlags)
{
ASSERT(!descendantDependentFlagsAreDirty());
if (establishesTopLayer())
return;
bool isStacking = isStackingContext();
bool layerOrDescendantsAreVisible = m_hasVisibleContent || m_alwaysIncludedInZOrderLists || m_hasVisibleDescendant || m_hasAlwaysIncludedInZOrderListsDescendants;
layerOrDescendantsAreVisible |= page().hasEverSetVisibilityAdjustment();
// Normal flow layers are just painted by their enclosing layers, so they don't get put in zorder lists.
if (!isNormalFlowOnly()) {
if (layerOrDescendantsAreVisible) {
auto& layerList = (zIndex() >= 0) ? positiveZOrderList : negativeZOrderList;
if (!layerList)
layerList = makeUnique<Vector<RenderLayer*>>();
layerList->append(this);
accumulatedDirtyFlags.add(m_compositingDirtyBits);
setWasIncludedInZOrderTree();
} else
setWasOmittedFromZOrderTree();
}
// Recur into our children to collect more layers, but only if we don't establish
// a stacking context/container.
if (!isStacking) {
for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
// Ignore reflections.
if (!isReflectionLayer(*child))
child->collectLayers(positiveZOrderList, negativeZOrderList, accumulatedDirtyFlags);
}
}
}
void RenderLayer::setNeedsPositionUpdate()
{
m_layerPositionDirtyBits.add(LayerPositionUpdates::NeedsPositionUpdate);
for (auto* layer = parent(); layer; layer = layer->parent()) {
if (layer->m_layerPositionDirtyBits.contains(LayerPositionUpdates::DescendantNeedsPositionUpdate))
break;
layer->m_layerPositionDirtyBits.add(LayerPositionUpdates::DescendantNeedsPositionUpdate);
}
}
bool RenderLayer::needsPositionUpdate() const
{
if (m_layerPositionDirtyBits.containsAny({ LayerPositionUpdates::NeedsPositionUpdate, LayerPositionUpdates::DescendantNeedsPositionUpdate }))
return true;
if (parent() && parent()->m_layerPositionDirtyBits.contains(LayerPositionUpdates::AllChildrenNeedPositionUpdate))
return true;
return false;
}
void RenderLayer::setSelfAndChildrenNeedPositionUpdate()
{
setNeedsPositionUpdate();
m_layerPositionDirtyBits.add({ LayerPositionUpdates::DescendantNeedsPositionUpdate, LayerPositionUpdates::AllChildrenNeedPositionUpdate });
}
void RenderLayer::setSelfAndDescendantsNeedPositionUpdate()
{
setNeedsPositionUpdate();
m_layerPositionDirtyBits.add({ LayerPositionUpdates::DescendantNeedsPositionUpdate, LayerPositionUpdates::AllDescendantsNeedPositionUpdate });
}
void RenderLayer::setAncestorsHaveCompositingDirtyFlag(Compositing flag)
{
for (auto* layer = paintOrderParent(); layer; layer = layer->paintOrderParent()) {
if (layer->m_compositingDirtyBits.contains(flag))
break;
layer->m_compositingDirtyBits.add(flag);
}
}
void RenderLayer::updateLayerListsIfNeeded()
{
updateDescendantDependentFlags();
updateZOrderLists();
updateNormalFlowList();
if (RenderLayer* reflectionLayer = this->reflectionLayer()) {
reflectionLayer->updateZOrderLists();
reflectionLayer->updateNormalFlowList();
}
}
String RenderLayer::name() const
{
if (!isReflection())
return renderer().debugDescription();
return makeString(renderer().debugDescription(), " (reflection)"_s);
}
RenderLayerCompositor& RenderLayer::compositor() const
{
return renderer().view().compositor();
}
void RenderLayer::contentChanged(ContentChangeType changeType)
{
if (changeType == ContentChangeType::Canvas || changeType == ContentChangeType::Video || changeType == ContentChangeType::FullScreen || changeType == ContentChangeType::Model || (isComposited() && changeType == ContentChangeType::Image)) {
setNeedsPostLayoutCompositingUpdate();
setNeedsCompositingConfigurationUpdate();
}
if (auto* backing = this->backing())
backing->contentChanged(changeType);
}
bool RenderLayer::canRender3DTransforms() const
{
return compositor().canRender3DTransforms();
}
bool RenderLayer::paintsWithFilters() const
{
const auto& filter = renderer().style().filter();
if (filter.isEmpty())
return false;
if (renderer().isRenderOrLegacyRenderSVGRoot() && filter.isReferenceFilter())
return false;
if (RenderLayerFilters::isIdentity(renderer()))
return false;
if (!isComposited())
return true;
return !m_backing->canCompositeFilters();
}
bool RenderLayer::requiresFullLayerImageForFilters() const
{
if (!paintsWithFilters())
return false;
return m_filters && m_filters->hasFilterThatMovesPixels();
}
OptionSet<RenderLayer::UpdateLayerPositionsFlag> RenderLayer::flagsForUpdateLayerPositions(RenderLayer& startingLayer)
{
OptionSet<UpdateLayerPositionsFlag> flags = { CheckForRepaint };
if (auto* parent = startingLayer.parent()) {
if (parent->hasFixedContainingBlockAncestor() || (!parent->isRenderViewLayer() && parent->renderer().canContainFixedPositionObjects()))
flags.add(SeenFixedContainingBlockLayer);
if (parent->hasTransformedAncestor() || parent->transform())
flags.add(SeenTransformedLayer);
if (parent->has3DTransformedAncestor() || (parent->transform() && !parent->transform()->isAffine()))
flags.add(Seen3DTransformedLayer);
if (parent->behavesAsFixed() || (parent->renderer().isFixedPositioned() && !parent->hasFixedContainingBlockAncestor()))
flags.add(SeenFixedLayer);
if (parent->hasCompositedScrollingAncestor() || parent->hasCompositedScrollableOverflow())
flags.add(SeenCompositedScrollingLayer);
}
return flags;
}
void RenderLayer::willUpdateLayerPositions()
{
if (CheckedPtr markers = renderer().document().markersIfExists())
markers->invalidateRectsForAllMarkers();
}
#if !LOG_DISABLED || ENABLE(TREE_DEBUGGING)
static inline bool compositingLogEnabledRenderLayer()
{
return LogCompositing.state == WTFLogChannelState::On;
}
#endif
void RenderLayer::updateLayerPositionsAfterStyleChange(bool environmentChanged)
{
LOG(Compositing, "RenderLayer %p updateLayerPositionsAfterStyleChange - before", this);
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabledRenderLayer())
showLayerPositionTree(this);
#endif
auto updateLayerPositionFlags = [&](bool environmentChanged) {
auto flags = flagsForUpdateLayerPositions(*this);
if (environmentChanged)
flags.add(RenderLayer::EnvironmentChanged);
return flags;
};
if (environmentChanged)
setSelfAndDescendantsNeedPositionUpdate();
willUpdateLayerPositions();
recursiveUpdateLayerPositions(updateLayerPositionFlags(environmentChanged));
LOG(Compositing, "RenderLayer %p updateLayerPositionsAfterStyleChange - after", this);
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabledRenderLayer())
showLayerPositionTree(this);
#endif
}
#if ASSERT_ENABLED
uint32_t gUpdatePositionsCount = 0;
uint32_t gVerifyPositionsCount = 0;
uint32_t gVisitedPositionsCount = 0;
#endif
void RenderLayer::updateLayerPositionsAfterLayout(bool didFullRepaint, bool environmentChanged)
{
ASSERT(isRenderViewLayer());
auto updateLayerPositionFlags = [&](bool didFullRepaint, bool environmentChanged) {
auto flags = flagsForUpdateLayerPositions(*this);
if (didFullRepaint) {
flags.remove(RenderLayer::CheckForRepaint);
flags.add(RenderLayer::NeedsFullRepaintInBacking);
}
if (environmentChanged)
flags.add(RenderLayer::EnvironmentChanged);
return flags;
};
#if ASSERT_ENABLED
gUpdatePositionsCount = 0;
gVerifyPositionsCount = 0;
gVisitedPositionsCount = 0;
#endif
LOG_WITH_STREAM(Compositing, stream << "RenderLayer " << this << " updateLayerPositionsAfterLayout (environment changed " << environmentChanged << " - before");
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabledRenderLayer())
showLayerPositionTree(root());
#endif
if (environmentChanged)
setSelfAndDescendantsNeedPositionUpdate();
willUpdateLayerPositions();
recursiveUpdateLayerPositions(updateLayerPositionFlags(didFullRepaint, environmentChanged));
LOG(Compositing, "RenderLayer %p updateLayerPositionsAfterLayout - after", this);
#if ASSERT_ENABLED
LOG_WITH_STREAM(Compositing, stream << "Visited " << gVisitedPositionsCount << ", updated " << gUpdatePositionsCount << " layers, and verified " << gVerifyPositionsCount << " layers");
#endif
#if ENABLE(TREE_DEBUGGING)
if (compositingLogEnabledRenderLayer())
showLayerPositionTree(root());
#endif
}
bool RenderLayer::ancestorLayerPositionStateChanged(OptionSet<UpdateLayerPositionsFlag> flags)
{
return m_hasFixedContainingBlockAncestor != flags.contains(SeenFixedContainingBlockLayer)
|| m_hasTransformedAncestor != flags.contains(SeenTransformedLayer)
|| m_has3DTransformedAncestor != flags.contains(Seen3DTransformedLayer)
|| m_hasFixedAncestor != flags.contains(SeenFixedLayer)
|| m_hasPaginatedAncestor != flags.contains(UpdatePagination)
|| m_hasCompositedScrollingAncestor != flags.contains(SeenCompositedScrollingLayer)
|| m_hasPaginatedAncestor != flags.contains(UpdatePagination);
}
#define LAYER_POSITIONS_ASSERT_ENABLED ASSERT_ENABLED || ENABLE(CONJECTURE_ASSERT)
#if ASSERT_ENABLED
#define LAYER_POSITIONS_ASSERT(assertion, ...) ASSERT(assertion, __VA_ARGS__)
#define LAYER_POSITIONS_ASSERT_IMPLIES(condition, assertion) ASSERT_IMPLIES(condition, assertion)
#elif ENABLE(CONJECTURE_ASSERT)
#define LAYER_POSITIONS_ASSERT(assertion, ...) CONJECTURE_ASSERT(assertion, __VAR_ARGS__)
#define LAYER_POSITIONS_ASSERT_IMPLIES(condition, assertion) CONJECTURE_ASSERT_IMPLIES(condition, assertion)
#else
#define LAYER_POSITIONS_ASSERT(assertion, ...) ((void)0)
#define LAYER_POSITIONS_ASSERT_IMPLIES(condition, assertion) ((void)0)
#endif
template<RenderLayer::UpdateLayerPositionsMode mode>
void RenderLayer::recursiveUpdateLayerPositions(OptionSet<UpdateLayerPositionsFlag> flags)
{
#if ASSERT_ENABLED
if (mode == Write)
gVisitedPositionsCount++;
#endif
if (ancestorLayerPositionStateChanged(flags))
flags.add(SubtreeNeedsUpdate);
if (mode == Write && !needsPositionUpdate() && !flags.containsAny(invalidationLayerPositionsFlags())) {
#if LAYER_POSITIONS_ASSERT_ENABLED
recursiveUpdateLayerPositions<Verify>(flags);
#endif
return;
}
if (m_layerPositionDirtyBits.contains(LayerPositionUpdates::AllDescendantsNeedPositionUpdate)) {
LAYER_POSITIONS_ASSERT(mode != Verify);
flags.add(SubtreeNeedsUpdate);
}
if (updateLayerPosition(&flags, mode))
flags.add(SubtreeNeedsUpdate);
#if ASSERT_ENABLED
if (mode == Write)
gUpdatePositionsCount++;
else
gVerifyPositionsCount++;
#endif
if (m_scrollableArea) {
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, !m_scrollableArea->hasPostLayoutScrollPosition());
m_scrollableArea->applyPostLayoutScrollPositionIfNeeded();
}
// Clear our cached clip rect information.
if (mode == Write)
clearClipRects();
else
verifyClipRects();
if (mode == Write && m_scrollableArea && m_scrollableArea->hasOverflowControls()) {
// FIXME: It looks suspicious to call convertToLayerCoords here
// as canUseOffsetFromAncestor may be true for an ancestor layer.
auto offsetFromRoot = offsetFromAncestor(root());
#if LAYER_POSITIONS_ASSERT_ENABLED
bool changed =
#endif
m_scrollableArea->positionOverflowControls(roundedIntSize(offsetFromRoot));
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, !changed);
}
if (mode == Write)
updateDescendantDependentFlags();
else {
LAYER_POSITIONS_ASSERT(!m_visibleDescendantStatusDirty);
LAYER_POSITIONS_ASSERT(!m_hasSelfPaintingLayerDescendantDirty);
LAYER_POSITIONS_ASSERT(!hasNotIsolatedBlendingDescendantsStatusDirty());
LAYER_POSITIONS_ASSERT(!m_visibleContentStatusDirty);
}
if (flags & UpdatePagination) {
#if LAYER_POSITIONS_ASSERT_ENABLED
CheckedPtr oldEnclosingPaginationLayer = m_enclosingPaginationLayer.get();
#endif
updatePagination();
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, m_enclosingPaginationLayer.get() == oldEnclosingPaginationLayer);
} else if (renderer().isRenderFragmentedFlow()) {
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, m_enclosingPaginationLayer.get() == this);
m_enclosingPaginationLayer = *this;
flags.add(UpdatePagination);
} else {
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, !m_enclosingPaginationLayer.get());
m_enclosingPaginationLayer = nullptr;
}
if (renderer().isSVGLayerAwareRenderer() && renderer().document().settings().layerBasedSVGEngineEnabled()) {
if (!is<RenderSVGRoot>(renderer())) {
ASSERT(!renderer().isFixedPositioned());
if (mode == Write)
m_repaintStatus = RepaintStatus::NeedsFullRepaint;
}
// Only the outermost <svg> and / <foreignObject> are potentially scrollable.
ASSERT_IMPLIES(is<RenderSVGModelObject>(renderer()) || is<RenderSVGText>(renderer()) || is<RenderSVGInline>(renderer()), !m_scrollableArea);
}
auto repaintIfNecessary = [&](bool checkForRepaint) {
if (isVisibilityHiddenOrOpacityZero() || !isSelfPaintingLayer()) {
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, !repaintRects());
clearRepaintRects();
return;
}
if (mode == Verify) {
WeakPtr repaintContainer = renderer().containerForRepaint().renderer.get();
LAYER_POSITIONS_ASSERT(repaintRects());
LAYER_POSITIONS_ASSERT(m_repaintContainer == repaintContainer);
LAYER_POSITIONS_ASSERT(*repaintRects() == renderer().rectsForRepaintingAfterLayout(repaintContainer.get(), RepaintOutlineBounds::Yes));
return;
}
// FIXME: Paint offset cache does not work with RenderLayers as there is not a 1-to-1
// mapping between them and the RenderObjects. It would be neat to enable
// LayoutState outside the layout() phase and use it here.
ASSERT(!renderer().view().frameView().layoutContext().isPaintOffsetCacheEnabled());
WeakPtr repaintContainer = renderer().containerForRepaint().renderer.get();
auto oldRects = repaintRects();
computeRepaintRects(repaintContainer.get());
auto newRects = repaintRects();
if (checkForRepaint && shouldRepaintAfterLayout() && newRects) {
auto needsFullRepaint = repaintStatus() == RepaintStatus::NeedsFullRepaint ? RequiresFullRepaint::Yes : RequiresFullRepaint::No;
auto resolvedOldRects = valueOrDefault(oldRects);
renderer().repaintAfterLayoutIfNeeded(WTFMove(repaintContainer), needsFullRepaint, resolvedOldRects, *newRects);
}
};
repaintIfNecessary(flags.contains(CheckForRepaint));
#define UPDATE_OR_VERIFY_STATE_BIT(dest, source) \
if (mode == Write) \
dest = source; \
else \
LAYER_POSITIONS_ASSERT(dest == source);
UPDATE_OR_VERIFY_STATE_BIT(this->m_repaintStatus, RepaintStatus::NeedsNormalRepaint);
UPDATE_OR_VERIFY_STATE_BIT(m_hasFixedContainingBlockAncestor, flags.contains(SeenFixedContainingBlockLayer));
UPDATE_OR_VERIFY_STATE_BIT(m_hasTransformedAncestor, flags.contains(SeenTransformedLayer));
UPDATE_OR_VERIFY_STATE_BIT(m_has3DTransformedAncestor, flags.contains(Seen3DTransformedLayer));
UPDATE_OR_VERIFY_STATE_BIT(m_hasFixedAncestor, flags.contains(SeenFixedLayer));
UPDATE_OR_VERIFY_STATE_BIT(m_hasPaginatedAncestor, flags.contains(UpdatePagination));
UPDATE_OR_VERIFY_STATE_BIT(m_hasCompositedScrollingAncestor, flags.contains(SeenCompositedScrollingLayer));
#undef UPDATE_OR_VERIFY_STATE_BIT
// Update the reflection's position and size.
if (m_reflection) {
if (mode == Write)
m_reflection->layout();
else
LAYER_POSITIONS_ASSERT(!m_reflection->needsLayout());
}
if (!isRenderViewLayer() && renderer().canContainFixedPositionObjects()) {
flags.add(SeenFixedContainingBlockLayer);
if (transform()) {
flags.add(SeenTransformedLayer);
if (!transform()->isAffine())
flags.add(Seen3DTransformedLayer);
}
}
// Fixed inside transform behaves like absolute (per spec).
if (m_hasFixedAncestor || (renderer().isFixedPositioned() && !m_hasFixedContainingBlockAncestor)) {
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, behavesAsFixed());
setBehavesAsFixed(true);
flags.add(SeenFixedLayer);
}
if (hasCompositedScrollableOverflow())
flags.add(SeenCompositedScrollingLayer);
if (flags.containsAny(invalidationLayerPositionsFlags()) || m_layerPositionDirtyBits.contains(LayerPositionUpdates::DescendantNeedsPositionUpdate)) {
for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
child->recursiveUpdateLayerPositions<mode>(flags);
} else {
#if LAYER_POSITIONS_ASSERT_ENABLED
for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
child->recursiveUpdateLayerPositions<Verify>(flags);
#endif
}
// FIXME: Verify?
if (mode == Write && m_scrollableArea)
m_scrollableArea->updateMarqueePosition();
if (renderer().isFixedPositioned() && renderer().settings().acceleratedCompositingForFixedPositionEnabled()) {
bool intersectsViewport = compositor().fixedLayerIntersectsViewport(*this);
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, intersectsViewport == m_isFixedIntersectingViewport);
if (intersectsViewport != m_isFixedIntersectingViewport) {
m_isFixedIntersectingViewport = intersectsViewport;
setNeedsPostLayoutCompositingUpdate();
}
}
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, !flags.contains(ContainingClippingLayerChangedSize));
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, !flags.contains(NeedsFullRepaintInBacking));
if (mode == Write && isComposited())
backing()->updateAfterLayout(flags.contains(ContainingClippingLayerChangedSize), flags.contains(NeedsFullRepaintInBacking));
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, m_layerPositionDirtyBits.isEmpty());
clearLayerPositionDirtyBits();
}
LayoutRect RenderLayer::repaintRectIncludingNonCompositingDescendants() const
{
LayoutRect repaintRect;
if (m_repaintRectsValid)
repaintRect = m_repaintRects.clippedOverflowRect;
for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
// Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.
if (child->isComposited())
continue;
repaintRect.uniteIfNonZero(child->repaintRectIncludingNonCompositingDescendants());
}
return repaintRect;
}
void RenderLayer::setAncestorChainHasSelfPaintingLayerDescendant()
{
for (RenderLayer* layer = this; layer; layer = layer->parent()) {
if (renderer().shouldApplyPaintContainment()) {
m_hasSelfPaintingLayerDescendant = true;
m_hasSelfPaintingLayerDescendantDirty = false;
break;
}
if (!layer->m_hasSelfPaintingLayerDescendantDirty && layer->hasSelfPaintingLayerDescendant())
break;
layer->m_hasSelfPaintingLayerDescendantDirty = false;
layer->m_hasSelfPaintingLayerDescendant = true;
}
}
void RenderLayer::dirtyAncestorChainHasSelfPaintingLayerDescendantStatus()
{
for (RenderLayer* layer = this; layer; layer = layer->parent()) {
if (layer->m_hasSelfPaintingLayerDescendantDirty)
break;
layer->m_hasSelfPaintingLayerDescendantDirty = true;
layer->setNeedsPositionUpdate();
}
}
std::optional<LayoutRect> RenderLayer::cachedClippedOverflowRect() const
{
if (!m_repaintRectsValid)
return std::nullopt;
return m_repaintRects.clippedOverflowRect;
}
void RenderLayer::computeRepaintRects(const RenderLayerModelObject* repaintContainer)
{
ASSERT(!m_visibleContentStatusDirty);
if (isVisibilityHiddenOrOpacityZero() || !isSelfPaintingLayer())
clearRepaintRects();
else
setRepaintRects(renderer().rectsForRepaintingAfterLayout(repaintContainer, RepaintOutlineBounds::Yes));
#if LAYER_POSITIONS_ASSERT_ENABLED
m_repaintContainer = repaintContainer;
#endif
}
void RenderLayer::computeRepaintRectsIncludingDescendants()
{
// FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.
// We should make this more efficient.
computeRepaintRects(renderer().containerForRepaint().renderer.get());
clearClipRects(PaintingClipRects);
for (RenderLayer* layer = firstChild(); layer; layer = layer->nextSibling())
layer->computeRepaintRectsIncludingDescendants();
}
void RenderLayer::compositingStatusChanged(LayoutUpToDate layoutUpToDate)
{
if (parent() || isRenderViewLayer())
computeRepaintRectsIncludingDescendants();
if (layoutUpToDate == LayoutUpToDate::No)
setSelfAndDescendantsNeedPositionUpdate();
}
void RenderLayer::setRepaintRects(const RenderObject::RepaintRects& rects)
{
m_repaintRects = rects;
m_repaintRectsValid = true;
}
void RenderLayer::clearRepaintRects()
{
m_repaintRectsValid = false;
}
void RenderLayer::updateLayerPositionsAfterOverflowScroll()
{
willUpdateLayerPositions();
// FIXME: why is it OK to not check the ancestors of this layer in order to
// initialize the HasSeenViewportConstrainedAncestor and HasSeenAncestorWithOverflowClip flags?
recursiveUpdateLayerPositionsAfterScroll(RenderLayer::IsOverflowScroll);
}
void RenderLayer::updateLayerPositionsAfterDocumentScroll()
{
ASSERT(isRenderViewLayer());
LOG(Scrolling, "RenderLayer::updateLayerPositionsAfterDocumentScroll");
willUpdateLayerPositions();
recursiveUpdateLayerPositionsAfterScroll();
}
void RenderLayer::recursiveUpdateLayerPositionsAfterScroll(OptionSet<UpdateLayerPositionsAfterScrollFlag> flags)
{
// FIXME: This shouldn't be needed, but there are some corner cases where
// these flags are still dirty. Update so that the check below is valid.
updateDescendantDependentFlags();
// If we have no visible content and no visible descendants, there is no point recomputing
// our rectangles as they will be empty. If our visibility changes, we are expected to
// recompute all our positions anyway.
if (!m_hasVisibleDescendant && !m_hasVisibleContent)
return;
bool positionChanged = updateLayerPosition();
if (positionChanged)
flags.add(HasChangedAncestor);
if (flags.containsAny({ HasChangedAncestor, HasSeenViewportConstrainedAncestor, IsOverflowScroll }))
clearClipRects();
if (renderer().style().hasViewportConstrainedPosition())
flags.add(HasSeenViewportConstrainedAncestor);
if (renderer().hasNonVisibleOverflow())
flags.add(HasSeenAncestorWithOverflowClip);
bool shouldComputeRepaintRects = (flags.contains(HasSeenViewportConstrainedAncestor) || flags.containsAll({ IsOverflowScroll, HasSeenAncestorWithOverflowClip })) && isSelfPaintingLayer();
// FIXME: We could track the repaint container as we walk down the tree.
if (shouldComputeRepaintRects)
computeRepaintRects(renderer().containerForRepaint().renderer.get());
for (auto* child = firstChild(); child; child = child->nextSibling())
child->recursiveUpdateLayerPositionsAfterScroll(flags);
// We don't update our reflection as scrolling is a translation which does not change the size()
// of an object, thus RenderReplica will still repaint itself properly as the layer position was
// updated above.
if (m_scrollableArea)
m_scrollableArea->updateMarqueePosition();
}
void RenderLayer::updateBlendMode()
{
bool hadBlendMode = static_cast<BlendMode>(m_blendMode) != BlendMode::Normal;
if (parent() && hadBlendMode != hasBlendMode()) {
if (hasBlendMode())
parent()->updateAncestorChainHasBlendingDescendants();
else
parent()->dirtyAncestorChainHasBlendingDescendants();
}
BlendMode newBlendMode = renderer().style().blendMode();
if (newBlendMode != static_cast<BlendMode>(m_blendMode))
m_blendMode = static_cast<unsigned>(newBlendMode);
}
void RenderLayer::willRemoveChildWithBlendMode()
{
parent()->dirtyAncestorChainHasBlendingDescendants();
}
void RenderLayer::updateAncestorChainHasBlendingDescendants()
{
for (auto* layer = this; layer; layer = layer->parent()) {
if (!layer->hasNotIsolatedBlendingDescendantsStatusDirty() && layer->hasNotIsolatedBlendingDescendants())
break;
layer->m_hasNotIsolatedBlendingDescendants = true;
layer->m_hasNotIsolatedBlendingDescendantsStatusDirty = false;
layer->updateSelfPaintingLayer();
if (layer->isCSSStackingContext())
break;
}
}
void RenderLayer::dirtyAncestorChainHasBlendingDescendants()
{
for (auto* layer = this; layer; layer = layer->parent()) {
if (layer->hasNotIsolatedBlendingDescendantsStatusDirty())
break;
layer->m_hasNotIsolatedBlendingDescendantsStatusDirty = true;
layer->setNeedsPositionUpdate();
}
}
void RenderLayer::setIntrinsicallyComposited(bool composited)
{
m_intrinsicallyComposited = composited;
updateAlwaysIncludedInZOrderLists();
}
void RenderLayer::updateAlwaysIncludedInZOrderLists()
{
bool alwaysIncludedInZOrderLists = m_intrinsicallyComposited || renderer().hasViewTransitionName();
if (m_alwaysIncludedInZOrderLists != alwaysIncludedInZOrderLists) {
m_alwaysIncludedInZOrderLists = alwaysIncludedInZOrderLists;
if (alwaysIncludedInZOrderLists)
updateAncestorChainHasAlwaysIncludedInZOrderListsDescendants();
else
dirtyAncestorChainHasAlwaysIncludedInZOrderListsDescendants();
if (!hasVisibleContent() && !isNormalFlowOnly())
dirtyHiddenStackingContextAncestorZOrderLists();
}
}
void RenderLayer::updateAncestorChainHasAlwaysIncludedInZOrderListsDescendants()
{
for (auto* layer = this; layer; layer = layer->parent()) {
if (!layer->m_hasAlwaysIncludedInZOrderListsDescendantsStatusDirty && layer->m_hasAlwaysIncludedInZOrderListsDescendants)
break;
layer->m_hasAlwaysIncludedInZOrderListsDescendants = true;
layer->m_hasAlwaysIncludedInZOrderListsDescendantsStatusDirty = false;
}
}
void RenderLayer::dirtyAncestorChainHasAlwaysIncludedInZOrderListsDescendants()
{
for (auto* layer = this; layer; layer = layer->parent()) {
if (layer->m_hasAlwaysIncludedInZOrderListsDescendantsStatusDirty)
break;
layer->m_hasAlwaysIncludedInZOrderListsDescendantsStatusDirty = true;
}
}
FloatRect RenderLayer::referenceBoxRectForClipPath(CSSBoxType boxType, const LayoutSize& offsetFromRoot, const LayoutRect& rootRelativeBounds) const
{
bool isReferenceBox = false;
if (renderer().document().settings().layerBasedSVGEngineEnabled() && renderer().isSVGLayerAwareRenderer())
isReferenceBox = true;
else
isReferenceBox = renderer().isRenderBox();
// FIXME: Support different reference boxes for inline content.
// https://bugs.webkit.org/show_bug.cgi?id=129047
if (!isReferenceBox)
return rootRelativeBounds;
auto referenceBoxRect = renderer().referenceBoxRect(boxType);
referenceBoxRect.move(offsetFromRoot);
return referenceBoxRect;
}
void RenderLayer::updateTransformFromStyle(TransformationMatrix& transform, const RenderStyle& style, OptionSet<RenderStyle::TransformOperationOption> options) const
{
auto referenceBoxRect = snapRectToDevicePixelsIfNeeded(renderer().transformReferenceBoxRect(style), renderer());
renderer().applyTransform(transform, style, referenceBoxRect, options);
// https://drafts.csswg.org/css-anchor-position-1/#anchor-pos
// "The positioned element is additionally visually shifted by its snapshotted scroll offset, as if by an additional translate() transform."
if (m_snapshottedScrollOffsetForAnchorPositioning)
transform.translate(m_snapshottedScrollOffsetForAnchorPositioning->width(), m_snapshottedScrollOffsetForAnchorPositioning->height());
makeMatrixRenderable(transform, canRender3DTransforms());
}
void RenderLayer::updateTransform()
{
bool hasTransform = renderer().isTransformed() || m_snapshottedScrollOffsetForAnchorPositioning;
bool had3DTransform = has3DTransform();
std::unique_ptr<TransformationMatrix> oldTransform;
if (m_transform && hasTransform)
oldTransform = makeUnique<TransformationMatrix>(*m_transform);
if (hasTransform != !!m_transform) {
if (hasTransform)
m_transform = makeUnique<TransformationMatrix>();
else
m_transform = nullptr;
// Layers with transforms act as clip rects roots, so clear the cached clip rects here.
clearClipRectsIncludingDescendants();
setSelfAndDescendantsNeedPositionUpdate();
LOG_WITH_STREAM(Compositing, stream << "Changed transform for " << this);
}
if (hasTransform) {
m_transform->makeIdentity();
updateTransformFromStyle(*m_transform, renderer().style(), RenderStyle::allTransformOperations());
}
if (had3DTransform != has3DTransform()) {
dirty3DTransformedDescendantStatus();
// Having a 3D transform affects whether enclosing perspective and preserve-3d layers composite, so trigger an update.
setNeedsPostLayoutCompositingUpdateOnAncestors();
}
if (oldTransform && m_transform && *oldTransform != *m_transform) {
LOG_WITH_STREAM(Compositing, stream << "Changed transform value for " << this << " from " << *oldTransform << " to " << *m_transform);
setSelfAndDescendantsNeedPositionUpdate();
}
}
void RenderLayer::forceStackingContextIfNeeded()
{
if (setIsCSSStackingContext(true)) {
setIsNormalFlowOnly(false);
if (parent()) {
if (!hasNotIsolatedBlendingDescendantsStatusDirty() && hasNotIsolatedBlendingDescendants())
parent()->dirtyAncestorChainHasBlendingDescendants();
}
}
}
TransformationMatrix RenderLayer::currentTransform(OptionSet<RenderStyle::TransformOperationOption> options) const
{
if (!m_transform)
return { };
// m_transform includes transform-origin and is affected by the choice of the transform-box.
// Therefore we can only use the cached m_transform, if the animation doesn't alter transform-box or excludes transform-origin.
// Query the animatedStyle() to obtain the current transformation, when accelerated transform animations are running.
auto styleable = Styleable::fromRenderer(renderer());
if ((styleable && styleable->isRunningAcceleratedTransformAnimation()) || !options.contains(RenderStyle::TransformOperationOption::TransformOrigin)) {
std::unique_ptr<RenderStyle> animatedStyle = renderer().animatedStyle();
TransformationMatrix transform;
updateTransformFromStyle(transform, *animatedStyle, options);
return transform;
}
return *m_transform;
}
TransformationMatrix RenderLayer::currentTransform() const
{
return currentTransform(RenderStyle::allTransformOperations());
}
TransformationMatrix RenderLayer::renderableTransform(OptionSet<PaintBehavior> paintBehavior) const
{
if (!m_transform)
return TransformationMatrix();
if (paintBehavior & PaintBehavior::FlattenCompositingLayers) {
TransformationMatrix matrix = *m_transform;
makeMatrixRenderable(matrix, false /* flatten 3d */);
return matrix;
}
return *m_transform;
}
RenderLayer* RenderLayer::enclosingOverflowClipLayer(IncludeSelfOrNot includeSelf) const
{
const RenderLayer* layer = (includeSelf == IncludeSelf) ? this : parent();
while (layer) {
if (layer->renderer().hasPotentiallyScrollableOverflow())
return const_cast<RenderLayer*>(layer);
layer = layer->parent();
}
return nullptr;
}
// FIXME: This is terrible. Bring back a cached bit for this someday. This crawl is going to slow down all
// painting of content inside paginated layers.
bool RenderLayer::hasCompositedLayerInEnclosingPaginationChain() const
{
// No enclosing layer means no compositing in the chain.
if (!m_enclosingPaginationLayer)
return false;
// If the enclosing layer is composited, we don't have to check anything in between us and that
// layer.
if (m_enclosingPaginationLayer->isComposited())
return true;
// If we are the enclosing pagination layer, then we can't be composited or we'd have passed the
// previous check.
if (m_enclosingPaginationLayer == this)
return false;
// The enclosing paginated layer is our ancestor and is not composited, so we have to check
// intermediate layers between us and the enclosing pagination layer. Start with our own layer.
if (isComposited())
return true;
// For normal flow layers, we can recur up the layer tree.
if (isNormalFlowOnly())
return parent()->hasCompositedLayerInEnclosingPaginationChain();
// Otherwise we have to go up the containing block chain. Find the first enclosing
// containing block layer ancestor, and check that.
for (const auto* containingBlock = renderer().containingBlock(); containingBlock && !is<RenderView>(*containingBlock); containingBlock = containingBlock->containingBlock()) {
if (containingBlock->hasLayer())
return containingBlock->layer()->hasCompositedLayerInEnclosingPaginationChain();
}
return false;
}
void RenderLayer::updatePagination()
{
m_enclosingPaginationLayer = nullptr;
if (!parent())
return;
// Each layer that is inside a multicolumn flow thread has to be checked individually and
// genuinely know if it is going to have to split itself up when painting only its contents (and not any other descendant
// layers). We track an enclosingPaginationLayer instead of using a simple bit, since we want to be able to get back
// to that layer easily.
if (renderer().isRenderFragmentedFlow()) {
m_enclosingPaginationLayer = *this;
return;
}
if (isNormalFlowOnly()) {
// Content inside a transform is not considered to be paginated, since we simply
// paint the transform multiple times in each column, so we don't have to use
// fragments for the transformed content.
if (parent()->isTransformed())
m_enclosingPaginationLayer = nullptr;
else
m_enclosingPaginationLayer = parent()->enclosingPaginationLayer(IncludeCompositedPaginatedLayers);
return;
}
// For the new columns code, we want to walk up our containing block chain looking for an enclosing layer. Once
// we find one, then we just check its pagination status.
for (const auto* containingBlock = renderer().containingBlock(); containingBlock && !is<RenderView>(*containingBlock); containingBlock = containingBlock->containingBlock()) {
if (containingBlock->hasLayer()) {
// Content inside a transform is not considered to be paginated, since we simply
// paint the transform multiple times in each column, so we don't have to use
// fragments for the transformed content.
if (containingBlock->layer()->isTransformed())
m_enclosingPaginationLayer = nullptr;
else
m_enclosingPaginationLayer = containingBlock->layer()->enclosingPaginationLayer(IncludeCompositedPaginatedLayers);
return;
}
}
}
void RenderLayer::setBehavesAsFixed(bool behavesAsFixed)
{
if (m_behavesAsFixed != behavesAsFixed && renderer().isFixedPositioned())
setNeedsCompositingConfigurationUpdate();
m_behavesAsFixed = behavesAsFixed;
}
void RenderLayer::setHasVisibleContent()
{
if (m_hasVisibleContent && !m_visibleContentStatusDirty) {
ASSERT(!parent() || parent()->m_visibleDescendantStatusDirty || parent()->hasVisibleDescendant());
return;
}
m_visibleContentStatusDirty = false;
m_hasVisibleContent = true;
computeRepaintRects(renderer().containerForRepaint().renderer.get());
setNeedsPositionUpdate();
if (!isNormalFlowOnly()) {
// We don't collect invisible layers in z-order lists if they are not composited.
// As we became visible, we need to dirty our stacking containers ancestors to be properly
// collected.
dirtyHiddenStackingContextAncestorZOrderLists();
}
if (parent())
parent()->dirtyAncestorChainVisibleDescendantStatus();
}
void RenderLayer::dirtyVisibleContentStatus()
{
m_visibleContentStatusDirty = true;
setNeedsPositionUpdate();
if (parent())
parent()->dirtyAncestorChainVisibleDescendantStatus();
}
void RenderLayer::dirtyAncestorChainVisibleDescendantStatus()
{
setNeedsPositionUpdate();
for (auto* layer = this; layer; layer = layer->parent()) {
if (layer->m_visibleDescendantStatusDirty)
break;
layer->m_visibleDescendantStatusDirty = true;
}
}
void RenderLayer::updateAncestorDependentState()
{
m_enclosingSVGHiddenOrResourceContainer = nullptr;
auto determineSVGAncestors = [&] (const RenderElement& renderer) {
for (auto* ancestor = renderer.parent(); ancestor; ancestor = ancestor->parent()) {
if (auto* container = dynamicDowncast<RenderSVGHiddenContainer>(ancestor)) {
m_enclosingSVGHiddenOrResourceContainer = container;
return;
}
}
};
if (renderer().document().settings().layerBasedSVGEngineEnabled())
determineSVGAncestors(renderer());
bool insideSVGForeignObject = false;
if (renderer().document().mayHaveRenderedSVGForeignObjects()) {
if (ancestorsOfType<LegacyRenderSVGForeignObject>(renderer()).first())
insideSVGForeignObject = true;
else if (renderer().document().settings().layerBasedSVGEngineEnabled() && ancestorsOfType<RenderSVGForeignObject>(renderer()).first())
insideSVGForeignObject = true;
}
if (insideSVGForeignObject == m_insideSVGForeignObject)
return;
m_insideSVGForeignObject = insideSVGForeignObject;
updateSelfPaintingLayer();
}
void RenderLayer::updateDescendantDependentFlags()
{
if (m_visibleDescendantStatusDirty || m_hasSelfPaintingLayerDescendantDirty || hasNotIsolatedBlendingDescendantsStatusDirty() || m_hasAlwaysIncludedInZOrderListsDescendantsStatusDirty) {
bool hasVisibleDescendant = false;
bool hasSelfPaintingLayerDescendant = false;
bool hasNotIsolatedBlendingDescendants = false;
bool hasAlwaysIncludedInZOrderListsDescendants = false;
if (m_hasNotIsolatedBlendingDescendantsStatusDirty) {
m_hasNotIsolatedBlendingDescendantsStatusDirty = false;
updateSelfPaintingLayer();
}
for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
child->updateDescendantDependentFlags();
hasVisibleDescendant |= child->m_hasVisibleContent || child->m_hasVisibleDescendant;
hasSelfPaintingLayerDescendant |= child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant();
hasNotIsolatedBlendingDescendants |= child->hasBlendMode() || (child->hasNotIsolatedBlendingDescendants() && !child->isolatesBlending());
hasAlwaysIncludedInZOrderListsDescendants |= child->alwaysIncludedInZOrderLists() || child->m_hasAlwaysIncludedInZOrderListsDescendants;
}
m_hasVisibleDescendant = hasVisibleDescendant;
m_visibleDescendantStatusDirty = false;
m_hasSelfPaintingLayerDescendant = hasSelfPaintingLayerDescendant;
m_hasSelfPaintingLayerDescendantDirty = false;
m_hasAlwaysIncludedInZOrderListsDescendants = hasAlwaysIncludedInZOrderListsDescendants;
m_hasAlwaysIncludedInZOrderListsDescendantsStatusDirty = false;
m_hasNotIsolatedBlendingDescendants = hasNotIsolatedBlendingDescendants;
}
if (m_visibleContentStatusDirty) {
// We need the parent to know if we have skipped content or content-visibility root.
if (renderer().style().hasSkippedContent() && !renderer().parent())
return;
bool hasVisibleContent = computeHasVisibleContent();
if (hasVisibleContent != m_hasVisibleContent) {
m_hasVisibleContent = hasVisibleContent;
if (!isNormalFlowOnly()) {
// We don't collect invisible layers in z-order lists if they are not composited.
// As we change visibility, we need to dirty our stacking containers ancestors to be properly
// collected.
dirtyHiddenStackingContextAncestorZOrderLists();
}
}
m_visibleContentStatusDirty = false;
}
ASSERT(!descendantDependentFlagsAreDirty());
}
bool RenderLayer::computeHasVisibleContent() const
{
if (renderer().isAnonymous() && is<RenderSVGViewportContainer>(renderer()))
return false;
if (m_isHiddenByOverflowTruncation)
return false;
if (renderer().isSkippedContent())
return false;
if (renderer().style().usedVisibility() == Visibility::Visible)
return true;
// Layer's renderer has visibility:hidden, but some non-layer child may have visibility:visible.
RenderObject* r = renderer().firstChild();
while (r) {
if (r->style().usedVisibility() == Visibility::Visible && !r->hasLayer())
return true;
RenderObject* child = nullptr;
if (!r->hasLayer() && (child = r->firstChildSlow()))
r = child;
else if (r->nextSibling())
r = r->nextSibling();
else {
do {
r = r->parent();
if (r == &renderer())
r = nullptr;
} while (r && !r->nextSibling());
if (r)
r = r->nextSibling();
}
}
return false;
}
static LayoutRect computeLayerPositionAndIntegralSize(const RenderLayerModelObject& renderer)
{
if (auto* inlineRenderer = dynamicDowncast<RenderInline>(renderer); inlineRenderer && inlineRenderer->isInline())
return { LayoutPoint(), inlineRenderer->linesBoundingBox().size() };
if (auto* boxRenderer = dynamicDowncast<RenderBox>(renderer)) {
const auto& frameRect = boxRenderer->frameRect();
return { boxRenderer->topLeftLocation(), snappedIntSize(frameRect.size(), frameRect.location()) };
}
if (auto* svgModelObjectRenderer = dynamicDowncast<RenderSVGModelObject>(renderer)) {
const auto& frameRect = svgModelObjectRenderer->frameRectEquivalent();
return { svgModelObjectRenderer->topLeftLocationEquivalent(), enclosingIntRect(frameRect).size() };
}
ASSERT_NOT_REACHED();
return { };
}
void RenderLayer::dirty3DTransformedDescendantStatus()
{
RenderLayer* curr = stackingContext();
if (curr)
curr->m_3DTransformedDescendantStatusDirty = true;
// This propagates up through preserve-3d hierarchies to the enclosing flattening layer.
// Note that preserves3D() creates stacking context, so we can just run up the stacking containers.
while (curr && curr->preserves3D()) {
curr->m_3DTransformedDescendantStatusDirty = true;
curr = curr->stackingContext();
}
}
// Return true if this layer or any preserve-3d descendants have 3d.
bool RenderLayer::update3DTransformedDescendantStatus()
{
if (m_3DTransformedDescendantStatusDirty) {
m_has3DTransformedDescendant = false;
updateZOrderLists();
// Transformed or preserve-3d descendants can only be in the z-order lists, not
// in the normal flow list, so we only need to check those.
for (auto* layer : positiveZOrderLayers())
m_has3DTransformedDescendant |= layer->update3DTransformedDescendantStatus();
// Now check our negative z-index children.
for (auto* layer : negativeZOrderLayers())
m_has3DTransformedDescendant |= layer->update3DTransformedDescendantStatus();
m_3DTransformedDescendantStatusDirty = false;
}
// If we live in a 3d hierarchy, then the layer at the root of that hierarchy needs
// the m_has3DTransformedDescendant set.
if (preserves3D())
return has3DTransform() || m_has3DTransformedDescendant;
return has3DTransform();
}
bool RenderLayer::updateLayerPosition(OptionSet<UpdateLayerPositionsFlag>* flags, UpdateLayerPositionsMode mode)
{
auto layerRect = computeLayerPositionAndIntegralSize(renderer());
auto localPoint = layerRect.location();
bool geometryChanged = false;
if (IntSize newSize(layerRect.width().toInt(), layerRect.height().toInt()); newSize != size()) {
geometryChanged = true;
setSize(newSize);
#if LAYER_POSITIONS_ASSERT_ENABLED
LAYER_POSITIONS_ASSERT(mode == Write);
#else
UNUSED_PARAM(mode);
#endif
if (flags && renderer().hasNonVisibleOverflow())
flags->add(ContainingClippingLayerChangedSize);
// Trigger RenderLayerCompositor::requiresCompositingForFrame() which depends on the contentBoxRect size.
if (compositor().hasCompositedWidgetContents(renderer()))
setNeedsPostLayoutCompositingUpdate();
}
if (!renderer().isOutOfFlowPositioned()) {
auto* ancestor = renderer().parent();
// We must adjust our position by walking up the render tree looking for the
// nearest enclosing object with a layer.
while (ancestor && !ancestor->hasLayer()) {
if (auto* boxRenderer = dynamicDowncast<RenderBox>(ancestor)) {
// Rows and cells share the same coordinate space (that of the section).
// Omit them when computing our xpos/ypos.
if (!is<RenderTableRow>(boxRenderer))
localPoint += boxRenderer->topLeftLocationOffset();
}
ancestor = ancestor->parent();
}
if (auto* tableRow = dynamicDowncast<RenderTableRow>(ancestor)) {
// Put ourselves into the row coordinate space.
localPoint -= tableRow->topLeftLocationOffset();
}
}
// Subtract our parent's scroll offset.
#if LAYER_POSITIONS_ASSERT_ENABLED
std::optional<ScrollingScope> oldBoxScrollingScope = m_boxScrollingScope;
std::optional<ScrollingScope> oldContentsScrollingScope = m_contentsScrollingScope;
#endif
RenderLayer* positionedParent;
if (renderer().isOutOfFlowPositioned() && (positionedParent = enclosingAncestorForPosition(renderer().style().position()))) {
// For positioned layers, we subtract out the enclosing positioned layer's scroll offset.
if (positionedParent->renderer().hasNonVisibleOverflow()) {
if (auto* positionedParentScrollableArea = positionedParent->scrollableArea())
localPoint -= toLayoutSize(positionedParentScrollableArea->scrollPosition());
}
if (positionedParent->renderer().isInFlowPositioned()) {
if (auto* inlinePositionedParent = dynamicDowncast<RenderInline>(positionedParent->renderer()))
localPoint += inlinePositionedParent->offsetForInFlowPositionedInline(renderBox());
}
ASSERT(positionedParent->contentsScrollingScope());
m_boxScrollingScope = positionedParent->contentsScrollingScope();
} else if (auto* parentLayer = parent()) {
if (parentLayer->renderer().hasNonVisibleOverflow()) {
if (auto* parentLayerScrollableArea = parentLayer->scrollableArea())
localPoint -= toLayoutSize(parentLayerScrollableArea->scrollPosition());
}
ASSERT(parentLayer->contentsScrollingScope());
m_boxScrollingScope = parentLayer->contentsScrollingScope();
}
if (hasCompositedScrollableOverflow()) {
if (!m_contentsScrollingScope || m_contentsScrollingScope == m_boxScrollingScope)
m_contentsScrollingScope = nextScrollingScope();
} else if (!m_contentsScrollingScope || m_contentsScrollingScope != m_boxScrollingScope)
m_contentsScrollingScope = m_boxScrollingScope;
if (renderer().isInFlowPositioned()) {
if (auto* boxModelObject = dynamicDowncast<RenderBoxModelObject>(renderer())) {
auto newOffset = boxModelObject->offsetForInFlowPosition();
geometryChanged |= newOffset != m_offsetForPosition;
m_offsetForPosition = newOffset;
localPoint.move(m_offsetForPosition);
}
}
geometryChanged |= location() != localPoint;
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, !geometryChanged);
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, oldBoxScrollingScope == m_boxScrollingScope);
LAYER_POSITIONS_ASSERT_IMPLIES(mode == Verify, oldContentsScrollingScope == m_contentsScrollingScope);
setLocation(localPoint);
if (geometryChanged && compositor().hasContentCompositingLayers()) {
if (isComposited())
setNeedsCompositingGeometryUpdate();
// This layer's footprint can affect the location of a composited descendant (which may be a sibling in z-order),
// so trigger a descendant walk from the enclosing stacking context.
if (auto* sc = stackingContext()) {
sc->setDescendantsNeedCompositingRequirementsTraversal();
sc->setDescendantsNeedUpdateBackingAndHierarchyTraversal();
}
}
return geometryChanged;
}
TransformationMatrix RenderLayer::perspectiveTransform() const
{
if (!renderer().hasTransformRelatedProperty())
return { };
const auto& style = renderer().style();
if (!style.hasPerspective())
return { };
auto transformReferenceBoxRect = snapRectToDevicePixelsIfNeeded(renderer().transformReferenceBoxRect(style), renderer());
auto perspectiveOrigin = style.computePerspectiveOrigin(transformReferenceBoxRect);
// In the regular case of a non-clipped, non-scrolled GraphicsLayer, all transformations
// (via CSS 'transform' / 'perspective') are applied with respect to a predefined anchor point,
// which depends on the chosen CSS 'transform-box' / 'transform-origin' properties.
//
// A transformation given by the CSS 'transform' property is applied, by translating
// to the 'transform origin', applying the transformation, and translating back.
// When an element specifies a CSS 'perspective' property, the perspective transformation matrix
// that's computed here is propagated to the GraphicsLayer by calling setChildrenTransform().
//
// However the GraphicsLayer platform implementations (e.g. CA on macOS) apply the children transform,
// defined on the parent, with respect to the anchor point of the parent, when rendering child elements.
// This is wrong, as the perspective transformation (applied to a child of the element defining the
// 3d effect), must be independant of the chosen transform-origin (the parents transform origin
// must not affect its children).
//
// To circumvent this, explicitely remove the transform-origin dependency in the perspective matrix.
auto transformOrigin = transformOriginPixelSnappedIfNeeded();
TransformationMatrix transform;
style.unapplyTransformOrigin(transform, transformOrigin);
style.applyPerspective(transform, perspectiveOrigin);
style.applyTransformOrigin(transform, transformOrigin);
return transform;
}
FloatPoint3D RenderLayer::transformOriginPixelSnappedIfNeeded() const
{
if (!renderer().hasTransformRelatedProperty())
return { };
const auto& style = renderer().style();
auto referenceBoxRect = renderer().transformReferenceBoxRect(style);
auto origin = style.computeTransformOrigin(referenceBoxRect);
if (rendererNeedsPixelSnapping(renderer()))
origin.setXY(roundPointToDevicePixels(LayoutPoint(origin.xy()), renderer().document().deviceScaleFactor()));
return origin;
}
FloatPoint RenderLayer::perspectiveOrigin() const
{
if (!renderer().hasTransformRelatedProperty())
return { };
return floatPointForLengthPoint(renderer().style().perspectiveOrigin(), renderer().transformReferenceBoxRect(renderer().style()).size());
}
static inline bool isContainerForPositioned(RenderLayer& layer, PositionType position, bool establishesTopLayer)
{
if (establishesTopLayer)
return layer.isRenderViewLayer();
switch (position) {
case PositionType::Fixed:
return layer.renderer().canContainFixedPositionObjects();
case PositionType::Absolute:
return layer.renderer().canContainAbsolutelyPositionedObjects();
default:
ASSERT_NOT_REACHED();
return false;
}
}
bool RenderLayer::ancestorLayerIsInContainingBlockChain(const RenderLayer& ancestor, const RenderLayer* checkLimit) const
{
if (&ancestor == this)
return true;
for (const auto* currentBlock = renderer().containingBlock(); currentBlock && !is<RenderView>(*currentBlock); currentBlock = currentBlock->containingBlock()) {
auto* currLayer = currentBlock->layer();
if (currLayer == &ancestor)
return true;
if (currLayer && currLayer == checkLimit)
return false;
}
return false;
}
RenderLayer* RenderLayer::enclosingAncestorForPosition(PositionType position) const
{
auto* curr = parent();
while (curr && !isContainerForPositioned(*curr, position, establishesTopLayer()))
curr = curr->parent();
ASSERT_IMPLIES(establishesTopLayer(), !curr || curr == renderer().view().layer());
return curr;
}
RenderLayer* RenderLayer::enclosingLayerInContainingBlockOrder() const
{
for (const auto* currentBlock = renderer().containingBlock(); currentBlock; currentBlock = currentBlock->containingBlock()) {
if (auto* layer = currentBlock->layer())
return layer;
}
return nullptr;
}
RenderLayer* RenderLayer::enclosingFrameRenderLayer() const
{
auto* ownerElement = renderer().document().ownerElement();
if (!ownerElement)
return nullptr;
auto* ownerRenderer = ownerElement->renderer();
if (!ownerRenderer)
return nullptr;
return ownerRenderer->enclosingLayer();
}
RenderLayer* RenderLayer::enclosingContainingBlockLayer(CrossFrameBoundaries crossFrameBoundaries) const
{
if (auto* ancestor = enclosingLayerInContainingBlockOrder())
return ancestor;
if (crossFrameBoundaries == CrossFrameBoundaries::No)
return nullptr;
return enclosingFrameRenderLayer();
}
RenderLayer* RenderLayer::enclosingScrollableLayer(IncludeSelfOrNot includeSelf, CrossFrameBoundaries crossFrameBoundaries) const
{
RenderTreeMutationDisallowedScope renderTreeMutationDisallowedScope;
auto isConsideredScrollable = [](const RenderLayer& layer) {
auto* box = dynamicDowncast<RenderBox>(layer.renderer());
return box && box->canBeScrolledAndHasScrollableArea();
};
if (includeSelf == IncludeSelfOrNot::IncludeSelf && isConsideredScrollable(*this))
return const_cast<RenderLayer*>(this);
for (auto* nextLayer = enclosingContainingBlockLayer(crossFrameBoundaries); nextLayer; nextLayer = nextLayer->enclosingContainingBlockLayer(crossFrameBoundaries)) {
if (isConsideredScrollable(*nextLayer))
return nextLayer;
}
return nullptr;
}
RenderLayer* RenderLayer::enclosingTransformedAncestor() const
{
RenderLayer* curr = parent();
while (curr && !curr->isRenderViewLayer() && !curr->transform())
curr = curr->parent();
return curr;
}
bool RenderLayer::shouldRepaintAfterLayout() const
{
// The SVG containers themselves never trigger repaints, only their contents are allowed to.
// SVG container sizes/positions are only ever determined by their children, so they will
// change as a reaction on a re-position/re-sizing of the children - which already properly
// trigger repaints.
if (is<RenderSVGContainer>(renderer()) && !paintsWithFilters())
return false;
if (m_repaintStatus == RepaintStatus::NeedsNormalRepaint || m_repaintStatus == RepaintStatus::NeedsFullRepaint)
return true;
// Composited layers that were moved during a positioned movement only
// layout, don't need to be repainted. They just need to be recomposited.
ASSERT(m_repaintStatus == RepaintStatus::NeedsFullRepaintForPositionedMovementLayout);
return !isComposited() || backing()->paintsIntoCompositedAncestor();
}
void RenderLayer::setBackingProviderLayer(RenderLayer* backingProvider)
{
if (backingProvider == m_backingProviderLayer)
return;
if (!renderer().renderTreeBeingDestroyed())
clearClipRectsIncludingDescendants();
m_backingProviderLayer = backingProvider;
}
void RenderLayer::disconnectFromBackingProviderLayer()
{
if (!m_backingProviderLayer)
return;
ASSERT(m_backingProviderLayer->isComposited());
if (m_backingProviderLayer->isComposited())
m_backingProviderLayer->backing()->removeBackingSharingLayer(*this);
}
bool compositedWithOwnBackingStore(const RenderLayer& layer)
{
return layer.isComposited() && !layer.backing()->paintsIntoCompositedAncestor();
}
RenderLayer* RenderLayer::enclosingCompositingLayer(IncludeSelfOrNot includeSelf) const
{
if (includeSelf == IncludeSelf && isComposited())
return const_cast<RenderLayer*>(this);
for (const RenderLayer* curr = paintOrderParent(); curr; curr = curr->paintOrderParent()) {
if (curr->isComposited())
return const_cast<RenderLayer*>(curr);
}
return nullptr;
}
RenderLayer::EnclosingCompositingLayerStatus RenderLayer::enclosingCompositingLayerForRepaint(IncludeSelfOrNot includeSelf) const
{
auto repaintTargetForLayer = [](const RenderLayer& layer) -> RenderLayer* {
if (compositedWithOwnBackingStore(layer))
return const_cast<RenderLayer*>(&layer);
if (layer.paintsIntoProvidedBacking())
return layer.backingProviderLayer();
return nullptr;
};
auto isEligibleForFullRepaintCheck = [&](const auto& layer) {
return layer.isSelfPaintingLayer() && !layer.renderer().hasPotentiallyScrollableOverflow() && !is<RenderView>(layer.renderer());
};
auto fullRepaintAlreadyScheduled = isEligibleForFullRepaintCheck(*this) && needsFullRepaint();
RenderLayer* repaintTarget = nullptr;
if (includeSelf == IncludeSelf && (repaintTarget = repaintTargetForLayer(*this)))
return { fullRepaintAlreadyScheduled, repaintTarget };
for (const RenderLayer* curr = paintOrderParent(); curr; curr = curr->paintOrderParent()) {
fullRepaintAlreadyScheduled = fullRepaintAlreadyScheduled || (isEligibleForFullRepaintCheck(*curr) && curr->needsFullRepaint());
if ((repaintTarget = repaintTargetForLayer(*curr)))
return { fullRepaintAlreadyScheduled, repaintTarget };
}
return { };
}
RenderLayer* RenderLayer::enclosingFilterLayer(IncludeSelfOrNot includeSelf) const
{
const RenderLayer* curr = (includeSelf == IncludeSelf) ? this : parent();
for (; curr; curr = curr->parent()) {
if (curr->requiresFullLayerImageForFilters())
return const_cast<RenderLayer*>(curr);
}
return nullptr;
}
RenderLayer* RenderLayer::enclosingFilterRepaintLayer() const
{
for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
if ((curr != this && curr->requiresFullLayerImageForFilters()) || compositedWithOwnBackingStore(*curr) || curr->isRenderViewLayer())
return const_cast<RenderLayer*>(curr);
}
return nullptr;
}
// FIXME: This needs a better name.
void RenderLayer::setFilterBackendNeedsRepaintingInRect(const LayoutRect& rect)
{
ASSERT(requiresFullLayerImageForFilters());
ASSERT(m_filters);
if (rect.isEmpty())
return;
LayoutRect rectForRepaint = rect;
rectForRepaint.expand(toLayoutBoxExtent(filterOutsets()));
m_filters->expandDirtySourceRect(rectForRepaint);
RenderLayer* parentLayer = enclosingFilterRepaintLayer();
ASSERT(parentLayer);
FloatQuad repaintQuad(rectForRepaint);
LayoutRect parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
if (parentLayer->isComposited()) {
if (!parentLayer->backing()->paintsIntoWindow()) {
parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
return;
}
// If the painting goes to window, redirect the painting to the parent RenderView.
parentLayer = renderer().view().layer();
parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
}
if (parentLayer->paintsWithFilters()) {
parentLayer->setFilterBackendNeedsRepaintingInRect(parentLayerRect);
return;
}
if (parentLayer->isRenderViewLayer()) {
downcast<RenderView>(parentLayer->renderer()).repaintViewRectangle(parentLayerRect);
return;
}
ASSERT_NOT_REACHED();
}
bool RenderLayer::hasAncestorWithFilterOutsets() const
{
for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
if (curr->hasFilterOutsets())
return true;
}
return false;
}
RenderLayer* RenderLayer::clippingRootForPainting() const
{
if (isComposited())
return const_cast<RenderLayer*>(this);
if (paintsIntoProvidedBacking())
return backingProviderLayer();
const RenderLayer* current = this;
while (current) {
if (current->isRenderViewLayer())
return const_cast<RenderLayer*>(current);
current = current->paintOrderParent();
ASSERT(current);
if (current->transform() || compositedWithOwnBackingStore(*current))
return const_cast<RenderLayer*>(current);
if (renderer().settings().css3DTransformBackfaceVisibilityInteroperabilityEnabled() && current->participatesInPreserve3D() && current->renderer().style().backfaceVisibility() == BackfaceVisibility::Hidden)
return const_cast<RenderLayer*>(current);
if (current->paintsIntoProvidedBacking())
return current->backingProviderLayer();
}
ASSERT_NOT_REACHED();
return nullptr;
}
LayoutPoint RenderLayer::absoluteToContents(const LayoutPoint& absolutePoint) const
{
// We don't use convertToLayerCoords because it doesn't know about transforms
return LayoutPoint(renderer().absoluteToLocal(absolutePoint, UseTransforms));
}
bool RenderLayer::cannotBlitToWindow() const
{
if (isTransparent() || hasReflection() || isTransformed())
return true;
if (!parent())
return false;
return parent()->cannotBlitToWindow();
}
RenderLayer* RenderLayer::transparentPaintingAncestor(const LayerPaintingInfo& info)
{
if (this == info.rootLayer || isComposited() || paintsIntoProvidedBacking())
return nullptr;
for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
if (ancestor->isStackingContext()) {
if (ancestor->isComposited() || ancestor->paintsIntoProvidedBacking())
return nullptr;
if (ancestor->isTransparent())
return ancestor;
}
if (ancestor == info.rootLayer)
return nullptr;
}
return nullptr;
}
enum TransparencyClipBoxBehavior {
PaintingTransparencyClipBox,
HitTestingTransparencyClipBox
};
enum TransparencyClipBoxMode {
DescendantsOfTransparencyClipBox,
RootOfTransparencyClipBox
};
static LayoutRect transparencyClipBox(const RenderLayer&, const RenderLayer* rootLayer, TransparencyClipBoxBehavior, TransparencyClipBoxMode, OptionSet<PaintBehavior> = { }, const LayoutRect* paintDirtyRect = nullptr);
static void expandClipRectForDescendantsAndReflection(LayoutRect& clipRect, const RenderLayer& layer, const RenderLayer* rootLayer,
TransparencyClipBoxBehavior transparencyBehavior, OptionSet<PaintBehavior> paintBehavior, const LayoutRect* paintDirtyRect)
{
// If we have a mask, then the clip is limited to the border box area (and there is
// no need to examine child layers).
if (!layer.renderer().hasMask()) {
// Note: we don't have to walk z-order lists since transparent elements always establish
// a stacking container. This means we can just walk the layer tree directly.
for (RenderLayer* curr = layer.firstChild(); curr; curr = curr->nextSibling()) {
if (!layer.isReflectionLayer(*curr))
clipRect.unite(transparencyClipBox(*curr, rootLayer, transparencyBehavior, DescendantsOfTransparencyClipBox, paintBehavior, paintDirtyRect));
}
}
// If we have a reflection, then we need to account for that when we push the clip. Reflect our entire
// current transparencyClipBox to catch all child layers.
// FIXME: Accelerated compositing will eventually want to do something smart here to avoid incorporating this
// size into the parent layer.
if (layer.renderer().isRenderBox() && layer.renderer().hasReflection()) {
LayoutSize delta = layer.offsetFromAncestor(rootLayer);
clipRect.move(-delta);
clipRect.unite(layer.renderBox()->reflectedRect(clipRect));
clipRect.move(delta);
}
}
static LayoutRect transparencyClipBox(const RenderLayer& layer, const RenderLayer* rootLayer, TransparencyClipBoxBehavior transparencyBehavior,
TransparencyClipBoxMode transparencyMode, OptionSet<PaintBehavior> paintBehavior, const LayoutRect* paintDirtyRect)
{
// FIXME: Although this function completely ignores CSS-imposed clipping, we did already intersect with the
// paintDirtyRect, and that should cut down on the amount we have to paint. Still it
// would be better to respect clips.
if (rootLayer != &layer && ((transparencyBehavior == PaintingTransparencyClipBox && layer.paintsWithTransform(paintBehavior))
|| (transparencyBehavior == HitTestingTransparencyClipBox && layer.isTransformed()))) {
// The best we can do here is to use enclosed bounding boxes to establish a "fuzzy" enough clip to encompass
// the transformed layer and all of its children.
RenderLayer::PaginationInclusionMode mode = transparencyBehavior == HitTestingTransparencyClipBox ? RenderLayer::IncludeCompositedPaginatedLayers : RenderLayer::ExcludeCompositedPaginatedLayers;
const RenderLayer* paginationLayer = transparencyMode == DescendantsOfTransparencyClipBox ? layer.enclosingPaginationLayer(mode) : nullptr;
const RenderLayer* rootLayerForTransform = paginationLayer ? paginationLayer : rootLayer;
LayoutSize delta = layer.offsetFromAncestor(rootLayerForTransform);
TransformationMatrix transform;
transform.translate(delta.width(), delta.height());
transform.multiply(*layer.transform());
// We don't use fragment boxes when collecting a transformed layer's bounding box, since it always
// paints unfragmented.
LayoutRect clipRect = layer.boundingBox(&layer);
expandClipRectForDescendantsAndReflection(clipRect, layer, &layer, transparencyBehavior, paintBehavior, paintDirtyRect);
clipRect.expand(toLayoutBoxExtent(layer.filterOutsets()));
LayoutRect result = transform.mapRect(clipRect);
if (!paginationLayer) {
if (paintDirtyRect)
result = intersection(result, *paintDirtyRect);
return result;
}
// We have to break up the transformed extent across our columns.
// Split our box up into the actual fragment boxes that render in the columns/pages and unite those together to
// get our true bounding box.
auto& enclosingFragmentedFlow = downcast<RenderFragmentedFlow>(paginationLayer->renderer());
result = enclosingFragmentedFlow.fragmentsBoundingBox(result);
result.move(paginationLayer->offsetFromAncestor(rootLayer));
if (paintDirtyRect)
result = intersection(result, *paintDirtyRect);
return result;
}
OptionSet<RenderLayer::CalculateLayerBoundsFlag> flags = transparencyBehavior == HitTestingTransparencyClipBox ? RenderLayer::UseFragmentBoxesIncludingCompositing : RenderLayer::UseFragmentBoxesExcludingCompositing;
flags.add(RenderLayer::IncludeRootBackgroundPaintingArea);
auto clipRect = layer.boundingBox(rootLayer, layer.offsetFromAncestor(rootLayer), flags);
expandClipRectForDescendantsAndReflection(clipRect, layer, rootLayer, transparencyBehavior, paintBehavior, paintDirtyRect);
clipRect.expand(toLayoutBoxExtent(layer.filterOutsets()));
if (paintDirtyRect)
clipRect = intersection(clipRect, *paintDirtyRect);
return clipRect;
}
void RenderLayer::beginTransparencyLayers(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, const LayoutRect& dirtyRect)
{
if (context.paintingDisabled() || (paintsWithTransparency(paintingInfo.paintBehavior) && m_usedTransparency))
return;
if (auto* ancestor = transparentPaintingAncestor(paintingInfo))
ancestor->beginTransparencyLayers(context, paintingInfo, dirtyRect);
if (paintsWithTransparency(paintingInfo.paintBehavior)) {
ASSERT(isStackingContext());
m_usedTransparency = true;
if (canPaintTransparencyWithSetOpacity()) {
m_savedAlphaForTransparency = context.alpha();
context.setAlpha(context.alpha() * renderer().opacity());
return;
}
context.save();
LayoutRect adjustedClipRect = transparencyClipBox(*this, paintingInfo.rootLayer, PaintingTransparencyClipBox, RootOfTransparencyClipBox, paintingInfo.paintBehavior, &dirtyRect);
adjustedClipRect.move(paintingInfo.subpixelOffset);
auto snappedClipRect = snapRectToDevicePixelsIfNeeded(adjustedClipRect, renderer());
context.clip(snappedClipRect);
bool usesCompositeOperation = hasBlendMode() && !(renderer().isLegacyRenderSVGRoot() && parent() && parent()->isRenderViewLayer());
if (usesCompositeOperation)
context.setCompositeOperation(context.compositeOperation(), blendMode());
context.beginTransparencyLayer(renderer().opacity());
if (usesCompositeOperation)
context.setCompositeOperation(context.compositeOperation(), BlendMode::Normal);
#ifdef REVEAL_TRANSPARENCY_LAYERS
context.setFillColor(SRGBA<uint8_t> { 0, 0, 128, 51 });
context.fillRect(pixelSnappedClipRect);
#endif
}
}
bool RenderLayer::isDescendantOf(const RenderLayer& layer) const
{
for (auto* ancestor = this; ancestor; ancestor = ancestor->parent()) {
if (&layer == ancestor)
return true;
}
return false;
}
static RenderLayer* findCommonAncestor(const RenderLayer& firstLayer, const RenderLayer& secondLayer)
{
if (&firstLayer == &secondLayer)
return const_cast<RenderLayer*>(&firstLayer);
SingleThreadWeakHashSet<const RenderLayer> ancestorChain;
for (auto* currLayer = &firstLayer; currLayer; currLayer = currLayer->parent())
ancestorChain.add(*currLayer);
for (auto* currLayer = &secondLayer; currLayer; currLayer = currLayer->parent()) {
if (ancestorChain.contains(*currLayer))
return const_cast<RenderLayer*>(currLayer);
}
return nullptr;
}
RenderLayer* RenderLayer::commonAncestorWithLayer(const RenderLayer& layer) const
{
return findCommonAncestor(*this, layer);
}
void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntPoint& roundedLocation, ColumnOffsetAdjustment adjustForColumns) const
{
LayoutPoint location = convertToLayerCoords(ancestorLayer, roundedLocation, adjustForColumns);
roundedLocation = roundedIntPoint(location);
}
// Returns the layer reached on the walk up towards the ancestor.
static inline const RenderLayer* accumulateOffsetTowardsAncestor(const RenderLayer* layer, const RenderLayer* ancestorLayer, LayoutPoint& location, RenderLayer::ColumnOffsetAdjustment adjustForColumns)
{
ASSERT(ancestorLayer != layer);
const auto& renderer = layer->renderer();
auto position = renderer.style().position();
// FIXME: Positioning of out-of-flow(fixed, absolute) elements collected in a RenderFragmentedFlow
// may need to be revisited in a future patch.
// If the fixed renderer is inside a RenderFragmentedFlow, we should not compute location using localToAbsolute,
// since localToAbsolute maps the coordinates from named flow to regions coordinates and regions can be
// positioned in a completely different place in the viewport (RenderView).
if (position == PositionType::Fixed && (!ancestorLayer || ancestorLayer == renderer.view().layer())) {
// If the fixed layer's container is the root, just add in the offset of the view. We can obtain this by calling
// localToAbsolute() on the RenderView.
location.moveBy(LayoutPoint(renderer.localToAbsolute({ }, IsFixed)));
return ancestorLayer;
}
// For the fixed positioned elements inside a render flow thread, we should also skip the code path below
// Otherwise, for the case of ancestorLayer == rootLayer and fixed positioned element child of a transformed
// element in render flow thread, we will hit the fixed positioned container before hitting the ancestor layer.
if (position == PositionType::Fixed) {
// For a fixed layers, we need to walk up to the root to see if there's a fixed position container
// (e.g. a transformed layer). It's an error to call offsetFromAncestor() across a layer with a transform,
// so we should always find the ancestor at or before we find the fixed position container, if
// the container is transformed.
RenderLayer* fixedPositionContainerLayer = nullptr;
bool foundAncestor = false;
for (auto* currLayer = layer->parent(); currLayer; currLayer = currLayer->parent()) {
if (currLayer == ancestorLayer)
foundAncestor = true;
if (isContainerForPositioned(*currLayer, PositionType::Fixed, layer->establishesTopLayer())) {
fixedPositionContainerLayer = currLayer;
// A layer that has a transform-related property but not a
// transform still acts as a fixed-position container.
// Accumulating offsets across such layers is allowed.
if (currLayer->transform())
ASSERT_UNUSED(foundAncestor, foundAncestor);
break;
}
}
ASSERT(fixedPositionContainerLayer); // We should have hit the RenderView's layer at least.
if (fixedPositionContainerLayer != ancestorLayer) {
auto fixedContainerCoords = layer->offsetFromAncestor(fixedPositionContainerLayer);
auto ancestorCoords = foundAncestor ? ancestorLayer->offsetFromAncestor(fixedPositionContainerLayer) : LayoutSize { };
location.move(fixedContainerCoords - ancestorCoords);
return foundAncestor ? ancestorLayer : fixedPositionContainerLayer;
}
}
if (position == PositionType::Fixed) {
ASSERT(ancestorLayer);
if (ancestorLayer == renderer.view().layer()) {
// Add location in flow thread coordinates.
location.moveBy(layer->location());
// Add flow thread offset in view coordinates since the view may be scrolled.
location.moveBy(LayoutPoint(renderer.view().localToAbsolute({ }, IsFixed)));
return ancestorLayer;
}
}
RenderLayer* parentLayer;
if (position == PositionType::Absolute || position == PositionType::Fixed) {
// Do what enclosingAncestorForPosition() does, but check for ancestorLayer along the way.
parentLayer = layer->parent();
bool foundAncestorFirst = false;
while (parentLayer) {
// RenderFragmentedFlow is a positioned container, child of RenderView, positioned at (0,0).
// This implies that, for out-of-flow positioned elements inside a RenderFragmentedFlow,
// we are bailing out before reaching root layer.
if (isContainerForPositioned(*parentLayer, position, layer->establishesTopLayer()))
break;
if (parentLayer == ancestorLayer) {
foundAncestorFirst = true;
break;
}
parentLayer = parentLayer->parent();
}
// We should not reach RenderView layer past the RenderFragmentedFlow layer for any
// children of the RenderFragmentedFlow.
if (renderer.enclosingFragmentedFlow())
ASSERT(parentLayer != renderer.view().layer());
if (foundAncestorFirst) {
// Found ancestorLayer before the abs. positioned container, so compute offset of both relative
// to enclosingAncestorForPosition and subtract.
auto* positionedAncestor = parentLayer->enclosingAncestorForPosition(position);
auto thisCoords = layer->offsetFromAncestor(positionedAncestor);
auto ancestorCoords = ancestorLayer->offsetFromAncestor(positionedAncestor);
location.move(thisCoords - ancestorCoords);
return ancestorLayer;
}
} else
parentLayer = layer->parent();
if (!parentLayer)
return nullptr;
location.moveBy(layer->location());
if (adjustForColumns == RenderLayer::AdjustForColumns) {
if (auto* parentLayer = layer->parent(); parentLayer && parentLayer != ancestorLayer) {
if (auto* multiColumnFlow = dynamicDowncast<RenderMultiColumnFlow>(parentLayer->renderer())) {
if (auto* fragment = multiColumnFlow->physicalTranslationFromFlowToFragment(location))
location.move(fragment->topLeftLocation() - parentLayer->renderBox()->topLeftLocation());
}
}
}
return parentLayer;
}
LayoutPoint RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, const LayoutPoint& location, ColumnOffsetAdjustment adjustForColumns) const
{
if (ancestorLayer == this)
return location;
const auto* currLayer = this;
auto locationInLayerCoords = location;
while (currLayer && currLayer != ancestorLayer)
currLayer = accumulateOffsetTowardsAncestor(currLayer, ancestorLayer, locationInLayerCoords, adjustForColumns);
// Pixel snap the whole SVG subtree as one "block" -- not individual layers down the SVG render tree.
if (renderer().isRenderSVGRoot())
return LayoutPoint(roundPointToDevicePixels(locationInLayerCoords, renderer().document().deviceScaleFactor()));
return locationInLayerCoords;
}
LayoutSize RenderLayer::offsetFromAncestor(const RenderLayer* ancestorLayer, ColumnOffsetAdjustment adjustForColumns) const
{
return toLayoutSize(convertToLayerCoords(ancestorLayer, LayoutPoint(), adjustForColumns));
}
bool RenderLayer::shouldTryToScrollForScrollIntoView() const
{
if (!renderer().isRenderBox() || !renderer().hasNonVisibleOverflow())
return false;
// Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
// FIXME: Is this still needed? It used to be relevant for Safari RSS.
if (renderer().parent() && !renderer().parent()->style().lineClamp().isNone())
return false;
auto& box = *renderBox();
if (box.frame().eventHandler().autoscrollInProgress()) {
// The "programmatically" here is misleading; this asks whether the box has scrollable overflow,
// or is a special case like a form control.
return box.canBeProgramaticallyScrolled();
}
// Programmatic scrolls can scroll overflow: hidden but not overflow: clip.
return box.hasPotentiallyScrollableOverflow() && (box.hasHorizontalOverflow() || box.hasVerticalOverflow());
}
void RenderLayer::autoscroll(const IntPoint& positionInWindow)
{
IntPoint currentDocumentPosition = renderer().view().frameView().windowToContents(positionInWindow);
LocalFrameView::scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), renderer(), false, { SelectionRevealMode::Reveal, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded, ShouldAllowCrossOriginScrolling::Yes });
}
bool RenderLayer::canResize() const
{
// We need a special case for <iframe> because they never have
// hasNonVisibleOverflow(). However, they do "implicitly" clip their contents, so
// we want to allow resizing them also.
return (renderer().hasNonVisibleOverflow() || renderer().isRenderIFrame()) && renderer().style().resize() != Resize::None;
}
LayoutSize RenderLayer::minimumSizeForResizing(float zoomFactor) const
{
// Use the resizer size as the strict minimum size
auto resizerRect = overflowControlsRects().resizer;
LayoutUnit minWidth = minimumValueForLength(renderer().style().minWidth(), renderer().containingBlock()->width());
LayoutUnit minHeight = minimumValueForLength(renderer().style().minHeight(), renderer().containingBlock()->height());
minWidth = std::max(LayoutUnit(minWidth / zoomFactor), LayoutUnit(resizerRect.width()));
minHeight = std::max(LayoutUnit(minHeight / zoomFactor), LayoutUnit(resizerRect.height()));
return LayoutSize(minWidth, minHeight);
}
void RenderLayer::resize(const PlatformMouseEvent& evt, const LayoutSize& oldOffset)
{
// FIXME: This should be possible on generated content but is not right now.
if (!inResizeMode() || !canResize())
return;
// FIXME: This should be possible on all elements but is not right now.
RefPtr styledElement = dynamicDowncast<StyledElement>(renderer().element());
if (!styledElement)
return;
// FIXME: The only case where renderer->element()->renderer() != renderer is with continuations. Do they matter here?
// If they do it would still be better to deal with them explicitly.
CheckedPtr renderer = downcast<RenderBox>(styledElement->renderer());
Ref document = styledElement->document();
if (!document->frame()->eventHandler().mousePressed())
return;
float zoomFactor = renderer->style().usedZoom();
auto absolutePoint = document->view()->windowToContents(evt.position());
auto localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
LayoutSize newOffset = offsetFromResizeCorner(localPoint);
newOffset.setWidth(newOffset.width() / zoomFactor);
newOffset.setHeight(newOffset.height() / zoomFactor);
LayoutSize currentSize = LayoutSize(renderer->width() / zoomFactor, renderer->height() / zoomFactor);
LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
if (renderer->shouldPlaceVerticalScrollbarOnLeft()) {
newOffset.setWidth(-newOffset.width());
adjustedOldOffset.setWidth(-adjustedOldOffset.width());
}
LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSizeForResizing(zoomFactor)) - currentSize;
StyleAttributeMutationScope mutationScope { styledElement.get() };
bool isBoxSizingBorder = renderer->style().boxSizing() == BoxSizing::BorderBox;
Resize resize = renderer->style().resize();
bool canResizeWidth = resize == Resize::Horizontal || resize == Resize::Both
|| (renderer->isHorizontalWritingMode() ? resize == Resize::Inline : resize == Resize::Block);
if (canResizeWidth && difference.width()) {
if (is<HTMLFormControlElement>(*styledElement)) {
// Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
styledElement->setInlineStyleProperty(CSSPropertyMarginLeft, renderer->marginLeft() / zoomFactor, CSSUnitType::CSS_PX);
styledElement->setInlineStyleProperty(CSSPropertyMarginRight, renderer->marginRight() / zoomFactor, CSSUnitType::CSS_PX);
}
LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? 0_lu : renderer->horizontalBorderAndPaddingExtent());
baseWidth = baseWidth / zoomFactor;
styledElement->setInlineStyleProperty(CSSPropertyWidth, roundToInt(baseWidth + difference.width()), CSSUnitType::CSS_PX);
mutationScope.enqueueMutationRecord();
}
bool canResizeHeight = resize == Resize::Vertical || resize == Resize::Both
|| (renderer->isHorizontalWritingMode() ? resize == Resize::Block : resize == Resize::Inline);
if (canResizeHeight && difference.height()) {
if (is<HTMLFormControlElement>(*styledElement)) {
// Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
styledElement->setInlineStyleProperty(CSSPropertyMarginTop, renderer->marginTop() / zoomFactor, CSSUnitType::CSS_PX);
styledElement->setInlineStyleProperty(CSSPropertyMarginBottom, renderer->marginBottom() / zoomFactor, CSSUnitType::CSS_PX);
}
LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? 0_lu : renderer->verticalBorderAndPaddingExtent());
baseHeight = baseHeight / zoomFactor;
styledElement->setInlineStyleProperty(CSSPropertyHeight, roundToInt(baseHeight + difference.height()), CSSUnitType::CSS_PX);
mutationScope.enqueueMutationRecord();
}
document->updateLayout();
// FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
}
IntSize RenderLayer::visibleSize() const
{
RenderBox* box = renderBox();
if (!box)
return IntSize();
return IntSize(roundToInt(box->clientWidth()), roundToInt(box->clientHeight()));
}
RenderLayer::OverflowControlRects RenderLayer::overflowControlsRects() const
{
if (m_scrollableArea)
return m_scrollableArea->overflowControlsRects();
auto& renderBox = downcast<RenderBox>(renderer());
// Scrollbars sit inside the border box.
auto overflowControlsPositioningRect = snappedIntRect(renderBox.paddingBoxRectIncludingScrollbar());
bool placeVerticalScrollbarOnTheLeft = renderBox.shouldPlaceVerticalScrollbarOnLeft();
bool haveResizer = renderer().style().resize() != Resize::None && renderer().style().pseudoElementType() == PseudoId::None;
OverflowControlRects result;
auto cornerRect = [&](IntSize cornerSize) {
if (placeVerticalScrollbarOnTheLeft) {
auto bottomLeftCorner = overflowControlsPositioningRect.minXMaxYCorner();
return IntRect { { bottomLeftCorner.x(), bottomLeftCorner.y() - cornerSize.height(), }, cornerSize };
}
return IntRect { overflowControlsPositioningRect.maxXMaxYCorner() - cornerSize, cornerSize };
};
if (haveResizer) {
auto scrollbarThickness = ScrollbarTheme::theme().scrollbarThickness();
result.resizer = cornerRect({ scrollbarThickness, scrollbarThickness });
}
return result;
}
String RenderLayer::debugDescription() const
{
String compositedDescription;
if (isComposited()) {
TextStream stream;
stream << " " << *backing();
compositedDescription = stream.release();
}
return makeString("RenderLayer 0x"_s, hex(reinterpret_cast<uintptr_t>(this), Lowercase),
' ', size().width(), 'x', size().height(),
transform() ? " has transform"_s : ""_s,
hasFilter() ? " has filter"_s : ""_s,
hasBackdropFilter() ? " has backdrop filter"_s : ""_s,
#if HAVE(CORE_MATERIAL)
hasAppleVisualEffect() ? " has apple visual effect"_s : ""_s,
#endif
hasBlendMode() ? " has blend mode"_s : ""_s,
isolatesBlending() ? " isolates blending"_s : ""_s,
compositedDescription);
}
IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& localPoint) const
{
auto resizerRect = overflowControlsRects().resizer;
auto resizeCorner = renderer().shouldPlaceVerticalScrollbarOnLeft() ? resizerRect.minXMaxYCorner() : resizerRect.maxXMaxYCorner();
return localPoint - resizeCorner;
}
int RenderLayer::scrollWidth() const
{
if (m_scrollableArea)
return m_scrollableArea->scrollWidth();
RenderBox* box = renderBox();
ASSERT(box);
LayoutRect overflowRect(box->layoutOverflowRect());
box->flipForWritingMode(overflowRect);
return roundToInt(overflowRect.maxX() - overflowRect.x());
}
int RenderLayer::scrollHeight() const
{
if (m_scrollableArea)
return m_scrollableArea->scrollHeight();
RenderBox* box = renderBox();
ASSERT(box);
LayoutRect overflowRect(box->layoutOverflowRect());
box->flipForWritingMode(overflowRect);
return roundToInt(overflowRect.maxY() - overflowRect.y());
}
void RenderLayer::updateScrollInfoAfterLayout()
{
updateLayerScrollableArea();
if (m_scrollableArea)
m_scrollableArea->updateScrollInfoAfterLayout();
}
void RenderLayer::updateScrollbarSteps()
{
if (m_scrollableArea)
m_scrollableArea->updateScrollbarSteps();
}
bool RenderLayer::canUseCompositedScrolling() const
{
if (m_scrollableArea)
return m_scrollableArea->canUseCompositedScrolling();
return false;
}
bool RenderLayer::hasCompositedScrollableOverflow() const
{
if (m_scrollableArea)
return m_scrollableArea->hasCompositedScrollableOverflow();
return false;
}
void RenderLayer::computeHasCompositedScrollableOverflow(LayoutUpToDate layoutUpToDate)
{
if (m_scrollableArea)
m_scrollableArea->computeHasCompositedScrollableOverflow(layoutUpToDate);
}
bool RenderLayer::hasOverlayScrollbars() const
{
if (m_scrollableArea)
return m_scrollableArea->hasOverlayScrollbars();
return false;
}
bool RenderLayer::usesCompositedScrolling() const
{
if (m_scrollableArea)
return m_scrollableArea->usesCompositedScrolling();
return false;
}
bool RenderLayer::isPointInResizeControl(IntPoint localPoint) const
{
if (!canResize())
return false;
return overflowControlsRects().resizer.contains(localPoint);
}
void RenderLayer::paint(GraphicsContext& context, const LayoutRect& damageRect, const LayoutSize& subpixelOffset, OptionSet<PaintBehavior> paintBehavior, RenderObject* subtreePaintRoot, OptionSet<PaintLayerFlag> paintFlags, SecurityOriginPaintPolicy paintPolicy, RegionContext* regionContext)
{
OverlapTestRequestMap overlapTestRequests;
LayerPaintingInfo paintingInfo(this, enclosingIntRect(damageRect), paintBehavior, subpixelOffset, subtreePaintRoot, &overlapTestRequests, paintPolicy == SecurityOriginPaintPolicy::AccessibleOriginOnly);
if (regionContext) {
paintingInfo.regionContext = regionContext;
if (is<EventRegionContext>(regionContext))
paintFlags.add(RenderLayer::PaintLayerFlag::CollectingEventRegion);
}
paintLayer(context, paintingInfo, paintFlags);
for (auto& widget : overlapTestRequests.keys())
widget->setOverlapTestResult(false);
}
void RenderLayer::clipToRect(GraphicsContext& context, GraphicsContextStateSaver& stateSaver, RegionContextStateSaver& regionContextStateSaver, const LayerPaintingInfo& paintingInfo, OptionSet<PaintBehavior> paintBehavior, const ClipRect& clipRect, BorderRadiusClippingRule rule)
{
float deviceScaleFactor = renderer().document().deviceScaleFactor();
bool needsClipping = !clipRect.isInfinite() && clipRect.rect() != paintingInfo.paintDirtyRect;
if (needsClipping || clipRect.affectedByRadius())
stateSaver.save();
if (needsClipping) {
LayoutRect adjustedClipRect = clipRect.rect();
adjustedClipRect.move(paintingInfo.subpixelOffset);
auto snappedClipRect = snapRectToDevicePixelsIfNeeded(adjustedClipRect, renderer());
context.clip(snappedClipRect);
regionContextStateSaver.pushClip(enclosingIntRect(snappedClipRect));
}
if (clipRect.affectedByRadius()) {
// If the clip rect has been tainted by a border radius, then we have to walk up our layer chain applying the clips from
// any layers with overflow. The condition for being able to apply these clips is that the overflow object be in our
// containing block chain so we check that also.
for (RenderLayer* layer = rule == IncludeSelfForBorderRadius ? this : parent(); layer; layer = layer->parent()) {
if (paintBehavior.contains(PaintBehavior::CompositedOverflowScrollContent) && layer->usesCompositedScrolling())
break;
if (layer->renderer().hasNonVisibleOverflow() && layer->renderer().style().hasBorderRadius() && ancestorLayerIsInContainingBlockChain(*layer)) {
LayoutRect adjustedClipRect = LayoutRect(toLayoutPoint(layer->offsetFromAncestor(paintingInfo.rootLayer, AdjustForColumns)), layer->size());
adjustedClipRect.move(paintingInfo.subpixelOffset);
auto borderShape = BorderShape::shapeForBorderRect(layer->renderer().style(), adjustedClipRect);
if (borderShape.innerShapeContains(paintingInfo.paintDirtyRect))
context.clip(snapRectToDevicePixels(intersection(paintingInfo.paintDirtyRect, adjustedClipRect), deviceScaleFactor));
else
borderShape.clipToInnerShape(context, deviceScaleFactor);
}
if (layer == paintingInfo.rootLayer)
break;
}
}
}
static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
{
if (overlapTestRequests.isEmpty())
return;
Vector<OverlapTestRequestClient*> overlappedRequestClients;
LayoutRect boundingBox = layer->boundingBox(rootLayer, layer->offsetFromAncestor(rootLayer));
for (auto& request : overlapTestRequests) {
if (!boundingBox.intersects(request.value))
continue;
request.key->setOverlapTestResult(true);
overlappedRequestClients.append(request.key);
}
for (auto* client : overlappedRequestClients)
overlapTestRequests.remove(client);
}
static inline bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
{
return paintingReflection && !layer->has3DTransform();
}
static inline bool shouldSuppressPaintingLayer(RenderLayer* layer)
{
// Avoid painting all layers if the document is in a state where visual updates aren't allowed.
// A full repaint will occur in Document::setVisualUpdatesAllowed(bool) if painting is suppressed here.
if (!layer->renderer().document().visualUpdatesAllowed())
return true;
return false;
}
void RenderLayer::paintSVGResourceLayer(GraphicsContext& context, const AffineTransform& layerContentTransform)
{
bool wasPaintingSVGResourceLayer = m_isPaintingSVGResourceLayer;
m_isPaintingSVGResourceLayer = true;
context.concatCTM(layerContentTransform);
auto localPaintDirtyRect = LayoutRect::infiniteRect();
auto* rootPaintingLayer = [&] () {
auto* curr = parent();
while (curr && !(curr->renderer().isAnonymous() && is<RenderSVGViewportContainer>(curr->renderer())))
curr = curr->parent();
return curr;
}();
ASSERT(rootPaintingLayer);
LayerPaintingInfo paintingInfo(rootPaintingLayer, localPaintDirtyRect, PaintBehavior::Normal, LayoutSize());
paintingInfo.clipToDirtyRect = false;
OptionSet<PaintLayerFlag> flags { PaintLayerFlag::TemporaryClipRects };
if (!renderer().hasNonVisibleOverflow())
flags.add({ PaintLayerFlag::PaintingOverflowContents, PaintLayerFlag::PaintingOverflowContentsRoot });
paintLayer(context, paintingInfo, flags);
m_isPaintingSVGResourceLayer = wasPaintingSVGResourceLayer;
}
static inline bool paintForFixedRootBackground(const RenderLayer* layer, OptionSet<RenderLayer::PaintLayerFlag> paintFlags)
{
return layer->renderer().isDocumentElementRenderer() && (paintFlags & RenderLayer::PaintLayerFlag::PaintingRootBackgroundOnly);
}
void RenderLayer::paintLayer(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags)
{
auto shouldContinuePaint = [&] () {
return backing()->paintsIntoWindow()
|| backing()->paintsIntoCompositedAncestor()
|| shouldDoSoftwarePaint(this, paintFlags.contains(PaintLayerFlag::PaintingReflection))
|| paintForFixedRootBackground(this, paintFlags);
};
auto paintsIntoDifferentCompositedDestination = [&]() {
if (paintsIntoProvidedBacking())
return true;
if (isComposited() && !shouldContinuePaint())
return true;
return false;
};
if (paintsIntoDifferentCompositedDestination()) {
if (!context.performingPaintInvalidation() && !(paintingInfo.paintBehavior & PaintBehavior::FlattenCompositingLayers))
return;
paintFlags.add(PaintLayerFlag::TemporaryClipRects);
}
if (viewportConstrainedNotCompositedReason() == NotCompositedForBoundsOutOfView && !(paintingInfo.paintBehavior & PaintBehavior::Snapshotting)) {
// Don't paint out-of-view viewport constrained layers (when doing prepainting) because they will never be visible
// unless their position or viewport size is changed.
ASSERT(renderer().isFixedPositioned());
return;
}
paintLayerWithEffects(context, paintingInfo, paintFlags);
}
void RenderLayer::paintLayerWithEffects(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags)
{
// Non self-painting leaf layers don't need to be painted as their renderer() should properly paint itself.
if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
return;
if (shouldSuppressPaintingLayer(this))
return;
// If this layer is totally invisible then there is nothing to paint.
if (!renderer().opacity())
return;
if (paintsWithTransparency(paintingInfo.paintBehavior))
paintFlags.add(PaintLayerFlag::HaveTransparency);
// PaintLayerFlag::AppliedTransform is used in RenderReplica, to avoid applying the transform twice.
if (paintsWithTransform(paintingInfo.paintBehavior) && !(paintFlags & PaintLayerFlag::AppliedTransform)) {
TransformationMatrix layerTransform = renderableTransform(paintingInfo.paintBehavior);
// If the transform can't be inverted, then don't paint anything.
if (!layerTransform.isInvertible())
return;
// If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
// layer from the parent now, assuming there is a parent
if (paintFlags & PaintLayerFlag::HaveTransparency) {
if (this != paintingInfo.rootLayer && parent())
parent()->beginTransparencyLayers(context, paintingInfo, paintingInfo.paintDirtyRect);
else
beginTransparencyLayers(context, paintingInfo, paintingInfo.paintDirtyRect);
}
if (enclosingPaginationLayer(ExcludeCompositedPaginatedLayers)) {
paintTransformedLayerIntoFragments(context, paintingInfo, paintFlags);
return;
}
// Make sure the parent's clip rects have been calculated.
ClipRect clipRect = paintingInfo.paintDirtyRect;
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(paintingInfo.regionContext);
if (parent()) {
auto options = paintFlags.contains(PaintLayerFlag::PaintingOverflowContents) ? clipRectOptionsForPaintingOverflowContents : clipRectDefaultOptions;
auto clipRectsContext = ClipRectsContext(paintingInfo.rootLayer, (paintFlags & PaintLayerFlag::TemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, options);
clipRect = backgroundClipRect(clipRectsContext);
clipRect.intersect(paintingInfo.paintDirtyRect);
OptionSet<PaintBehavior> paintBehavior = PaintBehavior::Normal;
if (paintFlags.contains(PaintLayerFlag::PaintingOverflowContents))
paintBehavior.add(PaintBehavior::CompositedOverflowScrollContent);
// Always apply SVG viewport clipping in coordinate system before the SVG viewBox transformation is applied.
if (CheckedPtr svgRoot = dynamicDowncast<RenderSVGRoot>(renderer())) {
if (svgRoot->shouldApplyViewportClip()) {
auto newRect = svgRoot->borderBoxRect();
auto offsetFromParent = offsetFromAncestor(clipRectsContext.rootLayer);
auto offsetForThisLayer = offsetFromParent + paintingInfo.subpixelOffset;
auto devicePixelSnappedOffsetForThisLayer = toFloatSize(roundPointToDevicePixels(toLayoutPoint(offsetForThisLayer), renderer().document().deviceScaleFactor()));
newRect.move(devicePixelSnappedOffsetForThisLayer.width(), devicePixelSnappedOffsetForThisLayer.height());
clipRect.intersect(newRect);
}
}
// Push the parent coordinate space's clip.
parent()->clipToRect(context, stateSaver, regionContextStateSaver, paintingInfo, paintBehavior, clipRect);
}
paintLayerByApplyingTransform(context, paintingInfo, paintFlags);
return;
}
paintLayerContentsAndReflection(context, paintingInfo, paintFlags);
}
void RenderLayer::paintLayerContentsAndReflection(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags)
{
ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
auto localPaintFlags = paintFlags - OptionSet<PaintLayerFlag> { PaintLayerFlag::AppliedTransform, PaintLayerFlag::PaintingOverflowContentsRoot };
// Paint the reflection first if we have one.
if (m_reflection && !m_paintingInsideReflection) {
// Mark that we are now inside replica painting.
m_paintingInsideReflection = true;
reflectionLayer()->paintLayer(context, paintingInfo, localPaintFlags | PaintLayerFlag::PaintingReflection);
m_paintingInsideReflection = false;
}
localPaintFlags.add(paintLayerPaintingCompositingAllPhasesFlags());
paintLayerContents(context, paintingInfo, localPaintFlags);
}
bool RenderLayer::setupFontSubpixelQuantization(GraphicsContext& context, bool& didQuantizeFonts)
{
if (context.paintingDisabled())
return false;
bool scrollingOnMainThread = true;
#if ENABLE(ASYNC_SCROLLING)
if (RefPtr scrollingCoordinator = page().scrollingCoordinator())
scrollingOnMainThread = scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously(renderer().view().frameView());
#endif
// FIXME: We shouldn't have to disable subpixel quantization for overflow clips or subframes once we scroll those
// things on the scrolling thread.
bool contentsScrollByPainting = (renderer().hasNonVisibleOverflow() && !usesCompositedScrolling()) || (renderer().frame().ownerElement());
bool isZooming = !page().chrome().client().hasStablePageScaleFactor();
if (scrollingOnMainThread || contentsScrollByPainting || isZooming) {
didQuantizeFonts = context.shouldSubpixelQuantizeFonts();
context.setShouldSubpixelQuantizeFonts(false);
return true;
}
return false;
}
std::pair<Path, WindRule> RenderLayer::computeClipPath(const LayoutSize& offsetFromRoot, const LayoutRect& rootRelativeBoundsForNonBoxes) const
{
const RenderStyle& style = renderer().style();
if (RefPtr clipPath = dynamicDowncast<ShapePathOperation>(*style.clipPath())) {
auto referenceBoxRect = referenceBoxRectForClipPath(clipPath->referenceBox(), offsetFromRoot, rootRelativeBoundsForNonBoxes);
auto snappedReferenceBoxRect = snapRectToDevicePixelsIfNeeded(referenceBoxRect, renderer());
return { clipPath->pathForReferenceRect(snappedReferenceBoxRect), clipPath->windRule() };
}
RefPtr clipPath = dynamicDowncast<BoxPathOperation>(*style.clipPath());
CheckedPtr box = dynamicDowncast<RenderBox>(renderer());
if (clipPath && box) {
auto shapeRect = computeRoundedRectForBoxShape(clipPath->referenceBox(), *box).pixelSnappedRoundedRectForPainting(renderer().document().deviceScaleFactor());
shapeRect.move(offsetFromRoot);
return { clipPath->pathForReferenceRect(shapeRect), WindRule::NonZero };
}
return { Path(), WindRule::NonZero };
}
void RenderLayer::setupClipPath(GraphicsContext& context, GraphicsContextStateSaver& stateSaver, RegionContextStateSaver& regionContextStateSaver, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag>& paintFlags, const LayoutSize& offsetFromRoot)
{
bool isCollectingRegions = paintFlags.contains(PaintLayerFlag::CollectingEventRegion) || is<AccessibilityRegionContext>(paintingInfo.regionContext);
if (!renderer().hasClipPath() || (context.paintingDisabled() && !isCollectingRegions) || paintingInfo.paintDirtyRect.isEmpty())
return;
// Applying clip-path on <clipPath> enforces us to use mask based clipping, so return false here to disable path based clipping.
// Furthermore if we're the child of a resource container (<clipPath> / <mask> / ...) disabled path based clipping.
if (is<RenderSVGResourceClipper>(m_enclosingSVGHiddenOrResourceContainer)) {
// If m_isPaintingSVGResourceLayer is true, this function was invoked via paintSVGResourceLayer() -- clipping on <clipPath> is already
// handled in RenderSVGResourceClipper::applyMaskClipping(), so do not set paintSVGClippingMask to true here.
paintFlags.set(PaintLayerFlag::PaintingSVGClippingMask, !m_isPaintingSVGResourceLayer);
return;
}
auto clippedContentBounds = calculateLayerBounds(paintingInfo.rootLayer, offsetFromRoot, { UseLocalClipRectIfPossible });
auto& style = renderer().style();
LayoutSize paintingOffsetFromRoot = LayoutSize(snapSizeToDevicePixel(offsetFromRoot + paintingInfo.subpixelOffset, LayoutPoint(), renderer().document().deviceScaleFactor()));
ASSERT(style.clipPath());
if (is<ShapePathOperation>(*style.clipPath()) || (is<BoxPathOperation>(*style.clipPath()) && is<RenderBox>(renderer()))) {
// clippedContentBounds is used as the reference box for inlines, which is also poorly specified: https://github.com/w3c/csswg-drafts/issues/6383.
auto [path, windRule] = computeClipPath(paintingOffsetFromRoot, clippedContentBounds);
if (isCollectingRegions) {
regionContextStateSaver.pushClip(path);
return;
}
stateSaver.save();
context.clipPath(path, windRule);
return;
}
if (RefPtr referenceClipPathOperation = dynamicDowncast<ReferencePathOperation>(style.clipPath())) {
if (auto* svgClipper = renderer().svgClipperResourceFromStyle()) {
RefPtr graphicsElement = svgClipper->shouldApplyPathClipping();
if (!graphicsElement) {
paintFlags.add(PaintLayerFlag::PaintingSVGClippingMask);
return;
}
stateSaver.save();
FloatRect svgReferenceBox;
FloatSize coordinateSystemOriginTranslation;
if (renderer().isSVGLayerAwareRenderer()) {
ASSERT(paintingInfo.subpixelOffset.isZero());
auto boundingBoxTopLeftCorner = renderer().nominalSVGLayoutLocation();
svgReferenceBox = renderer().objectBoundingBox();
coordinateSystemOriginTranslation = toLayoutPoint(offsetFromRoot) - boundingBoxTopLeftCorner;
} else {
auto clipPathObjectBoundingBox = referenceBoxRectForClipPath(CSSBoxType::BorderBox, offsetFromRoot, clippedContentBounds);
svgReferenceBox = snapRectToDevicePixels(LayoutRect(clipPathObjectBoundingBox), renderer().document().deviceScaleFactor());
}
if (!coordinateSystemOriginTranslation.isZero())
context.translate(coordinateSystemOriginTranslation);
svgClipper->applyPathClipping(context, renderer(), svgReferenceBox, *graphicsElement);
if (!coordinateSystemOriginTranslation.isZero())
context.translate(-coordinateSystemOriginTranslation);
return;
}
if (auto* clipperRenderer = ReferencedSVGResources::referencedClipperRenderer(renderer().treeScopeForSVGReferences(), *referenceClipPathOperation)) {
// Use the border box as the reference box, even though this is not clearly specified: https://github.com/w3c/csswg-drafts/issues/5786.
// clippedContentBounds is used as the reference box for inlines, which is also poorly specified: https://github.com/w3c/csswg-drafts/issues/6383.
auto referenceBox = referenceBoxRectForClipPath(CSSBoxType::BorderBox, offsetFromRoot, clippedContentBounds);
auto snappedReferenceBox = snapRectToDevicePixelsIfNeeded(referenceBox, renderer());
auto offset = snappedReferenceBox.location();
auto snappedClippingBounds = snapRectToDevicePixelsIfNeeded(clippedContentBounds, renderer());
snappedClippingBounds.moveBy(-offset);
stateSaver.save();
context.translate(offset);
clipperRenderer->applyClippingToContext(context, renderer(), { { }, referenceBox.size() }, snappedClippingBounds, renderer().style().usedZoom());
context.translate(-offset);
// FIXME: Support event regions.
}
}
}
RenderLayerFilters* RenderLayer::filtersForPainting(GraphicsContext& context, OptionSet<PaintLayerFlag> paintFlags) const
{
if (context.paintingDisabled())
return nullptr;
if (paintFlags & PaintLayerFlag::PaintingOverlayScrollbars)
return nullptr;
if (!paintsWithFilters())
return nullptr;
if (m_filters)
return m_filters.get();
return nullptr;
}
GraphicsContext* RenderLayer::setupFilters(GraphicsContext& destinationContext, LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags, const LayoutSize& offsetFromRoot, const ClipRect& backgroundRect)
{
auto* paintingFilters = filtersForPainting(destinationContext, paintFlags);
if (!paintingFilters)
return nullptr;
LayoutRect filterRepaintRect = paintingFilters->dirtySourceRect();
filterRepaintRect.move(offsetFromRoot);
auto rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, offsetFromRoot, { });
GraphicsContext* filterContext = paintingFilters->beginFilterEffect(renderer(), destinationContext, enclosingIntRect(rootRelativeBounds), enclosingIntRect(paintingInfo.paintDirtyRect), enclosingIntRect(filterRepaintRect), backgroundRect.rect());
if (!filterContext)
return nullptr;
paintingInfo.paintDirtyRect = paintingFilters->repaintRect();
// If the filter needs the full source image, we need to avoid using the clip rectangles.
// Otherwise, if for example this layer has overflow:hidden, a drop shadow will not compute correctly.
// Note that we will still apply the clipping on the final rendering of the filter.
paintingInfo.clipToDirtyRect = !paintingFilters->hasFilterThatMovesPixels();
paintingInfo.requireSecurityOriginAccessForWidgets = paintingFilters->hasFilterThatShouldBeRestrictedBySecurityOrigin();
return filterContext;
}
void RenderLayer::applyFilters(GraphicsContext& originalContext, const LayerPaintingInfo& paintingInfo, OptionSet<PaintBehavior> behavior, const ClipRect& backgroundRect)
{
GraphicsContextStateSaver stateSaver(originalContext, false);
bool needsClipping = m_filters->hasSourceImage();
if (needsClipping) {
RegionContextStateSaver regionContextStateSaver(paintingInfo.regionContext);
clipToRect(originalContext, stateSaver, regionContextStateSaver, paintingInfo, behavior, backgroundRect);
}
m_filters->applyFilterEffect(originalContext);
}
void RenderLayer::paintLayerContents(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags)
{
ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
if (context.detectingContentfulPaint() && context.contentfulPaintDetected())
return;
auto localPaintFlags = paintFlags - PaintLayerFlag::AppliedTransform;
bool haveTransparency = localPaintFlags.contains(PaintLayerFlag::HaveTransparency);
bool isPaintingOverlayScrollbars = localPaintFlags.contains(PaintLayerFlag::PaintingOverlayScrollbars);
bool isPaintingCompositedForeground = localPaintFlags.contains(PaintLayerFlag::PaintingCompositingForegroundPhase);
bool isPaintingCompositedBackground = localPaintFlags.contains(PaintLayerFlag::PaintingCompositingBackgroundPhase);
bool isPaintingOverflowContents = localPaintFlags.contains(PaintLayerFlag::PaintingOverflowContents);
bool isCollectingEventRegion = localPaintFlags.contains(PaintLayerFlag::CollectingEventRegion);
bool isCollectingAccessibilityRegion = is<AccessibilityRegionContext>(paintingInfo.regionContext);
bool isSelfPaintingLayer = this->isSelfPaintingLayer();
auto hasVisibleContent = [&]() -> bool {
if (!m_hasVisibleContent)
return false;
if (!m_enclosingSVGHiddenOrResourceContainer)
return true;
// Hidden SVG containers (<defs> / <symbol> ...) and their children are never painted directly.
if (!is<RenderSVGResourceContainer>(m_enclosingSVGHiddenOrResourceContainer))
return false;
// SVG resource layers and their children are only painted indirectly, via paintSVGResourceLayer().
ASSERT(m_enclosingSVGHiddenOrResourceContainer->hasLayer());
return m_enclosingSVGHiddenOrResourceContainer->layer()->isPaintingSVGResourceLayer();
};
bool shouldPaintContent = hasVisibleContent() && isSelfPaintingLayer && !isPaintingOverlayScrollbars && !isCollectingEventRegion && !isCollectingAccessibilityRegion;
bool shouldPaintOutline = [&]() {
if (!isSelfPaintingLayer)
return false;
if (!shouldPaintContent)
return false;
if (isPaintingOverlayScrollbars || isCollectingEventRegion || isCollectingAccessibilityRegion)
return false;
// For the current layer, the outline has been painted by the primary GraphicsLayer.
if (localPaintFlags.contains(PaintLayerFlag::PaintingOverflowContentsRoot))
return false;
// Paint outlines in the background phase for a scroll container so that they don't scroll with the content.
// FIXME: inset outlines will have the wrong z-ordering with scrolled content. See also webkit.org/b/249457.
if (localPaintFlags.contains(PaintLayerFlag::PaintingOverflowContainer))
return isPaintingCompositedBackground;
return isPaintingCompositedForeground;
}();
bool shouldPaintNegativeZIndexChildren = [&]() {
if (localPaintFlags.contains(PaintLayerFlag::PaintingOverflowContainer))
return false;
if (localPaintFlags.contains(PaintLayerFlag::PaintingOverflowContents)) {
// Overflow contents has the "PaintingCompositingForegroundPhase" phase,
// but we need to paint negative z-index layers here so they scroll with the content.
return true;
}
return isPaintingCompositedBackground;
}();
if (localPaintFlags.contains(PaintLayerFlag::PaintingRootBackgroundOnly) && !renderer().isRenderView() && !renderer().isDocumentElementRenderer()) {
// If beginTransparencyLayers was called prior to this, ensure the transparency state is cleaned up before returning.
if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
if (m_savedAlphaForTransparency) {
context.setAlpha(*m_savedAlphaForTransparency);
m_savedAlphaForTransparency = std::nullopt;
} else {
context.endTransparencyLayer();
context.restore();
}
m_usedTransparency = false;
}
return;
}
updateLayerListsIfNeeded();
LayoutSize offsetFromRoot = offsetFromAncestor(paintingInfo.rootLayer);
// FIXME: We shouldn't have to disable subpixel quantization for overflow clips or subframes once we scroll those
// things on the scrolling thread.
bool didQuantizeFonts = true;
bool needToAdjustSubpixelQuantization = setupFontSubpixelQuantization(context, didQuantizeFonts);
// Apply clip-path to context.
LayoutSize columnAwareOffsetFromRoot = offsetFromRoot;
if (renderer().enclosingFragmentedFlow() && (renderer().hasClipPath() || filtersForPainting(context, paintFlags)))
columnAwareOffsetFromRoot = toLayoutSize(convertToLayerCoords(paintingInfo.rootLayer, LayoutPoint(), AdjustForColumns));
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(paintingInfo.regionContext);
if (shouldApplyClipPath(paintingInfo.paintBehavior, localPaintFlags))
setupClipPath(context, stateSaver, regionContextStateSaver, paintingInfo, localPaintFlags, columnAwareOffsetFromRoot);
bool applySVGClippingMask = localPaintFlags.contains(PaintLayerFlag::PaintingSVGClippingMask);
if (applySVGClippingMask)
localPaintFlags.remove(PaintLayerFlag::PaintingSVGClippingMask);
bool selectionAndBackgroundsOnly = paintingInfo.paintBehavior.contains(PaintBehavior::SelectionAndBackgroundsOnly);
bool selectionOnly = paintingInfo.paintBehavior.contains(PaintBehavior::SelectionOnly);
m_paintFrequencyTracker.track(page().lastRenderingUpdateTimestamp());
LayerFragments layerFragments;
RenderObject* subtreePaintRootForRenderer = nullptr;
auto paintBehavior = [&]() {
constexpr OptionSet<PaintBehavior> flagsToCopy = { PaintBehavior::FlattenCompositingLayers, PaintBehavior::Snapshotting, PaintBehavior::ExcludeSelection, PaintBehavior::ExcludeReplacedContent };
OptionSet<PaintBehavior> paintBehavior = paintingInfo.paintBehavior & flagsToCopy;
if (localPaintFlags.contains(PaintLayerFlag::PaintingSkipRootBackground))
paintBehavior.add(PaintBehavior::SkipRootBackground);
else if (localPaintFlags.contains(PaintLayerFlag::PaintingRootBackgroundOnly))
paintBehavior.add(PaintBehavior::RootBackgroundOnly);
// FIXME: This seems wrong. We should retain the DefaultAsynchronousImageDecode flag for all RenderLayers painted into the root tile cache.
if ((paintingInfo.paintBehavior & PaintBehavior::DefaultAsynchronousImageDecode) && isRenderViewLayer())
paintBehavior.add(PaintBehavior::DefaultAsynchronousImageDecode);
if (isPaintingOverflowContents)
paintBehavior.add(PaintBehavior::CompositedOverflowScrollContent);
if (isCollectingEventRegion) {
paintBehavior = paintBehavior & PaintBehavior::CompositedOverflowScrollContent;
if (isPaintingCompositedForeground)
paintBehavior.add(PaintBehavior::EventRegionIncludeForeground);
if (isPaintingCompositedBackground)
paintBehavior.add(PaintBehavior::EventRegionIncludeBackground);
}
return paintBehavior;
}();
{ // Scope for filter-related state changes.
ClipRect backgroundRect;
if (filtersForPainting(context, paintFlags)) {
// When we called collectFragments() last time, paintDirtyRect was reset to represent the filter bounds.
// Now we need to compute the backgroundRect uncontaminated by filters, in order to clip the filtered result.
// Note that we also use paintingInfo here, not localPaintingInfo which filters also contaminated.
LayerFragments layerFragments;
auto clipRectOptions = isPaintingOverflowContents ? clipRectOptionsForPaintingOverflowContents : clipRectDefaultOptions;
collectFragments(layerFragments, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, ExcludeCompositedPaginatedLayers,
(localPaintFlags & PaintLayerFlag::TemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, clipRectOptions, offsetFromRoot);
updatePaintingInfoForFragments(layerFragments, paintingInfo, localPaintFlags, shouldPaintContent, offsetFromRoot);
// FIXME: Handle more than one fragment.
backgroundRect = layerFragments.isEmpty() ? ClipRect() : layerFragments[0].backgroundRect;
}
LayerPaintingInfo localPaintingInfo(paintingInfo);
GraphicsContext* filterContext = setupFilters(context, localPaintingInfo, paintFlags, columnAwareOffsetFromRoot, backgroundRect);
if (filterContext && haveTransparency) {
// If we have a filter and transparency, we have to eagerly start a transparency layer here, rather than risk a child layer lazily starts one with the wrong context.
beginTransparencyLayers(context, localPaintingInfo, paintingInfo.paintDirtyRect);
}
GraphicsContext& currentContext = filterContext ? *filterContext : context;
if (filterContext)
localPaintingInfo.paintBehavior.add(PaintBehavior::DontShowVisitedLinks);
// If this layer's renderer is a child of the subtreePaintRoot, we render unconditionally, which
// is done by passing a nil subtreePaintRoot down to our renderer (as if no subtreePaintRoot was ever set).
// Otherwise, our renderer tree may or may not contain the subtreePaintRoot root, so we pass that root along
// so it will be tested against as we descend through the renderers.
if (localPaintingInfo.subtreePaintRoot && !renderer().isDescendantOf(localPaintingInfo.subtreePaintRoot))
subtreePaintRootForRenderer = localPaintingInfo.subtreePaintRoot;
if (localPaintingInfo.overlapTestRequests && isSelfPaintingLayer)
performOverlapTests(*localPaintingInfo.overlapTestRequests, localPaintingInfo.rootLayer, this);
LayoutRect paintDirtyRect = localPaintingInfo.paintDirtyRect;
if (shouldPaintContent || shouldPaintOutline || isPaintingOverlayScrollbars || isCollectingEventRegion || isCollectingAccessibilityRegion) {
// Collect the fragments. This will compute the clip rectangles and paint offsets for each layer fragment, as well as whether or not the content of each
// fragment should paint. If the parent's filter dictates full repaint to ensure proper filter effect,
// use the overflow clip as dirty rect, instead of no clipping. It maintains proper clipping for overflow::scroll.
if (!localPaintingInfo.clipToDirtyRect && renderer().hasNonVisibleOverflow()) {
// We can turn clipping back by requesting full repaint for the overflow area.
localPaintingInfo.clipToDirtyRect = true;
paintDirtyRect = clipRectRelativeToAncestor(localPaintingInfo.rootLayer, offsetFromRoot, LayoutRect::infiniteRect(), !!(localPaintFlags & PaintLayerFlag::TemporaryClipRects));
}
auto clipRectOptions = isPaintingOverflowContents ? clipRectOptionsForPaintingOverflowContents : clipRectDefaultOptions;
collectFragments(layerFragments, localPaintingInfo.rootLayer, paintDirtyRect, ExcludeCompositedPaginatedLayers,
(localPaintFlags & PaintLayerFlag::TemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, clipRectOptions, offsetFromRoot);
updatePaintingInfoForFragments(layerFragments, localPaintingInfo, localPaintFlags, shouldPaintContent, offsetFromRoot);
}
if (isPaintingCompositedBackground) {
// Paint only the backgrounds for all of the fragments of the layer.
if (shouldPaintContent && !selectionOnly) {
paintBackgroundForFragments(layerFragments, currentContext, context, paintingInfo.paintDirtyRect, haveTransparency,
localPaintingInfo, paintBehavior, subtreePaintRootForRenderer);
}
}
// Now walk the sorted list of children with negative z-indices.
if (shouldPaintNegativeZIndexChildren)
paintList(negativeZOrderLayers(), currentContext, paintingInfo, localPaintFlags);
if (isPaintingCompositedForeground) {
if (shouldPaintContent) {
paintForegroundForFragments(layerFragments, currentContext, context, paintingInfo.paintDirtyRect, haveTransparency,
localPaintingInfo, paintBehavior, subtreePaintRootForRenderer);
}
}
if (isCollectingEventRegion)
collectEventRegionForFragments(layerFragments, currentContext, localPaintingInfo, paintBehavior);
if (isCollectingAccessibilityRegion)
collectAccessibilityRegionsForFragments(layerFragments, currentContext, localPaintingInfo, paintBehavior);
if (shouldPaintOutline)
paintOutlineForFragments(layerFragments, currentContext, localPaintingInfo, paintBehavior, subtreePaintRootForRenderer);
if (isPaintingCompositedForeground) {
// Paint any child layers that have overflow.
paintList(normalFlowLayers(), currentContext, paintingInfo, localPaintFlags);
// Now walk the sorted list of children with positive z-indices.
paintList(positiveZOrderLayers(), currentContext, localPaintingInfo, localPaintFlags);
}
if (m_scrollableArea) {
if (isPaintingOverlayScrollbars && m_scrollableArea->hasScrollbars())
paintOverflowControlsForFragments(layerFragments, currentContext, localPaintingInfo);
}
if (filterContext)
applyFilters(context, paintingInfo, paintBehavior, backgroundRect);
}
if (shouldPaintContent && !(selectionOnly || selectionAndBackgroundsOnly)) {
if (shouldPaintMask(paintingInfo.paintBehavior, localPaintFlags)) {
// Paint the mask for the fragments.
paintMaskForFragments(layerFragments, context, paintingInfo, paintBehavior, subtreePaintRootForRenderer);
}
if (applySVGClippingMask || (!(paintFlags & PaintLayerFlag::PaintingCompositingMaskPhase) && (paintFlags & PaintLayerFlag::PaintingCompositingClipPathPhase))) {
// Re-use paintChildClippingMaskForFragments to paint black for the compositing clipping mask.
paintChildClippingMaskForFragments(layerFragments, context, paintingInfo, paintBehavior, subtreePaintRootForRenderer);
}
if (localPaintFlags & PaintLayerFlag::PaintingChildClippingMaskPhase) {
// Paint the border radius mask for the fragments.
paintChildClippingMaskForFragments(layerFragments, context, paintingInfo, paintBehavior, subtreePaintRootForRenderer);
}
}
// End our transparency layer
if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
if (m_savedAlphaForTransparency) {
context.setAlpha(*m_savedAlphaForTransparency);
m_savedAlphaForTransparency = std::nullopt;
} else {
context.endTransparencyLayer();
context.restore();
}
m_usedTransparency = false;
}
// Re-set this to whatever it was before we painted the layer.
if (needToAdjustSubpixelQuantization)
context.setShouldSubpixelQuantizeFonts(didQuantizeFonts);
}
void RenderLayer::paintLayerByApplyingTransform(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags, const LayoutSize& translationOffset)
{
// This involves subtracting out the position of the layer in our current coordinate space, but preserving
// the accumulated error for sub-pixel layout.
// Note: The pixel-snapping logic is disabled for the whole SVG render tree, except the outermost <svg>.
float deviceScaleFactor = renderer().document().deviceScaleFactor();
LayoutSize offsetFromParent = offsetFromAncestor(paintingInfo.rootLayer);
offsetFromParent += translationOffset;
TransformationMatrix transform(renderableTransform(paintingInfo.paintBehavior));
// Add the subpixel accumulation to the current layer's offset so that we can always snap the translateRight value to where the renderer() is supposed to be painting.
LayoutSize offsetForThisLayer = offsetFromParent + paintingInfo.subpixelOffset;
FloatSize alignedOffsetForThisLayer = rendererNeedsPixelSnapping(renderer()) ? toFloatSize(roundPointToDevicePixels(toLayoutPoint(offsetForThisLayer), deviceScaleFactor)) : offsetForThisLayer;
// We handle accumulated subpixels through nested layers here. Since the context gets translated to device pixels,
// all we need to do is add the delta to the accumulated pixels coming from ancestor layers.
// Translate the graphics context to the snapping position to avoid off-device-pixel positing.
transform.translateRight(alignedOffsetForThisLayer.width(), alignedOffsetForThisLayer.height());
// Apply the transform.
auto oldTransform = context.getCTM();
auto affineTransform = transform.toAffineTransform();
context.concatCTM(affineTransform);
if (paintingInfo.regionContext)
paintingInfo.regionContext->pushTransform(affineTransform);
// Only propagate the subpixel offsets to the descendant layers, if we're not the root
// of a SVG subtree, where no pixel snapping is applied -- only the outermost <svg> layer
// is pixel-snapped "as whole", if it's part of a compound document, e.g. inline SVG in HTML.
LayoutSize adjustedSubpixelOffset;
if (rendererNeedsPixelSnapping(renderer()) && !renderer().isRenderSVGRoot())
adjustedSubpixelOffset = offsetForThisLayer - LayoutSize(alignedOffsetForThisLayer);
// Now do a paint with the root layer shifted to be us.
LayerPaintingInfo transformedPaintingInfo(paintingInfo);
transformedPaintingInfo.rootLayer = this;
if (!transformedPaintingInfo.paintDirtyRect.isInfinite())
transformedPaintingInfo.paintDirtyRect = LayoutRect(encloseRectToDevicePixels(valueOrDefault(transform.inverse()).mapRect(paintingInfo.paintDirtyRect), deviceScaleFactor));
paintFlags.remove(PaintLayerFlag::PaintingOverflowContents);
transformedPaintingInfo.subpixelOffset = adjustedSubpixelOffset;
paintLayerContentsAndReflection(context, transformedPaintingInfo, paintFlags);
if (paintingInfo.regionContext)
paintingInfo.regionContext->popTransform();
context.setCTM(oldTransform);
}
void RenderLayer::paintList(LayerList layerIterator, GraphicsContext& context, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags)
{
if (layerIterator.begin() == layerIterator.end())
return;
if (!hasSelfPaintingLayerDescendant())
return;
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(*this);
#endif
for (auto* childLayer : layerIterator) {
if (paintFlags.contains(PaintLayerFlag::PaintingSkipDescendantViewTransition)) {
if (childLayer->renderer().effectiveCapturedInViewTransition())
continue;
if (childLayer->renderer().isViewTransitionPseudo())
continue;
}
childLayer->paintLayer(context, paintingInfo, paintFlags);
}
}
RenderLayer* RenderLayer::enclosingPaginationLayerInSubtree(const RenderLayer* rootLayer, PaginationInclusionMode mode) const
{
// If we don't have an enclosing layer, or if the root layer is the same as the enclosing layer,
// then just return the enclosing pagination layer (it will be 0 in the former case and the rootLayer in the latter case).
RenderLayer* paginationLayer = enclosingPaginationLayer(mode);
if (!paginationLayer || rootLayer == paginationLayer)
return paginationLayer;
// Walk up the layer tree and see which layer we hit first. If it's the root, then the enclosing pagination
// layer isn't in our subtree and we return nullptr. If we hit the enclosing pagination layer first, then
// we can return it.
for (const RenderLayer* layer = this; layer; layer = layer->parent()) {
if (layer == rootLayer)
return nullptr;
if (layer == paginationLayer)
return paginationLayer;
}
// This should never be reached, since an enclosing layer should always either be the rootLayer or be
// our enclosing pagination layer.
ASSERT_NOT_REACHED();
return nullptr;
}
void RenderLayer::collectFragments(LayerFragments& fragments, const RenderLayer* rootLayer, const LayoutRect& dirtyRect, PaginationInclusionMode inclusionMode,
ClipRectsType clipRectsType, OptionSet<ClipRectsOption> clipRectOptions, const LayoutSize& offsetFromRoot,
const LayoutRect* layerBoundingBox, ShouldApplyRootOffsetToFragments applyRootOffsetToFragments)
{
RenderLayer* paginationLayer = enclosingPaginationLayerInSubtree(rootLayer, inclusionMode);
if (!paginationLayer || isTransformed()) {
// For unpaginated layers, there is only one fragment.
LayerFragment fragment;
ClipRectsContext clipRectsContext(rootLayer, clipRectsType, clipRectOptions);
calculateRects(clipRectsContext, dirtyRect, fragment.layerBounds, fragment.backgroundRect, fragment.foregroundRect, offsetFromRoot);
fragments.append(fragment);
return;
}
// Compute our offset within the enclosing pagination layer.
LayoutSize offsetWithinPaginatedLayer = offsetFromAncestor(paginationLayer);
// Calculate clip rects relative to the enclosingPaginationLayer. The purpose of this call is to determine our bounds clipped to intermediate
// layers between us and the pagination context. It's important to minimize the number of fragments we need to create and this helps with that.
ClipRectsContext paginationClipRectsContext(paginationLayer, TemporaryClipRects, clipRectOptions);
LayoutRect layerBoundsInFragmentedFlow;
ClipRect backgroundRectInFragmentedFlow;
ClipRect foregroundRectInFragmentedFlow;
calculateRects(paginationClipRectsContext, LayoutRect::infiniteRect(), layerBoundsInFragmentedFlow, backgroundRectInFragmentedFlow, foregroundRectInFragmentedFlow,
offsetWithinPaginatedLayer);
// Take our bounding box within the flow thread and clip it.
LayoutRect layerBoundingBoxInFragmentedFlow = layerBoundingBox ? *layerBoundingBox : boundingBox(paginationLayer, offsetWithinPaginatedLayer);
layerBoundingBoxInFragmentedFlow.intersect(backgroundRectInFragmentedFlow.rect());
auto& enclosingFragmentedFlow = downcast<RenderFragmentedFlow>(paginationLayer->renderer());
RenderLayer* parentPaginationLayer = paginationLayer->parent()->enclosingPaginationLayerInSubtree(rootLayer, inclusionMode);
LayerFragments ancestorFragments;
if (parentPaginationLayer) {
// Compute a bounding box accounting for fragments.
LayoutRect layerFragmentBoundingBoxInParentPaginationLayer = enclosingFragmentedFlow.fragmentsBoundingBox(layerBoundingBoxInFragmentedFlow);
// Convert to be in the ancestor pagination context's coordinate space.
LayoutSize offsetWithinParentPaginatedLayer = paginationLayer->offsetFromAncestor(parentPaginationLayer);
layerFragmentBoundingBoxInParentPaginationLayer.move(offsetWithinParentPaginatedLayer);
// Now collect ancestor fragments.
parentPaginationLayer->collectFragments(ancestorFragments, rootLayer, dirtyRect, inclusionMode, clipRectsType, clipRectOptions,
offsetFromAncestor(rootLayer), &layerFragmentBoundingBoxInParentPaginationLayer, ApplyRootOffsetToFragments);
if (ancestorFragments.isEmpty())
return;
for (auto& ancestorFragment : ancestorFragments) {
// Shift the dirty rect into flow thread coordinates.
LayoutRect dirtyRectInFragmentedFlow(dirtyRect);
dirtyRectInFragmentedFlow.move(-offsetWithinParentPaginatedLayer - ancestorFragment.paginationOffset);
size_t oldSize = fragments.size();
// Tell the flow thread to collect the fragments. We pass enough information to create a minimal number of fragments based off the pages/columns
// that intersect the actual dirtyRect as well as the pages/columns that intersect our layer's bounding box.
enclosingFragmentedFlow.collectLayerFragments(fragments, layerBoundingBoxInFragmentedFlow, dirtyRectInFragmentedFlow);
size_t newSize = fragments.size();
if (oldSize == newSize)
continue;
for (size_t i = oldSize; i < newSize; ++i) {
LayerFragment& fragment = fragments.at(i);
// Set our four rects with all clipping applied that was internal to the flow thread.
fragment.setRects(layerBoundsInFragmentedFlow, backgroundRectInFragmentedFlow, foregroundRectInFragmentedFlow, layerBoundingBoxInFragmentedFlow);
// Shift to the root-relative physical position used when painting the flow thread in this fragment.
fragment.moveBy(toLayoutPoint(ancestorFragment.paginationOffset + fragment.paginationOffset + offsetWithinParentPaginatedLayer));
// Intersect the fragment with our ancestor's background clip so that e.g., columns in an overflow:hidden block are
// properly clipped by the overflow.
fragment.intersect(ancestorFragment.paginationClip);
// Now intersect with our pagination clip. This will typically mean we're just intersecting the dirty rect with the column
// clip, so the column clip ends up being all we apply.
fragment.intersect(fragment.paginationClip);
if (applyRootOffsetToFragments == ApplyRootOffsetToFragments)
fragment.paginationOffset = fragment.paginationOffset + offsetWithinParentPaginatedLayer;
}
}
return;
}
// Shift the dirty rect into flow thread coordinates.
LayoutSize offsetOfPaginationLayerFromRoot = enclosingPaginationLayer(inclusionMode)->offsetFromAncestor(rootLayer);
LayoutRect dirtyRectInFragmentedFlow(dirtyRect);
dirtyRectInFragmentedFlow.move(-offsetOfPaginationLayerFromRoot);
// Tell the flow thread to collect the fragments. We pass enough information to create a minimal number of fragments based off the pages/columns
// that intersect the actual dirtyRect as well as the pages/columns that intersect our layer's bounding box.
enclosingFragmentedFlow.collectLayerFragments(fragments, layerBoundingBoxInFragmentedFlow, dirtyRectInFragmentedFlow);
if (fragments.isEmpty())
return;
// Get the parent clip rects of the pagination layer, since we need to intersect with that when painting column contents.
ClipRect ancestorClipRect = dirtyRect;
if (paginationLayer->parent()) {
ClipRectsContext clipRectsContext(rootLayer, clipRectsType, clipRectOptions);
ancestorClipRect = paginationLayer->backgroundClipRect(clipRectsContext);
ancestorClipRect.intersect(dirtyRect);
}
for (auto& fragment : fragments) {
// Set our four rects with all clipping applied that was internal to the flow thread.
fragment.setRects(layerBoundsInFragmentedFlow, backgroundRectInFragmentedFlow, foregroundRectInFragmentedFlow, layerBoundingBoxInFragmentedFlow);
// Shift to the root-relative physical position used when painting the flow thread in this fragment.
fragment.moveBy(toLayoutPoint(fragment.paginationOffset + offsetOfPaginationLayerFromRoot));
// Intersect the fragment with our ancestor's background clip so that e.g., columns in an overflow:hidden block are
// properly clipped by the overflow.
fragment.intersect(ancestorClipRect);
// Now intersect with our pagination clip. This will typically mean we're just intersecting the dirty rect with the column
// clip, so the column clip ends up being all we apply.
fragment.intersect(fragment.paginationClip);
if (applyRootOffsetToFragments == ApplyRootOffsetToFragments)
fragment.paginationOffset = fragment.paginationOffset + offsetOfPaginationLayerFromRoot;
}
}
void RenderLayer::updatePaintingInfoForFragments(LayerFragments& fragments, const LayerPaintingInfo& localPaintingInfo, OptionSet<PaintLayerFlag> localPaintFlags,
bool shouldPaintContent, const LayoutSize& offsetFromRoot)
{
for (auto& fragment : fragments) {
fragment.shouldPaintContent = shouldPaintContent;
if (this != localPaintingInfo.rootLayer || !(localPaintFlags & PaintLayerFlag::PaintingOverflowContents)) {
LayoutSize newOffsetFromRoot = offsetFromRoot + fragment.paginationOffset;
fragment.shouldPaintContent &= intersectsDamageRect(fragment.layerBounds, fragment.backgroundRect.rect(), localPaintingInfo.rootLayer, newOffsetFromRoot, fragment.boundingBox);
}
}
}
void RenderLayer::paintTransformedLayerIntoFragments(GraphicsContext& context, const LayerPaintingInfo& paintingInfo, OptionSet<PaintLayerFlag> paintFlags)
{
LayerFragments enclosingPaginationFragments;
LayoutSize offsetOfPaginationLayerFromRoot;
RenderLayer* paginatedLayer = enclosingPaginationLayer(ExcludeCompositedPaginatedLayers);
LayoutRect transformedExtent = transparencyClipBox(*this, paginatedLayer, PaintingTransparencyClipBox, RootOfTransparencyClipBox, paintingInfo.paintBehavior);
auto clipRectOptions = paintFlags.contains(PaintLayerFlag::PaintingOverflowContents) ? clipRectOptionsForPaintingOverflowContents : clipRectDefaultOptions;
paginatedLayer->collectFragments(enclosingPaginationFragments, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, ExcludeCompositedPaginatedLayers,
(paintFlags & PaintLayerFlag::TemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, clipRectOptions, offsetOfPaginationLayerFromRoot, &transformedExtent);
for (const auto& fragment : enclosingPaginationFragments) {
// Apply the page/column clip for this fragment, as well as any clips established by layers in between us and
// the enclosing pagination layer.
LayoutRect clipRect = fragment.backgroundRect.rect();
// Now compute the clips within a given fragment
if (parent() != paginatedLayer) {
offsetOfPaginationLayerFromRoot = toLayoutSize(paginatedLayer->convertToLayerCoords(paintingInfo.rootLayer, toLayoutPoint(offsetOfPaginationLayerFromRoot)));
auto clipRectsContext = ClipRectsContext(paginatedLayer, (paintFlags & PaintLayerFlag::TemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, clipRectOptions);
LayoutRect parentClipRect = backgroundClipRect(clipRectsContext).rect();
parentClipRect.move(fragment.paginationOffset + offsetOfPaginationLayerFromRoot);
clipRect.intersect(parentClipRect);
}
OptionSet<PaintBehavior> paintBehavior = PaintBehavior::Normal;
if (paintFlags.contains(PaintLayerFlag::PaintingOverflowContents))
paintBehavior.add(PaintBehavior::CompositedOverflowScrollContent);
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(paintingInfo.regionContext);
parent()->clipToRect(context, stateSaver, regionContextStateSaver, paintingInfo, paintBehavior, clipRect);
paintLayerByApplyingTransform(context, paintingInfo, paintFlags, fragment.paginationOffset);
}
}
void RenderLayer::paintBackgroundForFragments(const LayerFragments& layerFragments, GraphicsContext& context, GraphicsContext& contextForTransparencyLayer,
const LayoutRect& transparencyPaintDirtyRect, bool haveTransparency, const LayerPaintingInfo& localPaintingInfo, OptionSet<PaintBehavior> paintBehavior,
RenderObject* subtreePaintRootForRenderer)
{
for (const auto& fragment : layerFragments) {
if (!fragment.shouldPaintContent)
continue;
// Begin transparency layers lazily now that we know we have to paint something.
if (haveTransparency)
beginTransparencyLayers(contextForTransparencyLayer, localPaintingInfo, transparencyPaintDirtyRect);
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(localPaintingInfo.regionContext);
if (localPaintingInfo.clipToDirtyRect) {
// Paint our background first, before painting any child layers.
// Establish the clip used to paint our background.
clipToRect(context, stateSaver, regionContextStateSaver, localPaintingInfo, paintBehavior, fragment.backgroundRect, DoNotIncludeSelfForBorderRadius); // Background painting will handle clipping to self.
}
// Paint the background.
// FIXME: Eventually we will collect the region from the fragment itself instead of just from the paint info.
PaintInfo paintInfo(context, fragment.backgroundRect.rect(), PaintPhase::BlockBackground, paintBehavior, subtreePaintRootForRenderer, nullptr, nullptr, &localPaintingInfo.rootLayer->renderer(), this);
renderer().paint(paintInfo, paintOffsetForRenderer(fragment, localPaintingInfo));
}
}
void RenderLayer::paintForegroundForFragments(const LayerFragments& layerFragments, GraphicsContext& context, GraphicsContext& contextForTransparencyLayer,
const LayoutRect& transparencyPaintDirtyRect, bool haveTransparency, const LayerPaintingInfo& localPaintingInfo, OptionSet<PaintBehavior> paintBehavior,
RenderObject* subtreePaintRootForRenderer)
{
// Begin transparency if we have something to paint.
if (haveTransparency) {
for (const auto& fragment : layerFragments) {
if (fragment.shouldPaintContent && !fragment.foregroundRect.isEmpty()) {
beginTransparencyLayers(contextForTransparencyLayer, localPaintingInfo, transparencyPaintDirtyRect);
break;
}
}
}
OptionSet<PaintBehavior> localPaintBehavior;
if (localPaintingInfo.paintBehavior & PaintBehavior::ForceBlackText)
localPaintBehavior = PaintBehavior::ForceBlackText;
else if (localPaintingInfo.paintBehavior & PaintBehavior::ForceWhiteText)
localPaintBehavior = PaintBehavior::ForceWhiteText;
else
localPaintBehavior = paintBehavior;
// FIXME: It's unclear if this flag copying is necessary.
constexpr OptionSet<PaintBehavior> flagsToCopy { PaintBehavior::ExcludeSelection, PaintBehavior::Snapshotting, PaintBehavior::DefaultAsynchronousImageDecode, PaintBehavior::CompositedOverflowScrollContent, PaintBehavior::ForceSynchronousImageDecode, PaintBehavior::ExcludeReplacedContent };
localPaintBehavior.add(localPaintingInfo.paintBehavior & flagsToCopy);
if (localPaintingInfo.paintBehavior & PaintBehavior::DontShowVisitedLinks)
localPaintBehavior.add(PaintBehavior::DontShowVisitedLinks);
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(localPaintingInfo.regionContext);
// Optimize clipping for the single fragment case.
bool shouldClip = localPaintingInfo.clipToDirtyRect && layerFragments.size() == 1 && layerFragments[0].shouldPaintContent && !layerFragments[0].foregroundRect.isEmpty();
if (shouldClip)
clipToRect(context, stateSaver, regionContextStateSaver, localPaintingInfo, localPaintBehavior, layerFragments[0].foregroundRect);
// We have to loop through every fragment multiple times, since we have to repaint in each specific phase in order for
// interleaving of the fragments to work properly.
bool selectionOnly = localPaintingInfo.paintBehavior.contains(PaintBehavior::SelectionOnly);
bool selectionAndBackgroundsOnly = localPaintingInfo.paintBehavior.contains(PaintBehavior::SelectionAndBackgroundsOnly);
if (is<RenderSVGModelObject>(renderer()) && !is<RenderSVGContainer>(renderer())) {
// SVG containers need to propagate paint phases. This could be saved if we remember somewhere if a SVG subtree
// contains e.g. LegacyRenderSVGForeignObject objects that do need the individual paint phases. For SVG shapes & SVG images
// we can avoid the multiple paintForegroundForFragmentsWithPhase() calls.
if (selectionOnly || selectionAndBackgroundsOnly)
return;
paintForegroundForFragmentsWithPhase(PaintPhase::Foreground, layerFragments, context, localPaintingInfo, localPaintBehavior, subtreePaintRootForRenderer);
return;
}
if (!selectionOnly)
paintForegroundForFragmentsWithPhase(PaintPhase::ChildBlockBackgrounds, layerFragments, context, localPaintingInfo, localPaintBehavior, subtreePaintRootForRenderer);
if (selectionOnly || selectionAndBackgroundsOnly)
paintForegroundForFragmentsWithPhase(PaintPhase::Selection, layerFragments, context, localPaintingInfo, localPaintBehavior, subtreePaintRootForRenderer);
else {
paintForegroundForFragmentsWithPhase(PaintPhase::Float, layerFragments, context, localPaintingInfo, localPaintBehavior, subtreePaintRootForRenderer);
paintForegroundForFragmentsWithPhase(PaintPhase::Foreground, layerFragments, context, localPaintingInfo, localPaintBehavior, subtreePaintRootForRenderer);
paintForegroundForFragmentsWithPhase(PaintPhase::ChildOutlines, layerFragments, context, localPaintingInfo, localPaintBehavior, subtreePaintRootForRenderer);
}
}
void RenderLayer::paintForegroundForFragmentsWithPhase(PaintPhase phase, const LayerFragments& layerFragments, GraphicsContext& context,
const LayerPaintingInfo& localPaintingInfo, OptionSet<PaintBehavior> paintBehavior, RenderObject* subtreePaintRootForRenderer)
{
bool shouldClip = localPaintingInfo.clipToDirtyRect && layerFragments.size() > 1;
for (const auto& fragment : layerFragments) {
if (!fragment.shouldPaintContent || fragment.foregroundRect.isEmpty())
continue;
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(localPaintingInfo.regionContext);
if (shouldClip)
clipToRect(context, stateSaver, regionContextStateSaver, localPaintingInfo, paintBehavior, fragment.foregroundRect);
PaintInfo paintInfo(context, fragment.foregroundRect.rect(), phase, paintBehavior, subtreePaintRootForRenderer, nullptr, nullptr, &localPaintingInfo.rootLayer->renderer(), this, localPaintingInfo.requireSecurityOriginAccessForWidgets);
if (phase == PaintPhase::Foreground)
paintInfo.overlapTestRequests = localPaintingInfo.overlapTestRequests;
renderer().paint(paintInfo, paintOffsetForRenderer(fragment, localPaintingInfo));
}
}
void RenderLayer::paintOutlineForFragments(const LayerFragments& layerFragments, GraphicsContext& context, const LayerPaintingInfo& localPaintingInfo,
OptionSet<PaintBehavior> paintBehavior, RenderObject* subtreePaintRootForRenderer)
{
for (const auto& fragment : layerFragments) {
if (fragment.backgroundRect.isEmpty())
continue;
// Paint our own outline
PaintInfo paintInfo(context, fragment.backgroundRect.rect(), PaintPhase::SelfOutline, paintBehavior, subtreePaintRootForRenderer, nullptr, nullptr, &localPaintingInfo.rootLayer->renderer(), this);
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(localPaintingInfo.regionContext);
clipToRect(context, stateSaver, regionContextStateSaver, localPaintingInfo, paintBehavior, fragment.backgroundRect, DoNotIncludeSelfForBorderRadius);
renderer().paint(paintInfo, paintOffsetForRenderer(fragment, localPaintingInfo));
}
}
void RenderLayer::paintMaskForFragments(const LayerFragments& layerFragments, GraphicsContext& context, const LayerPaintingInfo& localPaintingInfo,
OptionSet<PaintBehavior> paintBehavior, RenderObject* subtreePaintRootForRenderer)
{
for (const auto& fragment : layerFragments) {
if (!fragment.shouldPaintContent)
continue;
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(localPaintingInfo.regionContext);
if (localPaintingInfo.clipToDirtyRect)
clipToRect(context, stateSaver, regionContextStateSaver, localPaintingInfo, paintBehavior, fragment.backgroundRect, DoNotIncludeSelfForBorderRadius); // Mask painting will handle clipping to self.
// Paint the mask.
// FIXME: Eventually we will collect the region from the fragment itself instead of just from the paint info.
PaintInfo paintInfo(context, fragment.backgroundRect.rect(), PaintPhase::Mask, paintBehavior, subtreePaintRootForRenderer, nullptr, nullptr, &localPaintingInfo.rootLayer->renderer(), this);
renderer().paint(paintInfo, paintOffsetForRenderer(fragment, localPaintingInfo));
}
}
void RenderLayer::paintChildClippingMaskForFragments(const LayerFragments& layerFragments, GraphicsContext& context, const LayerPaintingInfo& localPaintingInfo, OptionSet<PaintBehavior> paintBehavior, RenderObject* subtreePaintRootForRenderer)
{
for (const auto& fragment : layerFragments) {
if (!fragment.shouldPaintContent)
continue;
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(localPaintingInfo.regionContext);
if (localPaintingInfo.clipToDirtyRect)
clipToRect(context, stateSaver, regionContextStateSaver, localPaintingInfo, paintBehavior, fragment.foregroundRect, IncludeSelfForBorderRadius); // Child clipping mask painting will handle clipping to self.
// Paint the clipped mask.
PaintInfo paintInfo(context, fragment.backgroundRect.rect(), PaintPhase::ClippingMask, paintBehavior, subtreePaintRootForRenderer, nullptr, nullptr, &localPaintingInfo.rootLayer->renderer(), this);
renderer().paint(paintInfo, paintOffsetForRenderer(fragment, localPaintingInfo));
}
}
void RenderLayer::paintOverflowControlsForFragments(const LayerFragments& layerFragments, GraphicsContext& context, const LayerPaintingInfo& localPaintingInfo)
{
ASSERT(m_scrollableArea);
for (const auto& fragment : layerFragments) {
if (fragment.backgroundRect.isEmpty())
continue;
GraphicsContextStateSaver stateSaver(context, false);
RegionContextStateSaver regionContextStateSaver(localPaintingInfo.regionContext);
clipToRect(context, stateSaver, regionContextStateSaver, localPaintingInfo, { }, fragment.backgroundRect);
m_scrollableArea->paintOverflowControls(context, roundedIntPoint(paintOffsetForRenderer(fragment, localPaintingInfo)), snappedIntRect(fragment.backgroundRect.rect()), true);
}
}
void RenderLayer::collectEventRegionForFragments(const LayerFragments& layerFragments, GraphicsContext& context, const LayerPaintingInfo& localPaintingInfo, OptionSet<PaintBehavior> paintBehavior)
{
ASSERT(is<EventRegionContext>(localPaintingInfo.regionContext));
for (const auto& fragment : layerFragments) {
PaintInfo paintInfo(context, fragment.foregroundRect.rect(), PaintPhase::EventRegion, paintBehavior);
paintInfo.regionContext = localPaintingInfo.regionContext;
if (localPaintingInfo.clipToDirtyRect) // clip-path?
paintInfo.regionContext->pushClip(enclosingIntRect(fragment.backgroundRect.rect()));
renderer().paint(paintInfo, paintOffsetForRenderer(fragment, localPaintingInfo));
if (localPaintingInfo.clipToDirtyRect)
paintInfo.regionContext->popClip();
}
}
void RenderLayer::collectAccessibilityRegionsForFragments(const LayerFragments& layerFragments, GraphicsContext& context, const LayerPaintingInfo& localPaintingInfo, OptionSet<PaintBehavior> paintBehavior)
{
ASSERT(is<AccessibilityRegionContext>(localPaintingInfo.regionContext));
for (const auto& fragment : layerFragments) {
PaintInfo paintInfo(context, fragment.foregroundRect.rect(), PaintPhase::Accessibility, paintBehavior);
paintInfo.regionContext = localPaintingInfo.regionContext;
renderer().paint(paintInfo, paintOffsetForRenderer(fragment, localPaintingInfo));
}
}
bool RenderLayer::hitTest(const HitTestRequest& request, HitTestResult& result)
{
return hitTest(request, result.hitTestLocation(), result);
}
bool RenderLayer::hitTest(const HitTestRequest& request, const HitTestLocation& hitTestLocation, HitTestResult& result)
{
ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
ASSERT(!renderer().view().needsLayout());
ASSERT(!isRenderFragmentedFlow());
LayoutRect hitTestArea = renderer().view().documentRect();
if (!request.ignoreClipping()) {
const auto& settings = renderer().settings();
if (settings.visualViewportEnabled() && settings.clientCoordinatesRelativeToLayoutViewport()) {
auto& frameView = renderer().view().frameView();
LayoutRect absoluteLayoutViewportRect = frameView.layoutViewportRect();
auto scaleFactor = frameView.frame().frameScaleFactor();
if (scaleFactor > 1)
absoluteLayoutViewportRect.scale(scaleFactor);
hitTestArea.intersect(absoluteLayoutViewportRect);
} else
hitTestArea.intersect(renderer().view().frameView().visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect));
}
auto insideLayer = hitTestLayer(this, nullptr, request, result, hitTestArea, hitTestLocation, false);
if (!insideLayer.layer) {
// We didn't hit any layer. If we are the root layer and the mouse is -- or just was -- down,
// return ourselves. We do this so mouse events continue getting delivered after a drag has
// exited the WebView, and so hit testing over a scrollbar hits the content document.
if (!request.isChildFrameHitTest() && (request.active() || request.release()) && isRenderViewLayer()) {
renderer().updateHitTestResult(result, downcast<RenderView>(renderer()).flipForWritingMode(hitTestLocation.point()));
insideLayer = { this };
}
}
// Now determine if the result is inside an anchor - if the urlElement isn't already set.
Node* node = result.innerNode();
if (node && !result.URLElement())
result.setURLElement(node->enclosingLinkEventParentOrSelf());
// Now return whether we were inside this layer (this will always be true for the root
// layer).
return insideLayer.layer;
}
Element* RenderLayer::enclosingElement() const
{
for (RenderElement* r = &renderer(); r; r = r->parent()) {
if (Element* e = r->element())
return e;
}
return nullptr;
}
Vector<RenderLayer*> RenderLayer::topLayerRenderLayers(const RenderView& renderView)
{
Vector<RenderLayer*> layers;
for (auto& element : renderView.document().topLayerElements()) {
auto* renderer = element->renderer();
if (!renderer)
continue;
auto backdropRenderer = renderer->backdropRenderer();
if (backdropRenderer && backdropRenderer->hasLayer() && backdropRenderer->layer()->parent())
layers.append(backdropRenderer->layer());
if (renderer->hasLayer()) {
auto& modelObject = downcast<RenderLayerModelObject>(*renderer);
if (modelObject.layer()->parent())
layers.append(modelObject.layer());
}
}
return layers;
}
bool RenderLayer::establishesTopLayer() const
{
return isInTopLayerOrBackdrop(renderer().style(), renderer().element());
}
void RenderLayer::establishesTopLayerWillChange()
{
compositor().establishesTopLayerWillChangeForLayer(*this);
if (auto* parentLayer = parent())
parentLayer->removeChild(*this);
}
void RenderLayer::establishesTopLayerDidChange()
{
if (auto* parentLayer = renderer().layerParent()) {
setIsNormalFlowOnly(shouldBeNormalFlowOnly());
auto* beforeChild = renderer().layerNextSibling(*parentLayer);
parentLayer->addChild(*this, beforeChild);
}
}
RenderLayer* RenderLayer::enclosingFragmentedFlowAncestor() const
{
RenderLayer* curr = parent();
for (; curr && !curr->isRenderFragmentedFlow(); curr = curr->parent()) {
if (curr->isStackingContext() && curr->isComposited()) {
// We only adjust the position of the first level of layers.
return nullptr;
}
}
return curr;
}
// Compute the z-offset of the point in the transformState.
// This is effectively projecting a ray normal to the plane of ancestor, finding where that
// ray intersects target, and computing the z delta between those two points.
static double computeZOffset(const HitTestingTransformState& transformState)
{
// We got an affine transform, so no z-offset
if (transformState.m_accumulatedTransform.isAffine())
return 0;
// Flatten the point into the target plane
FloatPoint targetPoint = transformState.mappedPoint();
// Now map the point back through the transform, which computes Z.
FloatPoint3D backmappedPoint = transformState.m_accumulatedTransform.mapPoint(FloatPoint3D(targetPoint));
return backmappedPoint.z();
}
Ref<HitTestingTransformState> RenderLayer::createLocalTransformState(RenderLayer* rootLayer, RenderLayer* containerLayer,
const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation,
const HitTestingTransformState* containerTransformState,
const LayoutSize& translationOffset) const
{
RefPtr<HitTestingTransformState> transformState;
LayoutSize offset;
if (containerTransformState) {
// If we're already computing transform state, then it's relative to the container (which we know is non-null).
transformState = HitTestingTransformState::create(*containerTransformState);
offset = offsetFromAncestor(containerLayer);
} else {
// If this is the first time we need to make transform state, then base it off of hitTestLocation,
// which is relative to rootLayer.
transformState = HitTestingTransformState::create(hitTestLocation.transformedPoint(), hitTestLocation.transformedRect(), FloatQuad(hitTestRect));
offset = offsetFromAncestor(rootLayer);
}
offset += translationOffset;
RenderObject* containerRenderer = containerLayer ? &containerLayer->renderer() : nullptr;
if (renderer().shouldUseTransformFromContainer(containerRenderer)) {
TransformationMatrix containerTransform;
renderer().getTransformFromContainer(offset, containerTransform);
transformState->applyTransform(containerTransform, HitTestingTransformState::AccumulateTransform);
} else {
transformState->translate(offset.width(), offset.height(), HitTestingTransformState::AccumulateTransform);
}
return transformState.releaseNonNull();
}
static RefPtr<Element> flattenedParent(Element* element)
{
if (!element)
return nullptr;
RefPtr parent = element->parentElementInComposedTree();
while (parent) {
if (!parent->isConnected() || parent->computedStyle()->display() != DisplayType::Contents)
break;
parent = parent->parentElementInComposedTree();
}
return parent;
}
bool RenderLayer::ancestorLayerIsDOMParent(const RenderLayer* ancestor) const
{
if (!ancestor)
return false;
auto parent = flattenedParent(renderer().element());
if (parent && ancestor->renderer().element() == parent)
return true;
std::optional<PseudoId> parentPseudoId = parentPseudoElement(renderer().style().pseudoElementType());
return parentPseudoId && *parentPseudoId == ancestor->renderer().style().pseudoElementType();
}
bool RenderLayer::participatesInPreserve3D() const
{
return ancestorLayerIsDOMParent(parent()) && parent()->preserves3D() && (transform() || renderer().style().backfaceVisibility() == BackfaceVisibility::Hidden || preserves3D());
}
void RenderLayer::setSnapshottedScrollOffsetForAnchorPositioning(LayoutSize offset)
{
if (m_snapshottedScrollOffsetForAnchorPositioning == offset)
return;
// FIXME: Scroll offset should be adjusted in the scrolling tree so layers stay exactly in sync.
m_snapshottedScrollOffsetForAnchorPositioning = offset;
updateTransform();
}
void RenderLayer::clearSnapshottedScrollOffsetForAnchorPositioning()
{
if (!m_snapshottedScrollOffsetForAnchorPositioning)
return;
m_snapshottedScrollOffsetForAnchorPositioning = { };
updateTransform();
}
// hitTestLocation and hitTestRect are relative to rootLayer.
// A 'flattening' layer is one preserves3D() == false.
// transformState.m_accumulatedTransform holds the transform from the containing flattening layer.
// transformState.m_lastPlanarPoint is the hitTestLocation in the plane of the containing flattening layer.
// transformState.m_lastPlanarQuad is the hitTestRect as a quad in the plane of the containing flattening layer.
//
// If zOffset is non-null (which indicates that the caller wants z offset information),
// *zOffset on return is the z offset of the hit point relative to the containing flattening layer.
RenderLayer::HitLayer RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation, bool appliedTransform,
const HitTestingTransformState* transformState, double* zOffset)
{
updateLayerListsIfNeeded();
if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
return { };
// Renderers that are captured in a view transition are not hit tested.
if (renderer().effectiveCapturedInViewTransition())
return { };
// If we're hit testing 'SVG clip content' (aka. RenderSVGResourceClipper) do not early exit.
if (!request.svgClipContent()) {
// SVG resource layers and their children are never hit tested.
if (is<RenderSVGResourceContainer>(m_enclosingSVGHiddenOrResourceContainer))
return { };
// Hidden SVG containers (<defs> / <symbol> ...) are never hit tested directly.
if (is<RenderSVGHiddenContainer>(renderer()))
return { };
}
// The natural thing would be to keep HitTestingTransformState on the stack, but it's big, so we heap-allocate.
// Apply a transform if we have one.
if (transform() && !appliedTransform) {
if (enclosingPaginationLayer(IncludeCompositedPaginatedLayers))
return hitTestTransformedLayerInFragments(rootLayer, containerLayer, request, result, hitTestRect, hitTestLocation, transformState, zOffset);
// Make sure the parent's clip rects have been calculated.
if (parent()) {
ClipRectsContext clipRectsContext(rootLayer, RootRelativeClipRects, { ClipRectsOption::RespectOverflowClip });
ClipRect clipRect = backgroundClipRect(clipRectsContext);
// Test the enclosing clip now.
if (!clipRect.intersects(hitTestLocation))
return { };
}
return hitTestLayerByApplyingTransform(rootLayer, containerLayer, request, result, hitTestRect, hitTestLocation, transformState, zOffset);
}
// Ensure our lists and 3d status are up-to-date.
update3DTransformedDescendantStatus();
RefPtr<HitTestingTransformState> localTransformState;
if (appliedTransform) {
// We computed the correct state in the caller (above code), so just reference it.
ASSERT(transformState);
localTransformState = const_cast<HitTestingTransformState*>(transformState);
} else if (transformState || has3DTransformedDescendant() || preserves3D()) {
// We need transform state for the first time, or to offset the container state, so create it here.
localTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestLocation, transformState);
}
// Check for hit test on backface if backface-visibility is 'hidden'
if (localTransformState && renderer().style().backfaceVisibility() == BackfaceVisibility::Hidden) {
std::optional<TransformationMatrix> invertedMatrix = localTransformState->m_accumulatedTransform.inverse();
// If the z-vector of the matrix is negative, the back is facing towards the viewer.
if (invertedMatrix && invertedMatrix.value().m33() < 0)
return { };
}
// The following are used for keeping track of the z-depth of the hit point of 3d-transformed
// descendants.
double localZOffset = -std::numeric_limits<double>::infinity();
double* zOffsetForDescendantsPtr = nullptr;
bool depthSortDescendants = false;
if (preserves3D()) {
depthSortDescendants = true;
// Our layers can depth-test with our container, so share the z depth pointer with the container, if it passed one down.
zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
} else if (zOffset)
zOffsetForDescendantsPtr = nullptr;
double selfZOffset = localTransformState ? computeZOffset(*localTransformState) : 0;
// This variable tracks which layer the mouse ends up being inside.
auto candidateLayer = HitLayer { nullptr, -std::numeric_limits<double>::infinity() };
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(*this);
#endif
auto offsetFromRoot = offsetFromAncestor(rootLayer);
// FIXME: We need to correctly hit test the clip-path when we have a RenderInline too.
if (auto* rendererBox = this->renderBox(); rendererBox && !rendererBox->hitTestClipPath(hitTestLocation, toLayoutPoint(offsetFromRoot - toLayoutSize(rendererLocation()))))
return { };
// Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
auto hitLayer = hitTestList(positiveZOrderLayers(), rootLayer, request, result, hitTestRect, hitTestLocation, localTransformState.get(), zOffsetForDescendantsPtr, depthSortDescendants);
if (hitLayer.layer) {
if (!depthSortDescendants)
return hitLayer;
if (hitLayer.zOffset > candidateLayer.zOffset)
candidateLayer = hitLayer;
}
// Now check our overflow objects.
{
HitTestResult tempResult(result.hitTestLocation());
hitLayer = hitTestList(normalFlowLayers(), rootLayer, request, tempResult, hitTestRect, hitTestLocation, localTransformState.get(), zOffsetForDescendantsPtr, depthSortDescendants);
if (request.resultIsElementList())
result.append(tempResult, request);
if (hitLayer.layer) {
if (!depthSortDescendants || hitLayer.zOffset > candidateLayer.zOffset) {
if (!request.resultIsElementList())
result = tempResult;
candidateLayer = hitLayer;
}
if (!depthSortDescendants)
return hitLayer;
}
}
// Collect the fragments. This will compute the clip rectangles for each layer fragment.
LayerFragments layerFragments;
collectFragments(layerFragments, rootLayer, hitTestRect, IncludeCompositedPaginatedLayers, RootRelativeClipRects, { ClipRectsOption::RespectOverflowClip }, offsetFromRoot);
LayoutPoint localPoint;
if (canResize() && m_scrollableArea && m_scrollableArea->hitTestResizerInFragments(layerFragments, hitTestLocation, localPoint)) {
renderer().updateHitTestResult(result, localPoint);
return { this, selfZOffset };
}
auto isHitCandidate = [&]() {
return !depthSortDescendants || selfZOffset > candidateLayer.zOffset;
};
// Next we want to see if the mouse pos is inside the child RenderObjects of the layer. Check
// every fragment in reverse order.
if (isSelfPaintingLayer()) {
// Hit test with a temporary HitTestResult, because we only want to commit to 'result' if we know we're frontmost.
HitTestResult tempResult(result.hitTestLocation());
bool insideFragmentForegroundRect = false;
if (hitTestContentsForFragments(layerFragments, request, tempResult, hitTestLocation, HitTestDescendants, insideFragmentForegroundRect) && isHitCandidate()) {
if (request.resultIsElementList())
result.append(tempResult, request);
else
result = tempResult;
if (!depthSortDescendants)
return { this, selfZOffset };
// Foreground can depth-sort with descendant layers, so keep this as a candidate.
candidateLayer = { this, selfZOffset };
} else if (insideFragmentForegroundRect && request.resultIsElementList())
result.append(tempResult, request);
}
// Now check our negative z-index children.
{
HitTestResult tempResult(result.hitTestLocation());
hitLayer = hitTestList(negativeZOrderLayers(), rootLayer, request, tempResult, hitTestRect, hitTestLocation, localTransformState.get(), zOffsetForDescendantsPtr, depthSortDescendants);
if (request.resultIsElementList())
result.append(tempResult, request);
if (hitLayer.layer) {
if (!depthSortDescendants || hitLayer.zOffset > candidateLayer.zOffset) {
if (!request.resultIsElementList())
result = tempResult;
candidateLayer = hitLayer;
}
if (!depthSortDescendants)
return hitLayer;
}
}
// If we found a layer, return. Child layers, and foreground always render in front of background.
if (candidateLayer.layer && !depthSortDescendants)
return candidateLayer;
if (isSelfPaintingLayer()) {
HitTestResult tempResult(result.hitTestLocation());
bool insideFragmentBackgroundRect = false;
if (hitTestContentsForFragments(layerFragments, request, tempResult, hitTestLocation, HitTestSelf, insideFragmentBackgroundRect) && isHitCandidate()) {
if (request.resultIsElementList())
result.append(tempResult, request);
else
result = tempResult;
if (!depthSortDescendants)
return { this, selfZOffset };
candidateLayer = { this, selfZOffset };
}
if (insideFragmentBackgroundRect && request.resultIsElementList())
result.append(tempResult, request);
}
return candidateLayer;
}
bool RenderLayer::hitTestContentsForFragments(const LayerFragments& layerFragments, const HitTestRequest& request, HitTestResult& result,
const HitTestLocation& hitTestLocation, HitTestFilter hitTestFilter, bool& insideClipRect) const
{
if (layerFragments.isEmpty())
return false;
for (int i = layerFragments.size() - 1; i >= 0; --i) {
const auto& fragment = layerFragments.at(i);
if ((hitTestFilter == HitTestSelf && !fragment.backgroundRect.intersects(hitTestLocation))
|| (hitTestFilter == HitTestDescendants && !fragment.foregroundRect.intersects(hitTestLocation)))
continue;
insideClipRect = true;
if (hitTestContents(request, result, fragment.layerBounds, hitTestLocation, hitTestFilter))
return true;
}
return false;
}
RenderLayer::HitLayer RenderLayer::hitTestTransformedLayerInFragments(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation, const HitTestingTransformState* transformState, double* zOffset)
{
LayerFragments enclosingPaginationFragments;
LayoutSize offsetOfPaginationLayerFromRoot;
RenderLayer* paginatedLayer = enclosingPaginationLayer(IncludeCompositedPaginatedLayers);
LayoutRect transformedExtent = transparencyClipBox(*this, paginatedLayer, HitTestingTransparencyClipBox, RootOfTransparencyClipBox);
paginatedLayer->collectFragments(enclosingPaginationFragments, rootLayer, hitTestRect, IncludeCompositedPaginatedLayers,
RootRelativeClipRects, { ClipRectsOption::RespectOverflowClip }, offsetOfPaginationLayerFromRoot, &transformedExtent);
for (int i = enclosingPaginationFragments.size() - 1; i >= 0; --i) {
const LayerFragment& fragment = enclosingPaginationFragments.at(i);
// Apply the page/column clip for this fragment, as well as any clips established by layers in between us and
// the enclosing pagination layer.
LayoutRect clipRect = fragment.backgroundRect.rect();
// Now compute the clips within a given fragment
if (parent() != paginatedLayer) {
offsetOfPaginationLayerFromRoot = toLayoutSize(paginatedLayer->convertToLayerCoords(rootLayer, toLayoutPoint(offsetOfPaginationLayerFromRoot)));
ClipRectsContext clipRectsContext(paginatedLayer, RootRelativeClipRects, { ClipRectsOption::RespectOverflowClip });
LayoutRect parentClipRect = backgroundClipRect(clipRectsContext).rect();
parentClipRect.move(fragment.paginationOffset + offsetOfPaginationLayerFromRoot);
clipRect.intersect(parentClipRect);
}
if (!hitTestLocation.intersects(clipRect))
continue;
auto hitLayer = hitTestLayerByApplyingTransform(rootLayer, containerLayer, request, result, hitTestRect, hitTestLocation,
transformState, zOffset, fragment.paginationOffset);
if (hitLayer.layer)
return hitLayer;
}
return { };
}
RenderLayer::HitLayer RenderLayer::hitTestLayerByApplyingTransform(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation, const HitTestingTransformState* transformState, double* zOffset, const LayoutSize& translationOffset)
{
// Create a transform state to accumulate this transform.
Ref<HitTestingTransformState> newTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestLocation, transformState, translationOffset);
// If the transform can't be inverted, then don't hit test this layer at all.
if (!newTransformState->m_accumulatedTransform.isInvertible())
return { };
// Compute the point and the hit test rect in the coords of this layer by using the values
// from the transformState, which store the point and quad in the coords of the last flattened
// layer, and the accumulated transform which lets up map through preserve-3d layers.
//
// We can't just map hitTestLocation and hitTestRect because they may have been flattened (losing z)
// by our container.
FloatPoint localPoint = newTransformState->mappedPoint();
FloatQuad localPointQuad = newTransformState->mappedQuad();
LayoutRect localHitTestRect = newTransformState->boundsOfMappedArea();
HitTestLocation newHitTestLocation;
if (hitTestLocation.isRectBasedTest())
newHitTestLocation = HitTestLocation(localPoint, localPointQuad);
else
newHitTestLocation = HitTestLocation(flooredLayoutPoint(localPoint));
// Now do a hit test with the root layer shifted to be us.
return hitTestLayer(this, containerLayer, request, result, localHitTestRect, newHitTestLocation, true, newTransformState.ptr(), zOffset);
}
bool RenderLayer::hitTestContents(const HitTestRequest& request, HitTestResult& result, const LayoutRect& layerBounds, const HitTestLocation& hitTestLocation, HitTestFilter hitTestFilter) const
{
ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
if (!renderer().hitTest(request, result, hitTestLocation, toLayoutPoint(layerBounds.location() - rendererLocation()), hitTestFilter)) {
// It's wrong to set innerNode, but then claim that you didn't hit anything, unless it is
// a rect-based test.
ASSERT(!result.innerNode() || (request.resultIsElementList() && result.listBasedTestResult().size()));
return false;
}
// For positioned generated content, we might still not have a
// node by the time we get to the layer level, since none of
// the content in the layer has an element. So just walk up
// the tree.
if (!result.innerNode() || !result.innerNonSharedNode()) {
Element* e = enclosingElement();
if (!result.innerNode())
result.setInnerNode(e);
if (!result.innerNonSharedNode())
result.setInnerNonSharedNode(e);
}
return true;
}
RenderLayer::HitLayer RenderLayer::hitTestList(LayerList layerIterator, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result, const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation, const HitTestingTransformState* transformState, double* zOffsetForDescendants, bool depthSortDescendants)
{
if (layerIterator.begin() == layerIterator.end())
return { };
if (!hasSelfPaintingLayerDescendant())
return { };
auto resultLayer = HitLayer { nullptr, -std::numeric_limits<double>::infinity() };
RefPtr<HitTestingTransformState> flattenedTransformState;
double unflattenedZOffset = 0;
for (auto iter = layerIterator.rbegin(); iter != layerIterator.rend(); ++iter) {
auto* childLayer = *iter;
// If we're about to cross a flattening boundary, then pass the (lazily-initialized)
// flattened transfomState to the child layer.
auto* transformStateForChild = transformState;
if (transformState && !childLayer->participatesInPreserve3D()) {
if (!flattenedTransformState) {
flattenedTransformState = HitTestingTransformState::create(*transformState);
flattenedTransformState->flatten();
unflattenedZOffset = computeZOffset(*transformState);
}
transformStateForChild = flattenedTransformState.get();
}
HitTestResult tempResult(result.hitTestLocation());
auto hitLayer = childLayer->hitTestLayer(rootLayer, this, request, tempResult, hitTestRect, hitTestLocation, false, transformStateForChild, zOffsetForDescendants);
// If it is a list-based test, we can safely append the temporary result since it might had hit
// nodes but not necessarily had hitLayer set.
ASSERT(!result.isRectBasedTest() || request.resultIsElementList());
if (request.resultIsElementList())
result.append(tempResult, request);
if (hitLayer.layer) {
// If the child was flattened, then override the returned depth with the depth of the
// plane we flattened into (ourselves) instead.
if (transformStateForChild == flattenedTransformState)
hitLayer.zOffset = unflattenedZOffset;
if (!depthSortDescendants || hitLayer.zOffset > resultLayer.zOffset) {
resultLayer = hitLayer;
if (!request.resultIsElementList())
result = tempResult;
if (!depthSortDescendants)
break;
}
}
}
return resultLayer;
}
void RenderLayer::verifyClipRects()
{
#ifdef CHECK_CACHED_CLIP_RECTS
if (!m_clipRectsCache)
return;
for (int i = 0; i < NumCachedClipRectsTypes; ++i) {
if (!m_clipRectsCache->m_clipRectsRoot[i])
continue;
ClipRectsContext clipRectsContext(m_clipRectsCache->m_clipRectsRoot[i], (ClipRectsType)i, { });
verifyClipRect(clipRectsContext);
clipRectsContext.options.add(ClipRectsOption::RespectOverflowClip);
verifyClipRect(clipRectsContext);
}
#endif
}
void RenderLayer::verifyClipRect(const ClipRectsContext& clipRectsContext)
{
#ifdef CHECK_CACHED_CLIP_RECTS
ASSERT(m_clipRectsCache);
if (auto* clipRects = m_clipRectsCache->getClipRects(clipRectsContext)) {
// This code is useful to check cached clip rects, but is too expensive to leave enabled in debug builds by default.
ClipRectsContext tempContext(clipRectsContext);
tempContext.clipRectsType = TemporaryClipRects;
Ref<ClipRects> tempClipRects = ClipRects::create();
calculateClipRects(tempContext, tempClipRects);
ASSERT(tempClipRects.get() == *clipRects);
}
#else
UNUSED_PARAM(clipRectsContext);
#endif
}
Ref<ClipRects> RenderLayer::updateClipRects(const ClipRectsContext& clipRectsContext)
{
ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
ASSERT(clipRectsType < NumCachedClipRectsTypes);
if (m_clipRectsCache) {
if (auto* clipRects = m_clipRectsCache->getClipRects(clipRectsContext)) {
ASSERT(clipRectsContext.rootLayer == m_clipRectsCache->m_clipRectsRoot[clipRectsType]);
verifyClipRect(clipRectsContext);
return *clipRects; // We have the correct cached value.
}
}
if (!m_clipRectsCache)
m_clipRectsCache = makeUnique<ClipRectsCache>();
#if ASSERT_ENABLED
m_clipRectsCache->m_clipRectsRoot[clipRectsType] = clipRectsContext.rootLayer;
#endif
ASSERT(enumToUnderlyingType(clipRectsContext.overlayScrollbarSizeRelevancy()) == (clipRectsContext.clipRectsType == RootRelativeClipRects));
RefPtr<ClipRects> parentClipRects;
// For transformed layers, the root layer was shifted to be us, so there is no need to
// examine the parent. We want to cache clip rects with us as the root.
if (clipRectsContext.rootLayer != this && parent())
parentClipRects = this->parentClipRects(clipRectsContext);
auto clipRects = ClipRects::create();
calculateClipRects(clipRectsContext, clipRects);
if (parentClipRects && *parentClipRects == clipRects) {
m_clipRectsCache->setClipRects(clipRectsType, clipRectsContext.respectOverflowClip(), parentClipRects.copyRef());
return parentClipRects.releaseNonNull();
}
m_clipRectsCache->setClipRects(clipRectsType, clipRectsContext.respectOverflowClip(), clipRects.copyRef());
return clipRects;
}
ClipRects* RenderLayer::clipRects(const ClipRectsContext& context) const
{
ASSERT(context.clipRectsType < NumCachedClipRectsTypes);
if (!m_clipRectsCache)
return nullptr;
return m_clipRectsCache->getClipRects(context);
}
bool RenderLayer::clipCrossesPaintingBoundary() const
{
return parent()->enclosingPaginationLayer(IncludeCompositedPaginatedLayers) != enclosingPaginationLayer(IncludeCompositedPaginatedLayers)
|| parent()->enclosingCompositingLayerForRepaint().layer != enclosingCompositingLayerForRepaint().layer;
}
void RenderLayer::calculateClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
{
if (!parent()) {
// The root layer's clip rect is always infinite.
clipRects.reset();
return;
}
ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
bool useCached = clipRectsType != TemporaryClipRects;
// For transformed layers, the root layer was shifted to be us, so there is no need to
// examine the parent. We want to cache clip rects with us as the root.
RenderLayer* parentLayer = clipRectsContext.rootLayer != this ? parent() : nullptr;
// Ensure that our parent's clip has been calculated so that we can examine the values.
if (parentLayer) {
if (useCached && parentLayer->clipRects(clipRectsContext))
clipRects = *parentLayer->clipRects(clipRectsContext);
else {
ClipRectsContext parentContext(clipRectsContext);
if ((parentContext.clipRectsType != TemporaryClipRects && parentContext.clipRectsType != AbsoluteClipRects) && clipCrossesPaintingBoundary())
parentContext.clipRectsType = TemporaryClipRects;
parentLayer->calculateClipRects(parentContext, clipRects);
}
} else
clipRects.reset();
// A fixed object is essentially the root of its containing block hierarchy, so when
// we encounter such an object, we reset our clip rects to the fixedClipRect.
if (renderer().isFixedPositioned()) {
clipRects.setPosClipRect(clipRects.fixedClipRect());
clipRects.setOverflowClipRect(clipRects.fixedClipRect());
clipRects.setFixed(true);
} else if (renderer().isInFlowPositioned())
clipRects.setPosClipRect(clipRects.overflowClipRect());
else if (renderer().shouldUsePositionedClipping())
clipRects.setOverflowClipRect(clipRects.posClipRect());
// Update the clip rects that will be passed to child layers.
#if PLATFORM(IOS_FAMILY)
if (renderer().hasClipOrNonVisibleOverflow() && (clipRectsContext.respectOverflowClip() || this != clipRectsContext.rootLayer)) {
#else
if ((renderer().hasNonVisibleOverflow() && (clipRectsContext.respectOverflowClip() || this != clipRectsContext.rootLayer)) || renderer().hasClip()) {
#endif
// This layer establishes a clip of some kind.
// FIXME: Transforming a clip doesn't make a whole lot of sense, since it we have to round out to the
// bounding box of the transformed quad.
// It would be better for callers to transform rects into the coordinate space of the nearest clipped layer, apply
// the clip in local space, and then repeat until the required coordinate space is reached.
bool needsTransform = clipRectsType == AbsoluteClipRects ? m_hasTransformedAncestor || !canUseOffsetFromAncestor() : !canUseOffsetFromAncestor(*clipRectsContext.rootLayer);
LayoutPoint offset;
if (!needsTransform)
offset = toLayoutPoint(offsetFromAncestor(clipRectsContext.rootLayer, AdjustForColumns));
if (clipRects.fixed() && &clipRectsContext.rootLayer->renderer() == &renderer().view())
offset -= toLayoutSize(renderer().view().frameView().scrollPositionForFixedPosition());
if (renderer().hasNonVisibleOverflow()) {
ClipRect newOverflowClip = rendererOverflowClipRectForChildLayers({ }, clipRectsContext.overlayScrollbarSizeRelevancy());
if (needsTransform)
newOverflowClip = LayoutRect(renderer().localToContainerQuad(FloatRect(newOverflowClip.rect()), &clipRectsContext.rootLayer->renderer()).boundingBox());
newOverflowClip.moveBy(offset);
newOverflowClip.setAffectedByRadius(renderer().style().hasBorderRadius());
clipRects.setOverflowClipRect(intersection(newOverflowClip, clipRects.overflowClipRect()));
if (renderer().canContainAbsolutelyPositionedObjects())
clipRects.setPosClipRect(intersection(newOverflowClip, clipRects.posClipRect()));
if (renderer().canContainFixedPositionObjects())
clipRects.setFixedClipRect(intersection(newOverflowClip, clipRects.fixedClipRect()));
}
if (renderer().hasClip()) {
if (CheckedPtr box = dynamicDowncast<RenderBox>(renderer())) {
LayoutRect newPosClip = box->clipRect({ });
if (needsTransform)
newPosClip = LayoutRect(renderer().localToContainerQuad(FloatRect(newPosClip), &clipRectsContext.rootLayer->renderer()).boundingBox());
newPosClip.moveBy(offset);
clipRects.setPosClipRect(intersection(newPosClip, clipRects.posClipRect()));
clipRects.setOverflowClipRect(intersection(newPosClip, clipRects.overflowClipRect()));
clipRects.setFixedClipRect(intersection(newPosClip, clipRects.fixedClipRect()));
}
}
} else if (renderer().hasNonVisibleOverflow() && transform() && renderer().style().hasBorderRadius())
clipRects.setOverflowClipRectAffectedByRadius();
LOG_WITH_STREAM(ClipRects, stream << "RenderLayer " << this << " calculateClipRects " << clipRectsContext << " computed " << clipRects);
}
Ref<ClipRects> RenderLayer::parentClipRects(const ClipRectsContext& clipRectsContext) const
{
ASSERT(parent());
auto containerLayer = parent();
auto temporaryParentClipRects = [&](const ClipRectsContext& clipContext) {
auto parentClipRects = ClipRects::create();
containerLayer->calculateClipRects(clipContext, parentClipRects);
return parentClipRects;
};
if (clipRectsContext.clipRectsType == TemporaryClipRects)
return temporaryParentClipRects(clipRectsContext);
if (clipRectsContext.clipRectsType != AbsoluteClipRects && clipCrossesPaintingBoundary()) {
ClipRectsContext tempClipRectsContext(clipRectsContext);
tempClipRectsContext.clipRectsType = TemporaryClipRects;
return temporaryParentClipRects(tempClipRectsContext);
}
return containerLayer->updateClipRects(clipRectsContext);
}
static inline ClipRect backgroundClipRectForPosition(const ClipRects& parentRects, PositionType position)
{
if (position == PositionType::Fixed)
return parentRects.fixedClipRect();
if (position == PositionType::Absolute)
return parentRects.posClipRect();
return parentRects.overflowClipRect();
}
ClipRect RenderLayer::backgroundClipRect(const ClipRectsContext& clipRectsContext) const
{
ASSERT(parent());
auto parentRects = parentClipRects(clipRectsContext);
ClipRect backgroundClipRect = backgroundClipRectForPosition(parentRects, renderer().style().position());
RenderView& view = renderer().view();
// Note: infinite clipRects should not be scrolled here, otherwise they will accidentally no longer be considered infinite.
if (parentRects->fixed() && &clipRectsContext.rootLayer->renderer() == &view && !backgroundClipRect.isInfinite())
backgroundClipRect.moveBy(view.frameView().scrollPositionForFixedPosition());
LOG_WITH_STREAM(ClipRects, stream << "RenderLayer " << this << " backgroundClipRect with context " << clipRectsContext << " returning " << backgroundClipRect);
return backgroundClipRect;
}
void RenderLayer::calculateRects(const ClipRectsContext& clipRectsContext, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds,
ClipRect& backgroundRect, ClipRect& foregroundRect, const LayoutSize& offsetFromRoot) const
{
if (clipRectsContext.rootLayer != this && parent()) {
backgroundRect = backgroundClipRect(clipRectsContext);
backgroundRect.intersect(paintDirtyRect);
} else
backgroundRect = paintDirtyRect;
LayoutSize offsetFromRootLocal = offsetFromRoot;
layerBounds = LayoutRect(toLayoutPoint(offsetFromRootLocal), size());
foregroundRect = backgroundRect;
// Update the clip rects that will be passed to child layers.
if (renderer().hasClipOrNonVisibleOverflow()) {
// This layer establishes a clip of some kind.
if (renderer().hasNonVisibleOverflow()) {
if (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip()) {
LayoutRect overflowClipRect = rendererOverflowClipRect(toLayoutPoint(offsetFromRootLocal), clipRectsContext.overlayScrollbarSizeRelevancy());
foregroundRect.intersect(overflowClipRect);
foregroundRect.setAffectedByRadius(true);
} else if (transform() && renderer().style().hasBorderRadius())
foregroundRect.setAffectedByRadius(true);
}
if (renderer().hasClip()) {
if (CheckedPtr box = dynamicDowncast<RenderBox>(renderer())) {
// Clip applies to *us* as well, so update the damageRect.
LayoutRect newPosClip = box->clipRect(toLayoutPoint(offsetFromRootLocal));
backgroundRect.intersect(newPosClip);
foregroundRect.intersect(newPosClip);
}
}
// If we establish a clip at all, then make sure our background rect is intersected with our layer's bounds including our visual overflow,
// since any visual overflow like box-shadow or border-outset is not clipped by overflow:auto/hidden.
if (rendererHasVisualOverflow()) {
// FIXME: Does not do the right thing with CSS regions yet, since we don't yet factor in the
// individual region boxes as overflow.
LayoutRect layerBoundsWithVisualOverflow = rendererVisualOverflowRect();
if (renderer().isRenderBox())
renderBox()->flipForWritingMode(layerBoundsWithVisualOverflow); // Layers are in physical coordinates, so the overflow has to be flipped.
layerBoundsWithVisualOverflow.move(offsetFromRootLocal);
if (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip())
backgroundRect.intersect(layerBoundsWithVisualOverflow);
} else {
// Shift the bounds to be for our region only.
LayoutRect bounds = rendererBorderBoxRect();
bounds.move(offsetFromRootLocal);
if (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip())
backgroundRect.intersect(bounds);
}
}
}
LayoutRect RenderLayer::childrenClipRect() const
{
// FIXME: border-radius not accounted for.
// FIXME: Regions not accounted for.
RenderLayer* clippingRootLayer = clippingRootForPainting();
LayoutRect layerBounds;
ClipRect backgroundRect;
ClipRect foregroundRect;
ClipRectsContext clipRectsContext(clippingRootLayer, TemporaryClipRects);
// Need to use temporary clip rects, because the value of 'dontClipToOverflow' may be different from the painting path (<rdar://problem/11844909>).
calculateRects(clipRectsContext, LayoutRect::infiniteRect(), layerBounds, backgroundRect, foregroundRect, offsetFromAncestor(clipRectsContext.rootLayer));
if (foregroundRect.rect().isInfinite())
return renderer().view().unscaledDocumentRect();
auto absoluteClippingRect = clippingRootLayer->renderer().localToAbsoluteQuad(FloatQuad(foregroundRect.rect())).enclosingBoundingBox();
return intersection(absoluteClippingRect, renderer().view().unscaledDocumentRect());
}
LayoutRect RenderLayer::clipRectRelativeToAncestor(const RenderLayer* ancestor, LayoutSize offsetFromAncestor, const LayoutRect& constrainingRect, bool temporaryClipRects) const
{
LayoutRect layerBounds;
ClipRect backgroundRect;
ClipRect foregroundRect;
auto clipRectType = (!m_enclosingPaginationLayer || m_enclosingPaginationLayer == ancestor) && !temporaryClipRects ? PaintingClipRects : TemporaryClipRects;
ClipRectsContext clipRectsContext(ancestor, clipRectType);
calculateRects(clipRectsContext, constrainingRect, layerBounds, backgroundRect, foregroundRect, offsetFromAncestor);
return backgroundRect.rect();
}
LayoutRect RenderLayer::selfClipRect() const
{
// FIXME: border-radius not accounted for.
// FIXME: Regions not accounted for.
RenderLayer* clippingRootLayer = clippingRootForPainting();
LayoutRect clipRect = clipRectRelativeToAncestor(clippingRootLayer, offsetFromAncestor(clippingRootLayer), renderer().view().documentRect());
return clippingRootLayer->renderer().localToAbsoluteQuad(FloatQuad(clipRect)).enclosingBoundingBox();
}
LayoutRect RenderLayer::localClipRect(bool& clipExceedsBounds, LocalClipRectMode mode) const
{
clipExceedsBounds = false;
// FIXME: border-radius not accounted for.
// FIXME: Regions not accounted for.
const RenderLayer* clippingRootLayer = mode == LocalClipRectMode::ExcludeCompositingState ? this : clippingRootForPainting();
LayoutSize offsetFromRoot = offsetFromAncestor(clippingRootLayer);
LayoutRect clipRect = clipRectRelativeToAncestor(clippingRootLayer, offsetFromRoot, LayoutRect::infiniteRect());
if (clipRect.isInfinite())
return clipRect;
if (renderer().hasClip()) {
if (CheckedPtr box = dynamicDowncast<RenderBox>(renderer())) {
// CSS clip may be larger than our border box.
LayoutRect cssClipRect = box->clipRect({ });
clipExceedsBounds = !cssClipRect.isEmpty() && (clipRect.width() < cssClipRect.width() || clipRect.height() < cssClipRect.height());
}
}
clipRect.move(-offsetFromRoot);
return clipRect;
}
void RenderLayer::addBlockSelectionGapsBounds(const LayoutRect& bounds)
{
m_blockSelectionGapsBounds.unite(enclosingIntRect(bounds));
}
void RenderLayer::clearBlockSelectionGapsBounds()
{
m_blockSelectionGapsBounds = IntRect();
for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
child->clearBlockSelectionGapsBounds();
}
void RenderLayer::repaintBlockSelectionGaps()
{
for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
child->repaintBlockSelectionGaps();
if (m_blockSelectionGapsBounds.isEmpty())
return;
LayoutRect rect = m_blockSelectionGapsBounds;
if (m_scrollableArea)
rect.moveBy(-m_scrollableArea->scrollPosition());
if (renderer().hasNonVisibleOverflow() && !usesCompositedScrolling())
rect.intersect(downcast<RenderBox>(renderer()).overflowClipRect({ }));
if (renderer().hasClip())
rect.intersect(downcast<RenderBox>(renderer()).clipRect({ }));
if (!rect.isEmpty())
renderer().repaintRectangle(rect);
}
bool RenderLayer::intersectsDamageRect(const LayoutRect& layerBounds, const LayoutRect& damageRect, const RenderLayer* rootLayer, const LayoutSize& offsetFromRoot, const std::optional<LayoutRect>& cachedBoundingBox) const
{
// Always examine the canvas and the root.
// FIXME: Could eliminate the isDocumentElementRenderer() check if we fix background painting so that the RenderView
// paints the root's background.
if (isRenderViewLayer() || renderer().isDocumentElementRenderer())
return true;
if (damageRect.isInfinite())
return true;
if (damageRect.isEmpty())
return false;
// If we aren't an inline flow, and our layer bounds do intersect the damage rect, then we can return true.
if (!renderer().isRenderInline() && layerBounds.intersects(damageRect))
return true;
// Otherwise we need to compute the bounding box of this single layer and see if it intersects
// the damage rect. It's possible the fragment computed the bounding box already, in which case we
// can use the cached value.
if (cachedBoundingBox)
return cachedBoundingBox->intersects(damageRect);
return boundingBox(rootLayer, offsetFromRoot).intersects(damageRect);
}
LayoutRect RenderLayer::localBoundingBox(OptionSet<CalculateLayerBoundsFlag> flags) const
{
// There are three special cases we need to consider.
// (1) Inline Flows. For inline flows we will create a bounding box that fully encompasses all of the lines occupied by the
// inline. In other words, if some <span> wraps to three lines, we'll create a bounding box that fully encloses the
// line boxes of all three lines (including overflow on those lines).
// (2) Left/Top Overflow. The width/height of layers already includes right/bottom overflow. However, in the case of left/top
// overflow, we have to create a bounding box that will extend to include this overflow.
// (3) Floats. When a layer has overhanging floats that it paints, we need to make sure to include these overhanging floats
// as part of our bounding box. We do this because we are the responsible layer for both hit testing and painting those
// floats.
LayoutRect result;
if (CheckedPtr renderInline = dynamicDowncast<RenderInline>(renderer()); renderInline && renderer().isInline())
result = renderInline->linesVisualOverflowBoundingBox();
else if (CheckedPtr modelObject = dynamicDowncast<RenderSVGModelObject>(renderer()))
result = modelObject->visualOverflowRectEquivalent();
else if (CheckedPtr tableRow = dynamicDowncast<RenderTableRow>(renderer())) {
// Our bounding box is just the union of all of our cells' border/overflow rects.
for (RenderTableCell* cell = tableRow->firstCell(); cell; cell = cell->nextCell()) {
LayoutRect bbox = cell->borderBoxRect();
result.unite(bbox);
LayoutRect overflowRect = tableRow->visualOverflowRect();
if (bbox != overflowRect)
result.unite(overflowRect);
}
} else {
RenderBox* box = renderBox();
ASSERT(box);
if (!(flags & DontConstrainForMask) && box->hasMask()) {
result = box->maskClipRect(LayoutPoint());
box->flipForWritingMode(result); // The mask clip rect is in physical coordinates, so we have to flip, since localBoundingBox is not.
} else
result = box->visualOverflowRect();
if (flags.contains(IncludeRootBackgroundPaintingArea) && renderer().isDocumentElementRenderer()) {
// If the root layer becomes composited (e.g. because some descendant with negative z-index is composited),
// then it has to be big enough to cover the viewport in order to display the background. This is akin
// to the code in RenderBox::paintRootBoxFillLayers().
auto& frameView = renderer().view().frameView();
result.setWidth(std::max(result.width(), frameView.contentsWidth() - result.x()));
result.setHeight(std::max(result.height(), frameView.contentsHeight() - result.y()));
}
}
return result;
}
LayoutRect RenderLayer::boundingBox(const RenderLayer* ancestorLayer, const LayoutSize& offsetFromRoot, OptionSet<CalculateLayerBoundsFlag> flags) const
{
LayoutRect result = localBoundingBox(flags);
if (renderer().view().frameView().hasFlippedBlockRenderers()) {
if (renderer().isRenderBox())
renderBox()->flipForWritingMode(result);
else
renderer().containingBlock()->flipForWritingMode(result);
}
PaginationInclusionMode inclusionMode = ExcludeCompositedPaginatedLayers;
if (flags & UseFragmentBoxesIncludingCompositing)
inclusionMode = IncludeCompositedPaginatedLayers;
const RenderLayer* paginationLayer = nullptr;
if (flags.containsAny({ UseFragmentBoxesExcludingCompositing, UseFragmentBoxesIncludingCompositing }))
paginationLayer = enclosingPaginationLayerInSubtree(ancestorLayer, inclusionMode);
const RenderLayer* childLayer = this;
bool isPaginated = paginationLayer;
while (paginationLayer) {
// Split our box up into the actual fragment boxes that render in the columns/pages and unite those together to
// get our true bounding box.
result.move(childLayer->offsetFromAncestor(paginationLayer));
auto& enclosingFragmentedFlow = downcast<RenderFragmentedFlow>(paginationLayer->renderer());
result = enclosingFragmentedFlow.fragmentsBoundingBox(result);
childLayer = paginationLayer;
paginationLayer = paginationLayer->parent()->enclosingPaginationLayerInSubtree(ancestorLayer, inclusionMode);
}
if (isPaginated) {
result.move(childLayer->offsetFromAncestor(ancestorLayer));
return result;
}
result.move(offsetFromRoot);
return result;
}
bool RenderLayer::getOverlapBoundsIncludingChildrenAccountingForTransformAnimations(LayoutRect& bounds, OptionSet<CalculateLayerBoundsFlag> additionalFlags) const
{
// The animation will override the display transform, so don't include it.
auto boundsFlags = additionalFlags | (defaultCalculateLayerBoundsFlags() - IncludeSelfTransform);
bounds = calculateLayerBounds(this, LayoutSize(), boundsFlags);
LayoutRect animatedBounds = bounds;
if (auto styleable = Styleable::fromRenderer(renderer())) {
if (styleable->computeAnimationExtent(animatedBounds)) {
bounds = animatedBounds;
return true;
}
}
return false;
}
IntRect RenderLayer::absoluteBoundingBox() const
{
const RenderLayer* rootLayer = root();
return snappedIntRect(boundingBox(rootLayer, offsetFromAncestor(rootLayer)));
}
FloatRect RenderLayer::absoluteBoundingBoxForPainting() const
{
const RenderLayer* rootLayer = root();
return snapRectToDevicePixels(boundingBox(rootLayer, offsetFromAncestor(rootLayer)), renderer().document().deviceScaleFactor());
}
LayoutRect RenderLayer::overlapBounds() const
{
if (overlapBoundsIncludeChildren())
return calculateLayerBounds(this, { }, { UseLocalClipRectExcludingCompositingIfPossible, IncludeFilterOutsets, UseFragmentBoxesExcludingCompositing });
return localBoundingBox();
}
LayoutRect RenderLayer::calculateLayerBounds(const RenderLayer* ancestorLayer, const LayoutSize& offsetFromRoot, OptionSet<CalculateLayerBoundsFlag> flags) const
{
if (!isSelfPaintingLayer())
return LayoutRect();
// FIXME: This could be improved to do a check like hasVisibleNonCompositingDescendantLayers() (bug 92580).
if ((flags & ExcludeHiddenDescendants) && this != ancestorLayer && !hasVisibleContent() && !hasVisibleDescendant())
return LayoutRect();
if (isRenderViewLayer()) {
// The root layer is always just the size of the document.
return renderer().view().unscaledDocumentRect();
}
LayoutRect boundingBoxRect = localBoundingBox(flags | IncludeRootBackgroundPaintingArea);
if (renderer().view().frameView().hasFlippedBlockRenderers()) {
if (CheckedPtr box = dynamicDowncast<RenderBox>(renderer()))
box->flipForWritingMode(boundingBoxRect);
else
renderer().containingBlock()->flipForWritingMode(boundingBoxRect);
}
LayoutRect unionBounds = boundingBoxRect;
if (flags.containsAny({ UseLocalClipRectIfPossible, UseLocalClipRectExcludingCompositingIfPossible })) {
bool clipExceedsBounds = false;
LayoutRect localClipRect = this->localClipRect(clipExceedsBounds, flags.contains(UseLocalClipRectExcludingCompositingIfPossible) ? LocalClipRectMode::ExcludeCompositingState : LocalClipRectMode::IncludeCompositingState);
if (!localClipRect.isInfinite() && !clipExceedsBounds) {
if ((flags & IncludeSelfTransform) && paintsWithTransform(PaintBehavior::Normal))
localClipRect = transform()->mapRect(localClipRect);
localClipRect.move(offsetFromAncestor(ancestorLayer));
return localClipRect;
}
}
// FIXME: should probably just pass 'flags' down to descendants.
auto descendantFlags = (flags & PreserveAncestorFlags) ? flags : defaultCalculateLayerBoundsFlags() | (flags & ExcludeHiddenDescendants) | (flags & IncludeCompositedDescendants);
const_cast<RenderLayer*>(this)->updateLayerListsIfNeeded();
if (RenderLayer* reflection = reflectionLayer()) {
if (!reflection->isComposited()) {
LayoutRect childUnionBounds = reflection->calculateLayerBounds(this, reflection->offsetFromAncestor(this), descendantFlags);
unionBounds.unite(childUnionBounds);
}
}
ASSERT(isStackingContext() || !positiveZOrderLayers().size());
#if ASSERT_ENABLED
LayerListMutationDetector mutationChecker(const_cast<RenderLayer&>(*this));
#endif
auto computeLayersUnion = [this, &unionBounds, flags, descendantFlags] (const RenderLayer& childLayer) {
if (!(flags & IncludeCompositedDescendants) && (childLayer.isComposited() || childLayer.paintsIntoProvidedBacking()))
return;
LayoutRect childBounds = childLayer.calculateLayerBounds(this, childLayer.offsetFromAncestor(this), descendantFlags);
// Ignore child layer (and behave as if we had overflow: hidden) when it is positioned off the parent layer so much
// that we hit the max LayoutUnit value.
unionBounds.checkedUnite(childBounds);
};
for (auto* childLayer : negativeZOrderLayers())
computeLayersUnion(*childLayer);
for (auto* childLayer : positiveZOrderLayers())
computeLayersUnion(*childLayer);
for (auto* childLayer : normalFlowLayers())
computeLayersUnion(*childLayer);
if (flags.contains(IncludeFilterOutsets) || (flags.contains(IncludePaintedFilterOutsets) && paintsWithFilters()))
unionBounds.expand(toLayoutBoxExtent(filterOutsets()));
if ((flags & IncludeSelfTransform) && paintsWithTransform(PaintBehavior::Normal)) {
TransformationMatrix* affineTrans = transform();
boundingBoxRect = affineTrans->mapRect(boundingBoxRect);
unionBounds = affineTrans->mapRect(unionBounds);
}
unionBounds.move(offsetFromRoot);
return unionBounds;
}
void RenderLayer::clearClipRectsIncludingDescendants(ClipRectsType typeToClear)
{
// FIXME: it's not clear how this layer not having clip rects guarantees that no descendants have any.
if (!m_clipRectsCache)
return;
clearClipRects(typeToClear);
for (RenderLayer* l = firstChild(); l; l = l->nextSibling())
l->clearClipRectsIncludingDescendants(typeToClear);
}
void RenderLayer::clearClipRects(ClipRectsType typeToClear)
{
if (typeToClear == AllClipRectTypes)
m_clipRectsCache = nullptr;
else if (m_clipRectsCache) {
ASSERT(typeToClear < NumCachedClipRectsTypes);
m_clipRectsCache->setClipRects(typeToClear, RespectOverflowClip, nullptr);
m_clipRectsCache->setClipRects(typeToClear, IgnoreOverflowClip, nullptr);
}
}
RenderLayerBacking* RenderLayer::ensureBacking()
{
if (!m_backing) {
m_backing = makeUnique<RenderLayerBacking>(*this);
compositor().layerBecameComposited(*this);
updateFilterPaintingStrategy();
}
return m_backing.get();
}
void RenderLayer::clearBacking(bool layerBeingDestroyed)
{
if (!m_backing)
return;
if (!renderer().renderTreeBeingDestroyed())
compositor().layerBecameNonComposited(*this);
m_backing->willBeDestroyed();
m_backing = nullptr;
if (!layerBeingDestroyed)
updateFilterPaintingStrategy();
}
bool RenderLayer::hasCompositedMask() const
{
return m_backing && m_backing->hasMaskLayer();
}
bool RenderLayer::paintsWithTransform(OptionSet<PaintBehavior> paintBehavior) const
{
bool paintsToWindow = !isComposited() || backing()->paintsIntoWindow();
return transform() && ((paintBehavior & PaintBehavior::FlattenCompositingLayers) || paintsToWindow);
}
bool RenderLayer::shouldPaintMask(OptionSet<PaintBehavior> paintBehavior, OptionSet<PaintLayerFlag> paintFlags) const
{
if (!renderer().hasMask())
return false;
bool paintsToWindow = !isComposited() || backing()->paintsIntoWindow();
if (paintsToWindow || (paintBehavior & PaintBehavior::FlattenCompositingLayers))
return true;
return paintFlags.contains(PaintLayerFlag::PaintingCompositingMaskPhase);
}
bool RenderLayer::shouldApplyClipPath(OptionSet<PaintBehavior> paintBehavior, OptionSet<PaintLayerFlag> paintFlags) const
{
if (!renderer().hasClipPath())
return false;
bool paintsToWindow = !isComposited() || backing()->paintsIntoWindow();
if (paintsToWindow || (paintBehavior & PaintBehavior::FlattenCompositingLayers))
return true;
return paintFlags.containsAny({ PaintLayerFlag::PaintingCompositingClipPathPhase, PaintLayerFlag::CollectingEventRegion });
}
bool RenderLayer::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
{
if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
return false;
if (paintsWithTransparency(PaintBehavior::Normal))
return false;
if (renderer().isDocumentElementRenderer()) {
// Normally the document element doens't have a layer. If it does have a layer, its background propagates to the RenderView
// so this layer doesn't draw it.
return false;
}
// We can't use hasVisibleContent(), because that will be true if our renderer is hidden, but some child
// is visible and that child doesn't cover the entire rect.
if (renderer().style().usedVisibility() != Visibility::Visible)
return false;
if (paintsWithFilters() && renderer().style().filter().hasFilterThatAffectsOpacity())
return false;
// FIXME: Handle simple transforms.
if (paintsWithTransform(PaintBehavior::Normal))
return false;
// FIXME: Remove this check.
// This function should not be called when layer-lists are dirty.
// It is somehow getting triggered during style update.
if (zOrderListsDirty() || normalFlowListDirty())
return false;
// Table painting is special; a table paints its sections.
if (renderer().isTablePart())
return false;
// A fieldset with a legend will have an irregular shape, so can't be treated as opaque.
if (renderer().isFieldset())
return false;
// FIXME: We currently only check the immediate renderer,
// which will miss many cases.
if (renderer().backgroundIsKnownToBeOpaqueInRect(localRect))
return true;
// We can't consult child layers if we clip, since they might cover
// parts of the rect that are clipped out.
if (renderer().hasNonVisibleOverflow())
return false;
return listBackgroundIsKnownToBeOpaqueInRect(positiveZOrderLayers(), localRect)
|| listBackgroundIsKnownToBeOpaqueInRect(negativeZOrderLayers(), localRect)
|| listBackgroundIsKnownToBeOpaqueInRect(normalFlowLayers(), localRect);
}
bool RenderLayer::listBackgroundIsKnownToBeOpaqueInRect(const LayerList& list, const LayoutRect& localRect) const
{
if (list.begin() == list.end())
return false;
for (auto iter = list.rbegin(); iter != list.rend(); ++iter) {
const auto* childLayer = *iter;
if (childLayer->isComposited())
continue;
if (!childLayer->canUseOffsetFromAncestor())
continue;
LayoutRect childLocalRect(localRect);
childLocalRect.move(-childLayer->offsetFromAncestor(this));
if (childLayer->backgroundIsKnownToBeOpaqueInRect(childLocalRect))
return true;
}
return false;
}
void RenderLayer::repaintIncludingDescendants()
{
renderer().repaint();
for (RenderLayer* current = firstChild(); current; current = current->nextSibling())
current->repaintIncludingDescendants();
}
bool RenderLayer::canUseOffsetFromAncestor(const RenderLayer& ancestor) const
{
for (auto* layer = this; layer && layer != &ancestor; layer = layer->parent()) {
if (!layer->canUseOffsetFromAncestor())
return false;
}
return true;
}
void RenderLayer::setBackingNeedsRepaint(GraphicsLayer::ShouldClipToLayer shouldClip)
{
ASSERT(isComposited());
if (backing()->paintsIntoWindow()) {
// If we're trying to repaint the placeholder document layer, propagate the
// repaint to the native view system.
renderer().view().repaintViewRectangle(absoluteBoundingBox());
} else
backing()->setContentsNeedDisplay(shouldClip);
}
void RenderLayer::setBackingNeedsRepaintInRect(const LayoutRect& r, GraphicsLayer::ShouldClipToLayer shouldClip)
{
// https://bugs.webkit.org/show_bug.cgi?id=61159 describes an unreproducible crash here,
// so assert but check that the layer is composited.
ASSERT(isComposited());
if (!isComposited() || backing()->paintsIntoWindow()) {
// If we're trying to repaint the placeholder document layer, propagate the
// repaint to the native view system.
LayoutRect absRect(r);
absRect.move(offsetFromAncestor(root()));
renderer().view().repaintViewRectangle(absRect);
} else
backing()->setContentsNeedDisplayInRect(r, shouldClip);
}
// Since we're only painting non-composited layers, we know that they all share the same repaintContainer.
void RenderLayer::repaintIncludingNonCompositingDescendants(const RenderLayerModelObject* repaintContainer)
{
auto clippedOverflowRect = m_repaintRectsValid ? m_repaintRects.clippedOverflowRect : renderer().clippedOverflowRectForRepaint(repaintContainer);
renderer().repaintUsingContainer(repaintContainer, clippedOverflowRect);
for (RenderLayer* curr = firstChild(); curr; curr = curr->nextSibling()) {
if (!curr->isComposited())
curr->repaintIncludingNonCompositingDescendants(repaintContainer);
}
}
bool RenderLayer::shouldBeSelfPaintingLayer() const
{
if (!isNormalFlowOnly())
return true;
return hasOverlayScrollbars()
|| hasCompositedScrollableOverflow()
|| renderer().isRenderTableRow()
|| renderer().isRenderHTMLCanvas()
|| renderer().isRenderVideo()
|| renderer().isRenderEmbeddedObject()
|| renderer().isRenderIFrame()
|| renderer().isRenderFragmentedFlow();
}
void RenderLayer::updateSelfPaintingLayer()
{
bool isSelfPaintingLayer = shouldBeSelfPaintingLayer();
if (m_isSelfPaintingLayer == isSelfPaintingLayer)
return;
m_isSelfPaintingLayer = isSelfPaintingLayer;
setNeedsPositionUpdate();
if (!parent())
return;
if (isSelfPaintingLayer)
parent()->setAncestorChainHasSelfPaintingLayerDescendant();
else {
parent()->dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
clearRepaintRects();
auto updateFloatBoxShouldPaintIfApplicable = [&] {
auto* renderBox = this->renderBox();
if (!renderBox || !renderBox->isFloating())
return;
renderBox->updateFloatPainterAfterSelfPaintingLayerChange();
};
updateFloatBoxShouldPaintIfApplicable();
}
}
static bool hasVisibleBoxDecorationsOrBackground(const RenderElement& renderer)
{
return renderer.hasVisibleBoxDecorations() || renderer.style().hasOutline();
}
#if HAVE(SUPPORT_HDR_DISPLAY)
static bool isReplacedElementWithHDR(const RenderElement& renderer)
{
if (CheckedPtr imageRenderer = dynamicDowncast<RenderImage>(renderer)) {
if (auto* cachedImage = imageRenderer->cachedImage()) {
if (cachedImage->isHDR())
return true;
}
return false;
}
#if ENABLE(PIXEL_FORMAT_RGBA16F)
if (CheckedPtr canavsRenderer = dynamicDowncast<RenderHTMLCanvas>(renderer)) {
if (auto* renderingContext = canavsRenderer->canvasElement().renderingContext()) {
if (renderingContext->isHDR())
return true;
}
return false;
}
#endif
return false;
}
#endif
static void determineNonLayerDescendantsPaintedContent(const RenderElement& renderer, unsigned& renderersTraversed, RenderLayer::PaintedContentRequest& request)
{
// Constrain the depth and breadth of the search for performance.
static constexpr unsigned maxRendererTraversalCount = 200;
for (const auto& child : childrenOfType<RenderObject>(renderer)) {
if (++renderersTraversed > maxRendererTraversalCount) {
if (!request.isPaintedContentSatisfied())
request.makePaintedContentUndetermined();
if (request.isSatisfied())
return;
}
if (CheckedPtr renderText = dynamicDowncast<RenderText>(child)) {
if (!renderText->hasRenderedText())
continue;
if (renderer.style().usedUserSelect() != UserSelect::None)
request.setHasPaintedContent();
if (!renderText->text().containsOnly<isASCIIWhitespace>())
request.setHasPaintedContent();
if (request.isSatisfied())
return;
}
CheckedPtr childElement = dynamicDowncast<RenderElement>(child);
if (!childElement)
continue;
if (auto* modelObject = dynamicDowncast<RenderLayerModelObject>(*childElement); modelObject && modelObject->hasSelfPaintingLayer())
continue;
if (hasVisibleBoxDecorationsOrBackground(*childElement)) {
request.setHasPaintedContent();
if (request.isSatisfied())
return;
}
if (is<RenderReplaced>(*childElement)) {
request.setHasPaintedContent();
if (request.isSatisfied())
return;
}
#if HAVE(SUPPORT_HDR_DISPLAY)
if (!request.isPaintedHDRContentSatisfied() && isReplacedElementWithHDR(*childElement)) {
request.setHasPaintedHDRContent();
if (request.isSatisfied())
return;
}
#endif
determineNonLayerDescendantsPaintedContent(*childElement, renderersTraversed, request);
if (request.isSatisfied())
return;
}
}
void RenderLayer::determineNonLayerDescendantsPaintedContent(PaintedContentRequest& request) const
{
unsigned renderersTraversed = 0;
WebCore::determineNonLayerDescendantsPaintedContent(renderer(), renderersTraversed, request);
}
#if HAVE(SUPPORT_HDR_DISPLAY)
bool RenderLayer::isReplacedElementWithHDR() const
{
if (auto* imageDocument = dynamicDowncast<ImageDocument>(renderer().document())) {
if (RefPtr imageElement = imageDocument->imageElement()) {
if (auto* cachedImage = imageElement->cachedImage())
return cachedImage->isHDR();
}
return false;
}
return WebCore::isReplacedElementWithHDR(renderer());
}
#endif
bool RenderLayer::hasVisibleBoxDecorationsOrBackground() const
{
return WebCore::hasVisibleBoxDecorationsOrBackground(renderer());
}
bool RenderLayer::hasVisibleBoxDecorations() const
{
if (!hasVisibleContent())
return false;
return hasVisibleBoxDecorationsOrBackground() || (m_scrollableArea && m_scrollableArea->hasOverflowControls());
}
bool RenderLayer::isVisibilityHiddenOrOpacityZero() const
{
return !hasVisibleContent() || renderer().style().hasZeroOpacity();
}
bool RenderLayer::isVisuallyNonEmpty(PaintedContentRequest* request) const
{
ASSERT(!m_visibleContentStatusDirty);
if (!hasVisibleContent() || renderer().style().hasZeroOpacity())
return false;
if (renderer().isRenderReplaced() || (m_scrollableArea && m_scrollableArea->hasOverflowControls())) {
if (!request)
return true;
request->setHasPaintedContent();
if (request->isSatisfied())
return true;
}
if (hasVisibleBoxDecorationsOrBackground()) {
if (!request)
return true;
request->setHasPaintedContent();
if (request->isSatisfied())
return true;
}
PaintedContentRequest localRequest;
if (!request)
request = &localRequest;
determineNonLayerDescendantsPaintedContent(*request);
return request->probablyHasPaintedContent();
}
void RenderLayer::styleChanged(StyleDifference diff, const RenderStyle* oldStyle)
{
setIsNormalFlowOnly(shouldBeNormalFlowOnly());
setCanBeBackdropRoot(computeCanBeBackdropRoot());
if (setIsCSSStackingContext(shouldBeCSSStackingContext())) {
if (parent()) {
if (isCSSStackingContext()) {
if (!hasNotIsolatedBlendingDescendantsStatusDirty() && hasNotIsolatedBlendingDescendants())
parent()->dirtyAncestorChainHasBlendingDescendants();
} else {
if (hasNotIsolatedBlendingDescendantsStatusDirty())
parent()->dirtyAncestorChainHasBlendingDescendants();
else if (hasNotIsolatedBlendingDescendants())
parent()->updateAncestorChainHasBlendingDescendants();
}
}
}
updateLayerScrollableArea();
// FIXME: RenderLayer already handles visibility changes through our visibility dirty bits. This logic could
// likely be folded along with the rest.
if (oldStyle) {
bool visibilityChanged = oldStyle->usedVisibility() != renderer().style().usedVisibility();
if (oldStyle->usedZIndex() != renderer().style().usedZIndex() || oldStyle->usedContentVisibility() != renderer().style().usedContentVisibility() || visibilityChanged) {
dirtyStackingContextZOrderLists();
if (isStackingContext())
dirtyZOrderLists();
}
if (!oldStyle->viewTransitionName().isNone() != renderer().hasViewTransitionName())
updateAlwaysIncludedInZOrderLists();
// Visibility and scrollability are input to canUseCompositedScrolling().
if (m_scrollableArea) {
if (oldStyle->writingMode() != renderer().style().writingMode())
m_scrollableArea->invalidateScrollCornerRect({ });
if (visibilityChanged || oldStyle->isOverflowVisible() != renderer().style().isOverflowVisible())
m_scrollableArea->computeHasCompositedScrollableOverflow(diff <= StyleDifference::RepaintLayer ? LayoutUpToDate::Yes : LayoutUpToDate::No);
}
if (oldStyle->isOverflowVisible() != renderer().style().isOverflowVisible())
setSelfAndDescendantsNeedPositionUpdate();
if (oldStyle->hasZeroOpacity() != renderer().style().hasZeroOpacity())
setNeedsPositionUpdate();
if (oldStyle->preserves3D() != preserves3D()) {
dirty3DTransformedDescendantStatus();
setNeedsPostLayoutCompositingUpdateOnAncestors();
}
}
if (m_scrollableArea) {
m_scrollableArea->createOrDestroyMarquee();
m_scrollableArea->updateScrollbarsAfterStyleChange(oldStyle);
}
// Overlay scrollbars can make this layer self-painting so we need
// to recompute the bit once scrollbars have been updated.
updateSelfPaintingLayer();
if (!hasReflection() && m_reflection)
removeReflection();
else if (hasReflection()) {
if (!m_reflection)
createReflection();
else
m_reflection->setStyle(createReflectionStyle());
}
// FIXME: Need to detect a swap from custom to native scrollbars (and vice versa).
if (m_scrollableArea)
m_scrollableArea->updateAllScrollbarRelatedStyle();
updateDescendantDependentFlags();
updateBlendMode();
updateFiltersAfterStyleChange(diff, oldStyle);
clearClipRects();
compositor().layerStyleChanged(diff, *this, oldStyle);
updateTransform();
updateFilterPaintingStrategy();
#if PLATFORM(IOS_FAMILY) && ENABLE(TOUCH_EVENTS)
if (diff == StyleDifference::RecompositeLayer || diff >= StyleDifference::LayoutPositionedMovementOnly)
renderer().document().invalidateRenderingDependentRegions();
#else
UNUSED_PARAM(diff);
#endif
}
RenderLayer* RenderLayer::reflectionLayer() const
{
return m_reflection ? m_reflection->layer() : nullptr;
}
bool RenderLayer::isReflectionLayer(const RenderLayer& layer) const
{
return m_reflection ? &layer == m_reflection->layer() : false;
}
void RenderLayer::createReflection()
{
ASSERT(!m_reflection);
m_reflection = createRenderer<RenderReplica>(renderer().document(), createReflectionStyle());
// FIXME: A renderer should be a child of its parent!
m_reflection->m_parent = &renderer(); // We create a 1-way connection.
m_reflection->initializeStyle();
}
void RenderLayer::removeReflection()
{
if (!m_reflection->renderTreeBeingDestroyed()) {
if (auto* layer = m_reflection->layer())
removeChild(*layer);
}
m_reflection->m_parent = nullptr;
m_reflection = nullptr;
}
RenderStyle RenderLayer::createReflectionStyle()
{
auto newStyle = RenderStyle::create();
newStyle.inheritFrom(renderer().style());
// Map in our transform.
Vector<Ref<TransformOperation>> operations;
switch (renderer().style().boxReflect()->direction()) {
case ReflectionDirection::Below:
operations = {
TranslateTransformOperation::create(Length(0, LengthType::Fixed), Length(100., LengthType::Percent), TransformOperation::Type::Translate),
TranslateTransformOperation::create(Length(0, LengthType::Fixed), renderer().style().boxReflect()->offset(), TransformOperation::Type::Translate),
ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Type::Scale)
};
break;
case ReflectionDirection::Above:
operations = {
ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Type::Scale),
TranslateTransformOperation::create(Length(0, LengthType::Fixed), Length(100., LengthType::Percent), TransformOperation::Type::Translate),
TranslateTransformOperation::create(Length(0, LengthType::Fixed), renderer().style().boxReflect()->offset(), TransformOperation::Type::Translate)
};
break;
case ReflectionDirection::Right:
operations = {
TranslateTransformOperation::create(Length(100., LengthType::Percent), Length(0, LengthType::Fixed), TransformOperation::Type::Translate),
TranslateTransformOperation::create(renderer().style().boxReflect()->offset(), Length(0, LengthType::Fixed), TransformOperation::Type::Translate),
ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Type::Scale)
};
break;
case ReflectionDirection::Left:
operations = {
ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Type::Scale),
TranslateTransformOperation::create(Length(100., LengthType::Percent), Length(0, LengthType::Fixed), TransformOperation::Type::Translate),
TranslateTransformOperation::create(renderer().style().boxReflect()->offset(), Length(0, LengthType::Fixed), TransformOperation::Type::Translate)
};
break;
}
newStyle.setTransform(TransformOperations { WTFMove(operations) });
// Map in our mask.
newStyle.setMaskBorder(renderer().style().boxReflect()->mask());
// Style has transform and mask, so needs to be stacking context.
newStyle.setUsedZIndex(0);
return newStyle;
}
void RenderLayer::ensureLayerFilters()
{
if (m_filters)
return;
m_filters = makeUnique<RenderLayerFilters>(*this);
}
void RenderLayer::clearLayerFilters()
{
m_filters = nullptr;
}
RenderLayerScrollableArea* RenderLayer::ensureLayerScrollableArea()
{
bool hadScrollableArea = scrollableArea();
if (!m_scrollableArea)
m_scrollableArea = makeUnique<RenderLayerScrollableArea>(*this);
if (!hadScrollableArea) {
if (renderer().settings().asyncOverflowScrollingEnabled())
setNeedsCompositingConfigurationUpdate();
m_scrollableArea->restoreScrollPosition();
}
return m_scrollableArea.get();
}
void RenderLayer::clearLayerScrollableArea()
{
if (m_scrollableArea) {
m_scrollableArea->clear();
m_scrollableArea = nullptr;
}
}
void RenderLayer::updateFiltersAfterStyleChange(StyleDifference diff, const RenderStyle* oldStyle)
{
if (renderer().style().filter().hasReferenceFilter()) {
ensureLayerFilters();
m_filters->updateReferenceFilterClients(renderer().style().filter());
} else if (!paintsWithFilters())
clearLayerFilters();
else if (m_filters)
m_filters->removeReferenceFilterClients();
if (diff >= StyleDifference::RepaintLayer && oldStyle && oldStyle->filter() != renderer().style().filter())
clearLayerFilters();
}
void RenderLayer::updateLayerScrollableArea()
{
bool hasScrollableArea = scrollableArea();
bool needsScrollableArea = [&] {
auto* box = dynamicDowncast<RenderBox>(renderer());
return box && box->requiresLayerWithScrollableArea();
}();
if (needsScrollableArea == hasScrollableArea)
return;
if (needsScrollableArea)
ensureLayerScrollableArea();
else {
clearLayerScrollableArea();
if (renderer().settings().asyncOverflowScrollingEnabled())
setNeedsCompositingConfigurationUpdate();
}
InspectorInstrumentation::didAddOrRemoveScrollbars(m_renderer);
}
void RenderLayer::updateFilterPaintingStrategy()
{
// RenderLayerFilters is only used to render the filters in software mode,
// so we always need to run updateFilterPaintingStrategy() after the composited
// mode might have changed for this layer.
if (!paintsWithFilters()) {
// Don't delete the whole filter info here, because we might use it
// for loading SVG reference filter files.
if (m_filters)
m_filters->clearFilter();
// Early-return only if we *don't* have reference filters.
// For reference filters, we still want the FilterEffect graph built
// for us, even if we're composited.
if (!renderer().style().filter().hasReferenceFilter())
return;
}
ensureLayerFilters();
m_filters->setPreferredFilterRenderingModes(renderer().page().preferredFilterRenderingModes());
m_filters->setFilterScale({ page().deviceScaleFactor(), page().deviceScaleFactor() });
}
IntOutsets RenderLayer::filterOutsets() const
{
if (m_filters)
return m_filters->calculateOutsets(renderer(), localBoundingBox());
return renderer().style().filterOutsets();
}
static RenderLayer* parentLayerCrossFrame(const RenderLayer& layer)
{
if (auto* parent = layer.parent())
return parent;
return layer.enclosingFrameRenderLayer();
}
bool RenderLayer::isTransparentRespectingParentFrames() const
{
static const double minimumVisibleOpacity = 0.01;
float currentOpacity = 1;
for (auto* layer = this; layer; layer = parentLayerCrossFrame(*layer)) {
currentOpacity *= layer->renderer().style().opacity();
if (currentOpacity < minimumVisibleOpacity)
return true;
}
return false;
}
#if ENABLE(RE_DYNAMIC_CONTENT_SCALING)
bool RenderLayer::allowsDynamicContentScaling() const
{
if (is<RenderHTMLCanvas>(renderer()))
return false;
if (isBitmapOnly())
return false;
return true;
}
#endif
bool RenderLayer::isBitmapOnly() const
{
if (hasVisibleBoxDecorationsOrBackground())
return false;
if (is<RenderHTMLCanvas>(renderer()))
return true;
if (CheckedPtr imageRenderer = dynamicDowncast<RenderImage>(renderer())) {
if (auto* cachedImage = imageRenderer->cachedImage()) {
if (!cachedImage->hasImage())
return false;
return is<BitmapImage>(cachedImage->imageForRenderer(imageRenderer.get()));
}
return false;
}
return false;
}
void RenderLayer::simulateFrequentPaint()
{
m_paintFrequencyTracker.track(page().lastRenderingUpdateTimestamp());
}
void RenderLayer::purgeFrontBufferForTesting()
{
if (backing())
backing()->purgeFrontBufferForTesting();
}
void RenderLayer::purgeBackBufferForTesting()
{
if (backing())
backing()->purgeBackBufferForTesting();
}
void RenderLayer::markFrontBufferVolatileForTesting()
{
if (backing())
backing()->markFrontBufferVolatileForTesting();
}
RenderLayerScrollableArea* RenderLayer::scrollableArea() const
{
return m_scrollableArea.get();
}
CheckedPtr<RenderLayerScrollableArea> RenderLayer::checkedScrollableArea() const
{
return scrollableArea();
}
#if ENABLE(ASYNC_SCROLLING) && !LOG_DISABLED
static TextStream& operator<<(TextStream& ts, RenderLayer::EventRegionInvalidationReason reason)
{
switch (reason) {
case RenderLayer::EventRegionInvalidationReason::Paint: ts << "Paint"; break;
case RenderLayer::EventRegionInvalidationReason::SettingDidChange: ts << "SettingDidChange"; break;
case RenderLayer::EventRegionInvalidationReason::Style: ts << "Style"; break;
case RenderLayer::EventRegionInvalidationReason::NonCompositedFrame: ts << "NonCompositedFrame"; break;
}
return ts;
}
#endif // !LOG_DISABLED
void RenderLayer::setAncestorsHaveDescendantNeedingEventRegionUpdate()
{
for (auto* layer = parent(); layer; layer = layer->parent()) {
if (layer->m_hasDescendantNeedingEventRegionUpdate)
break;
layer->m_hasDescendantNeedingEventRegionUpdate = true;
}
}
bool RenderLayer::invalidateEventRegion(EventRegionInvalidationReason reason)
{
#if ENABLE(ASYNC_SCROLLING)
auto* compositingLayer = enclosingCompositingLayerForRepaint().layer;
auto shouldInvalidate = [&] {
if (!compositingLayer)
return false;
if (reason == EventRegionInvalidationReason::NonCompositedFrame)
return true;
return compositingLayer->backing()->maintainsEventRegion();
};
if (!shouldInvalidate())
return false;
LOG_WITH_STREAM(EventRegions, stream << this << " invalidateEventRegion for reason " << reason << " invalidating in compositing layer " << compositingLayer);
compositingLayer->backing()->setNeedsEventRegionUpdate();
compositingLayer->setAncestorsHaveDescendantNeedingEventRegionUpdate();
if (reason == EventRegionInvalidationReason::NonCompositedFrame) {
auto& view = renderer().view();
LOG_WITH_STREAM(EventRegions, stream << " calling setNeedsEventRegionUpdateForNonCompositedFrame on " << view);
view.setNeedsEventRegionUpdateForNonCompositedFrame();
auto visibleDebugOverlayRegions = OptionSet<DebugOverlayRegions>::fromRaw(renderer().settings().visibleDebugOverlayRegions());
if (visibleDebugOverlayRegions.containsAny({ DebugOverlayRegions::TouchActionRegion, DebugOverlayRegions::EditableElementRegion, DebugOverlayRegions::WheelEventHandlerRegion }))
view.setNeedsRepaintHackAfterCompositingLayerUpdateForDebugOverlaysOnly();
view.compositor().scheduleCompositingLayerUpdate();
}
return true;
#else
UNUSED_PARAM(reason);
return false;
#endif
}
TextStream& operator<<(WTF::TextStream& ts, ClipRectsType clipRectsType)
{
switch (clipRectsType) {
case PaintingClipRects: ts << "painting"; break;
case RootRelativeClipRects: ts << "root-relative"; break;
case AbsoluteClipRects: ts << "absolute"; break;
case TemporaryClipRects: ts << "temporary"; break;
case NumCachedClipRectsTypes:
case AllClipRectTypes:
ts << "?";
break;
}
return ts;
}
TextStream& operator<<(TextStream& ts, const RenderLayer& layer)
{
ts << layer.debugDescription();
return ts;
}
TextStream& operator<<(TextStream& ts, const RenderLayer::ClipRectsContext& context)
{
ts.dumpProperty("root layer:", context.rootLayer);
ts.dumpProperty("type:", context.clipRectsType);
ts.dumpProperty("overflow-clip:", context.respectOverflowClip() ? "respect" : "ignore");
return ts;
}
TextStream& operator<<(TextStream& ts, IndirectCompositingReason reason)
{
switch (reason) {
case IndirectCompositingReason::None: ts << "none"; break;
case IndirectCompositingReason::Clipping: ts << "clipping"; break;
case IndirectCompositingReason::Stacking: ts << "stacking"; break;
case IndirectCompositingReason::OverflowScrollPositioning: ts << "overflow positioning"; break;
case IndirectCompositingReason::Overlap: ts << "overlap"; break;
case IndirectCompositingReason::BackgroundLayer: ts << "background layer"; break;
case IndirectCompositingReason::GraphicalEffect: ts << "graphical effect"; break;
case IndirectCompositingReason::Perspective: ts << "perspective"; break;
case IndirectCompositingReason::Preserve3D: ts << "preserve-3d"; break;
}
return ts;
}
TextStream& operator<<(TextStream& ts, PaintBehavior behavior)
{
switch (behavior) {
case PaintBehavior::Normal: ts << "Normal"; break;
case PaintBehavior::SelectionOnly: ts << "SelectionOnly"; break;
case PaintBehavior::SkipSelectionHighlight: ts << "SkipSelectionHighlight"; break;
case PaintBehavior::ForceBlackText: ts << "ForceBlackText"; break;
case PaintBehavior::ForceWhiteText: ts << "ForceWhiteText"; break;
case PaintBehavior::ForceBlackBorder: ts << "ForceBlackBorder"; break;
case PaintBehavior::RenderingSVGClipOrMask: ts << "RenderingSVGClipOrMask"; break;
case PaintBehavior::SkipRootBackground: ts << "SkipRootBackground"; break;
case PaintBehavior::RootBackgroundOnly: ts << "RootBackgroundOnly"; break;
case PaintBehavior::SelectionAndBackgroundsOnly: ts << "SelectionAndBackgroundsOnly"; break;
case PaintBehavior::ExcludeSelection: ts << "ExcludeSelection"; break;
case PaintBehavior::FlattenCompositingLayers: ts << "FlattenCompositingLayers"; break;
case PaintBehavior::ForceSynchronousImageDecode: ts << "ForceSynchronousImageDecode"; break;
case PaintBehavior::DefaultAsynchronousImageDecode: ts << "DefaultAsynchronousImageDecode"; break;
case PaintBehavior::CompositedOverflowScrollContent: ts << "CompositedOverflowScrollContent"; break;
case PaintBehavior::AnnotateLinks: ts << "AnnotateLinks"; break;
case PaintBehavior::EventRegionIncludeForeground: ts << "EventRegionIncludeForeground"; break;
case PaintBehavior::EventRegionIncludeBackground: ts << "EventRegionIncludeBackground"; break;
case PaintBehavior::Snapshotting: ts << "Snapshotting"; break;
case PaintBehavior::DontShowVisitedLinks: ts << "DontShowVisitedLinks"; break;
case PaintBehavior::ExcludeReplacedContent: ts << "ExcludeReplacedContent"; break;
}
return ts;
}
TextStream& operator<<(TextStream& ts, RenderLayer::PaintLayerFlag flag)
{
switch (flag) {
case RenderLayer::PaintLayerFlag::HaveTransparency: ts << "HaveTransparency"; break;
case RenderLayer::PaintLayerFlag::AppliedTransform: ts << "AppliedTransform"; break;
case RenderLayer::PaintLayerFlag::TemporaryClipRects: ts << "TemporaryClipRects"; break;
case RenderLayer::PaintLayerFlag::PaintingReflection: ts << "PaintingReflection"; break;
case RenderLayer::PaintLayerFlag::PaintingOverlayScrollbars: ts << "PaintingOverlayScrollbars"; break;
case RenderLayer::PaintLayerFlag::PaintingCompositingBackgroundPhase: ts << "PaintingCompositingBackgroundPhase"; break;
case RenderLayer::PaintLayerFlag::PaintingCompositingForegroundPhase: ts << "PaintingCompositingForegroundPhase"; break;
case RenderLayer::PaintLayerFlag::PaintingCompositingMaskPhase: ts << "PaintingCompositingMaskPhase"; break;
case RenderLayer::PaintLayerFlag::PaintingCompositingClipPathPhase: ts << "PaintingCompositingClipPathPhase"; break;
case RenderLayer::PaintLayerFlag::PaintingOverflowContainer: ts << "PaintingOverflowContainer"; break;
case RenderLayer::PaintLayerFlag::PaintingOverflowContents: ts << "PaintingOverflowContents"; break;
case RenderLayer::PaintLayerFlag::PaintingOverflowContentsRoot: ts << "PaintingOverflowContentsRoot"; break;
case RenderLayer::PaintLayerFlag::PaintingRootBackgroundOnly: ts << "PaintingRootBackgroundOnly"; break;
case RenderLayer::PaintLayerFlag::PaintingSkipRootBackground: ts << "PaintingSkipRootBackground"; break;
case RenderLayer::PaintLayerFlag::PaintingChildClippingMaskPhase: ts << "PaintingChildClippingMaskPhase"; break;
case RenderLayer::PaintLayerFlag::PaintingSVGClippingMask: ts << "PaintingSVGClippingMask"; break;
case RenderLayer::PaintLayerFlag::CollectingEventRegion: ts << "CollectingEventRegion"; break;
case RenderLayer::PaintLayerFlag::PaintingSkipDescendantViewTransition: ts << "PaintingSkipDescendantViewTransition"; break;
}
return ts;
}
#undef LAYER_POSITIONS_ASSERT_ENABLED
#undef LAYER_POSITIONS_ASSERT
#undef LAYER_POSITIONS_ASSERT_IMPLIES
} // namespace WebCore
#if ENABLE(TREE_DEBUGGING)
void showLayerTree(const WebCore::RenderLayer* layer)
{
if (!layer)
return;
String output = externalRepresentation(&layer->renderer().frame(), {
WebCore::RenderAsTextFlag::ShowAllLayers,
WebCore::RenderAsTextFlag::ShowLayerNesting,
WebCore::RenderAsTextFlag::ShowCompositedLayers,
WebCore::RenderAsTextFlag::ShowOverflow,
WebCore::RenderAsTextFlag::ShowSVGGeometry,
WebCore::RenderAsTextFlag::ShowLayerFragments,
WebCore::RenderAsTextFlag::ShowAddresses,
WebCore::RenderAsTextFlag::ShowIDAndClass,
WebCore::RenderAsTextFlag::DontUpdateLayout,
WebCore::RenderAsTextFlag::ShowLayoutState,
});
SAFE_FPRINTF(stderr, "\n%s\n", output.utf8());
}
void showLayerTree(const WebCore::RenderObject* renderer)
{
if (!renderer)
return;
showLayerTree(renderer->enclosingLayer());
}
static void outputPaintOrderTreeLegend(TextStream& stream)
{
stream.nextLine();
stream << "(T)op layer, (S)tacking Context/(F)orced SC/O(P)portunistic SC, (N)ormal flow only, (O)verflow clip, (A)lpha (opacity or mask), has (B)lend mode, (I)solates blending, (T)ransform-ish, (F)ilter, Fi(X)ed position, Behaves as fi(x)ed, (C)omposited, (P)rovides backing/uses (p)rovided backing/paints to (a)ncestor, (c)omposited descendant, (s)scrolling ancestor, (t)transformed ancestor\n"
"Dirty (z)-lists, Dirty (n)ormal flow lists\n"
"Traversal needs: requirements (t)raversal on descendants, (b)acking or hierarchy traversal on descendants, (r)equirements traversal on all descendants, requirements traversal on all (s)ubsequent layers, (h)ierarchy traversal on all descendants, update of paint (o)rder children\n"
"Update needs: post-(l)ayout requirements, (g)eometry, (k)ids geometry, (c)onfig, layer conne(x)ion, (s)crolling tree\n"
"Scrolling scope: box contents\n";
stream.nextLine();
}
static void outputIdent(TextStream& stream, unsigned depth)
{
unsigned i = 0;
while (++i <= depth * 2)
stream << " ";
}
static void outputPaintOrderTreeRecursive(TextStream& stream, const WebCore::RenderLayer& layer, ASCIILiteral prefix, unsigned depth = 0)
{
stream << (layer.establishesTopLayer() ? "T"_s : "-"_s);
stream << (layer.isCSSStackingContext() ? "S"_s : (layer.isForcedStackingContext() ? "F"_s : (layer.isOpportunisticStackingContext() ? "P"_s : "-"_s)));
stream << (layer.isNormalFlowOnly() ? "N"_s : "-"_s);
stream << (layer.renderer().hasNonVisibleOverflow() ? "O"_s : "-"_s);
stream << (layer.isTransparent() ? "A"_s : "-"_s);
stream << (layer.hasBlendMode() ? "B"_s : "-"_s);
stream << (layer.isolatesBlending() ? "I"_s : "-"_s);
stream << (layer.renderer().hasTransformRelatedProperty() ? "T"_s : "-"_s);
stream << (layer.hasFilter() ? "F"_s : "-"_s);
stream << (layer.renderer().isFixedPositioned() ? "X"_s : "-"_s);
stream << (layer.behavesAsFixed() ? "x"_s : "-"_s);
stream << (layer.isComposited() ? "C"_s : "-"_s);
auto compositedPaintingDestinationString = [&layer]() {
if (layer.paintsIntoProvidedBacking())
return "p"_s;
if (!layer.isComposited())
return "-"_s;
if (layer.backing()->hasBackingSharingLayers())
return "P"_s;
if (layer.backing()->paintsIntoCompositedAncestor())
return "a"_s;
return "-"_s;
};
stream << compositedPaintingDestinationString();
stream << (layer.hasCompositingDescendant() ? "c"_s : "-"_s);
stream << (layer.hasCompositedScrollingAncestor() ? "s"_s : "-"_s);
stream << (layer.hasTransformedAncestor() ? "t"_s : "-"_s);
stream << " "_s;
stream << (layer.zOrderListsDirty() ? "z"_s : "-"_s);
stream << (layer.normalFlowListDirty() ? "n"_s : "-"_s);
stream << " "_s;
stream << (layer.hasDescendantNeedingCompositingRequirementsTraversal() ? "t"_s : "-"_s);
stream << (layer.hasDescendantNeedingUpdateBackingOrHierarchyTraversal() ? "b"_s : "-"_s);
stream << (layer.descendantsNeedCompositingRequirementsTraversal() ? "r"_s : "-"_s);
stream << (layer.subsequentLayersNeedCompositingRequirementsTraversal() ? "s"_s : "-"_s);
stream << (layer.descendantsNeedUpdateBackingAndHierarchyTraversal() ? "h"_s : "-"_s);
stream << (layer.needsCompositingPaintOrderChildrenUpdate() ? "o"_s : "-"_s);
stream << " "_s;
stream << (layer.needsPostLayoutCompositingUpdate() ? "l"_s : "-"_s);
stream << (layer.needsCompositingGeometryUpdate() ? "g"_s : "-"_s);
stream << (layer.childrenNeedCompositingGeometryUpdate() ? "k"_s : "-"_s);
stream << (layer.needsCompositingConfigurationUpdate() ? "c"_s : "-"_s);
stream << (layer.needsCompositingLayerConnection() ? "x"_s : "-"_s);
stream << (layer.needsScrollingTreeUpdate() ? "s"_s : "-"_s);
stream << " "_s;
stream << layer.boxScrollingScope();
stream << " "_s;
stream << layer.contentsScrollingScope();
stream << " "_s;
outputIdent(stream, depth);
stream << prefix;
auto layerRect = layer.rect();
stream << &layer << " "_s << layerRect;
if (auto* scrollableArea = layer.scrollableArea())
stream << " [SA "_s << scrollableArea << "]"_s;
if (layer.isComposited()) {
auto& backing = *layer.backing();
stream << " (layerID "_s << (backing.graphicsLayer()->primaryLayerID() ? backing.graphicsLayer()->primaryLayerID()->object().toUInt64() : 0) << ")"_s;
if (layer.indirectCompositingReason() != WebCore::IndirectCompositingReason::None)
stream << " "_s << layer.indirectCompositingReason();
auto scrollingNodeID = backing.scrollingNodeIDForRole(WebCore::ScrollCoordinationRole::Scrolling);
auto frameHostingNodeID = backing.scrollingNodeIDForRole(WebCore::ScrollCoordinationRole::FrameHosting);
auto pluginHostingNodeID = backing.scrollingNodeIDForRole(WebCore::ScrollCoordinationRole::PluginHosting);
auto viewportConstrainedNodeID = backing.scrollingNodeIDForRole(WebCore::ScrollCoordinationRole::ViewportConstrained);
auto positionedNodeID = backing.scrollingNodeIDForRole(WebCore::ScrollCoordinationRole::Positioning);
if (scrollingNodeID || frameHostingNodeID || viewportConstrainedNodeID || positionedNodeID) {
stream << " {"_s;
bool first = true;
if (scrollingNodeID) {
stream << "sc "_s << scrollingNodeID;
first = false;
}
if (frameHostingNodeID) {
if (!first)
stream << ", "_s;
stream << "fh "_s << frameHostingNodeID;
first = false;
}
if (pluginHostingNodeID) {
if (!first)
stream << ", "_s;
stream << "ph "_s << pluginHostingNodeID;
first = false;
}
if (viewportConstrainedNodeID) {
if (!first)
stream << ", "_s;
stream << "vc "_s << viewportConstrainedNodeID;
first = false;
}
if (positionedNodeID) {
if (!first)
stream << ", "_s;
stream << "pos "_s << positionedNodeID;
}
stream << "}"_s;
}
}
stream << " "_s << layer.name();
stream.nextLine();
const_cast<WebCore::RenderLayer&>(layer).updateLayerListsIfNeeded();
for (auto* child : layer.negativeZOrderLayers())
outputPaintOrderTreeRecursive(stream, *child, "- "_s, depth + 1);
for (auto* child : layer.normalFlowLayers())
outputPaintOrderTreeRecursive(stream, *child, "n "_s, depth + 1);
for (auto* child : layer.positiveZOrderLayers())
outputPaintOrderTreeRecursive(stream, *child, "+ "_s, depth + 1);
}
void showPaintOrderTree(const WebCore::RenderLayer* layer)
{
TextStream stream;
outputPaintOrderTreeLegend(stream);
if (layer)
outputPaintOrderTreeRecursive(stream, *layer, ""_s);
WTFLogAlways("%s", stream.release().utf8().data());
}
void showPaintOrderTree(const WebCore::RenderObject* renderer)
{
if (!renderer)
return;
showPaintOrderTree(renderer->enclosingLayer());
}
static void outputLayerPositionTreeLegend(TextStream& stream)
{
stream.nextLine();
stream << "Dirty flags: NeedsPosition(U)pdate, (D)escendantNeedsPositionUpdate, All(C)hildrenNeedPositionUpdate, (A)llDescendantsNeedPositionUpdate\n";
stream << "Repaint status: (-)NeedsNormalRepaint, Needs(F)ullRepaint, NeedsFullRepaintFor(P)ositionedMovementLayout\n";
stream << "Layer state: has(P)aginatedAncestor, has(F)ixedAncestor, hasFixedContaining(B)lockAncestor, has(T)ransformedAncestor, has(3)DTransformedAncestor, hasComposited(S)crollingAncestor, !is(V)isibilityHiddenOrOpacityZero(), isSelfPainting(L)ayer\n";
stream.nextLine();
}
void outputLayerPositionTreeRecursive(TextStream& stream, const WebCore::RenderLayer& layer, unsigned depth)
{
stream << (layer.m_layerPositionDirtyBits.contains(WebCore::RenderLayer::LayerPositionUpdates::NeedsPositionUpdate) ? "U"_s : "-"_s);
stream << (layer.m_layerPositionDirtyBits.contains(WebCore::RenderLayer::LayerPositionUpdates::DescendantNeedsPositionUpdate) ? "D"_s : "-"_s);
stream << (layer.m_layerPositionDirtyBits.contains(WebCore::RenderLayer::LayerPositionUpdates::AllChildrenNeedPositionUpdate) ? "C"_s : "-"_s);
stream << (layer.m_layerPositionDirtyBits.contains(WebCore::RenderLayer::LayerPositionUpdates::AllDescendantsNeedPositionUpdate) ? "A"_s : "-"_s);
stream << " "_s;
if (layer.repaintStatus() == WebCore::RepaintStatus::NeedsFullRepaintForPositionedMovementLayout)
stream << "P";
else if (layer.repaintStatus() == WebCore::RepaintStatus::NeedsFullRepaint)
stream << "F";
else
stream << "-";
stream << " "_s;
stream << (layer.hasPaginatedAncestor() ? "P"_s : "-"_s);
stream << (layer.hasFixedAncestor() ? "F"_s : "-"_s);
stream << (layer.hasFixedContainingBlockAncestor() ? "B"_s : "-"_s);
stream << (layer.hasTransformedAncestor() ? "T"_s : "-"_s);
stream << (layer.has3DTransformedAncestor() ? "3"_s : "-"_s);
stream << (layer.hasCompositedScrollingAncestor() ? "S"_s : "-"_s);
stream << (!layer.isVisibilityHiddenOrOpacityZero() ? "V"_s : "-"_s);
stream << (layer.isSelfPaintingLayer() ? "L"_s : "-"_s);
// FIXME: cached clip rects?
stream << " "_s;
outputIdent(stream, depth);
auto layerRect = layer.rect();
stream << &layer << " "_s << layerRect;
stream << " "_s << layer.name();
#if ASSERT_ENABLED || ENABLE(CONJECTURE_ASSERT)
if (layer.m_repaintContainer)
stream << " (repaint container: " << layer.m_repaintContainer.get() << ")";
#endif
if (layer.repaintRects())
stream << " (repaint rects " << *layer.repaintRects() << ")";
stream.nextLine();
for (WebCore::RenderLayer* child = layer.firstChild(); child; child = child->nextSibling())
outputLayerPositionTreeRecursive(stream, *child, depth + 1);
}
void showLayerPositionTree(const WebCore::RenderLayer* layer)
{
TextStream stream;
outputLayerPositionTreeLegend(stream);
if (layer)
outputLayerPositionTreeRecursive(stream, *layer, 0);
WTFLogAlways("%s", stream.release().utf8().data());
}
#endif
|