1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* structures that represent things to be painted (ordered in z-order),
* used during painting and hit testing
*/
#include "nsDisplayList.h"
#include <stdint.h>
#include <algorithm>
#include <limits>
#include "ActiveLayerTracker.h"
#include "BorderConsts.h"
#include "ImageContainer.h"
#include "LayerAnimationInfo.h"
#include "StickyScrollContainer.h"
#include "TextDrawTarget.h"
#include "UnitTransforms.h"
#include "gfxContext.h"
#include "gfxMatrix.h"
#include "gfxUtils.h"
#include "imgIContainer.h"
#include "mozilla/AnimationPerformanceWarning.h"
#include "mozilla/AnimationUtils.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/DisplayPortUtils.h"
#include "mozilla/EffectCompositor.h"
#include "mozilla/EffectSet.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/Likely.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/OperatorNewExtensions.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/ProfilerMarkers.h"
#include "mozilla/SVGClipPathFrame.h"
#include "mozilla/SVGIntegrationUtils.h"
#include "mozilla/SVGMaskFrame.h"
#include "mozilla/SVGObserverUtils.h"
#include "mozilla/SVGUtils.h"
#include "mozilla/ScrollContainerFrame.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/ShapeUtils.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_layers.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_print.h"
#include "mozilla/StyleAnimationValue.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/ViewportFrame.h"
#include "mozilla/ViewportUtils.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/HTMLCanvasElement.h"
#include "mozilla/dom/PerformanceMainThread.h"
#include "mozilla/dom/RemoteBrowser.h"
#include "mozilla/dom/SVGElement.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/ServiceWorkerRegistrar.h"
#include "mozilla/dom/ServiceWorkerRegistration.h"
#include "mozilla/dom/TouchEvent.h"
#include "mozilla/dom/ViewTransition.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/glean/GfxMetrics.h"
#include "mozilla/layers/AnimationHelper.h"
#include "mozilla/layers/CompositorThread.h"
#include "mozilla/layers/InputAPZContext.h"
#include "mozilla/layers/RenderRootStateManager.h"
#include "mozilla/layers/StackingContextHelper.h"
#include "mozilla/layers/TreeTraversal.h"
#include "mozilla/layers/WebRenderBridgeChild.h"
#include "mozilla/layers/WebRenderLayerManager.h"
#include "mozilla/layers/WebRenderMessages.h"
#include "mozilla/layers/WebRenderScrollData.h"
#include "nsCSSProps.h"
#include "nsCSSRendering.h"
#include "nsCSSRenderingGradients.h"
#include "nsCanvasFrame.h"
#include "nsCaret.h"
#include "nsCaseTreatment.h"
#include "nsDOMTokenList.h"
#include "nsEscape.h"
#include "nsFocusManager.h"
#include "nsIFrameInlines.h"
#include "nsImageFrame.h"
#include "nsLayoutUtils.h"
#include "nsPresContextInlines.h"
#include "nsPrintfCString.h"
#include "nsRefreshDriver.h"
#include "nsRegion.h"
#include "nsSliderFrame.h"
#include "nsStyleConsts.h"
#include "nsStyleStructInlines.h"
#include "nsStyleTransformMatrix.h"
#include "nsSubDocumentFrame.h"
#include "nsTableCellFrame.h"
#include "nsTableColFrame.h"
#include "nsTextFrame.h"
#include "nsTextPaintStyle.h"
#include "nsTransitionManager.h"
namespace mozilla {
using namespace dom;
using namespace gfx;
using namespace layout;
using namespace layers;
using namespace image;
LazyLogModule sContentDisplayListLog("dl.content");
LazyLogModule sParentDisplayListLog("dl.parent");
LazyLogModule& GetLoggerByProcess() {
return XRE_IsContentProcess() ? sContentDisplayListLog
: sParentDisplayListLog;
}
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
void AssertUniqueItem(nsDisplayItem* aItem) {
for (nsDisplayItem* i : aItem->Frame()->DisplayItems()) {
if (i != aItem && !i->HasDeletedFrame() && i->Frame() == aItem->Frame() &&
i->GetPerFrameKey() == aItem->GetPerFrameKey()) {
if (i->IsPreProcessedItem() || i->IsPreProcessed()) {
continue;
}
MOZ_DIAGNOSTIC_CRASH("Duplicate display item!");
}
}
}
#endif
bool ShouldBuildItemForEvents(const DisplayItemType aType) {
return aType == DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO ||
aType == DisplayItemType::TYPE_REMOTE ||
(GetDisplayItemFlagsForType(aType) & TYPE_IS_CONTAINER);
}
static bool ItemTypeSupportsHitTesting(const DisplayItemType aType) {
switch (aType) {
case DisplayItemType::TYPE_BACKGROUND:
case DisplayItemType::TYPE_BACKGROUND_COLOR:
case DisplayItemType::TYPE_THEMED_BACKGROUND:
return true;
default:
return false;
}
}
void InitializeHitTestInfo(nsDisplayListBuilder* aBuilder,
nsPaintedDisplayItem* aItem,
const DisplayItemType aType) {
if (ItemTypeSupportsHitTesting(aType)) {
aItem->InitializeHitTestInfo(aBuilder);
}
}
/* static */
already_AddRefed<ActiveScrolledRoot> ActiveScrolledRoot::GetOrCreateASRForFrame(
const ActiveScrolledRoot* aParent,
ScrollContainerFrame* aScrollContainerFrame,
nsTArray<RefPtr<ActiveScrolledRoot>>& aActiveScrolledRoots) {
RefPtr<ActiveScrolledRoot> asr =
aScrollContainerFrame->GetProperty(ActiveScrolledRootCache());
#ifdef DEBUG
if (asr && aActiveScrolledRoots.Contains(asr)) {
// If this is the second time we are called for this frame in this same
// paint, assert that we aren't changing any of the values. (The values can
// change *between* paints, but not during one paint.)
MOZ_ASSERT(asr->mParent == aParent);
MOZ_ASSERT(asr->mFrame == aScrollContainerFrame);
MOZ_ASSERT(asr->mKind == ASRKind::Scroll);
MOZ_ASSERT(asr->mDepth == (aParent ? aParent->mDepth + 1 : 1));
}
#endif
if (!asr) {
asr = new ActiveScrolledRoot();
RefPtr<ActiveScrolledRoot> ref = asr;
aScrollContainerFrame->SetProperty(ActiveScrolledRootCache(),
ref.forget().take());
aActiveScrolledRoots.AppendElement(asr);
}
asr->mParent = aParent;
asr->mFrame = aScrollContainerFrame;
asr->mKind = ASRKind::Scroll;
asr->mDepth = aParent ? aParent->mDepth + 1 : 1;
return asr.forget();
}
/* static */
already_AddRefed<ActiveScrolledRoot>
ActiveScrolledRoot::GetOrCreateASRForStickyFrame(
const ActiveScrolledRoot* aParent, nsIFrame* aStickyFrame,
nsTArray<RefPtr<ActiveScrolledRoot>>& aActiveScrolledRoots) {
aStickyFrame = aStickyFrame->FirstContinuation();
RefPtr<ActiveScrolledRoot> asr =
aStickyFrame->GetProperty(StickyActiveScrolledRootCache());
#ifdef DEBUG
if (asr && aActiveScrolledRoots.Contains(asr)) {
// If this is the second time we are called for this frame in this same
// paint, assert that we aren't changing any of the values. (The values can
// change *between* paints, but not during one paint.)
MOZ_ASSERT(asr->mParent == aParent);
MOZ_ASSERT(asr->mFrame == aStickyFrame);
MOZ_ASSERT(asr->mKind == ASRKind::Sticky);
MOZ_ASSERT(asr->mDepth == (aParent ? aParent->mDepth + 1 : 1));
}
#endif
if (!asr) {
asr = new ActiveScrolledRoot();
RefPtr<ActiveScrolledRoot> ref = asr;
aStickyFrame->SetProperty(StickyActiveScrolledRootCache(),
ref.forget().take());
aActiveScrolledRoots.AppendElement(asr);
}
asr->mParent = aParent;
asr->mFrame = aStickyFrame;
asr->mKind = ASRKind::Sticky;
asr->mDepth = aParent ? aParent->mDepth + 1 : 1;
return asr.forget();
}
/* static */
bool ActiveScrolledRoot::IsAncestor(const ActiveScrolledRoot* aAncestor,
const ActiveScrolledRoot* aDescendant) {
if (!aAncestor) {
// nullptr is the root
return true;
}
if (Depth(aAncestor) > Depth(aDescendant)) {
return false;
}
const ActiveScrolledRoot* asr = aDescendant;
while (asr) {
if (asr == aAncestor) {
return true;
}
asr = asr->mParent;
}
return false;
}
/* static */
bool ActiveScrolledRoot::IsProperAncestor(
const ActiveScrolledRoot* aAncestor,
const ActiveScrolledRoot* aDescendant) {
return aAncestor != aDescendant && IsAncestor(aAncestor, aDescendant);
}
ScrollContainerFrame* ActiveScrolledRoot::ScrollFrameOrNull() const {
if (mKind == ASRKind::Scroll) {
ScrollContainerFrame* scrollFrame =
static_cast<ScrollContainerFrame*>(mFrame);
MOZ_ASSERT(scrollFrame);
return scrollFrame;
}
return nullptr;
}
const ActiveScrolledRoot* ActiveScrolledRoot::GetNearestScrollASR() const {
const ActiveScrolledRoot* ret = this;
while (ret && ret->mKind != ASRKind::Scroll) {
ret = ret->mParent;
}
if (!ret || ret->mKind != ASRKind::Scroll) {
return nullptr;
}
return ret;
}
layers::ScrollableLayerGuid::ViewID
ActiveScrolledRoot::GetNearestScrollASRViewId() const {
const ActiveScrolledRoot* scrollASR = GetNearestScrollASR();
if (scrollASR) {
return scrollASR->GetViewId();
}
return ScrollableLayerGuid::NULL_SCROLL_ID;
}
/* static */
const ActiveScrolledRoot* ActiveScrolledRoot::GetStickyASRFromFrame(
nsIFrame* aStickyFrame) {
return aStickyFrame->FirstContinuation()->GetProperty(
StickyActiveScrolledRootCache());
}
/* static */
nsCString ActiveScrolledRoot::ToString(
const ActiveScrolledRoot* aActiveScrolledRoot) {
nsAutoCString str;
if (!aActiveScrolledRoot) {
str.AppendPrintf("null");
return str;
}
if (aActiveScrolledRoot->mKind == ASRKind::Sticky) {
str.AppendPrintf("sticky ");
}
for (const auto* asr = aActiveScrolledRoot; asr; asr = asr->mParent) {
str.AppendPrintf("<0x%p>", asr->mFrame);
if (asr->mParent) {
str.AppendLiteral(", ");
}
}
return std::move(str);
}
ScrollableLayerGuid::ViewID ActiveScrolledRoot::ComputeViewId() const {
const ActiveScrolledRoot* scrollASR = GetNearestScrollASR();
MOZ_ASSERT(scrollASR,
"ComputeViewId() called on ASR with no enclosing scroll frame");
nsIContent* content = scrollASR->ScrollFrame()->GetContent();
return nsLayoutUtils::FindOrCreateIDFor(content);
}
ActiveScrolledRoot::~ActiveScrolledRoot() {
if (mFrame) {
mFrame->RemoveProperty(mKind == ASRKind::Sticky
? StickyActiveScrolledRootCache()
: ActiveScrolledRootCache());
}
}
static uint64_t AddAnimationsForWebRender(
nsDisplayItem* aItem, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder,
const Maybe<LayoutDevicePoint>& aPosition = Nothing()) {
auto* effects = EffectSet::GetForFrame(aItem->Frame(), aItem->GetType());
if (!effects || effects->IsEmpty()) {
// If there is no animation on the nsIFrame, that means
// 1) we've never created any animations on this frame or
// 2) the frame was reconstruced or
// 3) all animations on the frame have finished
// in such cases we don't need do anything here.
//
// Even if there is a WebRenderAnimationData for the display item type on
// this frame, it's going to be discarded since it's not marked as being
// used.
return 0;
}
RefPtr<WebRenderAnimationData> animationData =
aManager->CommandBuilder()
.CreateOrRecycleWebRenderUserData<WebRenderAnimationData>(aItem);
AnimationInfo& animationInfo = animationData->GetAnimationInfo();
nsIFrame* frame = aItem->Frame();
animationInfo.AddAnimationsForDisplayItem(
frame, aDisplayListBuilder, aItem, aItem->GetType(),
aManager->LayerManager(), aPosition);
// Note that animationsId can be 0 (uninitialized in AnimationInfo) if there
// are no active animations.
uint64_t animationsId = animationInfo.GetCompositorAnimationsId();
if (!animationInfo.GetAnimations().IsEmpty()) {
OpAddCompositorAnimations anim(
CompositorAnimations(animationInfo.GetAnimations(), animationsId));
aManager->WrBridge()->AddWebRenderParentCommand(anim);
aManager->AddActiveCompositorAnimationId(animationsId);
} else if (animationsId) {
aManager->AddCompositorAnimationsIdForDiscard(animationsId);
animationsId = 0;
}
return animationsId;
}
static bool GenerateAndPushTextMask(nsIFrame* aFrame, gfxContext* aContext,
const nsRect& aFillRect,
nsDisplayListBuilder* aBuilder) {
if (aBuilder->IsForGenerateGlyphMask()) {
return false;
}
SVGObserverUtils::GetAndObserveBackgroundClip(aFrame);
// The main function of enabling background-clip:text property value.
// When a nsDisplayBackgroundImage detects "text" bg-clip style, it will call
// this function to
// 1. Generate a mask by all descendant text frames
// 2. Push the generated mask into aContext.
gfxContext* sourceCtx = aContext;
LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
aFillRect, aFrame->PresContext()->AppUnitsPerDevPixel());
// Create a mask surface.
RefPtr<DrawTarget> sourceTarget = sourceCtx->GetDrawTarget();
RefPtr<DrawTarget> maskDT = sourceTarget->CreateClippedDrawTarget(
bounds.ToUnknownRect(), SurfaceFormat::A8);
if (!maskDT || !maskDT->IsValid()) {
return false;
}
gfxContext maskCtx(maskDT, /* aPreserveTransform */ true);
maskCtx.Multiply(Matrix::Translation(bounds.TopLeft().ToUnknownPoint()));
// Shade text shape into mask A8 surface.
nsLayoutUtils::PaintFrame(
&maskCtx, aFrame, nsRect(nsPoint(0, 0), aFrame->GetSize()),
NS_RGB(255, 255, 255), nsDisplayListBuilderMode::GenerateGlyph);
// Push the generated mask into aContext, so that the caller can pop and
// blend with it.
Matrix currentMatrix = sourceCtx->CurrentMatrix();
Matrix invCurrentMatrix = currentMatrix;
invCurrentMatrix.Invert();
RefPtr<SourceSurface> maskSurface = maskDT->Snapshot();
sourceCtx->PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, 1.0,
maskSurface, invCurrentMatrix);
return true;
}
nsDisplayWrapper* nsDisplayWrapList::CreateShallowCopy(
nsDisplayListBuilder* aBuilder) {
const nsDisplayWrapList* wrappedItem = AsDisplayWrapList();
MOZ_ASSERT(wrappedItem);
// Create a new nsDisplayWrapList using a copy-constructor. This is done
// to preserve the information about bounds.
nsDisplayWrapper* wrapper =
new (aBuilder) nsDisplayWrapper(aBuilder, *wrappedItem);
wrapper->SetType(nsDisplayWrapper::ItemType());
MOZ_ASSERT(wrapper);
// Set the display list pointer of the new wrapper item to the display list
// of the wrapped item.
wrapper->mListPtr = wrappedItem->mListPtr;
return wrapper;
}
nsDisplayWrapList* nsDisplayListBuilder::MergeItems(
nsTArray<nsDisplayItem*>& aItems) {
// For merging, we create a temporary item by cloning the last item of the
// mergeable items list. This ensures that the temporary item will have the
// correct frame and bounds.
nsDisplayWrapList* last = aItems.PopLastElement()->AsDisplayWrapList();
MOZ_ASSERT(last);
nsDisplayWrapList* merged = last->Clone(this);
MOZ_ASSERT(merged);
AddTemporaryItem(merged);
// Create nsDisplayWrappers that point to the internal display lists of the
// items we are merging. These nsDisplayWrappers are added to the display list
// of the temporary item.
for (nsDisplayItem* item : aItems) {
MOZ_ASSERT(item);
MOZ_ASSERT(merged->CanMerge(item));
merged->Merge(item);
MOZ_ASSERT(item->AsDisplayWrapList());
merged->GetChildren()->AppendToTop(
static_cast<nsDisplayWrapList*>(item)->CreateShallowCopy(this));
}
merged->GetChildren()->AppendToTop(last->CreateShallowCopy(this));
return merged;
}
// FIXME(emilio): This whole business should ideally not be needed at all, but
// there are a variety of hard-to-deal-with caret invalidation issues, like
// bug 1888583, and caret changes are relatively uncommon, enough that it
// probably isn't worth chasing all them down.
void nsDisplayListBuilder::InvalidateCaretFramesIfNeeded() {
if (mPaintedCarets.IsEmpty()) {
return;
}
size_t i = mPaintedCarets.Length();
while (i--) {
nsCaret* caret = mPaintedCarets[i];
nsIFrame* oldCaret = caret->GetLastPaintedFrame();
nsIFrame* currentCaret = caret->GetPaintGeometry();
if (oldCaret == currentCaret) {
// Keep tracking this caret, it hasn't changed.
continue;
}
if (oldCaret) {
oldCaret->MarkNeedsDisplayItemRebuild();
}
if (currentCaret) {
currentCaret->MarkNeedsDisplayItemRebuild();
}
// If / when we paint this caret, we'll track it again.
caret->SetLastPaintedFrame(nullptr);
mPaintedCarets.RemoveElementAt(i);
}
}
void nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter::
SetCurrentActiveScrolledRoot(
const ActiveScrolledRoot* aActiveScrolledRoot) {
MOZ_ASSERT(!mUsed);
// Set the builder's mCurrentActiveScrolledRoot.
mBuilder->mCurrentActiveScrolledRoot = aActiveScrolledRoot;
// We also need to adjust the builder's mCurrentContainerASR.
// mCurrentContainerASR needs to be an ASR that all the container's
// contents have finite bounds with respect to. If aActiveScrolledRoot
// is an ancestor ASR of mCurrentContainerASR, that means we need to
// set mCurrentContainerASR to aActiveScrolledRoot, because otherwise
// the items that will be created with aActiveScrolledRoot wouldn't
// have finite bounds with respect to mCurrentContainerASR. There's one
// exception, in the case where there's a content clip on the builder
// that is scrolled by a descendant ASR of aActiveScrolledRoot. This
// content clip will clip all items that are created while this
// AutoCurrentActiveScrolledRootSetter exists. This means that the items
// created during our lifetime will have finite bounds with respect to
// the content clip's ASR, even if the items' actual ASR is an ancestor
// of that. And it also means that mCurrentContainerASR only needs to be
// set to the content clip's ASR and not all the way to aActiveScrolledRoot.
// This case is tested by fixed-pos-scrolled-clip-opacity-layerize.html
// and fixed-pos-scrolled-clip-opacity-inside-layerize.html.
// finiteBoundsASR is the leafmost ASR that all items created during
// object's lifetime have finite bounds with respect to.
// TODO(bug 2001862): Explanation may need revising.
const ActiveScrolledRoot* finiteBoundsASR = aActiveScrolledRoot;
if (!mBuilder->IsInViewTransitionCapture()) {
finiteBoundsASR =
ActiveScrolledRoot::IsAncestor(aActiveScrolledRoot, mContentClipASR)
? mContentClipASR
: aActiveScrolledRoot;
}
// mCurrentContainerASR is adjusted so that it's still an ancestor of
// finiteBoundsASR.
mBuilder->mCurrentContainerASR = ActiveScrolledRoot::PickAncestor(
mBuilder->mCurrentContainerASR, finiteBoundsASR);
// If we are entering out-of-flow content inside a CSS filter, mark
// scroll frames wrt. which the content is fixed as containing such content.
if (mBuilder->mFilterASR && ActiveScrolledRoot::IsAncestor(
aActiveScrolledRoot, mBuilder->mFilterASR)) {
for (const ActiveScrolledRoot* asr = mBuilder->mFilterASR;
asr && asr != aActiveScrolledRoot; asr = asr->mParent) {
if (ScrollContainerFrame* scrollFrame = asr->ScrollFrameOrNull()) {
scrollFrame->SetHasOutOfFlowContentInsideFilter();
}
}
}
mUsed = true;
}
void nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter::
InsertScrollFrame(ScrollContainerFrame* aScrollContainerFrame) {
MOZ_ASSERT(!mUsed);
size_t descendantsEndIndex = mBuilder->mActiveScrolledRoots.Length();
const ActiveScrolledRoot* parentASR = mBuilder->mCurrentActiveScrolledRoot;
const ActiveScrolledRoot* asr =
mBuilder->GetOrCreateActiveScrolledRoot(parentASR, aScrollContainerFrame);
mBuilder->mCurrentActiveScrolledRoot = asr;
// All child ASRs of parentASR that were created while this
// AutoCurrentActiveScrolledRootSetter object was on the stack belong to us
// now. Reparent them to asr.
for (size_t i = mDescendantsStartIndex; i < descendantsEndIndex; i++) {
ActiveScrolledRoot* descendantASR = mBuilder->mActiveScrolledRoots[i];
if (ActiveScrolledRoot::IsAncestor(parentASR, descendantASR)) {
descendantASR->IncrementDepth();
if (descendantASR->mParent == parentASR) {
descendantASR->mParent = asr;
}
}
}
mUsed = true;
}
nsDisplayListBuilder::AutoContainerASRTracker::AutoContainerASRTracker(
nsDisplayListBuilder* aBuilder)
: mBuilder(aBuilder), mSavedContainerASR(aBuilder->mCurrentContainerASR) {
mBuilder->mCurrentContainerASR = mBuilder->mCurrentActiveScrolledRoot;
}
nsPresContext* nsDisplayListBuilder::CurrentPresContext() {
return CurrentPresShellState()->mPresShell->GetPresContext();
}
/* static */
nsRect nsDisplayListBuilder::OutOfFlowDisplayData::ComputeVisibleRectForFrame(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
const nsRect& aVisibleRect, const nsRect& aDirtyRect,
nsRect* aOutDirtyRect) {
nsRect visible = aVisibleRect;
nsRect dirtyRectRelativeToDirtyFrame = aDirtyRect;
bool inPartialUpdate =
aBuilder->IsRetainingDisplayList() && aBuilder->IsPartialUpdate();
if (MOZ_LIKELY(StaticPrefs::apz_allow_zooming()) &&
aBuilder->IsPaintingToWindow() && !inPartialUpdate &&
DisplayPortUtils::IsFixedPosFrameInDisplayPort(aFrame)) {
dirtyRectRelativeToDirtyFrame =
nsRect(nsPoint(0, 0), aFrame->GetParent()->GetSize());
// If there's a visual viewport size set, restrict the amount of the
// fixed-position element we paint to the visual viewport. (In general
// the fixed-position element can be as large as the layout viewport,
// which at a high zoom level can cause us to paint too large of an
// area.)
PresShell* presShell = aFrame->PresShell();
if (presShell->IsVisualViewportSizeSet()) {
dirtyRectRelativeToDirtyFrame =
nsRect(presShell->GetVisualViewportOffsetRelativeToLayoutViewport(),
presShell->GetVisualViewportSize());
// But if we have a displayport, expand it to the displayport, so
// that async-scrolling the visual viewport within the layout viewport
// will not checkerboard.
if (nsIFrame* rootScrollContainerFrame =
presShell->GetRootScrollContainerFrame()) {
nsRect displayport;
// Note that the displayport here is already in the right coordinate
// space: it's relative to the scroll port (= layout viewport), but
// covers the visual viewport with some margins around it, which is
// exactly what we want.
if (DisplayPortUtils::GetDisplayPort(
rootScrollContainerFrame->GetContent(), &displayport,
DisplayPortOptions().With(ContentGeometryType::Fixed))) {
dirtyRectRelativeToDirtyFrame = displayport;
}
}
}
visible = dirtyRectRelativeToDirtyFrame;
if (StaticPrefs::apz_test_logging_enabled() &&
presShell->GetDocument()->IsContentDocument()) {
nsLayoutUtils::LogAdditionalTestData(
aBuilder, "fixedPosDisplayport",
ToString(CSSSize::FromAppUnits(visible)));
}
}
*aOutDirtyRect = dirtyRectRelativeToDirtyFrame - aFrame->GetPosition();
visible -= aFrame->GetPosition();
nsRect overflowRect = aFrame->InkOverflowRect();
if (aFrame->IsTransformed() && EffectCompositor::HasAnimationsForCompositor(
aFrame, DisplayItemType::TYPE_TRANSFORM)) {
/**
* Add a fuzz factor to the overflow rectangle so that elements only
* just out of view are pulled into the display list, so they can be
* prerendered if necessary.
*/
overflowRect.Inflate(nsPresContext::CSSPixelsToAppUnits(32));
}
visible.IntersectRect(visible, overflowRect);
aOutDirtyRect->IntersectRect(*aOutDirtyRect, overflowRect);
return visible;
}
nsDisplayListBuilder::Linkifier::Linkifier(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
nsDisplayList* aList)
: mList(aList) {
// Find the element that we need to check for link-ness, bailing out if
// we can't find one.
Element* elem = Element::FromNodeOrNull(aFrame->GetContent());
if (!elem) {
return;
}
// If the element has an id and/or name attribute, generate a destination
// for possible internal linking.
auto maybeGenerateDest = [&](const nsAtom* aAttr) {
nsAutoString attrValue;
elem->GetAttr(aAttr, attrValue);
if (!attrValue.IsEmpty()) {
NS_ConvertUTF16toUTF8 dest(attrValue);
// Ensure that we only emit a given destination once, although there may
// be multiple frames associated with a given element; we'll simply use
// the first of them as the target of any links to it.
// XXX(jfkthame) This prevents emitting duplicate destinations *on the
// same page*, but does not prevent duplicates on subsequent pages, as
// each new page is handled by a new temporary DisplayListBuilder. This
// seems to be harmless in practice, though a bit wasteful of space. To
// fix, we need to maintain the set of already-seen destinations globally
// for the print job, rather than attached to the (per-page) builder.
if (aBuilder->mDestinations.EnsureInserted(dest)) {
auto* destination = MakeDisplayItem<nsDisplayDestination>(
aBuilder, aFrame, dest.get(), aFrame->GetRect().TopLeft());
mList->AppendToTop(destination);
}
}
};
if (StaticPrefs::print_save_as_pdf_internal_destinations_enabled()) {
if (elem->HasID()) {
maybeGenerateDest(nsGkAtoms::id);
}
if (elem->HasName()) {
maybeGenerateDest(nsGkAtoms::name);
}
}
// Links don't nest, so if the builder already has a destination, no need to
// check for a link element here.
if (!aBuilder->mLinkURI.IsEmpty() || !aBuilder->mLinkDest.IsEmpty()) {
return;
}
// Check if we have actually found a link.
if (!elem->IsLink()) {
return;
}
nsCOMPtr<nsIURI> uri = elem->GetHrefURI();
if (!uri) {
return;
}
// Is it potentially a local (in-document) destination?
bool hasRef, eqExRef;
nsIURI* docURI;
if (StaticPrefs::print_save_as_pdf_internal_destinations_enabled() &&
NS_SUCCEEDED(uri->GetHasRef(&hasRef)) && hasRef &&
(docURI = aFrame->PresContext()->Document()->GetDocumentURI()) &&
NS_SUCCEEDED(uri->EqualsExceptRef(docURI, &eqExRef)) && eqExRef) {
// Try to get a local destination name. If this fails, we'll leave the
// mLinkDest string empty, but still try to set mLinkURI below.
if (NS_FAILED(uri->GetRef(aBuilder->mLinkDest))) {
aBuilder->mLinkDest.Truncate();
}
// The destination name is simply a string; we don't want URL-escaping
// applied to it.
if (!aBuilder->mLinkDest.IsEmpty()) {
NS_UnescapeURL(aBuilder->mLinkDest);
}
}
if (NS_FAILED(uri->GetSpec(aBuilder->mLinkURI))) {
aBuilder->mLinkURI.Truncate();
}
// If we didn't get either kind of destination, we won't try to linkify at
// this level.
if (aBuilder->mLinkDest.IsEmpty() && aBuilder->mLinkURI.IsEmpty()) {
return;
}
// Record that we need to reset the builder's state on destruction.
mBuilderToReset = aBuilder;
}
void nsDisplayListBuilder::Linkifier::MaybeAppendLink(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame) {
// Note that we may generate a link here even if the constructor bailed out
// without updating aBuilder->mLinkURI/Dest, because it may have been set by
// an ancestor that was associated with a link element.
if (!aBuilder->mLinkURI.IsEmpty() || !aBuilder->mLinkDest.IsEmpty()) {
auto* link = MakeDisplayItem<nsDisplayLink>(
aBuilder, aFrame, aBuilder->mLinkDest.get(), aBuilder->mLinkURI.get(),
aFrame->GetRect());
mList->AppendToTop(link);
}
}
uint32_t nsDisplayListBuilder::sPaintSequenceNumber(1);
nsDisplayListBuilder::nsDisplayListBuilder(nsIFrame* aReferenceFrame,
nsDisplayListBuilderMode aMode,
bool aBuildCaret,
bool aRetainingDisplayList)
: mReferenceFrame(aReferenceFrame),
mIgnoreScrollFrame(nullptr),
mCurrentActiveScrolledRoot(nullptr),
mCurrentContainerASR(nullptr),
mCurrentFrame(aReferenceFrame),
mCurrentReferenceFrame(aReferenceFrame),
mScrollInfoItemsForHoisting(nullptr),
mFirstClipChainToDestroy(nullptr),
mTableBackgroundSet(nullptr),
mCurrentScrollParentId(ScrollableLayerGuid::NULL_SCROLL_ID),
mCurrentScrollbarTarget(ScrollableLayerGuid::NULL_SCROLL_ID),
mFilterASR(nullptr),
mDirtyRect(-1, -1, -1, -1),
mMode(aMode),
mIsBuildingScrollbar(false),
mCurrentScrollbarWillHaveLayer(false),
mBuildCaret(aBuildCaret),
mRetainingDisplayList(aRetainingDisplayList),
mPartialUpdate(false),
mIgnoreSuppression(false),
mIncludeAllOutOfFlows(false),
mDescendIntoSubdocuments(true),
mSelectedFramesOnly(false),
mAllowMergingAndFlattening(true),
mInTransform(false),
mInEventsOnly(false),
mInFilter(false),
mInViewTransitionCapture(false),
mIsInChromePresContext(false),
mSyncDecodeImages(false),
mIsPaintingToWindow(false),
mAsyncPanZoomEnabled(nsLayoutUtils::AsyncPanZoomEnabled(aReferenceFrame)),
mUseHighQualityScaling(false),
mIsPaintingForWebRender(false),
mAncestorHasApzAwareEventHandler(false),
mHaveScrollableDisplayPort(false),
mWindowDraggingAllowed(false),
mIsBuildingForPopup(nsLayoutUtils::IsPopup(aReferenceFrame)),
mForceLayerForScrollParent(false),
mContainsNonMinimalDisplayPort(false),
mBuildingInvisibleItems(false),
mIsBuilding(false),
mInInvalidSubtree(false),
mDisablePartialUpdates(false),
mPartialBuildFailed(false),
mIsInActiveDocShell(false),
mBuildAsyncZoomContainer(false),
mIsRelativeToLayoutViewport(false),
mUseOverlayScrollbars(false),
mAlwaysLayerizeScrollbars(false),
mIsDestroying(false) {
MOZ_COUNT_CTOR(nsDisplayListBuilder);
ShouldRebuildDisplayListDueToPrefChange();
mUseOverlayScrollbars =
!!LookAndFeel::GetInt(LookAndFeel::IntID::UseOverlayScrollbars);
mAlwaysLayerizeScrollbars =
StaticPrefs::layout_scrollbars_always_layerize_track();
static_assert(
static_cast<uint32_t>(DisplayItemType::TYPE_MAX) < (1 << TYPE_BITS),
"Check TYPE_MAX should not overflow");
mIsReusingStackingContextItems =
mRetainingDisplayList && StaticPrefs::layout_display_list_retain_sc();
}
void nsDisplayListBuilder::BeginFrame() {
nsCSSRendering::BeginFrameTreesLocked();
mIsPaintingToWindow = false;
mUseHighQualityScaling = false;
mIgnoreSuppression = false;
mInTransform = false;
mInFilter = false;
mSyncDecodeImages = false;
}
void nsDisplayListBuilder::EndFrame() {
NS_ASSERTION(!mInInvalidSubtree,
"Someone forgot to cleanup mInInvalidSubtree!");
mCurrentContainerASR = nullptr;
mActiveScrolledRoots.Clear();
FreeClipChains();
FreeTemporaryItems();
mAsyncScrollsWithAnchor.Clear();
nsCSSRendering::EndFrameTreesLocked();
}
void nsDisplayListBuilder::MarkFrameForDisplay(nsIFrame* aFrame,
const nsIFrame* aStopAtFrame) {
mFramesMarkedForDisplay.AppendElement(aFrame);
for (nsIFrame* f = aFrame; f;
f = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(f)) {
if (f->HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) {
return;
}
f->AddStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO);
if (f == aStopAtFrame) {
// we've reached a frame that we know will be painted, so we can stop.
break;
}
}
}
void nsDisplayListBuilder::AddFrameMarkedForDisplayIfVisible(nsIFrame* aFrame) {
mFramesMarkedForDisplayIfVisible.AppendElement(aFrame);
}
static void MarkFrameForDisplayIfVisibleInternal(nsIFrame* aFrame,
const nsIFrame* aStopAtFrame) {
for (nsIFrame* f = aFrame; f; f = nsLayoutUtils::GetDisplayListParent(f)) {
if (f->ForceDescendIntoIfVisible()) {
return;
}
f->SetForceDescendIntoIfVisible(true);
// This condition must match the condition in
// nsLayoutUtils::GetParentOrPlaceholderFor which is used by
// nsLayoutUtils::GetDisplayListParent
if (f->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) && !f->GetPrevInFlow()) {
nsIFrame* parent = f->GetParent();
if (parent && !parent->ForceDescendIntoIfVisible()) {
// If the GetDisplayListParent call is going to walk to a placeholder,
// in rare cases the placeholder might be contained in a different
// continuation from the oof. So we have to make sure to mark the oofs
// parent. In the common case this doesn't make us do any extra work,
// just changes the order in which we visit the frames since walking
// through placeholders will walk through the parent, and we stop when
// we find a ForceDescendIntoIfVisible bit set.
MarkFrameForDisplayIfVisibleInternal(parent, aStopAtFrame);
}
}
if (f == aStopAtFrame) {
// we've reached a frame that we know will be painted, so we can stop.
break;
}
}
}
void nsDisplayListBuilder::MarkFrameForDisplayIfVisible(
nsIFrame* aFrame, const nsIFrame* aStopAtFrame) {
AddFrameMarkedForDisplayIfVisible(aFrame);
MarkFrameForDisplayIfVisibleInternal(aFrame, aStopAtFrame);
}
void nsDisplayListBuilder::SetIsRelativeToLayoutViewport() {
mIsRelativeToLayoutViewport = true;
UpdateShouldBuildAsyncZoomContainer();
}
void nsDisplayListBuilder::ForceLayerForScrollParent() {
mForceLayerForScrollParent = true;
mNumActiveScrollframesEncountered++;
}
void nsDisplayListBuilder::UpdateShouldBuildAsyncZoomContainer() {
const Document* document = mReferenceFrame->PresContext()->Document();
mBuildAsyncZoomContainer = !mIsRelativeToLayoutViewport &&
!document->Fullscreen() &&
nsLayoutUtils::AllowZoomingForDocument(document);
// If mIsRelativeToLayoutViewport == false, hit-testing on this
// display list will take into account the pres shell resolution.
// If we're not building an async zoom container (meaning, the
// resolution will not take effect visually), the resolution better
// be 1.0, otherwise rendering and hit-testing are out of sync.
#ifdef DEBUG
if (!mIsRelativeToLayoutViewport && !mBuildAsyncZoomContainer) {
MOZ_ASSERT(document->GetPresShell()->GetResolution() == 1.0f);
}
#endif
}
// Certain prefs may cause display list items to be added or removed when they
// are toggled. In those cases, we need to fully rebuild the display list.
bool nsDisplayListBuilder::ShouldRebuildDisplayListDueToPrefChange() {
// If we transition between wrapping the RCD-RSF contents into an async
// zoom container vs. not, we need to rebuild the display list. This only
// happens when the zooming or container scrolling prefs are toggled
// (manually by the user, or during test setup).
bool didBuildAsyncZoomContainer = mBuildAsyncZoomContainer;
UpdateShouldBuildAsyncZoomContainer();
bool hadOverlayScrollbarsLastTime = mUseOverlayScrollbars;
mUseOverlayScrollbars =
!!LookAndFeel::GetInt(LookAndFeel::IntID::UseOverlayScrollbars);
bool alwaysLayerizedScrollbarsLastTime = mAlwaysLayerizeScrollbars;
mAlwaysLayerizeScrollbars =
StaticPrefs::layout_scrollbars_always_layerize_track();
bool oldShouldActivateAllScrollFrames = mShouldActivateAllScrollFrames;
mShouldActivateAllScrollFrames =
ScrollContainerFrame::ShouldActivateAllScrollFrames(nullptr,
mReferenceFrame);
if (didBuildAsyncZoomContainer != mBuildAsyncZoomContainer) {
return true;
}
if (hadOverlayScrollbarsLastTime != mUseOverlayScrollbars) {
return true;
}
if (alwaysLayerizedScrollbarsLastTime != mAlwaysLayerizeScrollbars) {
return true;
}
if (oldShouldActivateAllScrollFrames != mShouldActivateAllScrollFrames) {
return true;
}
return false;
}
void nsDisplayListBuilder::AddScrollContainerFrameToNotify(
ScrollContainerFrame* aScrollContainerFrame) {
mScrollContainerFramesToNotify.insert(aScrollContainerFrame);
}
void nsDisplayListBuilder::NotifyAndClearScrollContainerFrames() {
for (const auto& it : mScrollContainerFramesToNotify) {
it->NotifyApzTransaction();
}
mScrollContainerFramesToNotify.clear();
}
bool nsDisplayListBuilder::MarkOutOfFlowFrameForDisplay(
nsIFrame* aDirtyFrame, nsIFrame* aFrame, const nsRect& aVisibleRect,
const nsRect& aDirtyRect) {
MOZ_ASSERT(aFrame->GetParent() == aDirtyFrame);
nsRect dirty;
nsRect visible = OutOfFlowDisplayData::ComputeVisibleRectForFrame(
this, aFrame, aVisibleRect, aDirtyRect, &dirty);
if (!aFrame->HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO) &&
visible.IsEmpty()) {
return false;
}
// Only MarkFrameForDisplay if we're dirty. If this is a nested out-of-flow
// frame, then it will also mark any outer frames to ensure that building
// reaches the dirty feame.
if (!dirty.IsEmpty() || aFrame->ForceDescendIntoIfVisible()) {
MarkFrameForDisplay(aFrame, aDirtyFrame);
}
return true;
}
static void UnmarkFrameForDisplay(nsIFrame* aFrame,
const nsIFrame* aStopAtFrame) {
for (nsIFrame* f = aFrame; f;
f = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(f)) {
if (!f->HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) {
return;
}
f->RemoveStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO);
if (f == aStopAtFrame) {
// we've reached a frame that we know will be painted, so we can stop.
break;
}
}
}
static void UnmarkFrameForDisplayIfVisible(nsIFrame* aFrame) {
for (nsIFrame* f = aFrame; f; f = nsLayoutUtils::GetDisplayListParent(f)) {
if (!f->ForceDescendIntoIfVisible()) {
return;
}
f->SetForceDescendIntoIfVisible(false);
// This condition must match the condition in
// nsLayoutUtils::GetParentOrPlaceholderFor which is used by
// nsLayoutUtils::GetDisplayListParent
if (f->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) && !f->GetPrevInFlow()) {
nsIFrame* parent = f->GetParent();
if (parent && parent->ForceDescendIntoIfVisible()) {
// If the GetDisplayListParent call is going to walk to a placeholder,
// in rare cases the placeholder might be contained in a different
// continuation from the oof. So we have to make sure to mark the oofs
// parent. In the common case this doesn't make us do any extra work,
// just changes the order in which we visit the frames since walking
// through placeholders will walk through the parent, and we stop when
// we find a ForceDescendIntoIfVisible bit set.
UnmarkFrameForDisplayIfVisible(f);
}
}
}
}
nsDisplayListBuilder::~nsDisplayListBuilder() {
NS_ASSERTION(mFramesMarkedForDisplay.Length() == 0,
"All frames should have been unmarked");
NS_ASSERTION(mFramesWithOOFData.Length() == 0,
"All OOF data should have been removed");
NS_ASSERTION(mPresShellStates.Length() == 0,
"All presshells should have been exited");
DisplayItemClipChain* c = mFirstClipChainToDestroy;
while (c) {
DisplayItemClipChain* next = c->mNextClipChainToDestroy;
c->DisplayItemClipChain::~DisplayItemClipChain();
c = next;
}
MOZ_COUNT_DTOR(nsDisplayListBuilder);
}
uint32_t nsDisplayListBuilder::GetBackgroundPaintFlags() {
uint32_t flags = 0;
if (mSyncDecodeImages) {
flags |= nsCSSRendering::PAINTBG_SYNC_DECODE_IMAGES;
}
if (mIsPaintingToWindow) {
flags |= nsCSSRendering::PAINTBG_TO_WINDOW;
}
if (mUseHighQualityScaling) {
flags |= nsCSSRendering::PAINTBG_HIGH_QUALITY_SCALING;
}
return flags;
}
// TODO(emilio): Maybe unify BackgroundPaintFlags and IamgeRendererFlags.
uint32_t nsDisplayListBuilder::GetImageRendererFlags() const {
uint32_t flags = 0;
if (mSyncDecodeImages) {
flags |= nsImageRenderer::FLAG_SYNC_DECODE_IMAGES;
}
if (mIsPaintingToWindow) {
flags |= nsImageRenderer::FLAG_PAINTING_TO_WINDOW;
}
if (mUseHighQualityScaling) {
flags |= nsImageRenderer::FLAG_HIGH_QUALITY_SCALING;
}
return flags;
}
uint32_t nsDisplayListBuilder::GetImageDecodeFlags() const {
uint32_t flags = imgIContainer::FLAG_ASYNC_NOTIFY;
if (mSyncDecodeImages) {
flags |= imgIContainer::FLAG_SYNC_DECODE;
} else {
flags |= imgIContainer::FLAG_SYNC_DECODE_IF_FAST;
}
if (mIsPaintingToWindow || mUseHighQualityScaling) {
flags |= imgIContainer::FLAG_HIGH_QUALITY_SCALING;
}
return flags;
}
nsCaret* nsDisplayListBuilder::GetCaret() {
RefPtr<nsCaret> caret = CurrentPresShellState()->mPresShell->GetCaret();
return caret;
}
void nsDisplayListBuilder::IncrementPresShellPaintCount(PresShell* aPresShell) {
if (mIsPaintingToWindow) {
aPresShell->IncrementPaintCount();
}
}
void nsDisplayListBuilder::EnterPresShell(const nsIFrame* aReferenceFrame,
bool aPointerEventsNoneDoc) {
PresShellState* state = mPresShellStates.AppendElement();
state->mPresShell = aReferenceFrame->PresShell();
state->mFirstFrameMarkedForDisplay = mFramesMarkedForDisplay.Length();
state->mFirstFrameWithOOFData = mFramesWithOOFData.Length();
ScrollContainerFrame* sf = state->mPresShell->GetRootScrollContainerFrame();
if (sf && IsInSubdocument()) {
// We are forcing a rebuild of nsDisplayCanvasBackgroundColor to make sure
// that the canvas background color will be set correctly, and that only one
// unscrollable item will be created.
// This is done to avoid, for example, a case where only scrollbar frames
// are invalidated - we would skip creating nsDisplayCanvasBackgroundColor
// and possibly end up with an extra nsDisplaySolidColor item.
// We skip this for the root document, since we don't want to use
// MarkFrameForDisplayIfVisible before ComputeRebuildRegion. We'll
// do it manually there.
nsCanvasFrame* canvasFrame = do_QueryFrame(sf->GetScrolledFrame());
if (canvasFrame) {
MarkFrameForDisplayIfVisible(canvasFrame, aReferenceFrame);
}
}
#ifdef DEBUG
state->mAutoLayoutPhase.emplace(aReferenceFrame->PresContext(),
nsLayoutPhase::DisplayListBuilding);
#endif
if (!IsForEventDelivery()) {
state->mPresShell->UpdateCanvasBackground();
}
bool buildCaret = mBuildCaret;
if (mIgnoreSuppression || !state->mPresShell->IsPaintingSuppressed()) {
state->mIsBackgroundOnly = false;
} else {
state->mIsBackgroundOnly = true;
buildCaret = false;
}
bool pointerEventsNone = aPointerEventsNoneDoc;
if (IsInSubdocument()) {
pointerEventsNone |= mPresShellStates[mPresShellStates.Length() - 2]
.mInsidePointerEventsNoneDoc;
}
state->mInsidePointerEventsNoneDoc = pointerEventsNone;
state->mPresShellIgnoreScrollFrame =
state->mPresShell->IgnoringViewportScrolling()
? state->mPresShell->GetRootScrollContainerFrame()
: nullptr;
nsPresContext* pc = aReferenceFrame->PresContext();
mIsInChromePresContext = pc->IsChrome();
nsIDocShell* docShell = pc->GetDocShell();
if (docShell) {
docShell->GetWindowDraggingAllowed(&mWindowDraggingAllowed);
}
state->mTouchEventPrefEnabledDoc = dom::TouchEvent::PrefEnabled(docShell);
if (auto* vt = pc->Document()->GetActiveViewTransition()) {
// We must ensure captured view transition elements, including offscreen
// elements, are reached for display list building.
AutoTArray<nsIFrame*, 32> capturedFrames;
vt->GetCapturedFrames(capturedFrames);
for (const auto& frame : capturedFrames) {
MarkFrameForDisplay(frame, aReferenceFrame);
}
}
if (!buildCaret) {
return;
}
state->mCaretFrame = [&]() -> nsIFrame* {
RefPtr<nsCaret> caret = state->mPresShell->GetCaret();
nsIFrame* currentCaret = caret->GetPaintGeometry(&mCaretRect);
if (!currentCaret) {
return nullptr;
}
// Check if the display root for the caret matches the display root that
// we're painting, and only use it if it matches. Likely we only need this
// for carets inside popups.
if (nsLayoutUtils::GetDisplayRootFrame(currentCaret) !=
nsLayoutUtils::GetDisplayRootFrame(aReferenceFrame)) {
return nullptr;
}
// Caret frames add visual area to their frame, but we don't update the
// overflow area. Use flags to make sure we build display items for that
// frame instead.
MOZ_ASSERT(currentCaret->PresShell() == state->mPresShell);
MarkFrameForDisplay(currentCaret, aReferenceFrame);
caret->SetLastPaintedFrame(currentCaret);
if (!mPaintedCarets.Contains(caret)) {
mPaintedCarets.AppendElement(std::move(caret));
}
return currentCaret;
}();
}
// A non-blank paint is a paint that does not just contain the canvas
// background.
static bool DisplayListIsNonBlank(nsDisplayList* aList) {
for (nsDisplayItem* i : *aList) {
switch (i->GetType()) {
case DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO:
case DisplayItemType::TYPE_CANVAS_BACKGROUND_IMAGE:
continue;
case DisplayItemType::TYPE_SOLID_COLOR:
case DisplayItemType::TYPE_BACKGROUND:
case DisplayItemType::TYPE_BACKGROUND_COLOR:
if (i->Frame()->IsCanvasFrame()) {
continue;
}
return true;
default:
return true;
}
}
return false;
}
// A contentful paint is a paint that does contains DOM content (text,
// images, non-blank canvases, SVG): "First Contentful Paint entry
// contains a DOMHighResTimeStamp reporting the time when the browser
// first rendered any text, image (including background images),
// non-white canvas or SVG. This excludes any content of iframes, but
// includes text with pending webfonts. This is the first time users
// could start consuming page content."
static bool DisplayListIsContentful(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList) {
for (nsDisplayItem* i : *aList) {
DisplayItemType type = i->GetType();
nsDisplayList* children = i->GetChildren();
switch (type) {
case DisplayItemType::TYPE_SUBDOCUMENT: // iframes are ignored
break;
// CANVASes check if they may have been modified (as a stand-in
// actually tracking all modifications)
default:
if (i->IsContentful()) {
bool dummy;
nsRect bound = i->GetBounds(aBuilder, &dummy);
if (!bound.IsEmpty()) {
return true;
}
}
if (children) {
if (DisplayListIsContentful(aBuilder, children)) {
return true;
}
}
break;
}
}
return false;
}
void nsDisplayListBuilder::LeavePresShell(const nsIFrame* aReferenceFrame,
nsDisplayList* aPaintedContents) {
NS_ASSERTION(
CurrentPresShellState()->mPresShell == aReferenceFrame->PresShell(),
"Presshell mismatch");
if (mIsPaintingToWindow && aPaintedContents) {
nsPresContext* pc = aReferenceFrame->PresContext();
if (!pc->HadNonBlankPaint()) {
if (!CurrentPresShellState()->mIsBackgroundOnly &&
DisplayListIsNonBlank(aPaintedContents)) {
pc->NotifyNonBlankPaint();
}
}
nsRootPresContext* rootPresContext = pc->GetRootPresContext();
if (!pc->HasStoppedGeneratingLCP() && rootPresContext) {
if (!CurrentPresShellState()->mIsBackgroundOnly) {
if (pc->HasEverBuiltInvisibleText() ||
DisplayListIsContentful(this, aPaintedContents)) {
pc->NotifyContentfulPaint();
}
}
}
}
ResetMarkedFramesForDisplayList(aReferenceFrame);
mPresShellStates.RemoveLastElement();
if (!mPresShellStates.IsEmpty()) {
nsPresContext* pc = CurrentPresContext();
nsIDocShell* docShell = pc->GetDocShell();
if (docShell) {
docShell->GetWindowDraggingAllowed(&mWindowDraggingAllowed);
}
mIsInChromePresContext = pc->IsChrome();
} else {
for (uint32_t i = 0; i < mFramesMarkedForDisplayIfVisible.Length(); ++i) {
UnmarkFrameForDisplayIfVisible(mFramesMarkedForDisplayIfVisible[i]);
}
mFramesMarkedForDisplayIfVisible.SetLength(0);
}
}
void nsDisplayListBuilder::FreeClipChains() {
// Iterate the clip chains from newest to oldest (forward
// iteration), so that we destroy descendants first which
// will drop the ref count on their ancestors.
DisplayItemClipChain** indirect = &mFirstClipChainToDestroy;
while (*indirect) {
if (!(*indirect)->mRefCount) {
DisplayItemClipChain* next = (*indirect)->mNextClipChainToDestroy;
mClipDeduplicator.erase(*indirect);
(*indirect)->DisplayItemClipChain::~DisplayItemClipChain();
Destroy(DisplayListArenaObjectId::CLIPCHAIN, *indirect);
*indirect = next;
} else {
indirect = &(*indirect)->mNextClipChainToDestroy;
}
}
}
void nsDisplayListBuilder::FreeTemporaryItems() {
for (nsDisplayItem* i : mTemporaryItems) {
// Temporary display items are not added to the frames.
MOZ_ASSERT(i->Frame());
i->RemoveFrame(i->Frame());
i->Destroy(this);
}
mTemporaryItems.Clear();
}
void nsDisplayListBuilder::ResetMarkedFramesForDisplayList(
const nsIFrame* aReferenceFrame) {
// Unmark and pop off the frames marked for display in this pres shell.
uint32_t firstFrameForShell =
CurrentPresShellState()->mFirstFrameMarkedForDisplay;
for (uint32_t i = firstFrameForShell; i < mFramesMarkedForDisplay.Length();
++i) {
UnmarkFrameForDisplay(mFramesMarkedForDisplay[i], aReferenceFrame);
}
mFramesMarkedForDisplay.SetLength(firstFrameForShell);
firstFrameForShell = CurrentPresShellState()->mFirstFrameWithOOFData;
for (uint32_t i = firstFrameForShell; i < mFramesWithOOFData.Length(); ++i) {
mFramesWithOOFData[i]->RemoveProperty(OutOfFlowDisplayDataProperty());
}
mFramesWithOOFData.SetLength(firstFrameForShell);
}
void nsDisplayListBuilder::ClearFixedBackgroundDisplayData() {
CurrentPresShellState()->mFixedBackgroundDisplayData = Nothing();
}
void nsDisplayListBuilder::MarkFramesForDisplayList(
nsIFrame* aDirtyFrame, const nsFrameList& aFrames) {
nsRect visibleRect = GetVisibleRect();
nsRect dirtyRect = GetDirtyRect();
// If we are entering content that is fixed to the RCD-RSF, we are
// crossing the async zoom container boundary, and need to convert from
// visual to layout coordinates.
if (ViewportFrame* viewportFrame = do_QueryFrame(aDirtyFrame)) {
if (IsForEventDelivery() && ShouldBuildAsyncZoomContainer() &&
viewportFrame->PresContext()->IsRootContentDocumentCrossProcess()) {
if (viewportFrame->PresShell()->GetRootScrollContainerFrame()) {
#ifdef DEBUG
for (nsIFrame* f : aFrames) {
MOZ_ASSERT(ViewportUtils::IsZoomedContentRoot(f));
}
#endif
visibleRect = ViewportUtils::VisualToLayout(visibleRect,
viewportFrame->PresShell());
dirtyRect = ViewportUtils::VisualToLayout(dirtyRect,
viewportFrame->PresShell());
}
#ifdef DEBUG
else {
// This is an edge case that should only happen if we are in a
// document with a XUL root element so that it does not have a root
// scroll frame but it has fixed pos content and all of the frames in
// aFrames are that fixed pos content.
for (nsIFrame* f : aFrames) {
MOZ_ASSERT(!ViewportUtils::IsZoomedContentRoot(f) &&
f->GetParent() == aDirtyFrame &&
f->StyleDisplay()->mPosition ==
StylePositionProperty::Fixed);
}
// There's no root scroll frame so there can't be any zooming or async
// panning so we don't need to adjust the visible and dirty rects.
}
#endif
}
}
bool markedFrames = false;
for (nsIFrame* e : aFrames) {
// Skip the AccessibleCaret frame when building no caret.
if (!IsBuildingCaret()) {
nsIContent* content = e->GetContent();
if (content && content->IsInNativeAnonymousSubtree() &&
content->IsElement()) {
const nsAttrValue* classes = content->AsElement()->GetClasses();
if (classes &&
classes->Contains(nsGkAtoms::mozAccessiblecaret, eCaseMatters)) {
continue;
}
}
}
if (MarkOutOfFlowFrameForDisplay(aDirtyFrame, e, visibleRect, dirtyRect)) {
markedFrames = true;
}
}
if (markedFrames) {
// mClipState.GetClipChainForContainingBlockDescendants can return pointers
// to objects on the stack, so we need to clone the chain.
const DisplayItemClipChain* clipChain =
CopyWholeChain(mClipState.GetClipChainForContainingBlockDescendants());
const DisplayItemClipChain* combinedClipChain =
mClipState.GetCurrentCombinedClipChain(this);
const ActiveScrolledRoot* asr = mCurrentActiveScrolledRoot;
OutOfFlowDisplayData* data = new OutOfFlowDisplayData(
clipChain, combinedClipChain, asr, mCurrentScrollParentId, visibleRect,
dirtyRect, mInViewTransitionCapture);
aDirtyFrame->SetProperty(
nsDisplayListBuilder::OutOfFlowDisplayDataProperty(), data);
mFramesWithOOFData.AppendElement(aDirtyFrame);
}
if (!aDirtyFrame->GetParent()) {
// This is the viewport frame of aDirtyFrame's presshell.
// Store the current display data so that it can be used for fixed
// background images.
NS_ASSERTION(
CurrentPresShellState()->mPresShell == aDirtyFrame->PresShell(),
"Presshell mismatch");
MOZ_ASSERT(!CurrentPresShellState()->mFixedBackgroundDisplayData,
"already traversed this presshell's root frame?");
const DisplayItemClipChain* clipChain =
CopyWholeChain(mClipState.GetClipChainForContainingBlockDescendants());
const DisplayItemClipChain* combinedClipChain =
mClipState.GetCurrentCombinedClipChain(this);
const ActiveScrolledRoot* asr = mCurrentActiveScrolledRoot;
CurrentPresShellState()->mFixedBackgroundDisplayData.emplace(
clipChain, combinedClipChain, asr, mCurrentScrollParentId,
GetVisibleRect(), GetDirtyRect(), mInViewTransitionCapture);
}
}
/**
* Mark all preserve-3d children with
* NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO to make sure
* nsIFrame::BuildDisplayListForChild() would visit them. Also compute
* dirty rect for preserve-3d children.
*
* @param aDirtyFrame is the frame to mark children extending context.
*/
void nsDisplayListBuilder::MarkPreserve3DFramesForDisplayList(
nsIFrame* aDirtyFrame) {
for (const auto& childList : aDirtyFrame->ChildLists()) {
for (nsIFrame* child : childList.mList) {
if (child->Combines3DTransformWithAncestors()) {
MarkFrameForDisplay(child, aDirtyFrame);
}
if (child->IsBlockWrapper()) {
// Mark preserve-3d frames inside the block wrapper.
MarkPreserve3DFramesForDisplayList(child);
}
}
}
}
ActiveScrolledRoot* nsDisplayListBuilder::GetOrCreateActiveScrolledRoot(
const ActiveScrolledRoot* aParent,
ScrollContainerFrame* aScrollContainerFrame) {
RefPtr<ActiveScrolledRoot> asr = ActiveScrolledRoot::GetOrCreateASRForFrame(
aParent, aScrollContainerFrame, mActiveScrolledRoots);
return asr;
}
ActiveScrolledRoot*
nsDisplayListBuilder::GetOrCreateActiveScrolledRootForSticky(
const ActiveScrolledRoot* aParent, nsIFrame* aStickyFrame) {
RefPtr<ActiveScrolledRoot> asr =
ActiveScrolledRoot::GetOrCreateASRForStickyFrame(aParent, aStickyFrame,
mActiveScrolledRoots);
return asr;
}
const DisplayItemClipChain* nsDisplayListBuilder::AllocateDisplayItemClipChain(
const DisplayItemClip& aClip, const ActiveScrolledRoot* aASR,
const DisplayItemClipChain* aParent) {
MOZ_DIAGNOSTIC_ASSERT(!(aParent && aParent->mOnStack));
void* p = Allocate(sizeof(DisplayItemClipChain),
DisplayListArenaObjectId::CLIPCHAIN);
DisplayItemClipChain* c = new (KnownNotNull, p)
DisplayItemClipChain(aClip, aASR, aParent, mFirstClipChainToDestroy);
#if defined(DEBUG) || defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
c->mOnStack = false;
#endif
auto result = mClipDeduplicator.insert(c);
if (!result.second) {
// An equivalent clip chain item was already created, so let's return that
// instead. Destroy the one we just created.
// Note that this can cause clip chains from different coordinate systems to
// collapse into the same clip chain object, because clip chains do not keep
// track of the reference frame that they were created in.
c->DisplayItemClipChain::~DisplayItemClipChain();
Destroy(DisplayListArenaObjectId::CLIPCHAIN, c);
return *(result.first);
}
mFirstClipChainToDestroy = c;
return c;
}
struct ClipChainItem {
DisplayItemClip clip;
const ActiveScrolledRoot* asr;
};
static const DisplayItemClipChain* FindCommonAncestorClipForIntersection(
const DisplayItemClipChain* aOne, const DisplayItemClipChain* aTwo) {
for (const ActiveScrolledRoot* asr =
ActiveScrolledRoot::PickDescendant(aOne->mASR, aTwo->mASR);
asr; asr = asr->mParent) {
if (aOne == aTwo) {
return aOne;
}
if (aOne->mASR == asr) {
aOne = aOne->mParent;
}
if (aTwo->mASR == asr) {
aTwo = aTwo->mParent;
}
if (!aOne) {
return aTwo;
}
if (!aTwo) {
return aOne;
}
}
return nullptr;
}
const DisplayItemClipChain* nsDisplayListBuilder::CreateClipChainIntersection(
const DisplayItemClipChain* aAncestor,
const DisplayItemClipChain* aLeafClip1,
const DisplayItemClipChain* aLeafClip2) {
AutoTArray<ClipChainItem, 8> intersectedClips;
const DisplayItemClipChain* clip1 = aLeafClip1;
const DisplayItemClipChain* clip2 = aLeafClip2;
const ActiveScrolledRoot* asr = ActiveScrolledRoot::PickDescendant(
clip1 ? clip1->mASR : nullptr, clip2 ? clip2->mASR : nullptr);
// Build up the intersection from the leaf to the root and put it into
// intersectedClips. The loop below will convert intersectedClips into an
// actual DisplayItemClipChain.
// (We need to do this in two passes because we need the parent clip in order
// to create the DisplayItemClipChain object, but the parent clip has not
// been created at that point.)
while (!aAncestor || asr != aAncestor->mASR) {
if (clip1 && clip1->mASR == asr) {
if (clip2 && clip2->mASR == asr) {
DisplayItemClip intersection = clip1->mClip;
intersection.IntersectWith(clip2->mClip);
intersectedClips.AppendElement(ClipChainItem{intersection, asr});
clip2 = clip2->mParent;
} else {
intersectedClips.AppendElement(ClipChainItem{clip1->mClip, asr});
}
clip1 = clip1->mParent;
} else if (clip2 && clip2->mASR == asr) {
intersectedClips.AppendElement(ClipChainItem{clip2->mClip, asr});
clip2 = clip2->mParent;
}
if (!asr) {
MOZ_ASSERT(!aAncestor, "We should have exited this loop earlier");
break;
}
asr = asr->mParent;
}
// Convert intersectedClips into a DisplayItemClipChain.
const DisplayItemClipChain* parentSC = aAncestor;
for (auto& sc : Reversed(intersectedClips)) {
parentSC = AllocateDisplayItemClipChain(sc.clip, sc.asr, parentSC);
}
return parentSC;
}
const DisplayItemClipChain* nsDisplayListBuilder::CreateClipChainIntersection(
const DisplayItemClipChain* aLeafClip1,
const DisplayItemClipChain* aLeafClip2) {
// aLeafClip2 might be a reference to a clip on the stack. We need to make
// sure that CreateClipChainIntersection will allocate the actual intersected
// clip in the builder's arena, so for the aLeafClip1 == nullptr case,
// we supply nullptr as the common ancestor so that
// CreateClipChainIntersection clones the whole chain.
const DisplayItemClipChain* ancestorClip =
aLeafClip1 ? FindCommonAncestorClipForIntersection(aLeafClip1, aLeafClip2)
: nullptr;
return CreateClipChainIntersection(ancestorClip, aLeafClip1, aLeafClip2);
}
const DisplayItemClipChain* nsDisplayListBuilder::CopyWholeChain(
const DisplayItemClipChain* aClipChain) {
return CreateClipChainIntersection(nullptr, aClipChain, nullptr);
}
const nsIFrame* nsDisplayListBuilder::FindReferenceFrameFor(
const nsIFrame* aFrame, nsPoint* aOffset) const {
auto MaybeApplyAdditionalOffset = [&]() {
if (auto offset = AdditionalOffset()) {
*aOffset += *offset;
}
};
if (aFrame == mCurrentFrame) {
if (aOffset) {
*aOffset = mCurrentOffsetToReferenceFrame;
}
return mCurrentReferenceFrame;
}
for (const nsIFrame* f = aFrame; f;
f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f)) {
if (f == mReferenceFrame || f->IsTransformed()) {
if (aOffset) {
*aOffset = aFrame->GetOffsetToCrossDoc(f);
MaybeApplyAdditionalOffset();
}
return f;
}
}
if (aOffset) {
*aOffset = aFrame->GetOffsetToCrossDoc(mReferenceFrame);
MaybeApplyAdditionalOffset();
}
return mReferenceFrame;
}
// Sticky frames are active if their nearest scrollable frame is also active.
static bool IsStickyFrameActive(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame) {
MOZ_ASSERT(aFrame->StyleDisplay()->mPosition ==
StylePositionProperty::Sticky);
auto* ssc = StickyScrollContainer::GetOrCreateForFrame(aFrame);
return ssc && ssc->ScrollContainer()->IsMaybeAsynchronouslyScrolled();
}
bool nsDisplayListBuilder::IsAnimatedGeometryRoot(nsIFrame* aFrame,
nsIFrame** aParent) {
if (aFrame == mReferenceFrame) {
return true;
}
if (!IsPaintingToWindow()) {
if (aParent) {
*aParent = nsLayoutUtils::GetCrossDocParentFrameInProcess(aFrame);
}
return false;
}
nsIFrame* parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(aFrame);
if (!parent) {
return true;
}
*aParent = parent;
if (aFrame->StyleDisplay()->mPosition == StylePositionProperty::Sticky &&
IsStickyFrameActive(this, aFrame)) {
return true;
}
if (aFrame->IsTransformed()) {
if (EffectCompositor::HasAnimationsForCompositor(
aFrame, DisplayItemType::TYPE_TRANSFORM)) {
return true;
}
}
if (parent->IsScrollContainerOrSubclass()) {
ScrollContainerFrame* sf = do_QueryFrame(parent);
if (sf->GetScrolledFrame() == aFrame) {
MOZ_ASSERT(!aFrame->IsTransformed());
return sf->IsMaybeAsynchronouslyScrolled();
}
}
return false;
}
nsIFrame* nsDisplayListBuilder::FindAnimatedGeometryRootFrameFor(
nsIFrame* aFrame) {
MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDocInProcess(
RootReferenceFrame(), aFrame));
nsIFrame* cursor = aFrame;
while (cursor != RootReferenceFrame()) {
nsIFrame* next;
if (IsAnimatedGeometryRoot(cursor, &next)) {
return cursor;
}
cursor = next;
}
return cursor;
}
static nsRect ApplyAllClipNonRoundedIntersection(
const DisplayItemClipChain* aClipChain, const nsRect& aRect) {
nsRect result = aRect;
while (aClipChain) {
result = aClipChain->mClip.ApplyNonRoundedIntersection(result);
aClipChain = aClipChain->mParent;
}
return result;
}
void nsDisplayListBuilder::AdjustWindowDraggingRegion(nsIFrame* aFrame) {
if (!mWindowDraggingAllowed || !IsForPainting()) {
return;
}
const nsStyleUIReset* styleUI = aFrame->StyleUIReset();
if (styleUI->mWindowDragging == StyleWindowDragging::Default) {
// This frame has the default value and doesn't influence the window
// dragging region.
return;
}
if (!aFrame->StyleVisibility()->IsVisible()) {
// Invisible frames don't influence the window dragging region.
return;
}
LayoutDeviceToLayoutDeviceMatrix4x4 referenceFrameToRootReferenceFrame;
// The const_cast is for nsLayoutUtils::GetTransformToAncestor.
nsIFrame* referenceFrame =
const_cast<nsIFrame*>(FindReferenceFrameFor(aFrame));
if (IsInTransform()) {
// Only support 2d rectilinear transforms. Transform support is needed for
// the horizontal flip transform that's applied to the urlbar textbox in
// RTL mode - it should be able to exclude itself from the draggable region.
referenceFrameToRootReferenceFrame =
ViewAs<LayoutDeviceToLayoutDeviceMatrix4x4>(
nsLayoutUtils::GetTransformToAncestor(RelativeTo{referenceFrame},
RelativeTo{mReferenceFrame})
.GetMatrix());
Matrix referenceFrameToRootReferenceFrame2d;
if (!referenceFrameToRootReferenceFrame.Is2D(
&referenceFrameToRootReferenceFrame2d) ||
!referenceFrameToRootReferenceFrame2d.IsRectilinear()) {
return;
}
} else {
MOZ_ASSERT(referenceFrame == mReferenceFrame,
"referenceFrameToRootReferenceFrame needs to be adjusted");
}
// We do some basic visibility checking on the frame's border box here.
// We intersect it both with the current dirty rect and with the current
// clip. Either one is just a conservative approximation on its own, but
// their intersection luckily works well enough for our purposes, so that
// we don't have to do full-blown visibility computations.
// The most important case we need to handle is the scrolled-off tab:
// If the tab bar overflows, tab parts that are clipped by the scrollbox
// should not be allowed to interfere with the window dragging region. Using
// just the current DisplayItemClip is not enough to cover this case
// completely because clips are reset while building stacking context
// contents, so for example we'd fail to clip frames that have a clip path
// applied to them. But the current dirty rect doesn't get reset in that
// case, so we use it to make this case work.
nsRect borderBox = aFrame->GetRectRelativeToSelf().Intersect(mVisibleRect);
borderBox += ToReferenceFrame(aFrame);
const DisplayItemClipChain* clip =
ClipState().GetCurrentCombinedClipChain(this);
borderBox = ApplyAllClipNonRoundedIntersection(clip, borderBox);
if (borderBox.IsEmpty()) {
return;
}
LayoutDeviceRect devPixelBorderBox = LayoutDevicePixel::FromAppUnits(
borderBox, aFrame->PresContext()->AppUnitsPerDevPixel());
LayoutDeviceRect transformedDevPixelBorderBox =
TransformBy(referenceFrameToRootReferenceFrame, devPixelBorderBox);
transformedDevPixelBorderBox.Round();
LayoutDeviceIntRect transformedDevPixelBorderBoxInt;
if (!transformedDevPixelBorderBox.ToIntRect(
&transformedDevPixelBorderBoxInt)) {
return;
}
LayoutDeviceIntRegion& region =
styleUI->mWindowDragging == StyleWindowDragging::Drag
? mWindowDraggingRegion
: mWindowNoDraggingRegion;
if (!IsRetainingDisplayList()) {
region.OrWith(transformedDevPixelBorderBoxInt);
return;
}
gfx::IntRect rect(transformedDevPixelBorderBoxInt.ToUnknownRect());
if (styleUI->mWindowDragging == StyleWindowDragging::Drag) {
mRetainedWindowDraggingRegion.Add(aFrame, rect);
} else {
mRetainedWindowNoDraggingRegion.Add(aFrame, rect);
}
}
LayoutDeviceIntRegion nsDisplayListBuilder::GetWindowDraggingRegion() const {
LayoutDeviceIntRegion result;
if (!IsRetainingDisplayList()) {
result.Sub(mWindowDraggingRegion, mWindowNoDraggingRegion);
return result;
}
LayoutDeviceIntRegion dragRegion =
mRetainedWindowDraggingRegion.ToLayoutDeviceIntRegion();
LayoutDeviceIntRegion noDragRegion =
mRetainedWindowNoDraggingRegion.ToLayoutDeviceIntRegion();
result.Sub(dragRegion, noDragRegion);
return result;
}
void nsDisplayTransform::AddSizeOfExcludingThis(nsWindowSizes& aSizes) const {
nsPaintedDisplayItem::AddSizeOfExcludingThis(aSizes);
aSizes.mLayoutRetainedDisplayListSize +=
aSizes.mState.mMallocSizeOf(mTransformPreserves3D.get());
}
void nsDisplayListBuilder::AddSizeOfExcludingThis(nsWindowSizes& aSizes) const {
mPool.AddSizeOfExcludingThis(aSizes, Arena::ArenaKind::DisplayList);
size_t n = 0;
MallocSizeOf mallocSizeOf = aSizes.mState.mMallocSizeOf;
n += mDocumentWillChangeBudgets.ShallowSizeOfExcludingThis(mallocSizeOf);
n += mFrameWillChangeBudgets.ShallowSizeOfExcludingThis(mallocSizeOf);
n += mRetainedWindowDraggingRegion.SizeOfExcludingThis(mallocSizeOf);
n += mRetainedWindowNoDraggingRegion.SizeOfExcludingThis(mallocSizeOf);
n += mRetainedWindowOpaqueRegion.SizeOfExcludingThis(mallocSizeOf);
// XXX can't measure mClipDeduplicator since it uses std::unordered_set.
aSizes.mLayoutRetainedDisplayListSize += n;
}
void RetainedDisplayList::AddSizeOfExcludingThis(nsWindowSizes& aSizes) const {
for (nsDisplayItem* item : *this) {
item->AddSizeOfExcludingThis(aSizes);
if (RetainedDisplayList* children = item->GetChildren()) {
children->AddSizeOfExcludingThis(aSizes);
}
}
size_t n = 0;
n += mDAG.mDirectPredecessorList.ShallowSizeOfExcludingThis(
aSizes.mState.mMallocSizeOf);
n += mDAG.mNodesInfo.ShallowSizeOfExcludingThis(aSizes.mState.mMallocSizeOf);
n += mOldItems.ShallowSizeOfExcludingThis(aSizes.mState.mMallocSizeOf);
aSizes.mLayoutRetainedDisplayListSize += n;
}
size_t nsDisplayListBuilder::WeakFrameRegion::SizeOfExcludingThis(
MallocSizeOf aMallocSizeOf) const {
size_t n = 0;
n += mFrames.ShallowSizeOfExcludingThis(aMallocSizeOf);
for (const auto& frame : mFrames) {
const UniquePtr<WeakFrame>& weakFrame = frame.mWeakFrame;
n += aMallocSizeOf(weakFrame.get());
}
n += mRects.ShallowSizeOfExcludingThis(aMallocSizeOf);
return n;
}
/**
* Removes modified frames and rects from this WeakFrameRegion.
*/
void nsDisplayListBuilder::WeakFrameRegion::RemoveModifiedFramesAndRects() {
MOZ_ASSERT(mFrames.Length() == mRects.Length());
uint32_t i = 0;
uint32_t length = mFrames.Length();
while (i < length) {
auto& wrapper = mFrames[i];
if (!wrapper.mWeakFrame->IsAlive() ||
AnyContentAncestorModified(wrapper.mWeakFrame->GetFrame())) {
// To avoid multiple O(n) shifts in the array, move the last element of
// the array to the current position and decrease the array length.
mFrameSet.Remove(wrapper.mFrame);
mFrames[i] = std::move(mFrames[length - 1]);
mRects[i] = std::move(mRects[length - 1]);
length--;
} else {
i++;
}
}
mFrames.TruncateLength(length);
mRects.TruncateLength(length);
}
void nsDisplayListBuilder::RemoveModifiedWindowRegions() {
mRetainedWindowDraggingRegion.RemoveModifiedFramesAndRects();
mRetainedWindowNoDraggingRegion.RemoveModifiedFramesAndRects();
mRetainedWindowOpaqueRegion.RemoveModifiedFramesAndRects();
}
void nsDisplayListBuilder::ClearRetainedWindowRegions() {
mRetainedWindowDraggingRegion.Clear();
mRetainedWindowNoDraggingRegion.Clear();
mRetainedWindowOpaqueRegion.Clear();
}
const uint32_t gWillChangeAreaMultiplier = 3;
static uint32_t GetLayerizationCost(const nsSize& aSize) {
// There's significant overhead for each layer created from Gecko
// (IPC+Shared Objects) and from the backend (like an OpenGL texture).
// Therefore we set a minimum cost threshold of a 64x64 area.
const int minBudgetCost = 64 * 64;
const uint32_t budgetCost = std::max(
minBudgetCost, nsPresContext::AppUnitsToIntCSSPixels(aSize.width) *
nsPresContext::AppUnitsToIntCSSPixels(aSize.height));
return budgetCost;
}
bool nsDisplayListBuilder::AddToWillChangeBudget(nsIFrame* aFrame,
const nsSize& aSize) {
MOZ_ASSERT(IsForPainting());
if (aFrame->MayHaveWillChangeBudget()) {
// The frame is already in the will-change budget.
return true;
}
const nsPresContext* presContext = aFrame->PresContext();
const nsRect area = presContext->GetVisibleArea();
const uint32_t budgetLimit =
nsPresContext::AppUnitsToIntCSSPixels(area.width) *
nsPresContext::AppUnitsToIntCSSPixels(area.height);
const uint32_t cost = GetLayerizationCost(aSize);
DocumentWillChangeBudget& documentBudget =
mDocumentWillChangeBudgets.LookupOrInsert(presContext);
const bool onBudget =
(documentBudget + cost) / gWillChangeAreaMultiplier < budgetLimit;
if (onBudget) {
documentBudget += cost;
mFrameWillChangeBudgets.InsertOrUpdate(
aFrame, FrameWillChangeBudget(presContext, cost));
aFrame->SetMayHaveWillChangeBudget(true);
}
return onBudget;
}
bool nsDisplayListBuilder::IsInWillChangeBudget(nsIFrame* aFrame,
const nsSize& aSize) {
if (!IsForPainting()) {
// If this nsDisplayListBuilder is not for painting, the layerization should
// not matter. Do the simple thing and return false.
return false;
}
const bool onBudget = AddToWillChangeBudget(aFrame, aSize);
if (onBudget) {
return true;
}
auto* pc = aFrame->PresContext();
auto* doc = pc->Document();
if (!doc->HasWarnedAbout(Document::eIgnoringWillChangeOverBudget)) {
AutoTArray<nsString, 2> params;
params.AppendElement()->AppendInt(gWillChangeAreaMultiplier);
nsRect area = pc->GetVisibleArea();
uint32_t budgetLimit = nsPresContext::AppUnitsToIntCSSPixels(area.width) *
nsPresContext::AppUnitsToIntCSSPixels(area.height);
params.AppendElement()->AppendInt(budgetLimit);
doc->WarnOnceAbout(Document::eIgnoringWillChangeOverBudget, false, params);
}
return false;
}
void nsDisplayListBuilder::ClearWillChangeBudgetStatus(nsIFrame* aFrame) {
MOZ_ASSERT(IsForPainting());
if (!aFrame->MayHaveWillChangeBudget()) {
return;
}
aFrame->SetMayHaveWillChangeBudget(false);
RemoveFromWillChangeBudgets(aFrame);
}
void nsDisplayListBuilder::RemoveFromWillChangeBudgets(const nsIFrame* aFrame) {
if (auto entry = mFrameWillChangeBudgets.Lookup(aFrame)) {
const FrameWillChangeBudget& frameBudget = entry.Data();
auto documentBudget =
mDocumentWillChangeBudgets.Lookup(frameBudget.mPresContext);
if (documentBudget) {
*documentBudget -= frameBudget.mUsage;
}
entry.Remove();
}
}
void nsDisplayListBuilder::ClearWillChangeBudgets() {
mFrameWillChangeBudgets.Clear();
mDocumentWillChangeBudgets.Clear();
}
void nsDisplayListBuilder::EnterSVGEffectsContents(
nsIFrame* aEffectsFrame, nsDisplayList* aHoistedItemsStorage) {
MOZ_ASSERT(aHoistedItemsStorage);
if (mSVGEffectsFrames.IsEmpty()) {
MOZ_ASSERT(!mScrollInfoItemsForHoisting);
mScrollInfoItemsForHoisting = aHoistedItemsStorage;
}
mSVGEffectsFrames.AppendElement(aEffectsFrame);
}
void nsDisplayListBuilder::ExitSVGEffectsContents() {
MOZ_ASSERT(!mSVGEffectsFrames.IsEmpty());
mSVGEffectsFrames.RemoveLastElement();
MOZ_ASSERT(mScrollInfoItemsForHoisting);
if (mSVGEffectsFrames.IsEmpty()) {
mScrollInfoItemsForHoisting = nullptr;
}
}
bool nsDisplayListBuilder::ShouldBuildScrollInfoItemsForHoisting() const {
/*
* Note: if changing the conditions under which scroll info layers
* are created, make a corresponding change to
* ScrollFrameWillBuildScrollInfoLayer() in nsSliderFrame.cpp.
*/
for (nsIFrame* frame : mSVGEffectsFrames) {
if (SVGIntegrationUtils::UsesSVGEffectsNotSupportedInCompositor(frame)) {
return true;
}
}
return false;
}
void nsDisplayListBuilder::AppendNewScrollInfoItemForHoisting(
nsDisplayScrollInfoLayer* aScrollInfoItem) {
MOZ_ASSERT(ShouldBuildScrollInfoItemsForHoisting());
MOZ_ASSERT(mScrollInfoItemsForHoisting);
mScrollInfoItemsForHoisting->AppendToTop(aScrollInfoItem);
}
void nsDisplayListBuilder::BuildCompositorHitTestInfoIfNeeded(
nsIFrame* aFrame, nsDisplayList* aList) {
MOZ_ASSERT(aFrame);
MOZ_ASSERT(aList);
if (!BuildCompositorHitTestInfo()) {
return;
}
const CompositorHitTestInfo info = aFrame->GetCompositorHitTestInfo(this);
if (info != CompositorHitTestInvisibleToHit) {
aList->AppendNewToTop<nsDisplayCompositorHitTestInfo>(this, aFrame);
}
}
void nsDisplayListBuilder::AddReusableDisplayItem(nsDisplayItem* aItem) {
mReuseableItems.Insert(aItem);
}
void nsDisplayListBuilder::RemoveReusedDisplayItem(nsDisplayItem* aItem) {
MOZ_ASSERT(aItem->IsReusedItem());
mReuseableItems.Remove(aItem);
}
void nsDisplayListBuilder::ClearReuseableDisplayItems() {
const size_t total = mReuseableItems.Count();
size_t reused = 0;
for (auto* item : mReuseableItems) {
if (item->IsReusedItem()) {
reused++;
item->SetReusable();
} else {
item->Destroy(this);
}
}
DL_LOGI("RDL - Reused %zu of %zu SC display items", reused, total);
mReuseableItems.Clear();
}
void nsDisplayListBuilder::ReuseDisplayItem(nsDisplayItem* aItem) {
const auto* previous = mCurrentContainerASR;
const auto* asr = aItem->GetActiveScrolledRoot();
mCurrentContainerASR =
ActiveScrolledRoot::PickAncestor(asr, mCurrentContainerASR);
if (previous != mCurrentContainerASR) {
DL_LOGV("RDL - Changed mCurrentContainerASR from %p to %p", previous,
mCurrentContainerASR);
}
aItem->SetReusedItem();
}
void nsDisplayListSet::CopyTo(const nsDisplayListSet& aDestination) const {
for (size_t i = 0; i < mLists.size(); ++i) {
auto* from = mLists[i];
auto* to = aDestination.mLists[i];
from->CopyTo(to);
}
}
void nsDisplayListSet::MoveTo(const nsDisplayListSet& aDestination) const {
aDestination.BorderBackground()->AppendToTop(BorderBackground());
aDestination.BlockBorderBackgrounds()->AppendToTop(BlockBorderBackgrounds());
aDestination.Floats()->AppendToTop(Floats());
aDestination.Content()->AppendToTop(Content());
aDestination.PositionedDescendants()->AppendToTop(PositionedDescendants());
aDestination.Outlines()->AppendToTop(Outlines());
}
nsRect nsDisplayList::GetClippedBounds(nsDisplayListBuilder* aBuilder) const {
nsRect bounds;
for (nsDisplayItem* i : *this) {
bounds.UnionRect(bounds, i->GetClippedBounds(aBuilder));
}
return bounds;
}
nsRect nsDisplayList::GetClippedBoundsWithRespectToASR(
nsDisplayListBuilder* aBuilder, const ActiveScrolledRoot* aASR,
nsRect* aBuildingRect) const {
nsRect bounds;
for (nsDisplayItem* i : *this) {
nsRect r = i->GetClippedBounds(aBuilder);
if (aASR != i->GetActiveScrolledRoot() && !r.IsEmpty()) {
if (Maybe<nsRect> clip = i->GetClipWithRespectToASR(aBuilder, aASR)) {
r = clip.ref();
}
}
if (aBuildingRect) {
aBuildingRect->UnionRect(*aBuildingRect, i->GetBuildingRect());
}
bounds.UnionRect(bounds, r);
}
return bounds;
}
nsRect nsDisplayList::GetBuildingRect() const {
nsRect result;
for (nsDisplayItem* i : *this) {
result.UnionRect(result, i->GetBuildingRect());
}
return result;
}
WindowRenderer* nsDisplayListBuilder::GetWidgetWindowRenderer() {
if (RootReferenceFrame() !=
nsLayoutUtils::GetDisplayRootFrame(RootReferenceFrame())) {
return nullptr;
}
if (nsIWidget* window = RootReferenceFrame()->GetNearestWidget()) {
return window->GetWindowRenderer();
}
return nullptr;
}
WebRenderLayerManager* nsDisplayListBuilder::GetWidgetLayerManager() {
if (WindowRenderer* renderer = GetWidgetWindowRenderer()) {
return renderer->AsWebRender();
}
return nullptr;
}
void nsDisplayList::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx,
int32_t aAppUnitsPerDevPixel) {
FlattenedDisplayListIterator iter(aBuilder, this);
while (iter.HasNext()) {
nsPaintedDisplayItem* item = iter.GetNextItem()->AsPaintedDisplayItem();
if (!item) {
continue;
}
nsRect visible = item->GetClippedBounds(aBuilder);
visible = visible.Intersect(item->GetPaintRect(aBuilder, aCtx));
if (visible.IsEmpty()) {
continue;
}
DisplayItemClip currentClip = item->GetClip();
if (currentClip.HasClip()) {
aCtx->Save();
if (currentClip.IsRectClippedByRoundedCorner(visible)) {
currentClip.ApplyTo(aCtx, aAppUnitsPerDevPixel);
} else {
currentClip.ApplyRectTo(aCtx, aAppUnitsPerDevPixel);
}
}
aCtx->NewPath();
item->Paint(aBuilder, aCtx);
if (currentClip.HasClip()) {
aCtx->Restore();
}
}
}
/**
* We paint by executing a layer manager transaction, constructing a
* single layer representing the display list, and then making it the
* root of the layer manager, drawing into the PaintedLayers.
*/
void nsDisplayList::PaintRoot(nsDisplayListBuilder* aBuilder, gfxContext* aCtx,
uint32_t aFlags,
Maybe<double> aDisplayListBuildTime) {
AUTO_PROFILER_LABEL("nsDisplayList::PaintRoot", GRAPHICS);
RefPtr<WebRenderLayerManager> layerManager;
WindowRenderer* renderer = nullptr;
bool widgetTransaction = false;
bool doBeginTransaction = true;
if (aFlags & PAINT_USE_WIDGET_LAYERS) {
renderer = aBuilder->GetWidgetWindowRenderer();
if (renderer) {
// The fallback renderer doesn't retain any content, so it's
// not meaningful to use it when drawing to an external context.
if (aCtx && renderer->AsFallback()) {
MOZ_ASSERT(!(aFlags & PAINT_EXISTING_TRANSACTION));
renderer = nullptr;
} else {
layerManager = renderer->AsWebRender();
doBeginTransaction = !(aFlags & PAINT_EXISTING_TRANSACTION);
widgetTransaction = true;
}
}
}
nsIFrame* frame = aBuilder->RootReferenceFrame();
nsPresContext* presContext = frame->PresContext();
PresShell* presShell = presContext->PresShell();
Document* document = presShell->GetDocument();
ScopeExit g([&]() {
#ifdef DEBUG
MOZ_ASSERT(!layerManager || !layerManager->GetTarget());
#endif
// For layers-free mode, we check the invalidation state bits in the
// EndTransaction. So we clear the invalidation state bits after
// EndTransaction.
if (widgetTransaction ||
// SVG-as-an-image docs don't paint as part of the retained layer tree,
// but they still need the invalidation state bits cleared in order for
// invalidation for CSS/SMIL animation to work properly.
(document && document->IsBeingUsedAsImage())) {
DL_LOGD("Clearing invalidation state bits");
frame->ClearInvalidationStateBits();
}
});
if (!renderer) {
if (!aCtx) {
NS_WARNING("Nowhere to paint into");
return;
}
Paint(aBuilder, aCtx, presContext->AppUnitsPerDevPixel());
return;
}
if (renderer->GetBackendType() == LayersBackend::LAYERS_WR) {
MOZ_ASSERT(layerManager);
if (doBeginTransaction) {
if (aCtx) {
if (!layerManager->BeginTransactionWithTarget(aCtx, nsCString())) {
return;
}
} else {
if (!layerManager->BeginTransaction(nsCString())) {
return;
}
}
}
layerManager->SetTransactionIdAllocator(presContext->RefreshDriver());
bool sent = false;
if (aFlags & PAINT_IDENTICAL_DISPLAY_LIST) {
MOZ_ASSERT(!aCtx);
sent = layerManager->EndEmptyTransaction();
}
if (!sent) {
auto* wrManager = static_cast<WebRenderLayerManager*>(layerManager.get());
nsIDocShell* docShell = presContext->GetDocShell();
WrFiltersHolder wrFilters;
gfx::Matrix5x4* colorMatrix =
nsDocShell::Cast(docShell)->GetColorMatrix();
if (colorMatrix) {
// Note: This color matrix was added here in for accessibility in
// https://bugzilla.mozilla.org/show_bug.cgi?id=1431466 , it could be
// done with regular SVG in the document as long as it is accelerated,
// and it's probably best to do this in linearRGB, now that it is
// feasible to do so
// TODO(ahale): Make sure to test this works correctly before enabling
if (StaticPrefs::gfx_webrender_svg_filter_effects() &&
StaticPrefs::
gfx_webrender_svg_filter_effects_also_use_for_docshell_fecolormatrix()) {
// WebRender SVGFE code needs a valid filter region, so use 1<<30 as
// rendering will already be heavily degraded at that range.
static constexpr float kExtent = 1024.0f * 1024.0f * 1024.0f;
wr::LayoutRect subregion = {{-kExtent, -kExtent}, {kExtent, kExtent}};
auto node = wr::FilterOpGraphNode{};
node.input.buffer_id = wr::FilterOpGraphPictureBufferId::None();
node.input2.buffer_id = wr::FilterOpGraphPictureBufferId::None();
node.subregion = subregion;
wrFilters.filters.AppendElement(
wr::FilterOp::SVGFESourceGraphic(node));
node.input.buffer_id = wr::FilterOpGraphPictureBufferId::BufferId(0);
wrFilters.filters.AppendElement(
wr::FilterOp::SVGFEColorMatrix(node, colorMatrix->components));
} else {
wrFilters.filters.AppendElement(
wr::FilterOp::ColorMatrix(colorMatrix->components));
}
}
wrManager->EndTransactionWithoutLayer(this, aBuilder,
std::move(wrFilters), nullptr,
aDisplayListBuildTime.valueOr(0.0),
aFlags & PAINT_COMPOSITE_OFFSCREEN);
}
if (presContext->RefreshDriver()->IsInRefresh() ||
presContext->RefreshDriver()->IsPaintPending()) {
presContext->NotifyInvalidation(layerManager->GetLastTransactionId(),
frame->GetRect());
}
return;
}
FallbackRenderer* fallback = renderer->AsFallback();
MOZ_ASSERT(fallback);
if (doBeginTransaction) {
MOZ_ASSERT(!aCtx);
if (!fallback->BeginTransaction()) {
return;
}
}
fallback->EndTransactionWithList(aBuilder, this,
presContext->AppUnitsPerDevPixel(),
WindowRenderer::END_DEFAULT);
}
void nsDisplayList::DeleteAll(nsDisplayListBuilder* aBuilder) {
for (auto* item : TakeItems()) {
item->Destroy(aBuilder);
}
}
static bool IsFrameReceivingPointerEvents(nsIFrame* aFrame) {
return aFrame->Style()->PointerEvents() != StylePointerEvents::None;
}
// A list of frames, and their z depth. Used for sorting
// the results of hit testing.
struct FramesWithDepth {
explicit FramesWithDepth(float aDepth) : mDepth(aDepth) {}
bool operator<(const FramesWithDepth& aOther) const {
// We want to sort so that the shallowest item (highest depth value) is
// first. Round to have some error tolerance (multiply with 8 translates
// effectively to <<3).
double lDepth = round(mDepth * 8.);
double rDepth = round(aOther.mDepth * 8.);
return lDepth > rDepth;
}
bool operator==(const FramesWithDepth& aOther) const {
return this == &aOther;
}
float mDepth;
nsTArray<nsIFrame*> mFrames;
};
// Sort the frames by depth and then moves all the contained frames to the
// destination
static void FlushFramesArray(nsTArray<FramesWithDepth>& aSource,
nsTArray<nsIFrame*>* aDest) {
if (aSource.IsEmpty()) {
return;
}
aSource.StableSort();
uint32_t length = aSource.Length();
for (uint32_t i = 0; i < length; i++) {
aDest->AppendElements(std::move(aSource[i].mFrames));
}
aSource.Clear();
}
void nsDisplayList::HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
nsDisplayItem::HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) const {
nsDisplayItem* item;
if (aState->mGatheringPreserves3DLeaves) {
// Collect leaves of the current 3D rendering context.
for (nsDisplayItem* item : *this) {
auto itemType = item->GetType();
if (itemType != DisplayItemType::TYPE_TRANSFORM ||
!static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext()) {
item->HitTest(aBuilder, aRect, aState, aOutFrames);
} else {
// One of leaves in the current 3D rendering context.
aState->mItemBuffer.AppendElement(item);
}
}
return;
}
int32_t itemBufferStart = aState->mItemBuffer.Length();
for (nsDisplayItem* item : *this) {
aState->mItemBuffer.AppendElement(item);
}
AutoTArray<FramesWithDepth, 16> temp;
for (int32_t i = aState->mItemBuffer.Length() - 1; i >= itemBufferStart;
--i) {
// Pop element off the end of the buffer. We want to shorten the buffer
// so that recursive calls to HitTest have more buffer space.
item = aState->mItemBuffer[i];
aState->mItemBuffer.SetLength(i);
bool snap;
nsRect r = item->GetBounds(aBuilder, &snap).Intersect(aRect);
auto itemType = item->GetType();
bool same3DContext =
(itemType == DisplayItemType::TYPE_TRANSFORM &&
static_cast<nsDisplayTransform*>(item)->IsParticipating3DContext()) ||
(itemType == DisplayItemType::TYPE_PERSPECTIVE &&
item->Frame()->Extend3DContext());
if (same3DContext &&
(itemType != DisplayItemType::TYPE_TRANSFORM ||
!static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext())) {
if (!item->GetClip().MayIntersect(aRect)) {
continue;
}
AutoTArray<nsIFrame*, 1> neverUsed;
// Start gathering leaves of the 3D rendering context, and
// append leaves at the end of mItemBuffer. Leaves are
// processed at following iterations.
aState->mGatheringPreserves3DLeaves = true;
item->HitTest(aBuilder, aRect, aState, &neverUsed);
aState->mGatheringPreserves3DLeaves = false;
i = aState->mItemBuffer.Length();
continue;
}
if (!same3DContext && !item->GetClip().MayIntersect(r)) {
continue;
}
const bool savedTransformHasBackfaceVisible =
aState->mTransformHasBackfaceVisible;
if (aState->mTransformHasBackfaceVisible &&
!item->Combines3DTransformWithAncestors()) {
// exiting a preserve 3d context, the transform is no longer applied to
// this item, so reset the tracking var
aState->mTransformHasBackfaceVisible = false;
}
AutoTArray<nsIFrame*, 16> outFrames;
item->HitTest(aBuilder, aRect, aState, &outFrames);
MOZ_ASSERT(!aState->mTransformHasBackfaceVisible ||
!item->In3DContextAndBackfaceIsHidden() ||
!outFrames.Contains(item->Frame()));
aState->mTransformHasBackfaceVisible = savedTransformHasBackfaceVisible;
// For 3d transforms with preserve-3d we add hit frames into the temp list
// so we can sort them later, otherwise we add them directly to the output
// list.
nsTArray<nsIFrame*>* writeFrames = aOutFrames;
if (item->GetType() == DisplayItemType::TYPE_TRANSFORM &&
static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext()) {
if (outFrames.Length()) {
nsDisplayTransform* transform = static_cast<nsDisplayTransform*>(item);
nsPoint point = aRect.TopLeft();
// A 1x1 rect means a point, otherwise use the center of the rect
if (aRect.width != 1 || aRect.height != 1) {
point = aRect.Center();
}
temp.AppendElement(
FramesWithDepth(transform->GetHitDepthAtPoint(aBuilder, point)));
writeFrames = &temp[temp.Length() - 1].mFrames;
}
} else {
// We may have just finished a run of consecutive preserve-3d
// transforms, so flush these into the destination array before
// processing our frame list.
FlushFramesArray(temp, aOutFrames);
}
for (uint32_t j = 0; j < outFrames.Length(); j++) {
nsIFrame* f = outFrames.ElementAt(j);
// Filter out some frames depending on the type of hittest
// we are doing. For visibility tests, pass through all frames.
// For pointer tests, only pass through frames that are styled
// to receive pointer events.
if (aBuilder->HitTestIsForVisibility() ||
IsFrameReceivingPointerEvents(f)) {
writeFrames->AppendElement(f);
}
}
if (aBuilder->HitTestIsForVisibility()) {
aState->mHitOccludingItem = [&] {
if (aState->mHitOccludingItem) {
// We already hit something before.
return true;
}
if (aState->mCurrentOpacity == 1.0f &&
item->GetOpaqueRegion(aBuilder, &snap).Contains(aRect)) {
// An opaque item always occludes everything. Note that we need to
// check wrapping opacity and such as well.
return true;
}
float threshold = aBuilder->VisibilityThreshold();
if (threshold == 1.0f) {
return false;
}
float itemOpacity = [&] {
switch (item->GetType()) {
case DisplayItemType::TYPE_OPACITY:
return static_cast<nsDisplayOpacity*>(item)->GetOpacity();
case DisplayItemType::TYPE_BACKGROUND_COLOR:
return static_cast<nsDisplayBackgroundColor*>(item)->GetOpacity();
default:
// Be conservative and assume it won't occlude other items.
return 0.0f;
}
}();
return itemOpacity * aState->mCurrentOpacity >= threshold;
}();
if (aState->mHitOccludingItem) {
// We're exiting early, so pop the remaining items off the buffer.
aState->mItemBuffer.TruncateLength(itemBufferStart);
break;
}
}
}
// Clear any remaining preserve-3d transforms.
FlushFramesArray(temp, aOutFrames);
NS_ASSERTION(aState->mItemBuffer.Length() == uint32_t(itemBufferStart),
"How did we forget to pop some elements?");
}
static nsIContent* FindContentInDocument(nsDisplayItem* aItem, Document* aDoc) {
nsIFrame* f = aItem->Frame();
while (f) {
nsPresContext* pc = f->PresContext();
if (pc->Document() == aDoc) {
return f->GetContent();
}
f = nsLayoutUtils::GetCrossDocParentFrameInProcess(
pc->PresShell()->GetRootFrame());
}
return nullptr;
}
struct ZSortItem {
nsDisplayItem* item;
int32_t zIndex;
explicit ZSortItem(nsDisplayItem* aItem)
: item(aItem), zIndex(aItem->ZIndex()) {}
operator nsDisplayItem*() { return item; }
};
struct ZOrderComparator {
bool LessThan(const ZSortItem& aLeft, const ZSortItem& aRight) const {
return aLeft.zIndex < aRight.zIndex;
}
};
void nsDisplayList::SortByZOrder() { Sort<ZSortItem>(ZOrderComparator()); }
struct ContentComparator {
nsIContent* mCommonAncestor;
explicit ContentComparator(nsIContent* aCommonAncestor)
: mCommonAncestor(aCommonAncestor) {}
bool LessThan(nsDisplayItem* aLeft, nsDisplayItem* aRight) const {
// It's possible that the nsIContent for aItem1 or aItem2 is in a
// subdocument of commonAncestor, because display items for subdocuments
// have been mixed into the same list. Ensure that we're looking at content
// in commonAncestor's document.
Document* commonAncestorDoc = mCommonAncestor->OwnerDoc();
nsIContent* content1 = FindContentInDocument(aLeft, commonAncestorDoc);
nsIContent* content2 = FindContentInDocument(aRight, commonAncestorDoc);
if (!content1 || !content2) {
NS_ERROR("Document trees are mixed up!");
// Something weird going on
return true;
}
return content1 != content2 &&
nsContentUtils::CompareTreePosition<TreeKind::Flat>(
content1, content2, mCommonAncestor) < 0;
}
};
void nsDisplayList::SortByContentOrder(nsIContent* aCommonAncestor) {
Sort<nsDisplayItem*>(ContentComparator(aCommonAncestor));
}
#if !defined(DEBUG) && !defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
static_assert(sizeof(nsDisplayItem) <= 176, "nsDisplayItem has grown");
#endif
nsDisplayItem::nsDisplayItem(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
: nsDisplayItem(aBuilder, aFrame, aBuilder->CurrentActiveScrolledRoot()) {}
nsDisplayItem::nsDisplayItem(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
const ActiveScrolledRoot* aActiveScrolledRoot)
: mFrame(aFrame), mActiveScrolledRoot(aActiveScrolledRoot) {
MOZ_COUNT_CTOR(nsDisplayItem);
MOZ_ASSERT(mFrame);
if (aBuilder->IsRetainingDisplayList()) {
mFrame->AddDisplayItem(this);
}
aBuilder->FindReferenceFrameFor(aFrame, &mToReferenceFrame);
NS_ASSERTION(
aBuilder->GetVisibleRect().width >= 0 || !aBuilder->IsForPainting(),
"visible rect not set");
mClipChain = aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder);
// The visible rect is for mCurrentFrame, so we have to use
// mCurrentOffsetToReferenceFrame
nsRect visible = aBuilder->GetVisibleRect() +
aBuilder->GetCurrentFrameOffsetToReferenceFrame();
SetBuildingRect(visible);
const nsStyleDisplay* disp = mFrame->StyleDisplay();
if (mFrame->BackfaceIsHidden(disp)) {
mItemFlags += ItemFlag::BackfaceHidden;
}
if (mFrame->Combines3DTransformWithAncestors()) {
mItemFlags += ItemFlag::Combines3DTransformWithAncestors;
}
}
void nsDisplayItem::SetDeletedFrame() { mItemFlags += ItemFlag::DeletedFrame; }
const ActiveScrolledRoot* nsDisplayItem::GetNearestScrollASR() const {
const ActiveScrolledRoot* asr = GetActiveScrolledRoot();
if (asr) {
return asr->GetNearestScrollASR();
}
return nullptr;
}
bool nsDisplayItem::HasDeletedFrame() const {
bool retval = mItemFlags.contains(ItemFlag::DeletedFrame) ||
(GetType() == DisplayItemType::TYPE_REMOTE &&
!static_cast<const nsDisplayRemote*>(this)->GetFrameLoader());
MOZ_ASSERT(retval || mFrame);
return retval;
}
/* static */
bool nsDisplayItem::ForceActiveLayers() {
return StaticPrefs::layers_force_active();
}
int32_t nsDisplayItem::ZIndex() const { return mFrame->ZIndex().valueOr(0); }
void nsDisplayItem::SetClipChain(const DisplayItemClipChain* aClipChain,
bool aStore) {
mClipChain = aClipChain;
}
Maybe<nsRect> nsDisplayItem::GetClipWithRespectToASR(
nsDisplayListBuilder* aBuilder, const ActiveScrolledRoot* aASR) const {
if (const DisplayItemClip* clip =
DisplayItemClipChain::ClipForASR(GetClipChain(), aASR)) {
return Some(clip->GetClipRect());
}
return Nothing();
}
const DisplayItemClip& nsDisplayItem::GetClip() const {
const DisplayItemClip* clip =
DisplayItemClipChain::ClipForASR(mClipChain, mActiveScrolledRoot);
return clip ? *clip : DisplayItemClip::NoClip();
}
void nsDisplayItem::IntersectClip(nsDisplayListBuilder* aBuilder,
const DisplayItemClipChain* aOther,
bool aStore) {
if (!aOther || mClipChain == aOther) {
return;
}
// aOther might be a reference to a clip on the stack. We need to make sure
// that CreateClipChainIntersection will allocate the actual intersected
// clip in the builder's arena, so for the mClipChain == nullptr case,
// we supply nullptr as the common ancestor so that
// CreateClipChainIntersection clones the whole chain.
const DisplayItemClipChain* ancestorClip =
mClipChain ? FindCommonAncestorClipForIntersection(mClipChain, aOther)
: nullptr;
SetClipChain(
aBuilder->CreateClipChainIntersection(ancestorClip, mClipChain, aOther),
aStore);
}
nsRect nsDisplayItem::GetClippedBounds(nsDisplayListBuilder* aBuilder) const {
bool snap;
nsRect r = GetBounds(aBuilder, &snap);
return GetClip().ApplyNonRoundedIntersection(r);
}
nsDisplayContainer::nsDisplayContainer(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, nsDisplayList* aList)
: nsDisplayItem(aBuilder, aFrame, aActiveScrolledRoot),
mChildren(aBuilder),
mFrameASR(aContainerASRType == ContainerASRType::AncestorOfContained
? aBuilder->CurrentActiveScrolledRoot()
: nullptr),
mContainerASRType(aContainerASRType) {
MOZ_COUNT_CTOR(nsDisplayContainer);
mChildren.AppendToTop(aList);
UpdateBounds(aBuilder);
// Clear and store the clip chain set by nsDisplayItem constructor.
nsDisplayItem::SetClipChain(nullptr, true);
}
nsRect nsDisplayItem::GetPaintRect(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
bool dummy;
nsRect result = GetBounds(aBuilder, &dummy);
if (aCtx) {
result.IntersectRect(result,
nsLayoutUtils::RoundGfxRectToAppRect(
aCtx->GetClipExtents(),
mFrame->PresContext()->AppUnitsPerDevPixel()));
}
return result;
}
bool nsDisplayContainer::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
aManager->CommandBuilder().CreateWebRenderCommandsFromDisplayList(
GetChildren(), this, aDisplayListBuilder, aSc, aBuilder, aResources,
false);
return true;
}
nsRect nsDisplayContainer::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
return mBounds;
}
nsRect nsDisplayContainer::GetComponentAlphaBounds(
nsDisplayListBuilder* aBuilder) const {
return mChildren.GetComponentAlphaBounds(aBuilder);
}
static nsRegion GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList,
const nsRect& aListBounds) {
return aList->GetOpaqueRegion(aBuilder);
}
nsRegion nsDisplayContainer::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
return ::mozilla::GetOpaqueRegion(aBuilder, GetChildren(),
GetBounds(aBuilder, aSnap));
}
Maybe<nsRect> nsDisplayContainer::GetClipWithRespectToASR(
nsDisplayListBuilder* aBuilder, const ActiveScrolledRoot* aASR) const {
// Our children should have finite bounds with respect to |aASR|.
if (aASR == mActiveScrolledRoot) {
return Some(mBounds);
}
return Some(mChildren.GetClippedBoundsWithRespectToASR(aBuilder, aASR));
}
void nsDisplayContainer::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect, HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
mChildren.HitTest(aBuilder, aRect, aState, aOutFrames);
}
void nsDisplayContainer::UpdateBounds(nsDisplayListBuilder* aBuilder) {
// Container item bounds are expected to be clipped.
mBounds =
mChildren.GetClippedBoundsWithRespectToASR(aBuilder, mActiveScrolledRoot);
}
nsRect nsDisplaySolidColor::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = true;
return mBounds;
}
void nsDisplaySolidColor::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
if (!NS_GET_A(mColor)) {
return;
}
int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
DrawTarget* drawTarget = aCtx->GetDrawTarget();
Rect rect = NSRectToSnappedRect(GetPaintRect(aBuilder, aCtx),
appUnitsPerDevPixel, *drawTarget);
drawTarget->FillRect(rect, ColorPattern(ToDeviceColor(mColor)));
}
void nsDisplaySolidColor::WriteDebugInfo(std::stringstream& aStream) {
aStream << " (rgba " << (int)NS_GET_R(mColor) << "," << (int)NS_GET_G(mColor)
<< "," << (int)NS_GET_B(mColor) << "," << (int)NS_GET_A(mColor)
<< ")";
}
bool nsDisplaySolidColor::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
if (!NS_GET_A(mColor)) {
return true;
}
LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
mBounds, mFrame->PresContext()->AppUnitsPerDevPixel());
wr::LayoutRect r = wr::ToLayoutRect(bounds);
aBuilder.PushRect(r, r, !BackfaceIsHidden(), false, mIsCheckerboardBackground,
wr::ToColorF(ToDeviceColor(mColor)));
return true;
}
nsRect nsDisplaySolidColorRegion::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = true;
return mRegion.GetBounds();
}
void nsDisplaySolidColorRegion::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
DrawTarget* drawTarget = aCtx->GetDrawTarget();
ColorPattern color(ToDeviceColor(mColor));
for (auto iter = mRegion.RectIter(); !iter.Done(); iter.Next()) {
Rect rect =
NSRectToSnappedRect(iter.Get(), appUnitsPerDevPixel, *drawTarget);
drawTarget->FillRect(rect, color);
}
}
void nsDisplaySolidColorRegion::WriteDebugInfo(std::stringstream& aStream) {
aStream << " (rgba " << int(mColor.r * 255) << "," << int(mColor.g * 255)
<< "," << int(mColor.b * 255) << "," << mColor.a << ")";
}
bool nsDisplaySolidColorRegion::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
for (auto iter = mRegion.RectIter(); !iter.Done(); iter.Next()) {
nsRect rect = iter.Get();
LayoutDeviceRect layerRects = LayoutDeviceRect::FromAppUnits(
rect, mFrame->PresContext()->AppUnitsPerDevPixel());
wr::LayoutRect r = wr::ToLayoutRect(layerRects);
aBuilder.PushRect(r, r, !BackfaceIsHidden(), false, false,
wr::ToColorF(ToDeviceColor(mColor)));
}
return true;
}
static void RegisterThemeGeometry(nsDisplayListBuilder* aBuilder,
nsDisplayItem* aItem, nsIFrame* aFrame,
nsITheme::ThemeGeometryType aType) {
if (aBuilder->IsInChromeDocumentOrPopup()) {
nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(aFrame);
bool preservesAxisAlignedRectangles = false;
nsRect borderBox = nsLayoutUtils::TransformFrameRectToAncestor(
aFrame, aFrame->GetRectRelativeToSelf(), displayRoot,
&preservesAxisAlignedRectangles);
if (preservesAxisAlignedRectangles) {
aBuilder->RegisterThemeGeometry(
aType, aItem,
LayoutDeviceIntRect::FromUnknownRect(borderBox.ToNearestPixels(
aFrame->PresContext()->AppUnitsPerDevPixel())));
}
}
}
// Return the bounds of the viewport relative to |aFrame|'s reference frame.
// Returns Nothing() if transforming into |aFrame|'s coordinate space fails.
static Maybe<nsRect> GetViewportRectRelativeToReferenceFrame(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame) {
nsIFrame* rootFrame = aFrame->PresShell()->GetRootFrame();
nsRect rootRect = rootFrame->GetRectRelativeToSelf();
if (nsLayoutUtils::TransformRect(rootFrame, aFrame, rootRect) ==
nsLayoutUtils::TRANSFORM_SUCCEEDED) {
return Some(rootRect + aBuilder->ToReferenceFrame(aFrame));
}
return Nothing();
}
/* static */ nsDisplayBackgroundImage::InitData
nsDisplayBackgroundImage::GetInitData(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, uint16_t aLayer,
const nsRect& aBackgroundRect,
const ComputedStyle* aBackgroundStyle) {
nsPresContext* presContext = aFrame->PresContext();
uint32_t flags = aBuilder->GetBackgroundPaintFlags();
const nsStyleImageLayers::Layer& layer =
aBackgroundStyle->StyleBackground()->mImage.mLayers[aLayer];
bool isTransformedFixed;
nsBackgroundLayerState state = nsCSSRendering::PrepareImageLayer(
presContext, aFrame, flags, aBackgroundRect, aBackgroundRect, layer,
&isTransformedFixed);
// background-attachment:fixed is treated as background-attachment:scroll
// if it's affected by a transform.
// See https://www.w3.org/Bugs/Public/show_bug.cgi?id=17521.
bool shouldTreatAsFixed =
layer.mAttachment == StyleImageLayerAttachment::Fixed &&
!isTransformedFixed;
bool shouldFixToViewport = shouldTreatAsFixed && !layer.mImage.IsNone();
bool isRasterImage = state.mImageRenderer.IsRasterImage();
nsCOMPtr<imgIContainer> image;
if (isRasterImage) {
image = state.mImageRenderer.GetImage();
}
return InitData{aBuilder, aBackgroundStyle, image,
aBackgroundRect, state.mFillArea, state.mDestArea,
aLayer, isRasterImage, shouldFixToViewport};
}
nsDisplayBackgroundImage::nsDisplayBackgroundImage(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, const InitData& aInitData,
nsIFrame* aFrameForBounds)
: nsPaintedDisplayItem(aBuilder, aFrame),
mBackgroundStyle(aInitData.backgroundStyle),
mImage(aInitData.image),
mDependentFrame(nullptr),
mBackgroundRect(aInitData.backgroundRect),
mFillRect(aInitData.fillArea),
mDestRect(aInitData.destArea),
mLayer(aInitData.layer),
mIsRasterImage(aInitData.isRasterImage) {
MOZ_COUNT_CTOR(nsDisplayBackgroundImage);
#ifdef DEBUG
if (mBackgroundStyle && mBackgroundStyle != mFrame->Style()) {
// If this changes, then you also need to adjust css::ImageLoader to
// invalidate mFrame as needed.
MOZ_ASSERT(mFrame->IsCanvasFrame() || mFrame->IsTablePart());
}
#endif
mBounds = GetBoundsInternal(aInitData.builder, aFrameForBounds);
if (aInitData.shouldFixToViewport) {
// Expand the item's visible rect to cover the entire bounds, limited to the
// viewport rect. This is necessary because the background's clip can move
// asynchronously.
if (Maybe<nsRect> viewportRect = GetViewportRectRelativeToReferenceFrame(
aInitData.builder, mFrame)) {
SetBuildingRect(mBounds.Intersect(*viewportRect));
}
}
}
void nsDisplayBackgroundImage::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mDependentFrame);
nsPaintedDisplayItem::Destroy(aBuilder);
}
static void SetBackgroundClipRegion(
DisplayListClipState::AutoSaveRestore& aClipState, nsIFrame* aFrame,
const nsStyleImageLayers::Layer& aLayer, const nsRect& aBackgroundRect,
bool aWillPaintBorder) {
nsCSSRendering::ImageLayerClipState clip;
nsCSSRendering::GetImageLayerClip(
aLayer, aFrame, *aFrame->StyleBorder(), aBackgroundRect, aBackgroundRect,
aWillPaintBorder, aFrame->PresContext()->AppUnitsPerDevPixel(), &clip);
if (clip.mHasAdditionalBGClipArea) {
aClipState.ClipContentDescendants(
clip.mAdditionalBGClipArea, clip.mBGClipArea,
clip.mHasRoundedCorners ? &clip.mRadii : nullptr);
} else {
aClipState.ClipContentDescendants(
clip.mBGClipArea, clip.mHasRoundedCorners ? &clip.mRadii : nullptr);
}
}
/**
* This is used for the find bar highlighter overlay. It's only accessible
* through the AnonymousContent API, so it's not exposed to general web pages.
*/
static bool SpecialCutoutRegionCase(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
const nsRect& aBackgroundRect,
nsDisplayList* aList, nscolor aColor) {
nsIContent* content = aFrame->GetContent();
if (!content) {
return false;
}
void* cutoutRegion = content->GetProperty(nsGkAtoms::cutoutregion);
if (!cutoutRegion) {
return false;
}
if (NS_GET_A(aColor) == 0) {
return true;
}
nsRegion region;
region.Sub(aBackgroundRect, *static_cast<nsRegion*>(cutoutRegion));
region.MoveBy(aBuilder->ToReferenceFrame(aFrame));
aList->AppendNewToTop<nsDisplaySolidColorRegion>(aBuilder, aFrame, region,
aColor);
return true;
}
enum class TableType : uint8_t {
Table,
TableCol,
TableColGroup,
TableRow,
TableRowGroup,
TableCell,
MAX,
};
enum class TableTypeBits : uint8_t { Count = 3 };
static_assert(static_cast<uint8_t>(TableType::MAX) <
(1 << (static_cast<uint8_t>(TableTypeBits::Count) + 1)),
"TableType cannot fit with TableTypeBits::Count");
TableType GetTableTypeFromFrame(nsIFrame* aFrame);
static uint16_t CalculateTablePerFrameKey(const uint16_t aIndex,
const TableType aType) {
const uint32_t key = (aIndex << static_cast<uint8_t>(TableTypeBits::Count)) |
static_cast<uint8_t>(aType);
return static_cast<uint16_t>(key);
}
static nsDisplayBackgroundImage* CreateBackgroundImage(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsIFrame* aSecondaryFrame,
const nsDisplayBackgroundImage::InitData& aBgData) {
const auto index = aBgData.layer;
if (aSecondaryFrame) {
const auto tableType = GetTableTypeFromFrame(aFrame);
const uint16_t tableItemIndex = CalculateTablePerFrameKey(index, tableType);
return MakeDisplayItemWithIndex<nsDisplayTableBackgroundImage>(
aBuilder, aSecondaryFrame, tableItemIndex, aBgData, aFrame);
}
return MakeDisplayItemWithIndex<nsDisplayBackgroundImage>(aBuilder, aFrame,
index, aBgData);
}
static nsDisplayThemedBackground* CreateThemedBackground(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsIFrame* aSecondaryFrame,
const nsRect& aBgRect) {
if (aSecondaryFrame) {
const uint16_t index = static_cast<uint16_t>(GetTableTypeFromFrame(aFrame));
return MakeDisplayItemWithIndex<nsDisplayTableThemedBackground>(
aBuilder, aSecondaryFrame, index, aBgRect, aFrame);
}
return MakeDisplayItem<nsDisplayThemedBackground>(aBuilder, aFrame, aBgRect);
}
static nsDisplayBackgroundColor* CreateBackgroundColor(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsIFrame* aSecondaryFrame,
nsRect& aBgRect, const ComputedStyle* aBgSC, nscolor aColor) {
if (aSecondaryFrame) {
const uint16_t index = static_cast<uint16_t>(GetTableTypeFromFrame(aFrame));
return MakeDisplayItemWithIndex<nsDisplayTableBackgroundColor>(
aBuilder, aSecondaryFrame, index, aBgRect, aBgSC, aColor, aFrame);
}
return MakeDisplayItem<nsDisplayBackgroundColor>(aBuilder, aFrame, aBgRect,
aBgSC, aColor);
}
static void DealWithWindowsAppearanceHacks(nsIFrame* aFrame,
nsDisplayListBuilder* aBuilder) {
if (!XRE_IsParentProcess()) {
return;
}
const auto& disp = *aFrame->StyleDisplay();
// We use default appearance rather than effective appearance because we want
// to handle when titlebar buttons that have appearance: none.
const auto defaultAppearance = disp.mDefaultAppearance;
if (MOZ_LIKELY(defaultAppearance == StyleAppearance::None)) {
return;
}
if (auto type = disp.GetWindowButtonType()) {
if (auto* widget = aFrame->GetNearestWidget()) {
auto rect = LayoutDevicePixel::FromAppUnitsToNearest(
nsRect(aBuilder->ToReferenceFrame(aFrame), aFrame->GetSize()),
aFrame->PresContext()->AppUnitsPerDevPixel());
widget->SetWindowButtonRect(*type, rect);
}
}
}
/*static*/
AppendedBackgroundType nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
const nsRect& aBackgroundRect, nsDisplayList* aList,
bool aAllowWillPaintBorderOptimization, const nsRect& aBackgroundOriginRect,
nsIFrame* aSecondaryReferenceFrame,
Maybe<nsDisplayListBuilder::AutoBuildingDisplayList>*
aAutoBuildingDisplayList) {
MOZ_ASSERT(!aFrame->IsCanvasFrame(),
"We don't expect propagated canvas backgrounds here");
#ifdef DEBUG
{
nsIFrame* bgFrame = nsCSSRendering::FindBackgroundFrame(aFrame);
MOZ_ASSERT(
!bgFrame || bgFrame == aFrame,
"Should only suppress backgrounds, never propagate to another frame");
}
#endif
DealWithWindowsAppearanceHacks(aFrame, aBuilder);
const bool isThemed = aFrame->IsThemed();
const ComputedStyle* bgSC = aFrame->Style();
const nsStyleBackground* bg = bgSC->StyleBackground();
const bool needsBackgroundColor =
aBuilder->IsForEventDelivery() ||
(EffectCompositor::HasAnimationsForCompositor(
aFrame, DisplayItemType::TYPE_BACKGROUND_COLOR) &&
!isThemed);
if (!needsBackgroundColor && !isThemed && bg->IsTransparent(bgSC)) {
return AppendedBackgroundType::None;
}
bool drawBackgroundColor = false;
bool drawBackgroundImage = false;
nscolor color = NS_RGBA(0, 0, 0, 0);
// Don't get background color / images if we propagated our background to the
// canvas (that is, if FindBackgroundFrame is null). But don't early return
// yet, since we might still need a background-color item for hit-testing.
if (!isThemed && nsCSSRendering::FindBackgroundFrame(aFrame)) {
color = nsCSSRendering::DetermineBackgroundColor(
aFrame->PresContext(), bgSC, aFrame, drawBackgroundImage,
drawBackgroundColor);
}
if (SpecialCutoutRegionCase(aBuilder, aFrame, aBackgroundRect, aList,
color)) {
return AppendedBackgroundType::None;
}
const nsStyleBorder& border = *aFrame->StyleBorder();
const bool willPaintBorder =
aAllowWillPaintBorderOptimization && !isThemed &&
!aFrame->StyleEffects()->HasBoxShadowWithInset(true) &&
border.HasBorder();
auto EnsureBuildingDisplayList = [&] {
if (!aAutoBuildingDisplayList || *aAutoBuildingDisplayList) {
return;
}
nsPoint offset = aBuilder->GetCurrentFrame()->GetOffsetTo(aFrame);
aAutoBuildingDisplayList->emplace(aBuilder, aFrame,
aBuilder->GetVisibleRect() + offset,
aBuilder->GetDirtyRect() + offset);
};
// An auxiliary list is necessary in case we have background blending; if that
// is the case, background items need to be wrapped by a blend container to
// isolate blending to the background
nsDisplayList bgItemList(aBuilder);
// Even if we don't actually have a background color to paint, we may still
// need to create an item for hit testing and we still need to create an item
// for background-color animations.
if ((drawBackgroundColor && color != NS_RGBA(0, 0, 0, 0)) ||
needsBackgroundColor) {
EnsureBuildingDisplayList();
Maybe<DisplayListClipState::AutoSaveRestore> clipState;
nsRect bgColorRect = aBackgroundRect;
if (!isThemed && !aBuilder->IsForEventDelivery()) {
// Disable the will-paint-border optimization for background
// colors with no border-radius. Enabling it for background colors
// doesn't help much (there are no tiling issues) and clipping the
// background breaks detection of the element's border-box being
// opaque. For nonzero border-radius we still need it because we
// want to inset the background if possible to avoid antialiasing
// artifacts along the rounded corners.
const bool useWillPaintBorderOptimization =
willPaintBorder &&
nsLayoutUtils::HasNonZeroCorner(border.mBorderRadius);
nsCSSRendering::ImageLayerClipState clip;
nsCSSRendering::GetImageLayerClip(
bg->BottomLayer(), aFrame, border, aBackgroundRect, aBackgroundRect,
useWillPaintBorderOptimization,
aFrame->PresContext()->AppUnitsPerDevPixel(), &clip);
bgColorRect = bgColorRect.Intersect(clip.mBGClipArea);
if (clip.mHasAdditionalBGClipArea) {
bgColorRect = bgColorRect.Intersect(clip.mAdditionalBGClipArea);
}
if (clip.mHasRoundedCorners) {
clipState.emplace(aBuilder);
clipState->ClipContentDescendants(clip.mBGClipArea, &clip.mRadii);
}
}
nsDisplayBackgroundColor* bgItem = CreateBackgroundColor(
aBuilder, aFrame, aSecondaryReferenceFrame, bgColorRect, bgSC,
drawBackgroundColor ? color : NS_RGBA(0, 0, 0, 0));
if (bgItem) {
bgItemList.AppendToTop(bgItem);
}
}
if (isThemed) {
nsDisplayThemedBackground* bgItem = CreateThemedBackground(
aBuilder, aFrame, aSecondaryReferenceFrame, aBackgroundRect);
if (bgItem) {
bgItem->Init(aBuilder);
bgItemList.AppendToTop(bgItem);
}
if (!bgItemList.IsEmpty()) {
aList->AppendToTop(&bgItemList);
return AppendedBackgroundType::ThemedBackground;
}
return AppendedBackgroundType::None;
}
if (!drawBackgroundImage) {
if (!bgItemList.IsEmpty()) {
aList->AppendToTop(&bgItemList);
return AppendedBackgroundType::Background;
}
return AppendedBackgroundType::None;
}
const ActiveScrolledRoot* asr = aBuilder->CurrentActiveScrolledRoot();
bool needBlendContainer = false;
const nsRect& bgOriginRect =
aBackgroundOriginRect.IsEmpty() ? aBackgroundRect : aBackgroundOriginRect;
// Passing bg == nullptr in this macro will result in one iteration with
// i = 0.
NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, bg->mImage) {
if (bg->mImage.mLayers[i].mImage.IsNone()) {
continue;
}
EnsureBuildingDisplayList();
if (bg->mImage.mLayers[i].mBlendMode != StyleBlend::Normal) {
needBlendContainer = true;
}
DisplayListClipState::AutoSaveRestore clipState(aBuilder);
if (!aBuilder->IsForEventDelivery()) {
const nsStyleImageLayers::Layer& layer = bg->mImage.mLayers[i];
SetBackgroundClipRegion(clipState, aFrame, layer, aBackgroundRect,
willPaintBorder);
}
nsDisplayList thisItemList(aBuilder);
nsDisplayBackgroundImage::InitData bgData =
nsDisplayBackgroundImage::GetInitData(aBuilder, aFrame, i, bgOriginRect,
bgSC);
if (bgData.shouldFixToViewport) {
auto* displayData = aBuilder->GetCurrentFixedBackgroundDisplayData();
nsDisplayListBuilder::AutoBuildingDisplayList buildingDisplayList(
aBuilder, aFrame, aBuilder->GetVisibleRect(),
aBuilder->GetDirtyRect());
nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter asrSetter(
aBuilder);
if (displayData) {
asrSetter.SetCurrentActiveScrolledRoot(
displayData->mContainingBlockActiveScrolledRoot);
asrSetter.SetCurrentScrollParentId(displayData->mScrollParentId);
if (nsLayoutUtils::UsesAsyncScrolling(aFrame)) {
// Override the dirty rect on the builder to be the dirty rect of
// the viewport.
// displayData->mDirtyRect is relative to the presshell's viewport
// frame (the root frame), and we need it to be relative to aFrame.
nsIFrame* rootFrame =
aBuilder->CurrentPresShellState()->mPresShell->GetRootFrame();
// There cannot be any transforms between aFrame and rootFrame
// because then bgData.shouldFixToViewport would have been false.
nsRect visibleRect =
displayData->mVisibleRect + aFrame->GetOffsetTo(rootFrame);
aBuilder->SetVisibleRect(visibleRect);
nsRect dirtyRect =
displayData->mDirtyRect + aFrame->GetOffsetTo(rootFrame);
aBuilder->SetDirtyRect(dirtyRect);
}
}
nsDisplayBackgroundImage* bgItem = nullptr;
{
// The clip is captured by the nsDisplayFixedPosition, so clear the
// clip for the nsDisplayBackgroundImage inside.
DisplayListClipState::AutoSaveRestore bgImageClip(aBuilder);
bgImageClip.Clear();
bgItem = CreateBackgroundImage(aBuilder, aFrame,
aSecondaryReferenceFrame, bgData);
}
if (bgItem) {
const ActiveScrolledRoot* scrollTargetASR =
asr ? asr->GetNearestScrollASR() : nullptr;
thisItemList.AppendToTop(
nsDisplayFixedPosition::CreateForFixedBackground(
aBuilder, aFrame, aSecondaryReferenceFrame, bgItem, i,
scrollTargetASR));
}
} else { // bgData.shouldFixToViewport == false
nsDisplayBackgroundImage* bgItem = CreateBackgroundImage(
aBuilder, aFrame, aSecondaryReferenceFrame, bgData);
if (bgItem) {
thisItemList.AppendToTop(bgItem);
}
}
if (bg->mImage.mLayers[i].mBlendMode != StyleBlend::Normal) {
// asr is scrolled. Even if we wrap a fixed background layer, that's
// fine, because the item will have a scrolled clip that limits the
// item with respect to asr.
if (aSecondaryReferenceFrame) {
const auto tableType = GetTableTypeFromFrame(aFrame);
const uint16_t index = CalculateTablePerFrameKey(i + 1, tableType);
thisItemList.AppendNewToTopWithIndex<nsDisplayTableBlendMode>(
aBuilder, aSecondaryReferenceFrame, index, &thisItemList,
bg->mImage.mLayers[i].mBlendMode, asr, ContainerASRType::Constant,
aFrame, true);
} else {
thisItemList.AppendNewToTopWithIndex<nsDisplayBlendMode>(
aBuilder, aFrame, i + 1, &thisItemList,
bg->mImage.mLayers[i].mBlendMode, asr, ContainerASRType::Constant,
true);
}
}
bgItemList.AppendToTop(&thisItemList);
}
if (needBlendContainer) {
bgItemList.AppendToTop(
nsDisplayBlendContainer::CreateForBackgroundBlendMode(
aBuilder, aFrame, aSecondaryReferenceFrame, &bgItemList, asr,
nsDisplayItem::ContainerASRType::Constant));
}
if (!bgItemList.IsEmpty()) {
aList->AppendToTop(&bgItemList);
return AppendedBackgroundType::Background;
}
return AppendedBackgroundType::None;
}
// Check that the rounded border of aFrame, added to aToReferenceFrame,
// intersects aRect. Assumes that the unrounded border has already
// been checked for intersection.
static bool RoundedBorderIntersectsRect(nsIFrame* aFrame,
const nsPoint& aFrameToReferenceFrame,
const nsRect& aTestRect) {
if (!nsRect(aFrameToReferenceFrame, aFrame->GetSize())
.Intersects(aTestRect)) {
return false;
}
nsRectCornerRadii radii;
return !aFrame->GetBorderRadii(radii) ||
nsLayoutUtils::RoundedRectIntersectsRect(
nsRect(aFrameToReferenceFrame, aFrame->GetSize()), radii,
aTestRect);
}
// Returns TRUE if aContainedRect is guaranteed to be contained in
// the rounded rect defined by aRoundedRect and aRadii. Complex cases are
// handled conservatively by returning FALSE in some situations where
// a more thorough analysis could return TRUE.
//
// See also RoundedRectIntersectsRect.
static bool RoundedRectContainsRect(const nsRect& aRoundedRect,
const nsRectCornerRadii& aRadii,
const nsRect& aContainedRect) {
nsRegion rgn = nsLayoutUtils::RoundedRectIntersectRect(aRoundedRect, aRadii,
aContainedRect);
return rgn.Contains(aContainedRect);
}
bool nsDisplayBackgroundImage::CanApplyOpacity(
WebRenderLayerManager* aManager, nsDisplayListBuilder* aBuilder) const {
return CanBuildWebRenderDisplayItems(aManager, aBuilder);
}
bool nsDisplayBackgroundImage::CanBuildWebRenderDisplayItems(
WebRenderLayerManager* aManager, nsDisplayListBuilder* aBuilder) const {
return mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer].mClip !=
StyleGeometryBox::Text &&
nsCSSRendering::CanBuildWebRenderDisplayItemsForStyleImageLayer(
aManager, *StyleFrame()->PresContext(), StyleFrame(),
mBackgroundStyle->StyleBackground(), mLayer,
aBuilder->GetBackgroundPaintFlags());
}
bool nsDisplayBackgroundImage::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
if (!CanBuildWebRenderDisplayItems(aManager->LayerManager(),
aDisplayListBuilder)) {
return false;
}
uint32_t paintFlags = aDisplayListBuilder->GetBackgroundPaintFlags();
bool dummy;
nsCSSRendering::PaintBGParams params =
nsCSSRendering::PaintBGParams::ForSingleLayer(
*StyleFrame()->PresContext(), GetBounds(aDisplayListBuilder, &dummy),
mBackgroundRect, StyleFrame(), paintFlags, mLayer,
CompositionOp::OP_OVER, aBuilder.GetInheritedOpacity());
params.bgClipRect = &mBounds;
ImgDrawResult result =
nsCSSRendering::BuildWebRenderDisplayItemsForStyleImageLayer(
params, aBuilder, aResources, aSc, aManager, this);
if (result == ImgDrawResult::NOT_SUPPORTED) {
return false;
}
if (nsIContent* content = StyleFrame()->GetContent()) {
if (imgRequestProxy* requestProxy = mBackgroundStyle->StyleBackground()
->mImage.mLayers[mLayer]
.mImage.GetImageRequest()) {
// LCP don't consider gradient backgrounds.
LCPHelpers::FinalizeLCPEntryForImage(content->AsElement(), requestProxy,
mBounds - ToReferenceFrame());
}
}
return true;
}
void nsDisplayBackgroundImage::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect,
HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
if (ShouldIgnoreForBackfaceHidden(aState)) {
return;
}
if (RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
aOutFrames->AppendElement(mFrame);
}
}
static nsRect GetInsideClipRect(const nsDisplayItem* aItem,
StyleGeometryBox aClip, const nsRect& aRect,
const nsRect& aBackgroundRect) {
if (aRect.IsEmpty()) {
return {};
}
nsIFrame* frame = aItem->Frame();
nsRect clipRect = aBackgroundRect;
if (frame->IsCanvasFrame()) {
nsCanvasFrame* canvasFrame = static_cast<nsCanvasFrame*>(frame);
clipRect = canvasFrame->CanvasArea() + aItem->ToReferenceFrame();
} else if (aClip == StyleGeometryBox::PaddingBox ||
aClip == StyleGeometryBox::ContentBox) {
nsMargin border = frame->GetUsedBorder();
if (aClip == StyleGeometryBox::ContentBox) {
border += frame->GetUsedPadding();
}
border.ApplySkipSides(frame->GetSkipSides());
clipRect.Deflate(border);
}
return clipRect.Intersect(aRect);
}
nsRegion nsDisplayBackgroundImage::GetOpaqueRegion(
nsDisplayListBuilder* aBuilder, bool* aSnap) const {
nsRegion result;
*aSnap = false;
if (!mBackgroundStyle) {
return result;
}
*aSnap = true;
// For StyleBoxDecorationBreak::Slice, don't try to optimize here, since
// this could easily lead to O(N^2) behavior inside InlineBackgroundData,
// which expects frames to be sent to it in content order, not reverse
// content order which we'll produce here.
// Of course, if there's only one frame in the flow, it doesn't matter.
if (mFrame->StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone ||
(!mFrame->GetPrevContinuation() && !mFrame->GetNextContinuation())) {
const nsStyleImageLayers::Layer& layer =
mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
if (layer.mImage.IsOpaque() && layer.mBlendMode == StyleBlend::Normal &&
layer.mRepeat.mXRepeat != StyleImageLayerRepeat::Space &&
layer.mRepeat.mYRepeat != StyleImageLayerRepeat::Space &&
layer.mClip != StyleGeometryBox::Text) {
result = GetInsideClipRect(this, layer.mClip, mBounds, mBackgroundRect);
}
}
return result;
}
Maybe<nscolor> nsDisplayBackgroundImage::IsUniform(
nsDisplayListBuilder* aBuilder) const {
if (!mBackgroundStyle) {
return Some(NS_RGBA(0, 0, 0, 0));
}
return Nothing();
}
nsRect nsDisplayBackgroundImage::GetPositioningArea() const {
if (!mBackgroundStyle) {
return nsRect();
}
nsIFrame* attachedToFrame;
bool transformedFixed;
return nsCSSRendering::ComputeImageLayerPositioningArea(
mFrame->PresContext(), mFrame, mBackgroundRect,
mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer],
&attachedToFrame, &transformedFixed) +
ToReferenceFrame();
}
bool nsDisplayBackgroundImage::RenderingMightDependOnPositioningAreaSizeChange()
const {
if (!mBackgroundStyle) {
return false;
}
nsRectCornerRadii radii;
if (mFrame->GetBorderRadii(radii)) {
// A change in the size of the positioning area might change the position
// of the rounded corners.
return true;
}
const nsStyleImageLayers::Layer& layer =
mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
return layer.RenderingMightDependOnPositioningAreaSizeChange();
}
void nsDisplayBackgroundImage::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
PaintInternal(aBuilder, aCtx, GetPaintRect(aBuilder, aCtx), &mBounds);
}
void nsDisplayBackgroundImage::PaintInternal(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx,
const nsRect& aBounds,
nsRect* aClipRect) {
gfxContext* ctx = aCtx;
StyleGeometryBox clip =
mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer].mClip;
if (clip == StyleGeometryBox::Text) {
if (!GenerateAndPushTextMask(StyleFrame(), aCtx, mBackgroundRect,
aBuilder)) {
return;
}
}
nsCSSRendering::PaintBGParams params =
nsCSSRendering::PaintBGParams::ForSingleLayer(
*StyleFrame()->PresContext(), aBounds, mBackgroundRect, StyleFrame(),
aBuilder->GetBackgroundPaintFlags(), mLayer, CompositionOp::OP_OVER,
1.0f);
params.bgClipRect = aClipRect;
(void)nsCSSRendering::PaintStyleImageLayer(params, *aCtx);
if (clip == StyleGeometryBox::Text) {
ctx->PopGroupAndBlend();
}
}
void nsDisplayBackgroundImage::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
if (!mBackgroundStyle) {
return;
}
const auto* geometry =
static_cast<const nsDisplayBackgroundGeometry*>(aGeometry);
bool snap;
nsRect bounds = GetBounds(aBuilder, &snap);
nsRect positioningArea = GetPositioningArea();
if (positioningArea.TopLeft() != geometry->mPositioningArea.TopLeft() ||
(positioningArea.Size() != geometry->mPositioningArea.Size() &&
RenderingMightDependOnPositioningAreaSizeChange())) {
// Positioning area changed in a way that could cause everything to change,
// so invalidate everything (both old and new painting areas).
aInvalidRegion->Or(bounds, geometry->mBounds);
return;
}
if (!mDestRect.IsEqualInterior(geometry->mDestRect)) {
// Dest area changed in a way that could cause everything to change,
// so invalidate everything (both old and new painting areas).
aInvalidRegion->Or(bounds, geometry->mBounds);
return;
}
if (!bounds.IsEqualInterior(geometry->mBounds)) {
// Positioning area is unchanged, so invalidate just the change in the
// painting area.
aInvalidRegion->Xor(bounds, geometry->mBounds);
}
}
nsRect nsDisplayBackgroundImage::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = true;
return mBounds;
}
nsRect nsDisplayBackgroundImage::GetBoundsInternal(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrameForBounds) {
// This allows nsDisplayTableBackgroundImage to change the frame used for
// bounds calculation.
nsIFrame* frame = aFrameForBounds ? aFrameForBounds : mFrame;
nsPresContext* presContext = frame->PresContext();
if (!mBackgroundStyle) {
return nsRect();
}
nsRect clipRect = mBackgroundRect;
if (frame->IsCanvasFrame()) {
nsCanvasFrame* canvasFrame = static_cast<nsCanvasFrame*>(frame);
clipRect = canvasFrame->CanvasArea() + ToReferenceFrame();
}
const nsStyleImageLayers::Layer& layer =
mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
return nsCSSRendering::GetBackgroundLayerRect(
presContext, frame, mBackgroundRect, clipRect, layer,
aBuilder->GetBackgroundPaintFlags());
}
nsDisplayTableBackgroundImage::nsDisplayTableBackgroundImage(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, const InitData& aData,
nsIFrame* aCellFrame)
: nsDisplayBackgroundImage(aBuilder, aFrame, aData, aCellFrame),
mStyleFrame(aCellFrame) {
if (aBuilder->IsRetainingDisplayList()) {
mStyleFrame->AddDisplayItem(this);
}
}
void nsDisplayTableBackgroundImage::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mStyleFrame);
nsDisplayBackgroundImage::Destroy(aBuilder);
}
bool nsDisplayTableBackgroundImage::IsInvalid(nsRect& aRect) const {
bool result = mStyleFrame ? mStyleFrame->IsInvalid(aRect) : false;
aRect += ToReferenceFrame();
return result;
}
nsDisplayThemedBackground::nsDisplayThemedBackground(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
const nsRect& aBackgroundRect)
: nsPaintedDisplayItem(aBuilder, aFrame), mBackgroundRect(aBackgroundRect) {
MOZ_COUNT_CTOR(nsDisplayThemedBackground);
}
void nsDisplayThemedBackground::Init(nsDisplayListBuilder* aBuilder) {
const nsStyleDisplay* disp = StyleFrame()->StyleDisplay();
mAppearance = disp->EffectiveAppearance();
StyleFrame()->IsThemed(disp, &mThemeTransparency);
// Perform necessary RegisterThemeGeometry
nsITheme* theme = StyleFrame()->PresContext()->Theme();
nsITheme::ThemeGeometryType type =
theme->ThemeGeometryTypeForWidget(StyleFrame(), mAppearance);
if (type != nsITheme::eThemeGeometryTypeUnknown) {
RegisterThemeGeometry(aBuilder, this, StyleFrame(), type);
}
mBounds = GetBoundsInternal();
}
void nsDisplayThemedBackground::WriteDebugInfo(std::stringstream& aStream) {
aStream << " (themed, appearance:" << (int)mAppearance << ")";
}
void nsDisplayThemedBackground::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect,
HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
if (ShouldIgnoreForBackfaceHidden(aState)) {
return;
}
// Assume that any point in our background rect is a hit.
if (mBackgroundRect.Intersects(aRect)) {
aOutFrames->AppendElement(mFrame);
}
}
nsRegion nsDisplayThemedBackground::GetOpaqueRegion(
nsDisplayListBuilder* aBuilder, bool* aSnap) const {
nsRegion result;
*aSnap = false;
if (mThemeTransparency == nsITheme::eOpaque) {
*aSnap = true;
result = mBackgroundRect;
}
return result;
}
Maybe<nscolor> nsDisplayThemedBackground::IsUniform(
nsDisplayListBuilder* aBuilder) const {
return Nothing();
}
nsRect nsDisplayThemedBackground::GetPositioningArea() const {
return mBackgroundRect;
}
void nsDisplayThemedBackground::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
PaintInternal(aBuilder, aCtx, GetPaintRect(aBuilder, aCtx), nullptr);
}
void nsDisplayThemedBackground::PaintInternal(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx,
const nsRect& aBounds,
nsRect* aClipRect) {
// XXXzw this ignores aClipRect.
nsPresContext* presContext = StyleFrame()->PresContext();
nsITheme* theme = presContext->Theme();
nsRect drawing(mBackgroundRect);
theme->GetWidgetOverflow(presContext->DeviceContext(), StyleFrame(),
mAppearance, &drawing);
drawing.IntersectRect(drawing, aBounds);
theme->DrawWidgetBackground(aCtx, StyleFrame(), mAppearance, mBackgroundRect,
drawing);
}
bool nsDisplayThemedBackground::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
nsITheme* theme = StyleFrame()->PresContext()->Theme();
return theme->CreateWebRenderCommandsForWidget(aBuilder, aResources, aSc,
aManager, StyleFrame(),
mAppearance, mBackgroundRect);
}
bool nsDisplayThemedBackground::IsWindowActive() const {
return !mFrame->PresContext()->Document()->IsTopLevelWindowInactive();
}
void nsDisplayThemedBackground::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
const auto* geometry =
static_cast<const nsDisplayThemedBackgroundGeometry*>(aGeometry);
bool snap;
nsRect bounds = GetBounds(aBuilder, &snap);
nsRect positioningArea = GetPositioningArea();
if (!positioningArea.IsEqualInterior(geometry->mPositioningArea)) {
// Invalidate everything (both old and new painting areas).
aInvalidRegion->Or(bounds, geometry->mBounds);
return;
}
if (!bounds.IsEqualInterior(geometry->mBounds)) {
// Positioning area is unchanged, so invalidate just the change in the
// painting area.
aInvalidRegion->Xor(bounds, geometry->mBounds);
}
nsITheme* theme = StyleFrame()->PresContext()->Theme();
if (theme->WidgetAppearanceDependsOnWindowFocus(mAppearance) &&
IsWindowActive() != geometry->mWindowIsActive) {
aInvalidRegion->Or(*aInvalidRegion, bounds);
}
}
nsRect nsDisplayThemedBackground::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = true;
return mBounds;
}
nsRect nsDisplayThemedBackground::GetBoundsInternal() {
nsPresContext* presContext = mFrame->PresContext();
nsRect r = mBackgroundRect - ToReferenceFrame();
presContext->Theme()->GetWidgetOverflow(
presContext->DeviceContext(), mFrame,
mFrame->StyleDisplay()->EffectiveAppearance(), &r);
return r + ToReferenceFrame();
}
void nsDisplayTableThemedBackground::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mAncestorFrame);
nsDisplayThemedBackground::Destroy(aBuilder);
}
#if defined(MOZ_REFLOW_PERF_DSP) && defined(MOZ_REFLOW_PERF)
void nsDisplayReflowCount::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
mFrame->PresShell()->PaintCount(mFrameName, aCtx, mFrame->PresContext(),
mFrame, ToReferenceFrame(), mColor);
}
#endif
void nsDisplayBackgroundColor::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mDependentFrame);
nsPaintedDisplayItem::Destroy(aBuilder);
}
bool nsDisplayBackgroundColor::CanApplyOpacity(
WebRenderLayerManager* aManager, nsDisplayListBuilder* aBuilder) const {
// Don't apply opacity if the background color is animated since the color is
// going to be changed on the compositor.
return !EffectCompositor::HasAnimationsForCompositor(
mFrame, DisplayItemType::TYPE_BACKGROUND_COLOR);
}
bool nsDisplayBackgroundColor::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
gfx::sRGBColor color = mColor;
color.a *= aBuilder.GetInheritedOpacity();
if (color == sRGBColor() &&
!EffectCompositor::HasAnimationsForCompositor(
mFrame, DisplayItemType::TYPE_BACKGROUND_COLOR)) {
return true;
}
if (HasBackgroundClipText()) {
return false;
}
uint64_t animationsId = 0;
// We don't support background-color animations on table elements yet.
if (GetType() == DisplayItemType::TYPE_BACKGROUND_COLOR) {
animationsId =
AddAnimationsForWebRender(this, aManager, aDisplayListBuilder);
}
LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
mBackgroundRect, mFrame->PresContext()->AppUnitsPerDevPixel());
wr::LayoutRect r = wr::ToLayoutRect(bounds);
if (animationsId) {
wr::WrAnimationProperty prop{
wr::WrAnimationType::BackgroundColor,
animationsId,
};
aBuilder.PushRectWithAnimation(r, r, !BackfaceIsHidden(),
wr::ToColorF(ToDeviceColor(color)), &prop);
} else {
aBuilder.StartGroup(this);
aBuilder.PushRect(r, r, !BackfaceIsHidden(), false, false,
wr::ToColorF(ToDeviceColor(color)));
aBuilder.FinishGroup();
}
return true;
}
void nsDisplayBackgroundColor::PaintWithClip(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx,
const DisplayItemClip& aClip) {
MOZ_ASSERT(!HasBackgroundClipText());
if (mColor == sRGBColor()) {
return;
}
nsRect fillRect = mBackgroundRect;
if (aClip.HasClip()) {
fillRect.IntersectRect(fillRect, aClip.GetClipRect());
}
DrawTarget* dt = aCtx->GetDrawTarget();
int32_t A2D = mFrame->PresContext()->AppUnitsPerDevPixel();
Rect bounds = ToRect(nsLayoutUtils::RectToGfxRect(fillRect, A2D));
MaybeSnapToDevicePixels(bounds, *dt);
ColorPattern fill(ToDeviceColor(mColor));
if (aClip.GetRoundedRectCount()) {
MOZ_ASSERT(aClip.GetRoundedRectCount() == 1);
AutoTArray<DisplayItemClip::RoundedRect, 1> roundedRect;
aClip.AppendRoundedRects(&roundedRect);
bool pushedClip = false;
if (!fillRect.Contains(roundedRect[0].mRect)) {
dt->PushClipRect(bounds);
pushedClip = true;
}
RectCornerRadii pixelRadii;
nsCSSRendering::ComputePixelRadii(roundedRect[0].mRadii, A2D, &pixelRadii);
dt->FillRoundedRect(
RoundedRect(NSRectToSnappedRect(roundedRect[0].mRect, A2D, *dt),
pixelRadii),
fill);
if (pushedClip) {
dt->PopClip();
}
} else {
dt->FillRect(bounds, fill);
}
}
void nsDisplayBackgroundColor::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
if (mColor == sRGBColor()) {
return;
}
#if 0
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1148418#c21 for why this
// results in a precision induced rounding issue that makes the rect one
// pixel shorter in rare cases. Disabled in favor of the old code for now.
// Note that the pref layout.css.devPixelsPerPx needs to be set to 1 to
// reproduce the bug.
//
// TODO:
// This new path does not include support for background-clip:text; need to
// be fixed if/when we switch to this new code path.
DrawTarget& aDrawTarget = *aCtx->GetDrawTarget();
Rect rect = NSRectToSnappedRect(mBackgroundRect,
mFrame->PresContext()->AppUnitsPerDevPixel(),
aDrawTarget);
ColorPattern color(ToDeviceColor(mColor));
aDrawTarget.FillRect(rect, color);
#else
gfxContext* ctx = aCtx;
gfxRect bounds = nsLayoutUtils::RectToGfxRect(
mBackgroundRect, mFrame->PresContext()->AppUnitsPerDevPixel());
if (HasBackgroundClipText()) {
if (!GenerateAndPushTextMask(mFrame, aCtx, mBackgroundRect, aBuilder)) {
return;
}
ctx->SetColor(mColor);
ctx->NewPath();
ctx->SnappedRectangle(bounds);
ctx->Fill();
ctx->PopGroupAndBlend();
return;
}
ctx->SetColor(mColor);
ctx->NewPath();
ctx->SnappedRectangle(bounds);
ctx->Fill();
#endif
}
nsRegion nsDisplayBackgroundColor::GetOpaqueRegion(
nsDisplayListBuilder* aBuilder, bool* aSnap) const {
*aSnap = false;
if (mColor.a != 1 ||
// Even if the current alpha channel is 1, we treat this item as if it's
// non-opaque if there is a background-color animation since the animation
// might change the alpha channel.
EffectCompositor::HasAnimationsForCompositor(
mFrame, DisplayItemType::TYPE_BACKGROUND_COLOR)) {
return nsRegion();
}
if (!mHasStyle || HasBackgroundClipText()) {
return nsRegion();
}
*aSnap = true;
return GetInsideClipRect(this, mBottomLayerClip, mBackgroundRect,
mBackgroundRect);
}
Maybe<nscolor> nsDisplayBackgroundColor::IsUniform(
nsDisplayListBuilder* aBuilder) const {
return Some(mColor.ToABGR());
}
void nsDisplayBackgroundColor::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect,
HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
if (ShouldIgnoreForBackfaceHidden(aState)) {
return;
}
if (!RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
// aRect doesn't intersect our border-radius curve.
return;
}
aOutFrames->AppendElement(mFrame);
}
void nsDisplayBackgroundColor::WriteDebugInfo(std::stringstream& aStream) {
aStream << " (rgba " << mColor.r << "," << mColor.g << "," << mColor.b << ","
<< mColor.a << ")";
aStream << " backgroundRect" << mBackgroundRect;
}
nsRect nsDisplayOutline::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
return mFrame->InkOverflowRectRelativeToSelf() + ToReferenceFrame();
}
nsRect nsDisplayOutline::GetInnerRect() const {
if (nsRect* savedOutlineInnerRect =
mFrame->GetProperty(nsIFrame::OutlineInnerRectProperty())) {
return *savedOutlineInnerRect;
}
return mFrame->GetRectRelativeToSelf();
}
void nsDisplayOutline::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
// TODO join outlines together
MOZ_ASSERT(mFrame->StyleOutline()->ShouldPaintOutline(),
"Should have not created a nsDisplayOutline!");
nsRect rect = GetInnerRect() + ToReferenceFrame();
nsPresContext* pc = mFrame->PresContext();
if (IsThemedOutline()) {
pc->Theme()->DrawWidgetBackground(aCtx, mFrame,
StyleAppearance::FocusOutline, rect,
GetPaintRect(aBuilder, aCtx));
return;
}
nsCSSRendering::PaintNonThemedOutline(
pc, *aCtx, mFrame, GetPaintRect(aBuilder, aCtx), rect, mFrame->Style());
}
bool nsDisplayOutline::IsThemedOutline() const {
#ifdef DEBUG
nsPresContext* pc = mFrame->PresContext();
MOZ_ASSERT(
pc->Theme()->ThemeSupportsWidget(pc, mFrame,
StyleAppearance::FocusOutline),
"All of our supported platforms have support for themed focus-outlines");
#endif
return mFrame->StyleOutline()->mOutlineStyle.IsAuto();
}
bool nsDisplayOutline::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
nsPresContext* pc = mFrame->PresContext();
nsRect rect = GetInnerRect() + ToReferenceFrame();
if (IsThemedOutline()) {
return pc->Theme()->CreateWebRenderCommandsForWidget(
aBuilder, aResources, aSc, aManager, mFrame,
StyleAppearance::FocusOutline, rect);
}
bool dummy;
Maybe<nsCSSBorderRenderer> borderRenderer =
nsCSSRendering::CreateBorderRendererForNonThemedOutline(
pc, /* aDrawTarget = */ nullptr, mFrame,
GetBounds(aDisplayListBuilder, &dummy), rect, mFrame->Style());
if (!borderRenderer) {
// No border renderer means "there is no outline".
// Paint nothing and return success.
return true;
}
borderRenderer->CreateWebRenderCommands(this, aBuilder, aResources, aSc);
return true;
}
bool nsDisplayOutline::HasRadius() const {
const auto& radius = mFrame->StyleBorder()->mBorderRadius;
return !nsLayoutUtils::HasNonZeroCorner(radius);
}
bool nsDisplayOutline::IsInvisibleInRect(const nsRect& aRect) const {
nsRect borderBox(ToReferenceFrame(), mFrame->GetSize());
// aRect is entirely inside the border-rect, and the outline isn't rendered
// inside the border-rect, so the outline is not visible.
return borderBox.Contains(aRect) && !HasRadius() &&
mFrame->StyleOutline()->mOutlineOffset >= 0;
}
void nsDisplayEventReceiver::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect, HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
if (ShouldIgnoreForBackfaceHidden(aState)) {
return;
}
if (!RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
// aRect doesn't intersect our border-radius curve.
return;
}
aOutFrames->AppendElement(mFrame);
}
bool nsDisplayCompositorHitTestInfo::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
return true;
}
int32_t nsDisplayCompositorHitTestInfo::ZIndex() const {
return mOverrideZIndex ? *mOverrideZIndex : nsDisplayItem::ZIndex();
}
void nsDisplayCompositorHitTestInfo::SetOverrideZIndex(int32_t aZIndex) {
mOverrideZIndex = Some(aZIndex);
}
nsDisplayCaret::nsDisplayCaret(nsDisplayListBuilder* aBuilder,
nsIFrame* aCaretFrame)
: nsPaintedDisplayItem(aBuilder, aCaretFrame),
mCaret(aBuilder->GetCaret()),
mBounds(aBuilder->GetCaretRect() + ToReferenceFrame()) {
MOZ_COUNT_CTOR(nsDisplayCaret);
// The presence of a caret doesn't change the overflow rect
// of the owning frame, so the normal building rect might not
// include the caret at all. We use MarkFrameForDisplay to ensure
// we build this item, and here we override the building rect
// to cover the pixels we're going to draw.
SetBuildingRect(mBounds);
}
nsRect nsDisplayCaret::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = true;
// The caret returns a rect in the coordinates of mFrame.
return mBounds;
}
void nsDisplayCaret::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
// Note: Because we exist, we know that the caret is visible, so we don't
// need to check for the caret's visibility.
mCaret->PaintCaret(*aCtx->GetDrawTarget(), mFrame, ToReferenceFrame());
}
bool nsDisplayCaret::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
using namespace layers;
nsRect caretRect;
nsRect hookRect;
nscolor caretColor;
nsIFrame* frame =
mCaret->GetPaintGeometry(&caretRect, &hookRect, &caretColor);
if (NS_WARN_IF(!frame) || NS_WARN_IF(frame != mFrame)) {
return true;
}
int32_t appUnitsPerDevPixel = frame->PresContext()->AppUnitsPerDevPixel();
gfx::DeviceColor color = ToDeviceColor(caretColor);
LayoutDeviceRect devCaretRect = LayoutDeviceRect::FromAppUnits(
caretRect + ToReferenceFrame(), appUnitsPerDevPixel);
LayoutDeviceRect devHookRect = LayoutDeviceRect::FromAppUnits(
hookRect + ToReferenceFrame(), appUnitsPerDevPixel);
wr::LayoutRect caret = wr::ToLayoutRect(devCaretRect);
wr::LayoutRect hook = wr::ToLayoutRect(devHookRect);
// Note, WR will pixel snap anything that is layout aligned.
aBuilder.PushRect(caret, caret, !BackfaceIsHidden(), false, false,
wr::ToColorF(color));
if (!devHookRect.IsEmpty()) {
aBuilder.PushRect(hook, hook, !BackfaceIsHidden(), false, false,
wr::ToColorF(color));
}
return true;
}
nsDisplayBorder::nsDisplayBorder(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame)
: nsPaintedDisplayItem(aBuilder, aFrame) {
MOZ_COUNT_CTOR(nsDisplayBorder);
mBounds = CalculateBounds<nsRect>(*mFrame->StyleBorder());
}
bool nsDisplayBorder::IsInvisibleInRect(const nsRect& aRect) const {
nsRect paddingRect = GetPaddingRect();
const nsStyleBorder* styleBorder;
if (paddingRect.Contains(aRect) &&
!(styleBorder = mFrame->StyleBorder())->IsBorderImageSizeAvailable() &&
!nsLayoutUtils::HasNonZeroCorner(styleBorder->mBorderRadius)) {
// aRect is entirely inside the content rect, and no part
// of the border is rendered inside the content rect, so we are not
// visible
// Skip this if there's a border-image (which draws a background
// too) or if there is a border-radius (which makes the border draw
// further in).
return true;
}
return false;
}
nsDisplayItemGeometry* nsDisplayBorder::AllocateGeometry(
nsDisplayListBuilder* aBuilder) {
return new nsDisplayBorderGeometry(this, aBuilder);
}
void nsDisplayBorder::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
const auto* geometry = static_cast<const nsDisplayBorderGeometry*>(aGeometry);
bool snap;
if (!geometry->mBounds.IsEqualInterior(GetBounds(aBuilder, &snap))) {
// We can probably get away with only invalidating the difference
// between the border and padding rects, but the XUL ui at least
// is apparently painting a background with this?
aInvalidRegion->Or(GetBounds(aBuilder, &snap), geometry->mBounds);
}
}
bool nsDisplayBorder::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
nsRect rect = nsRect(ToReferenceFrame(), mFrame->GetSize());
ImgDrawResult drawResult = nsCSSRendering::CreateWebRenderCommandsForBorder(
this, mFrame, rect, aBuilder, aResources, aSc, aManager,
aDisplayListBuilder);
if (drawResult == ImgDrawResult::NOT_SUPPORTED) {
return false;
}
return true;
};
void nsDisplayBorder::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
nsPoint offset = ToReferenceFrame();
PaintBorderFlags flags = aBuilder->ShouldSyncDecodeImages()
? PaintBorderFlags::SyncDecodeImages
: PaintBorderFlags();
(void)nsCSSRendering::PaintBorder(
mFrame->PresContext(), *aCtx, mFrame, GetPaintRect(aBuilder, aCtx),
nsRect(offset, mFrame->GetSize()), mFrame->Style(), flags,
mFrame->GetSkipSides());
}
nsRect nsDisplayBorder::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = true;
return mBounds;
}
void nsDisplayBoxShadowOuter::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
nsPoint offset = ToReferenceFrame();
nsRect borderRect = mFrame->VisualBorderRectRelativeToSelf() + offset;
nsPresContext* presContext = mFrame->PresContext();
AUTO_PROFILER_LABEL("nsDisplayBoxShadowOuter::Paint", GRAPHICS);
nsCSSRendering::PaintBoxShadowOuter(presContext, *aCtx, mFrame, borderRect,
GetPaintRect(aBuilder, aCtx), 1.0f);
}
nsRect nsDisplayBoxShadowOuter::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
return mBounds;
}
nsRect nsDisplayBoxShadowOuter::GetBoundsInternal() {
return nsLayoutUtils::GetBoxShadowRectForFrame(mFrame, mFrame->GetSize()) +
ToReferenceFrame();
}
bool nsDisplayBoxShadowOuter::IsInvisibleInRect(const nsRect& aRect) const {
nsPoint origin = ToReferenceFrame();
nsRect frameRect(origin, mFrame->GetSize());
if (!frameRect.Contains(aRect)) {
return false;
}
// the visible region is entirely inside the border-rect, and box shadows
// never render within the border-rect (unless there's a border radius).
nsRectCornerRadii twipsRadii;
bool hasBorderRadii = mFrame->GetBorderRadii(twipsRadii);
if (!hasBorderRadii) {
return true;
}
return RoundedRectContainsRect(frameRect, twipsRadii, aRect);
}
bool nsDisplayBoxShadowOuter::CanBuildWebRenderDisplayItems() const {
auto shadows = mFrame->StyleEffects()->mBoxShadow.AsSpan();
if (shadows.IsEmpty()) {
return false;
}
bool hasBorderRadius;
// We don't support native themed things yet like box shadows around
// input buttons.
//
// TODO(emilio): The non-native theme could provide the right rect+radius
// instead relatively painlessly, if we find this causes performance issues or
// what not.
return !nsCSSRendering::HasBoxShadowNativeTheme(mFrame, hasBorderRadius);
}
bool nsDisplayBoxShadowOuter::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
if (!CanBuildWebRenderDisplayItems()) {
return false;
}
int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
nsPoint offset = ToReferenceFrame();
nsRect borderRect = mFrame->VisualBorderRectRelativeToSelf() + offset;
bool snap;
nsRect bounds = GetBounds(aDisplayListBuilder, &snap);
bool hasBorderRadius;
bool nativeTheme =
nsCSSRendering::HasBoxShadowNativeTheme(mFrame, hasBorderRadius);
// Don't need the full size of the shadow rect like we do in
// nsCSSRendering since WR takes care of calculations for blur
// and spread radius.
nsRect frameRect =
nsCSSRendering::GetShadowRect(borderRect, nativeTheme, mFrame);
RectCornerRadii borderRadii;
if (hasBorderRadius) {
hasBorderRadius = nsCSSRendering::GetBorderRadii(frameRect, borderRect,
mFrame, borderRadii);
}
// Everything here is in app units, change to device units.
LayoutDeviceRect clipRect =
LayoutDeviceRect::FromAppUnits(bounds, appUnitsPerDevPixel);
auto shadows = mFrame->StyleEffects()->mBoxShadow.AsSpan();
MOZ_ASSERT(!shadows.IsEmpty());
for (const auto& shadow : Reversed(shadows)) {
if (shadow.inset) {
continue;
}
float blurRadius =
float(shadow.base.blur.ToAppUnits()) / float(appUnitsPerDevPixel);
gfx::sRGBColor shadowColor = nsCSSRendering::GetShadowColor(
shadow.base, mFrame, aBuilder.GetInheritedOpacity());
// We don't move the shadow rect here since WR does it for us
// Now translate everything to device pixels.
const nsRect& shadowRect = frameRect;
LayoutDevicePoint shadowOffset = LayoutDevicePoint::FromAppUnits(
nsPoint(shadow.base.horizontal.ToAppUnits(),
shadow.base.vertical.ToAppUnits()),
appUnitsPerDevPixel);
LayoutDeviceRect deviceBox =
LayoutDeviceRect::FromAppUnits(shadowRect, appUnitsPerDevPixel);
wr::LayoutRect deviceBoxRect = wr::ToLayoutRect(deviceBox);
wr::LayoutRect deviceClipRect = wr::ToLayoutRect(clipRect);
LayoutDeviceSize zeroSize;
wr::BorderRadius borderRadius =
wr::ToBorderRadius(zeroSize, zeroSize, zeroSize, zeroSize);
if (hasBorderRadius) {
borderRadius = wr::ToBorderRadius(
LayoutDeviceSize::FromUnknownSize(borderRadii.TopLeft()),
LayoutDeviceSize::FromUnknownSize(borderRadii.TopRight()),
LayoutDeviceSize::FromUnknownSize(borderRadii.BottomLeft()),
LayoutDeviceSize::FromUnknownSize(borderRadii.BottomRight()));
}
float spreadRadius =
float(shadow.spread.ToAppUnits()) / float(appUnitsPerDevPixel);
aBuilder.PushBoxShadow(deviceBoxRect, deviceClipRect, !BackfaceIsHidden(),
deviceBoxRect, wr::ToLayoutVector2D(shadowOffset),
wr::ToColorF(ToDeviceColor(shadowColor)), blurRadius,
spreadRadius, borderRadius,
wr::BoxShadowClipMode::Outset);
}
return true;
}
void nsDisplayBoxShadowOuter::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
const auto* geometry =
static_cast<const nsDisplayItemGenericGeometry*>(aGeometry);
bool snap;
if (!geometry->mBounds.IsEqualInterior(GetBounds(aBuilder, &snap)) ||
!geometry->mBorderRect.IsEqualInterior(GetBorderRect())) {
nsRegion oldShadow, newShadow;
nsRectCornerRadii dontCare;
bool hasBorderRadius = mFrame->GetBorderRadii(dontCare);
if (hasBorderRadius) {
// If we have rounded corners then we need to invalidate the frame area
// too since we paint into it.
oldShadow = geometry->mBounds;
newShadow = GetBounds(aBuilder, &snap);
} else {
oldShadow.Sub(geometry->mBounds, geometry->mBorderRect);
newShadow.Sub(GetBounds(aBuilder, &snap), GetBorderRect());
}
aInvalidRegion->Or(oldShadow, newShadow);
}
}
void nsDisplayBoxShadowInner::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
nsPoint offset = ToReferenceFrame();
nsRect borderRect = nsRect(offset, mFrame->GetSize());
nsPresContext* presContext = mFrame->PresContext();
AUTO_PROFILER_LABEL("nsDisplayBoxShadowInner::Paint", GRAPHICS);
nsCSSRendering::PaintBoxShadowInner(presContext, *aCtx, mFrame, borderRect);
}
bool nsDisplayBoxShadowInner::CanCreateWebRenderCommands(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
const nsPoint& aReferenceOffset) {
auto shadows = aFrame->StyleEffects()->mBoxShadow.AsSpan();
if (shadows.IsEmpty()) {
// Means we don't have to paint anything
return true;
}
bool hasBorderRadius;
bool nativeTheme =
nsCSSRendering::HasBoxShadowNativeTheme(aFrame, hasBorderRadius);
// We don't support native themed things yet like box shadows around
// input buttons.
return !nativeTheme;
}
/* static */
void nsDisplayBoxShadowInner::CreateInsetBoxShadowWebRenderCommands(
wr::DisplayListBuilder& aBuilder, const StackingContextHelper& aSc,
nsRect& aVisibleRect, nsIFrame* aFrame, const nsRect& aBorderRect) {
if (!nsCSSRendering::ShouldPaintBoxShadowInner(aFrame)) {
return;
}
int32_t appUnitsPerDevPixel = aFrame->PresContext()->AppUnitsPerDevPixel();
auto shadows = aFrame->StyleEffects()->mBoxShadow.AsSpan();
LayoutDeviceRect clipRect =
LayoutDeviceRect::FromAppUnits(aVisibleRect, appUnitsPerDevPixel);
for (const auto& shadow : Reversed(shadows)) {
if (!shadow.inset) {
continue;
}
nsRect shadowRect =
nsCSSRendering::GetBoxShadowInnerPaddingRect(aFrame, aBorderRect);
RectCornerRadii innerRadii;
nsCSSRendering::GetShadowInnerRadii(aFrame, aBorderRect, innerRadii);
// Now translate everything to device pixels.
LayoutDeviceRect deviceBoxRect =
LayoutDeviceRect::FromAppUnits(shadowRect, appUnitsPerDevPixel);
wr::LayoutRect deviceClipRect = wr::ToLayoutRect(clipRect);
sRGBColor shadowColor =
nsCSSRendering::GetShadowColor(shadow.base, aFrame, 1.0);
LayoutDevicePoint shadowOffset = LayoutDevicePoint::FromAppUnits(
nsPoint(shadow.base.horizontal.ToAppUnits(),
shadow.base.vertical.ToAppUnits()),
appUnitsPerDevPixel);
float blurRadius =
float(shadow.base.blur.ToAppUnits()) / float(appUnitsPerDevPixel);
wr::BorderRadius borderRadius = wr::ToBorderRadius(
LayoutDeviceSize::FromUnknownSize(innerRadii.TopLeft()),
LayoutDeviceSize::FromUnknownSize(innerRadii.TopRight()),
LayoutDeviceSize::FromUnknownSize(innerRadii.BottomLeft()),
LayoutDeviceSize::FromUnknownSize(innerRadii.BottomRight()));
// NOTE: Any spread radius > 0 will render nothing. WR Bug.
float spreadRadius =
float(shadow.spread.ToAppUnits()) / float(appUnitsPerDevPixel);
aBuilder.PushBoxShadow(
wr::ToLayoutRect(deviceBoxRect), deviceClipRect,
!aFrame->BackfaceIsHidden(), wr::ToLayoutRect(deviceBoxRect),
wr::ToLayoutVector2D(shadowOffset),
wr::ToColorF(ToDeviceColor(shadowColor)), blurRadius, spreadRadius,
borderRadius, wr::BoxShadowClipMode::Inset);
}
}
bool nsDisplayBoxShadowInner::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
if (!CanCreateWebRenderCommands(aDisplayListBuilder, mFrame,
ToReferenceFrame())) {
return false;
}
bool snap;
nsRect visible = GetBounds(aDisplayListBuilder, &snap);
nsPoint offset = ToReferenceFrame();
nsRect borderRect = nsRect(offset, mFrame->GetSize());
nsDisplayBoxShadowInner::CreateInsetBoxShadowWebRenderCommands(
aBuilder, aSc, visible, mFrame, borderRect);
return true;
}
nsDisplayWrapList::nsDisplayWrapList(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList,
bool aClearClipChain)
: nsDisplayWrapList(aBuilder, aFrame, aList,
aBuilder->CurrentActiveScrolledRoot(),
ContainerASRType::Constant, aClearClipChain) {}
nsDisplayWrapList::nsDisplayWrapList(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, bool aClearClipChain)
: nsPaintedDisplayItem(aBuilder, aFrame, aActiveScrolledRoot),
mList(aBuilder),
mFrameASR(aContainerASRType == ContainerASRType::AncestorOfContained
? aBuilder->CurrentActiveScrolledRoot()
: nullptr),
mOverrideZIndex(0),
mContainerASRType(aContainerASRType),
mHasZIndexOverride(false),
mClearingClipChain(aClearClipChain) {
MOZ_COUNT_CTOR(nsDisplayWrapList);
mBaseBuildingRect = GetBuildingRect();
mListPtr = &mList;
mListPtr->AppendToTop(aList);
mOriginalClipChain = mClipChain;
nsDisplayWrapList::UpdateBounds(aBuilder);
}
nsDisplayWrapList::nsDisplayWrapList(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayItem* aItem)
: nsPaintedDisplayItem(aBuilder, aFrame),
mList(aBuilder),
mOverrideZIndex(0),
mHasZIndexOverride(false) {
MOZ_COUNT_CTOR(nsDisplayWrapList);
mBaseBuildingRect = GetBuildingRect();
mListPtr = &mList;
mListPtr->AppendToTop(aItem);
mOriginalClipChain = mClipChain;
nsDisplayWrapList::UpdateBounds(aBuilder);
if (!aFrame || !aFrame->IsTransformed()) {
return;
}
// See the previous nsDisplayWrapList constructor
if (aItem->Frame() == aFrame) {
mToReferenceFrame = aItem->ToReferenceFrame();
}
nsRect visible = aBuilder->GetVisibleRect() +
aBuilder->GetCurrentFrameOffsetToReferenceFrame();
SetBuildingRect(visible);
}
void nsDisplayWrapList::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect, HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
mListPtr->HitTest(aBuilder, aRect, aState, aOutFrames);
}
nsRect nsDisplayWrapList::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
return mBounds;
}
nsRegion nsDisplayWrapList::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
bool snap;
return ::mozilla::GetOpaqueRegion(aBuilder, GetChildren(),
GetBounds(aBuilder, &snap));
}
Maybe<nscolor> nsDisplayWrapList::IsUniform(
nsDisplayListBuilder* aBuilder) const {
// We could try to do something but let's conservatively just return Nothing.
return Nothing();
}
void nsDisplayWrapper::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
NS_ERROR("nsDisplayWrapper should have been flattened away for painting");
}
nsRect nsDisplayWrapList::GetComponentAlphaBounds(
nsDisplayListBuilder* aBuilder) const {
return mListPtr->GetComponentAlphaBounds(aBuilder);
}
bool nsDisplayWrapList::CreateWebRenderCommandsNewClipListOption(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder, bool aNewClipList) {
aManager->CommandBuilder().CreateWebRenderCommandsFromDisplayList(
GetChildren(), this, aDisplayListBuilder, aSc, aBuilder, aResources,
aNewClipList);
return true;
}
static nsresult WrapDisplayList(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList,
nsDisplayItemWrapper* aWrapper) {
if (!aList->GetTop()) {
return NS_OK;
}
nsDisplayItem* item = aWrapper->WrapList(aBuilder, aFrame, aList);
if (!item) {
return NS_ERROR_OUT_OF_MEMORY;
}
// aList was emptied
aList->AppendToTop(item);
return NS_OK;
}
static nsresult WrapEachDisplayItem(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList,
nsDisplayItemWrapper* aWrapper) {
for (nsDisplayItem* item : aList->TakeItems()) {
item = aWrapper->WrapItem(aBuilder, item);
if (!item) {
return NS_ERROR_OUT_OF_MEMORY;
}
aList->AppendToTop(item);
}
// aList was emptied
return NS_OK;
}
nsresult nsDisplayItemWrapper::WrapLists(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
const nsDisplayListSet& aIn,
const nsDisplayListSet& aOut) {
nsresult rv = WrapListsInPlace(aBuilder, aFrame, aIn);
NS_ENSURE_SUCCESS(rv, rv);
if (&aOut == &aIn) {
return NS_OK;
}
aOut.BorderBackground()->AppendToTop(aIn.BorderBackground());
aOut.BlockBorderBackgrounds()->AppendToTop(aIn.BlockBorderBackgrounds());
aOut.Floats()->AppendToTop(aIn.Floats());
aOut.Content()->AppendToTop(aIn.Content());
aOut.PositionedDescendants()->AppendToTop(aIn.PositionedDescendants());
aOut.Outlines()->AppendToTop(aIn.Outlines());
return NS_OK;
}
nsresult nsDisplayItemWrapper::WrapListsInPlace(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
const nsDisplayListSet& aLists) {
nsresult rv;
if (WrapBorderBackground()) {
// Our border-backgrounds are in-flow
rv = WrapDisplayList(aBuilder, aFrame, aLists.BorderBackground(), this);
NS_ENSURE_SUCCESS(rv, rv);
}
// Our block border-backgrounds are in-flow
rv = WrapDisplayList(aBuilder, aFrame, aLists.BlockBorderBackgrounds(), this);
NS_ENSURE_SUCCESS(rv, rv);
// The floats are not in flow
rv = WrapEachDisplayItem(aBuilder, aLists.Floats(), this);
NS_ENSURE_SUCCESS(rv, rv);
// Our child content is in flow
rv = WrapDisplayList(aBuilder, aFrame, aLists.Content(), this);
NS_ENSURE_SUCCESS(rv, rv);
// The positioned descendants may not be in-flow
rv = WrapEachDisplayItem(aBuilder, aLists.PositionedDescendants(), this);
NS_ENSURE_SUCCESS(rv, rv);
// The outlines may not be in-flow
return WrapEachDisplayItem(aBuilder, aLists.Outlines(), this);
}
nsDisplayOpacity::nsDisplayOpacity(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, bool aForEventsOnly,
bool aNeedsActiveLayer, bool aWrapsBackdropFilter, bool aForceIsolation)
: nsDisplayWrapList(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType, true),
mOpacity(aFrame->StyleEffects()->mOpacity),
mForEventsOnly(aForEventsOnly),
mNeedsActiveLayer(aNeedsActiveLayer),
mChildOpacityState(ChildOpacityState::Unknown),
mWrapsBackdropFilter(aWrapsBackdropFilter),
mForceIsolation(aForceIsolation) {
MOZ_COUNT_CTOR(nsDisplayOpacity);
}
void nsDisplayOpacity::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect,
nsDisplayItem::HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
AutoRestore<float> opacity(aState->mCurrentOpacity);
aState->mCurrentOpacity *= mOpacity;
// TODO(emilio): special-casing zero is a bit arbitrary... Maybe we should
// only consider fully opaque items? Or make this configurable somehow?
if (aBuilder->HitTestIsForVisibility() && mOpacity == 0.0f) {
return;
}
nsDisplayWrapList::HitTest(aBuilder, aRect, aState, aOutFrames);
}
nsRegion nsDisplayOpacity::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
// The only time where mOpacity == 1.0 should be when we have will-change.
// We could report this as opaque then but when the will-change value starts
// animating the element would become non opaque and could cause repaints.
return nsRegion();
}
void nsDisplayOpacity::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
if (GetOpacity() == 0.0f) {
return;
}
int32_t apd = mFrame->PresContext()->AppUnitsPerDevPixel();
if (GetOpacity() == 1.0f) {
GetChildren()->Paint(aBuilder, aCtx, apd);
return;
}
bool unusedSnap = false;
auto deviceSpaceBounds = IntRect::FromUnknownRect(
RoundedOut(ToRect(aCtx->UserToDevice(nsLayoutUtils::RectToGfxRect(
GetBounds(aBuilder, &unusedSnap), apd)))));
aCtx->GetDrawTarget()->PushLayer(false, GetOpacity(), nullptr, gfx::Matrix(),
deviceSpaceBounds);
GetChildren()->Paint(aBuilder, aCtx, apd);
aCtx->GetDrawTarget()->PopLayer();
}
/* static */
bool nsDisplayOpacity::NeedsActiveLayer(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame) {
return EffectCompositor::HasAnimationsForCompositor(
aFrame, DisplayItemType::TYPE_OPACITY) ||
ActiveLayerTracker::IsStyleAnimated(
aBuilder, aFrame, nsCSSPropertyIDSet::OpacityProperties());
}
bool nsDisplayOpacity::CanApplyOpacity(WebRenderLayerManager* aManager,
nsDisplayListBuilder* aBuilder) const {
return !EffectCompositor::HasAnimationsForCompositor(
mFrame, DisplayItemType::TYPE_OPACITY);
}
// Only try folding our opacity down if we have at most |kOpacityMaxChildCount|
// children that don't overlap and can all apply the opacity to themselves.
static const size_t kOpacityMaxChildCount = 3;
// |kOpacityMaxListSize| defines an early exit condition for opacity items that
// are likely have more child items than |kOpacityMaxChildCount|.
static const size_t kOpacityMaxListSize = kOpacityMaxChildCount * 2;
/**
* Recursively iterates through |aList| and collects at most
* |kOpacityMaxChildCount| display item pointers to items that return true for
* CanApplyOpacity(). The item pointers are added to |aArray|.
*
* LayerEventRegions and WrapList items are ignored.
*
* We need to do this recursively, because the child display items might contain
* nested nsDisplayWrapLists.
*
* Returns false if there are more than |kOpacityMaxChildCount| items, or if an
* item that returns false for CanApplyOpacity() is encountered.
* Otherwise returns true.
*/
static bool CollectItemsWithOpacity(WebRenderLayerManager* aManager,
nsDisplayListBuilder* aBuilder,
nsDisplayList* aList,
nsTArray<nsPaintedDisplayItem*>& aArray) {
if (aList->Length() > kOpacityMaxListSize) {
// Exit early, since |aList| will likely contain more than
// |kOpacityMaxChildCount| items.
return false;
}
for (nsDisplayItem* i : *aList) {
const DisplayItemType type = i->GetType();
if (type == DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO) {
continue;
}
// Descend only into wraplists.
if (type == DisplayItemType::TYPE_WRAP_LIST ||
type == DisplayItemType::TYPE_CONTAINER) {
// The current display item has children, process them first.
if (!CollectItemsWithOpacity(aManager, aBuilder, i->GetChildren(),
aArray)) {
return false;
}
continue;
}
if (aArray.Length() == kOpacityMaxChildCount) {
return false;
}
auto* item = i->AsPaintedDisplayItem();
if (!item || !item->CanApplyOpacity(aManager, aBuilder)) {
return false;
}
aArray.AppendElement(item);
}
return true;
}
bool nsDisplayOpacity::CanApplyToChildren(WebRenderLayerManager* aManager,
nsDisplayListBuilder* aBuilder) {
if (mChildOpacityState == ChildOpacityState::Deferred) {
return false;
}
// Iterate through the child display list and copy at most
// |kOpacityMaxChildCount| child display item pointers to a temporary list.
AutoTArray<nsPaintedDisplayItem*, kOpacityMaxChildCount> items;
if (!CollectItemsWithOpacity(aManager, aBuilder, &mList, items)) {
mChildOpacityState = ChildOpacityState::Deferred;
return false;
}
struct {
nsPaintedDisplayItem* item{};
nsRect bounds;
} children[kOpacityMaxChildCount];
bool snap;
size_t childCount = 0;
for (nsPaintedDisplayItem* item : items) {
children[childCount].item = item;
children[childCount].bounds = item->GetBounds(aBuilder, &snap);
childCount++;
}
for (size_t i = 0; i < childCount; i++) {
for (size_t j = i + 1; j < childCount; j++) {
if (children[i].bounds.Intersects(children[j].bounds)) {
mChildOpacityState = ChildOpacityState::Deferred;
return false;
}
}
}
mChildOpacityState = ChildOpacityState::Applied;
return true;
}
/**
* Returns true if this nsDisplayOpacity contains only a filter or a mask item
* that has the same frame as the opacity item, and that supports painting with
* opacity. In this case the opacity item can be optimized away.
*/
bool nsDisplayOpacity::ApplyToMask() {
if (mList.Length() != 1) {
return false;
}
nsDisplayItem* item = mList.GetBottom();
if (item->Frame() != mFrame) {
// The effect item needs to have the same frame as the opacity item.
return false;
}
const DisplayItemType type = item->GetType();
if (type == DisplayItemType::TYPE_MASK) {
return true;
}
return false;
}
bool nsDisplayOpacity::CanApplyOpacityToChildren(
WebRenderLayerManager* aManager, nsDisplayListBuilder* aBuilder,
float aInheritedOpacity) {
if (mFrame->GetPrevContinuation() || mFrame->GetNextContinuation() ||
mFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
// If we've been split, then we might need to merge, so
// don't flatten us away.
return false;
}
if (mNeedsActiveLayer || mOpacity == 0.0) {
// If our opacity is zero then we'll discard all descendant display items
// except for layer event regions, so there's no point in doing this
// optimization (and if we do do it, then invalidations of those descendants
// might trigger repainting).
return false;
}
if (mList.IsEmpty()) {
return false;
}
// We can only flatten opacity items into a mask if we haven't
// already flattened an earlier ancestor, since the SVG code pulls the opacity
// from style directly, and won't know about the outer opacity value.
if (aInheritedOpacity == 1.0f && ApplyToMask()) {
MOZ_ASSERT(SVGIntegrationUtils::UsingEffectsForFrame(mFrame));
mChildOpacityState = ChildOpacityState::Applied;
return true;
}
// Return true if we successfully applied opacity to child items.
return CanApplyToChildren(aManager, aBuilder);
}
void nsDisplayOpacity::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
const auto* geometry =
static_cast<const nsDisplayOpacityGeometry*>(aGeometry);
bool snap;
if (mOpacity != geometry->mOpacity) {
aInvalidRegion->Or(GetBounds(aBuilder, &snap), geometry->mBounds);
}
}
void nsDisplayOpacity::WriteDebugInfo(std::stringstream& aStream) {
aStream << " (opacity " << mOpacity << ", mChildOpacityState: ";
switch (mChildOpacityState) {
case ChildOpacityState::Unknown:
aStream << "Unknown";
break;
case ChildOpacityState::Applied:
aStream << "Applied";
break;
case ChildOpacityState::Deferred:
aStream << "Deferred";
break;
default:
break;
}
aStream << ")";
}
bool nsDisplayOpacity::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
MOZ_ASSERT(mChildOpacityState != ChildOpacityState::Applied);
float oldOpacity = aBuilder.GetInheritedOpacity();
const DisplayItemClipChain* oldClipChain = aBuilder.GetInheritedClipChain();
aBuilder.SetInheritedOpacity(1.0f);
aBuilder.SetInheritedClipChain(nullptr);
float opacity = mOpacity * oldOpacity;
float* opacityForSC = &opacity;
uint64_t animationsId =
AddAnimationsForWebRender(this, aManager, aDisplayListBuilder);
wr::WrAnimationProperty prop{
wr::WrAnimationType::Opacity,
animationsId,
};
wr::StackingContextParams params;
params.animation = animationsId ? &prop : nullptr;
params.opacity = opacityForSC;
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
if (mWrapsBackdropFilter) {
params.flags |= wr::StackingContextFlags::WRAPS_BACKDROP_FILTER;
}
if (mForceIsolation) {
params.flags |= wr::StackingContextFlags::FORCED_ISOLATION;
}
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params);
aManager->CommandBuilder().CreateWebRenderCommandsFromDisplayList(
&mList, this, aDisplayListBuilder, sc, aBuilder, aResources);
aBuilder.SetInheritedOpacity(oldOpacity);
aBuilder.SetInheritedClipChain(oldClipChain);
return true;
}
nsDisplayBlendMode::nsDisplayBlendMode(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
StyleBlend aBlendMode, const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, const bool aIsForBackground)
: nsDisplayWrapList(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType, true),
mBlendMode(aBlendMode),
mIsForBackground(aIsForBackground) {
MOZ_COUNT_CTOR(nsDisplayBlendMode);
}
nsRegion nsDisplayBlendMode::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
// We are never considered opaque
return nsRegion();
}
bool nsDisplayBlendMode::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
wr::StackingContextParams params;
params.mix_blend_mode =
wr::ToMixBlendMode(nsCSSRendering::GetGFXBlendMode(mBlendMode));
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params);
return nsDisplayWrapList::CreateWebRenderCommands(
aBuilder, aResources, sc, aManager, aDisplayListBuilder);
}
void nsDisplayBlendMode::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
// This should be switched to use PushLayerWithBlend, once it's
// been implemented for all DrawTarget backends.
DrawTarget* dt = aCtx->GetDrawTarget();
int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
Rect rect = NSRectToRect(GetPaintRect(aBuilder, aCtx), appUnitsPerDevPixel);
rect.RoundOut();
// Create a temporary DrawTarget that is clipped to the area that
// we're going to draw to. This will include the same transform as
// is currently on |dt|.
RefPtr<DrawTarget> temp =
dt->CreateClippedDrawTarget(rect, SurfaceFormat::B8G8R8A8);
if (!temp) {
return;
}
gfxContext ctx(temp, /* aPreserveTransform */ true);
GetChildren()->Paint(aBuilder, &ctx,
mFrame->PresContext()->AppUnitsPerDevPixel());
// Draw the temporary DT to the real destination, applying the blend mode, but
// no transform.
temp->Flush();
RefPtr<SourceSurface> surface = temp->Snapshot();
gfxContextMatrixAutoSaveRestore saveMatrix(aCtx);
dt->SetTransform(Matrix());
dt->DrawSurface(
surface, Rect(surface->GetRect()), Rect(surface->GetRect()),
DrawSurfaceOptions(),
DrawOptions(1.0f, nsCSSRendering::GetGFXBlendMode(mBlendMode)));
}
gfx::CompositionOp nsDisplayBlendMode::BlendMode() {
return nsCSSRendering::GetGFXBlendMode(mBlendMode);
}
bool nsDisplayBlendMode::CanMerge(const nsDisplayItem* aItem) const {
// Items for the same content element should be merged into a single
// compositing group.
if (!HasDifferentFrame(aItem) || !HasSameTypeAndClip(aItem) ||
!HasSameContent(aItem)) {
return false;
}
const auto* item = static_cast<const nsDisplayBlendMode*>(aItem);
if (mIsForBackground || item->mIsForBackground) {
// Don't merge background-blend-mode items
return false;
}
return true;
}
/* static */
nsDisplayBlendContainer* nsDisplayBlendContainer::CreateForMixBlendMode(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType) {
return MakeDisplayItemWithIndex<nsDisplayBlendContainer>(
aBuilder, aFrame, uint16_t(BlendContainerType::MixBlendMode), aList,
aActiveScrolledRoot, aContainerASRType, BlendContainerType::MixBlendMode);
}
/* static */
nsDisplayBlendContainer* nsDisplayBlendContainer::CreateForBackgroundBlendMode(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsIFrame* aSecondaryFrame,
nsDisplayList* aList, const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType) {
if (aSecondaryFrame) {
auto type = GetTableTypeFromFrame(aFrame);
auto index = static_cast<uint16_t>(type);
return MakeDisplayItemWithIndex<nsDisplayTableBlendContainer>(
aBuilder, aSecondaryFrame, index, aList, aActiveScrolledRoot,
aContainerASRType, BlendContainerType::BackgroundBlendMode, aFrame);
}
return MakeDisplayItemWithIndex<nsDisplayBlendContainer>(
aBuilder, aFrame, uint16_t(BlendContainerType::BackgroundBlendMode),
aList, aActiveScrolledRoot, aContainerASRType,
BlendContainerType::BackgroundBlendMode);
}
/* static */
nsDisplayBlendContainer* nsDisplayBlendContainer::CreateForIsolation(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, bool aNeedsIsolation) {
auto type = aNeedsIsolation ? BlendContainerType::NeedsIsolationNeedsContainer
: BlendContainerType::NeedsIsolationNothing;
return MakeDisplayItemWithIndex<nsDisplayBlendContainer>(
aBuilder, aFrame, uint16_t(BlendContainerType::NeedsIsolationNothing),
aList, aActiveScrolledRoot, aContainerASRType, type);
}
nsDisplayBlendContainer::nsDisplayBlendContainer(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, BlendContainerType aBlendContainerType)
: nsDisplayWrapList(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType, true),
mBlendContainerType(aBlendContainerType) {
MOZ_COUNT_CTOR(nsDisplayBlendContainer);
}
void nsDisplayBlendContainer::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
aCtx->GetDrawTarget()->PushLayer(false, 1.0, nullptr, gfx::Matrix());
GetChildren()->Paint(aBuilder, aCtx,
mFrame->PresContext()->AppUnitsPerDevPixel());
aCtx->GetDrawTarget()->PopLayer();
}
bool nsDisplayBlendContainer::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
Maybe<StackingContextHelper> layer;
const StackingContextHelper* sc = &aSc;
if (CreatesStackingContextHelper()) {
wr::StackingContextParams params;
params.flags |= wr::StackingContextFlags::IS_BLEND_CONTAINER;
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
layer.emplace(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder, params);
sc = layer.ptr();
}
return nsDisplayWrapList::CreateWebRenderCommandsNewClipListOption(
aBuilder, aResources, *sc, aManager, aDisplayListBuilder, layer.isSome());
}
void nsDisplayTableBlendContainer::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mAncestorFrame);
nsDisplayBlendContainer::Destroy(aBuilder);
}
void nsDisplayTableBlendMode::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mAncestorFrame);
nsDisplayBlendMode::Destroy(aBuilder);
}
nsDisplayOwnLayer::nsDisplayOwnLayer(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, nsDisplayOwnLayerFlags aFlags,
const ScrollbarData& aScrollbarData, bool aForceActive,
bool aClearClipChain)
: nsDisplayWrapList(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType, aClearClipChain),
mFlags(aFlags),
mScrollbarData(aScrollbarData),
mForceActive(aForceActive),
mWrAnimationId(0) {
MOZ_COUNT_CTOR(nsDisplayOwnLayer);
}
bool nsDisplayOwnLayer::IsScrollThumbLayer() const {
return mScrollbarData.mScrollbarLayerType == ScrollbarLayerType::Thumb;
}
bool nsDisplayOwnLayer::IsScrollbarContainer() const {
return mScrollbarData.mScrollbarLayerType == ScrollbarLayerType::Container;
}
bool nsDisplayOwnLayer::IsRootScrollbarContainer() const {
return IsScrollbarContainer() && IsScrollbarLayerForRoot();
}
bool nsDisplayOwnLayer::IsScrollbarLayerForRoot() const {
return mFrame->PresContext()->IsRootContentDocumentCrossProcess() &&
mScrollbarData.mTargetViewId ==
nsLayoutUtils::ScrollIdForRootScrollFrame(mFrame->PresContext());
}
bool nsDisplayOwnLayer::IsZoomingLayer() const {
return GetType() == DisplayItemType::TYPE_ASYNC_ZOOM;
}
bool nsDisplayOwnLayer::IsFixedPositionLayer() const {
return GetType() == DisplayItemType::TYPE_FIXED_POSITION ||
GetType() == DisplayItemType::TYPE_TABLE_FIXED_POSITION;
}
bool nsDisplayOwnLayer::IsStickyPositionLayer() const {
return GetType() == DisplayItemType::TYPE_STICKY_POSITION;
}
/* static */
bool nsDisplayOwnLayer::HasDynamicToolbar(nsIFrame* aFrame) {
if (!aFrame->PresContext()->IsRootContentDocumentCrossProcess()) {
return false;
}
return aFrame->PresContext()->HasDynamicToolbar() ||
// For tests on Android, this pref is set to simulate the dynamic
// toolbar
StaticPrefs::apz_fixed_margin_override_enabled();
}
bool nsDisplayOwnLayer::HasDynamicToolbar() const {
return HasDynamicToolbar(mFrame);
}
bool nsDisplayOwnLayer::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder, bool aForceIsolation) {
Maybe<wr::WrAnimationProperty> prop;
const bool needsProp = aManager->LayerManager()->AsyncPanZoomEnabled() &&
(IsScrollThumbLayer() || IsZoomingLayer() ||
ShouldGetFixedAnimationId() ||
(IsRootScrollbarContainer() && HasDynamicToolbar()));
if (needsProp) {
// APZ is enabled and this is a scroll thumb or zooming layer, so we need
// to create and set an animation id. That way APZ can adjust the position/
// zoom of this content asynchronously as needed.
RefPtr<WebRenderAPZAnimationData> animationData =
aManager->CommandBuilder()
.CreateOrRecycleWebRenderUserData<WebRenderAPZAnimationData>(this);
mWrAnimationId = animationData->GetAnimationId();
prop.emplace();
prop->id = mWrAnimationId;
prop->key = wr::SpatialKey(uint64_t(mFrame), GetPerFrameKey(),
wr::SpatialKeyKind::APZ);
prop->effect_type = wr::WrAnimationType::Transform;
}
wr::StackingContextParams params;
params.animation = prop.ptrOr(nullptr);
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
const bool rootScrollbarContainer = IsRootScrollbarContainer();
if (rootScrollbarContainer) {
params.prim_flags |= wr::PrimitiveFlags::IS_SCROLLBAR_CONTAINER;
}
if (aForceIsolation) {
params.flags |= wr::StackingContextFlags::FORCED_ISOLATION;
}
if (IsZoomingLayer() || ShouldGetFixedAnimationId() ||
(rootScrollbarContainer && HasDynamicToolbar())) {
params.is_2d_scale_translation = true;
params.should_snap = true;
}
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params);
nsDisplayWrapList::CreateWebRenderCommands(aBuilder, aResources, sc, aManager,
aDisplayListBuilder);
return true;
}
bool nsDisplayOwnLayer::UpdateScrollData(WebRenderScrollData* aData,
WebRenderLayerScrollData* aLayerData) {
bool isRelevantToApz = (IsScrollThumbLayer() || IsScrollbarContainer() ||
IsZoomingLayer() || ShouldGetFixedAnimationId());
if (!isRelevantToApz) {
return false;
}
if (!aLayerData) {
return true;
}
if (IsZoomingLayer()) {
aLayerData->SetZoomAnimationId(mWrAnimationId);
return true;
}
if (IsFixedPositionLayer() && ShouldGetFixedAnimationId()) {
aLayerData->SetFixedPositionAnimationId(mWrAnimationId);
return true;
}
MOZ_ASSERT(IsScrollbarContainer() || IsScrollThumbLayer());
aLayerData->SetScrollbarData(mScrollbarData);
if (IsRootScrollbarContainer() && HasDynamicToolbar()) {
aLayerData->SetScrollbarAnimationId(mWrAnimationId);
return true;
}
if (IsScrollThumbLayer()) {
aLayerData->SetScrollbarAnimationId(mWrAnimationId);
LayoutDeviceRect bounds = LayoutDeviceIntRect::FromAppUnits(
mBounds, mFrame->PresContext()->AppUnitsPerDevPixel());
// Subframe scrollbars are subject to the pinch-zoom scale,
// but root scrollbars are not because they are outside of the
// region that is zoomed.
const float resolution =
IsScrollbarLayerForRoot()
? 1.0f
: mFrame->PresShell()->GetCumulativeResolution();
LayerIntRect layerBounds =
RoundedOut(bounds * LayoutDeviceToLayerScale(resolution));
aLayerData->SetVisibleRect(layerBounds);
}
return true;
}
void nsDisplayOwnLayer::WriteDebugInfo(std::stringstream& aStream) {
aStream << nsPrintfCString(" (flags 0x%x) (scrolltarget %" PRIu64 ")",
(int)mFlags, mScrollbarData.mTargetViewId)
.get();
}
bool nsDisplayViewTransitionCapture::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
Maybe<wr::SnapshotInfo> si;
nsPresContext* pc = mFrame->PresContext();
nsIFrame* capturedFrame =
mIsRoot ? pc->FrameConstructor()->GetRootElementStyleFrame() : mFrame;
auto captureRect =
ViewTransition::CapturedInkOverflowRectForFrame(mFrame, mIsRoot);
auto* vt = pc->Document()->GetActiveViewTransition();
auto key = [&]() -> Maybe<wr::SnapshotImageKey> {
if (NS_WARN_IF(!vt)) {
return Nothing();
}
const auto* key =
vt->GetImageKeyForCapturedFrame(capturedFrame, aManager, aResources);
return key ? Some(wr::SnapshotImageKey{*key}) : Nothing();
}();
VT_LOG_DEBUG(
"nsDisplayViewTransitionCapture::CreateWebrenderCommands(%s, key=%s)",
capturedFrame->ListTag().get(), ToString(key).c_str());
wr::StackingContextParams params;
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
// This is for the case if this frame is transformed. In this case, the wr
// display list looks like:
//
// PushStackingContext(...) // For the root
// ...
// nsDisplayTransform // For the captured element if it is transformed
// PushReferenceFrame // If the transform matrix is not identity
// PushStackingContext(...)
// VTCapture // For the captured element
// PushReferenceFrame
// PushStackingContext
// ...
// Other display items // For the descendants of the captured element
// ...
// PopStackingContext
// PopReferenceFrame
// PopStackingContext
// PopReferenceFrame
// ...
// PopStackingContext
//
// The wrapper, nsDisplayTransform, creates a new coordinate system whose
// origin is from ToReferenceFrame(mFrame). The VTCapture item is inside this
// nsDisplayTransform, so it's in this coordinate system. This works well if
// the transform matrix is not identity. However, if the transform matrix is
// identity, we don't create a new coordinate system (because we don't push a
// reference frame in WR), at this moment, the |ref_frame_offset| of the
// stacking context of this VTCapture becomes the |origin| of the
// nsDisplayTransform (see wr_dp_push_stacking_context() and
// push_stacking_context() for more details), so this offset may makes the
// position of this VTCapture wrong. (Note that the ToReferenceFrame(mFrame)
// of this VTCapture is the frame itself, but ToReferenceFrame(mFrame) of the
// nsDisplayTransform is its containing frame, e.g. viewport frame.)
//
// Therefore, we push a reference frame for this display item if the frame is
// transformed. This makes this VTCapture creates a new coordinate system, so
// its |ref_frame_offset| will be (0, 0), just fit the nsDisplayTransform's
// position.
//
// FIXME: We can avoid pushing a reference frame if the transform matrix is
// not identity, because we generate a new coordinate system already from the
// nsDisplayTransform (see nsDisplayTransform::CreateWebRenderCommands() for
// more details).
wr::WrTransformInfo info;
if (mFrame->IsTransformed()) {
// Use an identity matrix to force to push a reference frame to create a new
// coordinate system for view transition captured frame.
params.mTransformPtr = [&]() {
info.transform = wr::ToLayoutTransform(gfx::Matrix4x4());
info.key = wr::SpatialKey(uint64_t(mFrame), GetPerFrameKey(),
wr::SpatialKeyKind::ViewTransition);
return &info;
}();
params.reference_frame_kind = wr::WrReferenceFrameKind::Transform;
}
if (key) {
vt->UpdateActiveRectForCapturedFrame(capturedFrame, aSc.GetInheritedScale(),
captureRect);
si.emplace(wr::SnapshotInfo{
.key = *key,
.area = wr::ToLayoutRect(LayoutDeviceRect::FromAppUnits(
captureRect + ToReferenceFrame(), pc->AppUnitsPerDevPixel())),
.detached = true,
});
params.snapshot = si.ptr();
}
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params);
nsDisplayWrapList::CreateWebRenderCommands(aBuilder, aResources, sc, aManager,
aDisplayListBuilder);
return true;
}
nsDisplaySubDocument::nsDisplaySubDocument(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
nsSubDocumentFrame* aSubDocFrame,
nsDisplayList* aList,
nsDisplayOwnLayerFlags aFlags)
: nsDisplayOwnLayer(aBuilder, aFrame, aList,
aBuilder->CurrentActiveScrolledRoot(),
ContainerASRType::Constant, aFlags),
mShouldFlatten(false),
mSubDocFrame(aSubDocFrame) {
MOZ_COUNT_CTOR(nsDisplaySubDocument);
if (aBuilder->IsRetainingDisplayList() && mSubDocFrame &&
mSubDocFrame != mFrame) {
mSubDocFrame->AddDisplayItem(this);
}
}
void nsDisplaySubDocument::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mSubDocFrame);
nsDisplayOwnLayer::Destroy(aBuilder);
}
nsIFrame* nsDisplaySubDocument::FrameForInvalidation() const {
return mSubDocFrame ? mSubDocFrame : mFrame;
}
void nsDisplaySubDocument::RemoveFrame(nsIFrame* aFrame) {
if (aFrame == mSubDocFrame) {
mSubDocFrame = nullptr;
SetDeletedFrame();
}
nsDisplayOwnLayer::RemoveFrame(aFrame);
}
static bool UseDisplayPortForViewport(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame) {
return aBuilder->IsPaintingToWindow() &&
DisplayPortUtils::ViewportHasDisplayPort(aFrame->PresContext());
}
nsRect nsDisplaySubDocument::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
bool usingDisplayPort = UseDisplayPortForViewport(aBuilder, mFrame);
if ((mFlags & nsDisplayOwnLayerFlags::GenerateScrollableLayer) &&
usingDisplayPort) {
*aSnap = false;
return mFrame->GetRect() + aBuilder->ToReferenceFrame(mFrame);
}
return nsDisplayOwnLayer::GetBounds(aBuilder, aSnap);
}
nsRegion nsDisplaySubDocument::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
bool usingDisplayPort = UseDisplayPortForViewport(aBuilder, mFrame);
if ((mFlags & nsDisplayOwnLayerFlags::GenerateScrollableLayer) &&
usingDisplayPort) {
*aSnap = false;
return nsRegion();
}
return nsDisplayOwnLayer::GetOpaqueRegion(aBuilder, aSnap);
}
/* static */
nsDisplayFixedPosition* nsDisplayFixedPosition::CreateForFixedBackground(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsIFrame* aSecondaryFrame,
nsDisplayBackgroundImage* aImage, const uint16_t aIndex,
const ActiveScrolledRoot* aScrollTargetASR) {
nsDisplayList temp(aBuilder);
temp.AppendToTop(aImage);
if (aSecondaryFrame) {
auto tableType = GetTableTypeFromFrame(aFrame);
const uint16_t index = CalculateTablePerFrameKey(aIndex + 1, tableType);
return MakeDisplayItemWithIndex<nsDisplayTableFixedPosition>(
aBuilder, aSecondaryFrame, index, &temp, aFrame, aScrollTargetASR);
}
return MakeDisplayItemWithIndex<nsDisplayFixedPosition>(
aBuilder, aFrame, aIndex + 1, &temp, aScrollTargetASR);
}
nsDisplayFixedPosition::nsDisplayFixedPosition(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType,
const ActiveScrolledRoot* aScrollTargetASR, bool aForceIsolation)
: nsDisplayOwnLayer(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType),
mScrollTargetASR(aScrollTargetASR),
mIsFixedBackground(false),
mForceIsolation(aForceIsolation) {
MOZ_COUNT_CTOR(nsDisplayFixedPosition);
MOZ_ASSERT_IF(mScrollTargetASR,
mScrollTargetASR->mKind == ActiveScrolledRoot::ASRKind::Scroll);
}
nsDisplayFixedPosition::nsDisplayFixedPosition(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aScrollTargetASR)
: nsDisplayOwnLayer(aBuilder, aFrame, aList,
aBuilder->CurrentActiveScrolledRoot(),
ContainerASRType::Constant),
// For fixed backgrounds, this is the ASR for the nearest scroll frame.
mScrollTargetASR(aScrollTargetASR),
mIsFixedBackground(true),
mForceIsolation(false) {
MOZ_COUNT_CTOR(nsDisplayFixedPosition);
MOZ_ASSERT_IF(mScrollTargetASR,
mScrollTargetASR->mKind == ActiveScrolledRoot::ASRKind::Scroll);
}
ScrollableLayerGuid::ViewID nsDisplayFixedPosition::GetScrollTargetId() const {
if (mScrollTargetASR &&
(mIsFixedBackground || !nsLayoutUtils::IsReallyFixedPos(mFrame))) {
return mScrollTargetASR->GetViewId();
}
return nsLayoutUtils::ScrollIdForRootScrollFrame(mFrame->PresContext());
}
bool nsDisplayFixedPosition::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
SideBits sides = SideBits::eNone;
if (!mIsFixedBackground) {
sides = nsLayoutUtils::GetSideBitsForFixedPositionContent(mFrame);
}
// We install this RAII scrolltarget tracker so that any
// nsDisplayCompositorHitTestInfo items inside this fixed-pos item (and that
// share the same ASR as this item) use the correct scroll target. That way
// attempts to scroll on those items will scroll the root scroll frame.
wr::DisplayListBuilder::FixedPosScrollTargetTracker tracker(
aBuilder, GetActiveScrolledRoot(), GetScrollTargetId(), sides);
return nsDisplayOwnLayer::CreateWebRenderCommands(
aBuilder, aResources, aSc, aManager, aDisplayListBuilder);
}
bool nsDisplayFixedPosition::UpdateScrollData(
WebRenderScrollData* aData, WebRenderLayerScrollData* aLayerData) {
if (aLayerData) {
if (!mIsFixedBackground) {
aLayerData->SetFixedPositionSides(
nsLayoutUtils::GetSideBitsForFixedPositionContent(mFrame));
}
aLayerData->SetFixedPositionScrollContainerId(GetScrollTargetId());
}
nsDisplayOwnLayer::UpdateScrollData(aData, aLayerData);
return true;
}
bool nsDisplayFixedPosition::ShouldGetFixedAnimationId() {
#if defined(MOZ_WIDGET_ANDROID)
return mFrame->PresContext()->IsRootContentDocumentCrossProcess() &&
nsLayoutUtils::ScrollIdForRootScrollFrame(mFrame->PresContext()) ==
GetScrollTargetId();
#else
return HasDynamicToolbar() &&
(nsLayoutUtils::ScrollIdForRootScrollFrame(mFrame->PresContext()) ==
GetScrollTargetId());
#endif
}
void nsDisplayFixedPosition::WriteDebugInfo(std::stringstream& aStream) {
aStream << nsPrintfCString(
" (containerASR %s) (scrolltarget %" PRIu64 ")",
ActiveScrolledRoot::ToString(mScrollTargetASR).get(),
GetScrollTargetId())
.get();
}
TableType GetTableTypeFromFrame(nsIFrame* aFrame) {
if (aFrame->IsTableFrame()) {
return TableType::Table;
}
if (aFrame->IsTableColFrame()) {
return TableType::TableCol;
}
if (aFrame->IsTableColGroupFrame()) {
return TableType::TableColGroup;
}
if (aFrame->IsTableRowFrame()) {
return TableType::TableRow;
}
if (aFrame->IsTableRowGroupFrame()) {
return TableType::TableRowGroup;
}
if (aFrame->IsTableCellFrame()) {
return TableType::TableCell;
}
MOZ_ASSERT_UNREACHABLE("Invalid frame.");
return TableType::Table;
}
nsDisplayTableFixedPosition::nsDisplayTableFixedPosition(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
nsIFrame* aAncestorFrame, const ActiveScrolledRoot* aScrollTargetASR)
: nsDisplayFixedPosition(aBuilder, aFrame, aList, aScrollTargetASR),
mAncestorFrame(aAncestorFrame) {
if (aBuilder->IsRetainingDisplayList()) {
mAncestorFrame->AddDisplayItem(this);
}
}
void nsDisplayTableFixedPosition::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mAncestorFrame);
nsDisplayFixedPosition::Destroy(aBuilder);
}
nsDisplayStickyPosition::nsDisplayStickyPosition(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, const ActiveScrolledRoot* aContainerASR)
: nsDisplayOwnLayer(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType, nsDisplayOwnLayerFlags::None,
layers::ScrollbarData{},
/*aForceActive=*/true, /*aClearClipChain=*/true),
mContainerASR(aContainerASR),
mShouldFlatten(false) {
MOZ_COUNT_CTOR(nsDisplayStickyPosition);
}
StickyScrollContainer* nsDisplayStickyPosition::GetStickyScrollContainer() {
auto* ssc = StickyScrollContainer::GetOrCreateForFrame(mFrame);
if (!ssc) {
return nullptr;
}
// If there's no ASR for the scrollframe that this sticky item is attached
// to, then don't create a WR sticky item for it either. Trying to do so
// will end in sadness because WR will interpret some coordinates as
// relative to the nearest enclosing scrollframe, which will correspond
// to the nearest ancestor ASR on the gecko side. That ASR will not be the
// same as the scrollframe this sticky item is actually supposed to be
// attached to, thus the sadness.
// Not sending WR the sticky item is ok, because the enclosing scrollframe
// will never be asynchronously scrolled. Instead we will always position
// the sticky items correctly on the gecko side and WR will never need to
// adjust their position itself.
MOZ_ASSERT(ssc->ScrollContainer()->IsMaybeAsynchronouslyScrolled());
if (!ssc->ScrollContainer()->IsMaybeAsynchronouslyScrolled()) {
return nullptr;
}
return ssc;
}
bool nsDisplayStickyPosition::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
StickyScrollContainer* stickyScrollContainer = GetStickyScrollContainer();
Maybe<wr::SpaceAndClipChainHelper> saccHelper;
if (stickyScrollContainer && !stickyScrollContainer->ShouldFlattenAway()) {
const ActiveScrolledRoot* stickyAsr =
ActiveScrolledRoot::GetStickyASRFromFrame(mFrame);
MOZ_ASSERT(stickyAsr);
auto spatialId = aBuilder.GetSpatialIdForDefinedStickyLayer(stickyAsr);
MOZ_ASSERT(spatialId.isSome());
saccHelper.emplace(aBuilder, *spatialId);
}
{
wr::StackingContextParams params;
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this,
aBuilder, params);
nsDisplayOwnLayer::CreateWebRenderCommands(aBuilder, aResources, sc,
aManager, aDisplayListBuilder);
}
return true;
}
void nsDisplayStickyPosition::CalculateLayerScrollRanges(
StickyScrollContainer* aStickyScrollContainer, float aAppUnitsPerDevPixel,
float aScaleX, float aScaleY, LayerRectAbsolute& aStickyOuter,
LayerRectAbsolute& aStickyInner) {
nsRectAbsolute outer;
nsRectAbsolute inner;
aStickyScrollContainer->GetScrollRanges(mFrame, &outer, &inner);
aStickyOuter.SetBox(
NSAppUnitsToFloatPixels(outer.X(), aAppUnitsPerDevPixel) * aScaleX,
NSAppUnitsToFloatPixels(outer.Y(), aAppUnitsPerDevPixel) * aScaleY,
NSAppUnitsToFloatPixels(outer.XMost(), aAppUnitsPerDevPixel) * aScaleX,
NSAppUnitsToFloatPixels(outer.YMost(), aAppUnitsPerDevPixel) * aScaleY);
aStickyInner.SetBox(
NSAppUnitsToFloatPixels(inner.X(), aAppUnitsPerDevPixel) * aScaleX,
NSAppUnitsToFloatPixels(inner.Y(), aAppUnitsPerDevPixel) * aScaleY,
NSAppUnitsToFloatPixels(inner.XMost(), aAppUnitsPerDevPixel) * aScaleX,
NSAppUnitsToFloatPixels(inner.YMost(), aAppUnitsPerDevPixel) * aScaleY);
}
bool nsDisplayStickyPosition::UpdateScrollData(
WebRenderScrollData* aData, WebRenderLayerScrollData* aLayerData) {
bool hasDynamicToolbar = HasDynamicToolbar();
if (aLayerData && hasDynamicToolbar) {
StickyScrollContainer* stickyScrollContainer = GetStickyScrollContainer();
if (stickyScrollContainer) {
float auPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
float cumulativeResolution =
mFrame->PresShell()->GetCumulativeResolution();
LayerRectAbsolute stickyOuter;
LayerRectAbsolute stickyInner;
CalculateLayerScrollRanges(stickyScrollContainer, auPerDevPixel,
cumulativeResolution, cumulativeResolution,
stickyOuter, stickyInner);
aLayerData->SetStickyScrollRangeOuter(stickyOuter);
aLayerData->SetStickyScrollRangeInner(stickyInner);
SideBits sides =
nsLayoutUtils::GetSideBitsForFixedPositionContent(mFrame);
aLayerData->SetFixedPositionSides(sides);
ScrollableLayerGuid::ViewID scrollId = nsLayoutUtils::FindOrCreateIDFor(
stickyScrollContainer->ScrollContainer()
->GetScrolledFrame()
->GetContent());
aLayerData->SetStickyPositionScrollContainerId(scrollId);
}
if (ShouldGetStickyAnimationId()) {
// TODO(follow-up to bug 1730749): Should there be a
// "GetWebRenderUserData" method we should be calling here, rather than
// "CreateOrRecycle"?
RefPtr<WebRenderAPZAnimationData> animationData =
aData->GetManager()
->CommandBuilder()
.CreateOrRecycleWebRenderUserData<WebRenderAPZAnimationData>(
this);
MOZ_ASSERT(animationData);
aLayerData->SetStickyPositionAnimationId(animationData->GetAnimationId());
}
}
// Return true if either there is a dynamic toolbar affecting this sticky
// item or the OwnLayer base implementation returns true for some other
// reason.
bool ret = hasDynamicToolbar;
ret |= nsDisplayOwnLayer::UpdateScrollData(aData, aLayerData);
return ret;
}
bool nsDisplayStickyPosition::ShouldGetStickyAnimationId(
nsIFrame* aStickyFrame) {
// Also implies being in the cross-process RCD.
// The animation id is how we translate the layer by the dynamic toolbar
// offset. It's not needed for regular sticky positioning, that's handled
// by WebRender without an animation id.
return nsDisplayOwnLayer::HasDynamicToolbar(aStickyFrame);
}
bool nsDisplayStickyPosition::ShouldGetStickyAnimationId() const {
return ShouldGetStickyAnimationId(mFrame);
}
nsDisplayScrollInfoLayer::nsDisplayScrollInfoLayer(
nsDisplayListBuilder* aBuilder, nsIFrame* aScrolledFrame,
nsIFrame* aScrollFrame, const CompositorHitTestInfo& aHitInfo,
const nsRect& aHitArea)
: nsDisplayWrapList(aBuilder, aScrollFrame),
mScrollFrame(aScrollFrame),
mScrolledFrame(aScrolledFrame),
mScrollParentId(aBuilder->GetCurrentScrollParentId()),
mHitInfo(aHitInfo),
mHitArea(aHitArea) {
#ifdef NS_BUILD_REFCNT_LOGGING
MOZ_COUNT_CTOR(nsDisplayScrollInfoLayer);
#endif
}
UniquePtr<ScrollMetadata> nsDisplayScrollInfoLayer::ComputeScrollMetadata(
nsDisplayListBuilder* aBuilder, WebRenderLayerManager* aLayerManager) {
ScrollMetadata metadata = nsLayoutUtils::ComputeScrollMetadata(
mScrolledFrame, mScrollFrame, mScrollFrame->GetContent(), Frame(),
ToReferenceFrame(), aLayerManager, mScrollParentId,
mScrollFrame->GetSize(), false);
metadata.GetMetrics().SetIsScrollInfoLayer(true);
ScrollContainerFrame* scrollContainerFrame =
mScrollFrame->GetScrollTargetFrame();
if (scrollContainerFrame) {
aBuilder->AddScrollContainerFrameToNotify(scrollContainerFrame);
}
return UniquePtr<ScrollMetadata>(new ScrollMetadata(metadata));
}
bool nsDisplayScrollInfoLayer::UpdateScrollData(
WebRenderScrollData* aData, WebRenderLayerScrollData* aLayerData) {
if (aLayerData) {
UniquePtr<ScrollMetadata> metadata =
ComputeScrollMetadata(aData->GetBuilder(), aData->GetManager());
MOZ_ASSERT(aData);
MOZ_ASSERT(metadata);
aLayerData->AppendScrollMetadata(*aData, *metadata);
}
return true;
}
bool nsDisplayScrollInfoLayer::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
ScrollableLayerGuid::ViewID scrollId =
nsLayoutUtils::FindOrCreateIDFor(mScrollFrame->GetContent());
const LayoutDeviceRect devRect = LayoutDeviceRect::FromAppUnits(
mHitArea, mScrollFrame->PresContext()->AppUnitsPerDevPixel());
const wr::LayoutRect rect = wr::ToLayoutRect(devRect);
aBuilder.PushHitTest(rect, rect, !BackfaceIsHidden(), scrollId, mHitInfo,
SideBits::eNone);
return true;
}
void nsDisplayScrollInfoLayer::WriteDebugInfo(std::stringstream& aStream) {
aStream << " (scrollframe " << mScrollFrame << " scrolledFrame "
<< mScrolledFrame << ")";
}
nsDisplayZoom::nsDisplayZoom(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
nsSubDocumentFrame* aSubDocFrame,
nsDisplayList* aList, int32_t aAPD,
int32_t aParentAPD, nsDisplayOwnLayerFlags aFlags)
: nsDisplaySubDocument(aBuilder, aFrame, aSubDocFrame, aList, aFlags),
mAPD(aAPD),
mParentAPD(aParentAPD) {
MOZ_COUNT_CTOR(nsDisplayZoom);
}
nsRect nsDisplayZoom::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
nsRect bounds = nsDisplaySubDocument::GetBounds(aBuilder, aSnap);
*aSnap = false;
return bounds.ScaleToOtherAppUnitsRoundOut(mAPD, mParentAPD);
}
void nsDisplayZoom::HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
nsRect rect;
// A 1x1 rect indicates we are just hit testing a point, so pass down a 1x1
// rect as well instead of possibly rounding the width or height to zero.
if (aRect.width == 1 && aRect.height == 1) {
rect.MoveTo(aRect.TopLeft().ScaleToOtherAppUnits(mParentAPD, mAPD));
rect.width = rect.height = 1;
} else {
rect = aRect.ScaleToOtherAppUnitsRoundOut(mParentAPD, mAPD);
}
mList.HitTest(aBuilder, rect, aState, aOutFrames);
}
nsDisplayAsyncZoom::nsDisplayAsyncZoom(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, FrameMetrics::ViewID aViewID)
: nsDisplayOwnLayer(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType),
mViewID(aViewID) {
MOZ_COUNT_CTOR(nsDisplayAsyncZoom);
}
void nsDisplayAsyncZoom::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect, HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
#ifdef DEBUG
ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(mFrame);
MOZ_ASSERT(scrollContainerFrame &&
ViewportUtils::IsZoomedContentRoot(
scrollContainerFrame->GetScrolledFrame()));
#endif
nsRect rect = ViewportUtils::VisualToLayout(aRect, mFrame->PresShell());
mList.HitTest(aBuilder, rect, aState, aOutFrames);
}
bool nsDisplayAsyncZoom::UpdateScrollData(
WebRenderScrollData* aData, WebRenderLayerScrollData* aLayerData) {
bool ret = nsDisplayOwnLayer::UpdateScrollData(aData, aLayerData);
MOZ_ASSERT(ret);
if (aLayerData) {
aLayerData->SetAsyncZoomContainerId(mViewID);
}
return ret;
}
///////////////////////////////////////////////////
// nsDisplayTransform Implementation
//
#ifndef DEBUG
static_assert(sizeof(nsDisplayTransform) <= 512,
"nsDisplayTransform has grown");
#endif
nsDisplayTransform::nsDisplayTransform(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList,
const nsRect& aChildrenBuildingRect)
: nsPaintedDisplayItem(aBuilder, aFrame),
mChildren(aBuilder),
mTransform(Some(Matrix4x4())),
mChildrenBuildingRect(aChildrenBuildingRect),
mPrerenderDecision(PrerenderDecision::No),
mIsTransformSeparator(true),
mHasTransformGetter(false),
mHasAssociatedPerspective(false),
mContainsASRs(false),
mWrapsBackdropFilter(false),
mForceIsolation(false) {
MOZ_COUNT_CTOR(nsDisplayTransform);
MOZ_ASSERT(aFrame, "Must have a frame!");
Init(aBuilder, aList);
}
nsDisplayTransform::nsDisplayTransform(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList,
const nsRect& aChildrenBuildingRect,
PrerenderDecision aPrerenderDecision,
bool aWrapsBackdropFilter,
bool aForceIsolation)
: nsPaintedDisplayItem(aBuilder, aFrame),
mChildren(aBuilder),
mChildrenBuildingRect(aChildrenBuildingRect),
mPrerenderDecision(aPrerenderDecision),
mIsTransformSeparator(false),
mHasTransformGetter(false),
mHasAssociatedPerspective(false),
mContainsASRs(false),
mWrapsBackdropFilter(aWrapsBackdropFilter),
mForceIsolation(aForceIsolation) {
MOZ_COUNT_CTOR(nsDisplayTransform);
MOZ_ASSERT(aFrame, "Must have a frame!");
SetReferenceFrameToAncestor(aBuilder);
Init(aBuilder, aList);
}
nsDisplayTransform::nsDisplayTransform(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList,
const nsRect& aChildrenBuildingRect,
decltype(WithTransformGetter))
: nsPaintedDisplayItem(aBuilder, aFrame),
mChildren(aBuilder),
mChildrenBuildingRect(aChildrenBuildingRect),
mPrerenderDecision(PrerenderDecision::No),
mIsTransformSeparator(false),
mHasTransformGetter(true),
mHasAssociatedPerspective(false),
mContainsASRs(false),
mWrapsBackdropFilter(false),
mForceIsolation(false) {
MOZ_COUNT_CTOR(nsDisplayTransform);
MOZ_ASSERT(aFrame, "Must have a frame!");
MOZ_ASSERT(aFrame->GetTransformGetter());
Init(aBuilder, aList);
}
void nsDisplayTransform::SetReferenceFrameToAncestor(
nsDisplayListBuilder* aBuilder) {
if (mFrame == aBuilder->RootReferenceFrame()) {
return;
}
// We manually recompute mToReferenceFrame without going through the
// builder, since this won't apply the 'additional offset'. Our
// children will already be painting with that applied, and we don't
// want to include it a second time in our transform. We don't recompute
// our visible/building rects, since those should still include the additional
// offset.
// TODO: Are there are things computed using our ToReferenceFrame that should
// have the additional offset applied? Should we instead just manually remove
// the offset from our transform instead of this more general value?
// Can we instead apply the additional offset to us and not our children, like
// we do for all other offsets (and how reference frames are supposed to
// work)?
// The reference frame on the builder has already been set to the ancestor
// reference frame by BuildDisplayListForStackingContext using
// SetReferenceFrameAndCurrentOffset, so we just compute the offset.
MOZ_ASSERT(aBuilder->FindReferenceFrameFor(
nsLayoutUtils::GetCrossDocParentFrameInProcess(mFrame)) ==
aBuilder->GetCurrentReferenceFrame());
mToReferenceFrame =
mFrame->GetOffsetToCrossDoc(aBuilder->GetCurrentReferenceFrame());
}
void nsDisplayTransform::Init(nsDisplayListBuilder* aBuilder,
nsDisplayList* aChildren) {
mChildren.AppendToTop(aChildren);
UpdateBounds(aBuilder);
}
bool nsDisplayTransform::ShouldFlattenAway(nsDisplayListBuilder* aBuilder) {
return false;
}
/* Returns the delta specified by the transform-origin property.
* This is a positive delta, meaning that it indicates the direction to move
* to get from (0, 0) of the frame to the transform origin. This function is
* called off the main thread.
*/
/* static */
Point3D nsDisplayTransform::GetDeltaToTransformOrigin(
const nsIFrame* aFrame, TransformReferenceBox& aRefBox,
float aAppUnitsPerPixel) {
MOZ_ASSERT(aFrame, "Can't get delta for a null frame!");
MOZ_ASSERT(aFrame->IsTransformed() || aFrame->BackfaceIsHidden() ||
aFrame->Combines3DTransformWithAncestors(),
"Shouldn't get a delta for an untransformed frame!");
if (!aFrame->IsTransformed()) {
return Point3D();
}
/* For both of the coordinates, if the value of transform is a
* percentage, it's relative to the size of the frame. Otherwise, if it's
* a distance, it's already computed for us!
*/
const nsStyleDisplay* display = aFrame->StyleDisplay();
const StyleTransformOrigin& transformOrigin = display->mTransformOrigin;
CSSPoint origin = nsStyleTransformMatrix::Convert2DPosition(
transformOrigin.horizontal, transformOrigin.vertical, aRefBox);
// Note:
// 1. SVG frames have a reference box that can be (and typically is) offset
// from the TopLeft() of the frame. We need to account for that here.
// 2. If we are using transform-box:content-box in CSS layout, we have the
// offset from TopLeft() of the frame as well.
origin.x += CSSPixel::FromAppUnits(aRefBox.X());
origin.y += CSSPixel::FromAppUnits(aRefBox.Y());
float scale = AppUnitsPerCSSPixel() / float(aAppUnitsPerPixel);
float z = transformOrigin.depth._0;
return Point3D(origin.x * scale, origin.y * scale, z * scale);
}
/* static */
bool nsDisplayTransform::ComputePerspectiveMatrix(const nsIFrame* aFrame,
float aAppUnitsPerPixel,
Matrix4x4& aOutMatrix) {
MOZ_ASSERT(aFrame, "Can't get delta for a null frame!");
MOZ_ASSERT(aFrame->IsTransformed() || aFrame->BackfaceIsHidden() ||
aFrame->Combines3DTransformWithAncestors(),
"Shouldn't get a delta for an untransformed frame!");
MOZ_ASSERT(aOutMatrix.IsIdentity(), "Must have a blank output matrix");
if (!aFrame->IsTransformed()) {
return false;
}
// TODO: Is it possible that the perspectiveFrame's bounds haven't been set
// correctly yet (similar to the aBoundsOverride case for
// GetResultingTransformMatrix)?
nsIFrame* perspectiveFrame =
aFrame->GetClosestFlattenedTreeAncestorPrimaryFrame();
if (!perspectiveFrame) {
return false;
}
/* Grab the values for perspective and perspective-origin (if present) */
const nsStyleDisplay* perspectiveDisplay = perspectiveFrame->StyleDisplay();
if (perspectiveDisplay->mChildPerspective.IsNone()) {
return false;
}
MOZ_ASSERT(perspectiveDisplay->mChildPerspective.IsLength());
float perspective =
perspectiveDisplay->mChildPerspective.AsLength().ToCSSPixels();
perspective = std::max(1.0f, perspective);
if (perspective < std::numeric_limits<Float>::epsilon()) {
return true;
}
TransformReferenceBox refBox(perspectiveFrame);
Point perspectiveOrigin = nsStyleTransformMatrix::Convert2DPosition(
perspectiveDisplay->mPerspectiveOrigin.horizontal,
perspectiveDisplay->mPerspectiveOrigin.vertical, refBox,
aAppUnitsPerPixel);
/* GetOffsetTo computes the offset required to move from 0,0 in
* perspectiveFrame to 0,0 in aFrame. Although we actually want the inverse of
* this, it's faster to compute this way.
*/
nsPoint frameToPerspectiveOffset = -aFrame->GetOffsetTo(perspectiveFrame);
Point frameToPerspectiveGfxOffset(
NSAppUnitsToFloatPixels(frameToPerspectiveOffset.x, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(frameToPerspectiveOffset.y, aAppUnitsPerPixel));
/* Move the perspective origin to be relative to aFrame, instead of relative
* to the containing block which is how it was specified in the style system.
*/
perspectiveOrigin += frameToPerspectiveGfxOffset;
aOutMatrix._34 =
-1.0 / NSAppUnitsToFloatPixels(CSSPixel::ToAppUnits(perspective),
aAppUnitsPerPixel);
aOutMatrix.ChangeBasis(Point3D(perspectiveOrigin.x, perspectiveOrigin.y, 0));
return true;
}
nsDisplayTransform::FrameTransformProperties::FrameTransformProperties(
const nsIFrame* aFrame, TransformReferenceBox& aRefBox,
float aAppUnitsPerPixel)
: mFrame(aFrame),
mTranslate(aFrame->StyleDisplay()->mTranslate),
mRotate(aFrame->StyleDisplay()->mRotate),
mScale(aFrame->StyleDisplay()->mScale),
mTransform(aFrame->StyleDisplay()->mTransform),
mMotion(aFrame->StyleDisplay()->mOffsetPath.IsNone()
? Nothing()
: MotionPathUtils::ResolveMotionPath(aFrame, aRefBox)),
mToTransformOrigin(
GetDeltaToTransformOrigin(aFrame, aRefBox, aAppUnitsPerPixel)) {}
/* Wraps up the transform matrix in a change-of-basis matrix pair that
* translates from local coordinate space to transform coordinate space, then
* hands it back.
*/
Matrix4x4 nsDisplayTransform::GetResultingTransformMatrix(
const FrameTransformProperties& aProperties, TransformReferenceBox& aRefBox,
float aAppUnitsPerPixel) {
return GetResultingTransformMatrixInternal(aProperties, aRefBox, nsPoint(),
aAppUnitsPerPixel, 0);
}
Matrix4x4 nsDisplayTransform::GetResultingTransformMatrix(
const nsIFrame* aFrame, const nsPoint& aOrigin, float aAppUnitsPerPixel,
uint32_t aFlags) {
TransformReferenceBox refBox(aFrame);
FrameTransformProperties props(aFrame, refBox, aAppUnitsPerPixel);
return GetResultingTransformMatrixInternal(props, refBox, aOrigin,
aAppUnitsPerPixel, aFlags);
}
Matrix4x4 nsDisplayTransform::GetResultingTransformMatrixInternal(
const FrameTransformProperties& aProperties, TransformReferenceBox& aRefBox,
const nsPoint& aOrigin, float aAppUnitsPerPixel, uint32_t aFlags) {
const nsIFrame* frame = aProperties.mFrame;
NS_ASSERTION(frame || !(aFlags & INCLUDE_PERSPECTIVE),
"Must have a frame to compute perspective!");
// IncrementScaleRestyleCountIfNeeded in ActiveLayerTracker.cpp is a
// simplified copy of this function.
// Get the underlying transform matrix:
/* Get the matrix, then change its basis to factor in the origin. */
Matrix4x4 result;
// See the comment for SVGContainerFrame::HasChildrenOnlyTransform for
// an explanation of what children-only transforms are.
Matrix parentsChildrenOnlyTransform;
const bool parentHasChildrenOnlyTransform =
frame && frame->HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED) &&
frame->GetParentSVGTransforms(&parentsChildrenOnlyTransform) &&
!parentsChildrenOnlyTransform.IsIdentity();
bool shouldRound = nsLayoutUtils::ShouldSnapToGrid(frame);
/* Transformed frames always have a transform, or are preserving 3d (and might
* still have perspective!) */
if (aProperties.HasTransform()) {
result = nsStyleTransformMatrix::ReadTransforms(
aProperties.mTranslate, aProperties.mRotate, aProperties.mScale,
aProperties.mMotion.ptrOr(nullptr), aProperties.mTransform, aRefBox,
aAppUnitsPerPixel);
}
// Apply any translation due to 'transform-origin' and/or 'transform-box':
if (aProperties.mToTransformOrigin != gfx::Point3D()) {
result.ChangeBasis(aProperties.mToTransformOrigin);
}
if (parentHasChildrenOnlyTransform) {
float pixelsPerCSSPx = AppUnitsPerCSSPixel() / aAppUnitsPerPixel;
parentsChildrenOnlyTransform._31 *= pixelsPerCSSPx;
parentsChildrenOnlyTransform._32 *= pixelsPerCSSPx;
auto parentsChildrenOnlyTransform3D =
Matrix4x4::From2D(parentsChildrenOnlyTransform);
// <svg> outer anon child frame doesn't need the extra basis change because
// it is the root of the svg rendering (and thus its offset with respect to
// its parent, like border / padding shouldn't be accounted for).
if (frame->GetPosition() != nsPoint() &&
!frame->IsSVGOuterSVGAnonChildFrame()) {
const Point3D frameOffset(
NSAppUnitsToFloatPixels(-frame->GetPosition().x, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(-frame->GetPosition().y, aAppUnitsPerPixel),
0);
parentsChildrenOnlyTransform3D.ChangeBasis(frameOffset);
}
result *= parentsChildrenOnlyTransform3D;
}
Matrix4x4 perspectiveMatrix;
bool hasPerspective = aFlags & INCLUDE_PERSPECTIVE;
if (hasPerspective) {
if (ComputePerspectiveMatrix(frame, aAppUnitsPerPixel, perspectiveMatrix)) {
result *= perspectiveMatrix;
}
}
if ((aFlags & INCLUDE_PRESERVE3D_ANCESTORS) && frame &&
frame->Combines3DTransformWithAncestors()) {
// Include the transform set on our parent
nsIFrame* parentFrame =
frame->GetClosestFlattenedTreeAncestorPrimaryFrame();
NS_ASSERTION(parentFrame && parentFrame->IsTransformed() &&
parentFrame->Extend3DContext(),
"Preserve3D mismatch!");
TransformReferenceBox refBox(parentFrame);
FrameTransformProperties props(parentFrame, refBox, aAppUnitsPerPixel);
// Whenever we are including preserve3d we want to also include perspective
// (if it exists).
uint32_t flags = (INCLUDE_PRESERVE3D_ANCESTORS | INCLUDE_PERSPECTIVE);
// If this frame isn't transformed (but we exist for backface-visibility),
// then we're not a reference frame so no offset to origin will be added.
// Otherwise we need to manually translate into our parent's coordinate
// space.
if (frame->IsTransformed()) {
nsLayoutUtils::PostTranslate(result, frame->GetPosition(),
aAppUnitsPerPixel, shouldRound);
}
Matrix4x4 parent = GetResultingTransformMatrixInternal(
props, refBox, nsPoint(0, 0), aAppUnitsPerPixel, flags);
result = result * parent;
}
MOZ_ASSERT((aOrigin == nsPoint()) || (aFlags & OFFSET_BY_ORIGIN));
if ((aFlags & OFFSET_BY_ORIGIN) && (aOrigin != nsPoint())) {
nsLayoutUtils::PostTranslate(result, aOrigin, aAppUnitsPerPixel,
shouldRound);
}
return result;
}
bool nsDisplayOpacity::CanUseAsyncAnimations(nsDisplayListBuilder* aBuilder) {
static constexpr nsCSSPropertyIDSet opacitySet =
nsCSSPropertyIDSet::OpacityProperties();
if (ActiveLayerTracker::IsStyleAnimated(aBuilder, mFrame, opacitySet)) {
return true;
}
EffectCompositor::SetPerformanceWarning(
mFrame, opacitySet,
AnimationPerformanceWarning(
AnimationPerformanceWarning::Type::OpacityFrameInactive));
return false;
}
bool nsDisplayTransform::CanUseAsyncAnimations(nsDisplayListBuilder* aBuilder) {
return mPrerenderDecision != PrerenderDecision::No;
}
bool nsDisplayBackgroundColor::CanUseAsyncAnimations(
nsDisplayListBuilder* aBuilder) {
return StaticPrefs::gfx_omta_background_color();
}
void nsDisplayTableBackgroundColor::Destroy(nsDisplayListBuilder* aBuilder) {
RemoveDisplayItemFromFrame(aBuilder, mAncestorFrame);
nsDisplayBackgroundColor::Destroy(aBuilder);
}
static bool IsInStickyPositionedSubtree(const nsIFrame* aFrame) {
for (const nsIFrame* frame = aFrame; frame;
frame = nsLayoutUtils::GetCrossDocParentFrameInProcess(frame)) {
if (frame->IsStickyPositioned()) {
return true;
}
}
return false;
}
static bool ShouldUsePartialPrerender(const nsIFrame* aFrame) {
return StaticPrefs::layout_animation_prerender_partial() &&
// Bug 1642547: Support partial prerender for position:sticky elements.
!IsInStickyPositionedSubtree(aFrame);
}
/* static */
auto nsDisplayTransform::ShouldPrerenderTransformedContent(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsRect* aDirtyRect)
-> PrerenderInfo {
PrerenderInfo result;
// Prerendering only makes sense if we are painting to the window so that the
// extra prerendered content can be animated into view by the compositor.
// GenerateGlyphMask (for background-clip: text) uses a nested builder, so it
// can be inside a builder that is painting to window, and it's buggy, so just
// allow it to minimize bugs.
if (!aBuilder->IsPaintingToWindow() && !aBuilder->IsForGenerateGlyphMask()) {
return result;
}
// If we are in a preserve-3d tree, and we've disallowed async animations, we
// return No prerender decision directly.
if ((aFrame->Extend3DContext() ||
aFrame->Combines3DTransformWithAncestors()) &&
!aBuilder->GetPreserves3DAllowAsyncAnimation()) {
return result;
}
// Elements whose transform has been modified recently, or which
// have a compositor-animated transform, can be prerendered. An element
// might have only just had its transform animated in which case
// the ActiveLayerManager may not have been notified yet.
static constexpr nsCSSPropertyIDSet transformSet =
nsCSSPropertyIDSet::TransformLikeProperties();
if (!ActiveLayerTracker::IsTransformMaybeAnimated(aFrame) &&
!EffectCompositor::HasAnimationsForCompositor(
aFrame, DisplayItemType::TYPE_TRANSFORM)) {
EffectCompositor::SetPerformanceWarning(
aFrame, transformSet,
AnimationPerformanceWarning(
AnimationPerformanceWarning::Type::TransformFrameInactive));
// This case happens when we're sure that the frame is not animated and its
// preserve-3d ancestors are not, either. So we don't need to pre-render.
// However, this decision shouldn't affect the decisions for other frames in
// the preserve-3d context. We need this flag to determine whether we should
// block async animations on other frames in the current preserve-3d tree.
result.mHasAnimations = false;
return result;
}
// We should not allow prerender if any ancestor container element has
// mask/clip-path effects.
//
// With prerender and async transform animation, we do not need to restyle an
// animated element to respect position changes, since that transform is done
// by layer animation. As a result, the container element is not aware of
// position change of that containing element and loses the chance to update
// the content of mask/clip-path.
//
// Why do we need to update a mask? This is relative to how we generate a
// mask layer in ContainerState::SetupMaskLayerForCSSMask. While creating a
// mask layer, to reduce memory usage, we did not choose the size of the
// masked element as mask size. Instead, we read the union of bounds of all
// children display items by nsDisplayWrapList::GetBounds, which is smaller
// than or equal to the masked element's boundary, and use it as the position
// size of the mask layer. That union bounds is actually affected by the
// geometry of the animated element. To keep the content of mask up to date,
// forbidding of prerender is required.
for (nsIFrame* container =
nsLayoutUtils::GetCrossDocParentFrameInProcess(aFrame);
container;
container = nsLayoutUtils::GetCrossDocParentFrameInProcess(container)) {
const nsStyleSVGReset* svgReset = container->StyleSVGReset();
if (svgReset->HasMask() || svgReset->HasClipPath()) {
return result;
}
}
// If the incoming dirty rect already contains the entire overflow area,
// we are already rendering the entire content.
nsRect overflow = aFrame->InkOverflowRectRelativeToSelf();
// UntransformRect will not touch the output rect (`&untranformedDirtyRect`)
// in cases of non-invertible transforms, so we set `untransformedRect` to
// `aDirtyRect` as an initial value for such cases.
nsRect untransformedDirtyRect = *aDirtyRect;
UntransformRect(*aDirtyRect, overflow, aFrame, &untransformedDirtyRect);
if (untransformedDirtyRect.Contains(overflow)) {
*aDirtyRect = untransformedDirtyRect;
result.mDecision = PrerenderDecision::Full;
return result;
}
float viewportRatio =
StaticPrefs::layout_animation_prerender_viewport_ratio_limit();
uint32_t absoluteLimitX =
StaticPrefs::layout_animation_prerender_absolute_limit_x();
uint32_t absoluteLimitY =
StaticPrefs::layout_animation_prerender_absolute_limit_y();
nsSize refSize = aBuilder->RootReferenceFrame()->GetSize();
float resolution = aFrame->PresShell()->GetCumulativeResolution();
if (resolution < 1.0f) {
refSize.SizeTo(
NSCoordSaturatingNonnegativeMultiply(refSize.width, 1.0f / resolution),
NSCoordSaturatingNonnegativeMultiply(refSize.height,
1.0f / resolution));
}
// Only prerender if the transformed frame's size is <= a multiple of the
// reference frame size (~viewport), and less than an absolute limit.
// Both the ratio and the absolute limit are configurable.
nscoord maxLength = std::max(nscoord(refSize.width * viewportRatio),
nscoord(refSize.height * viewportRatio));
nsSize relativeLimit(maxLength, maxLength);
nsSize absoluteLimit(
aFrame->PresContext()->DevPixelsToAppUnits(absoluteLimitX),
aFrame->PresContext()->DevPixelsToAppUnits(absoluteLimitY));
nsSize maxSize = Min(relativeLimit, absoluteLimit);
const auto transform = nsLayoutUtils::GetTransformToAncestor(
RelativeTo{aFrame},
RelativeTo{nsLayoutUtils::GetDisplayRootFrame(aFrame)});
const gfxRect transformedBounds = transform.TransformAndClipBounds(
gfxRect(overflow.x, overflow.y, overflow.width, overflow.height),
gfxRect::MaxIntRect());
const nsSize frameSize =
nsSize(transformedBounds.width, transformedBounds.height);
uint64_t maxLimitArea = uint64_t(maxSize.width) * maxSize.height;
uint64_t frameArea = uint64_t(frameSize.width) * frameSize.height;
if (frameArea <= maxLimitArea && frameSize <= absoluteLimit) {
*aDirtyRect = overflow;
result.mDecision = PrerenderDecision::Full;
return result;
}
if (ShouldUsePartialPrerender(aFrame)) {
*aDirtyRect = nsLayoutUtils::ComputePartialPrerenderArea(
aFrame, untransformedDirtyRect, overflow, maxSize);
result.mDecision = PrerenderDecision::Partial;
return result;
}
if (frameArea > maxLimitArea) {
uint64_t appUnitsPerPixel = AppUnitsPerCSSPixel();
EffectCompositor::SetPerformanceWarning(
aFrame, transformSet,
AnimationPerformanceWarning(
AnimationPerformanceWarning::Type::ContentTooLargeArea,
{
int(frameArea / (appUnitsPerPixel * appUnitsPerPixel)),
int(maxLimitArea / (appUnitsPerPixel * appUnitsPerPixel)),
}));
} else {
EffectCompositor::SetPerformanceWarning(
aFrame, transformSet,
AnimationPerformanceWarning(
AnimationPerformanceWarning::Type::ContentTooLarge,
{
nsPresContext::AppUnitsToIntCSSPixels(frameSize.width),
nsPresContext::AppUnitsToIntCSSPixels(frameSize.height),
nsPresContext::AppUnitsToIntCSSPixels(relativeLimit.width),
nsPresContext::AppUnitsToIntCSSPixels(relativeLimit.height),
nsPresContext::AppUnitsToIntCSSPixels(absoluteLimit.width),
nsPresContext::AppUnitsToIntCSSPixels(absoluteLimit.height),
}));
}
return result;
}
/* If the matrix is singular, or a hidden backface is shown, the frame won't be
* visible or hit. */
static bool IsFrameVisible(nsIFrame* aFrame, const Matrix4x4& aMatrix) {
if (aMatrix.IsSingular()) {
return false;
}
if (aFrame->BackfaceIsHidden() && aMatrix.IsBackfaceVisible()) {
return false;
}
return true;
}
const Matrix4x4Flagged& nsDisplayTransform::GetTransform() const {
if (mTransform) {
return *mTransform;
}
float scale = mFrame->PresContext()->AppUnitsPerDevPixel();
if (mHasTransformGetter) {
mTransform.emplace((mFrame->GetTransformGetter())(mFrame, scale));
Point3D newOrigin =
Point3D(NSAppUnitsToFloatPixels(mToReferenceFrame.x, scale),
NSAppUnitsToFloatPixels(mToReferenceFrame.y, scale), 0.0f);
mTransform->ChangeBasis(newOrigin.x, newOrigin.y, newOrigin.z);
} else if (!mIsTransformSeparator) {
DebugOnly<bool> isReference = mFrame->IsTransformed() ||
mFrame->Combines3DTransformWithAncestors() ||
mFrame->Extend3DContext();
MOZ_ASSERT(isReference);
mTransform.emplace(
GetResultingTransformMatrix(mFrame, ToReferenceFrame(), scale,
INCLUDE_PERSPECTIVE | OFFSET_BY_ORIGIN));
} else {
// Use identity matrix
mTransform.emplace();
}
return *mTransform;
}
const Matrix4x4Flagged& nsDisplayTransform::GetInverseTransform() const {
if (mInverseTransform) {
return *mInverseTransform;
}
MOZ_ASSERT(!GetTransform().IsSingular());
mInverseTransform.emplace(GetTransform().Inverse());
return *mInverseTransform;
}
Matrix4x4 nsDisplayTransform::GetTransformForRendering(
LayoutDevicePoint* aOutOrigin) const {
if (!mFrame->HasPerspective() || mHasTransformGetter ||
mIsTransformSeparator) {
if (!mHasTransformGetter && !mIsTransformSeparator && aOutOrigin) {
// If aOutOrigin is provided, put the offset to origin into it, because
// we need to keep it separate for webrender. The combination of
// *aOutOrigin and the returned matrix here should always be equivalent
// to what GetTransform() would have returned.
float scale = mFrame->PresContext()->AppUnitsPerDevPixel();
*aOutOrigin = LayoutDevicePoint::FromAppUnits(ToReferenceFrame(), scale);
// The rounding behavior should also be the same as GetTransform().
if (nsLayoutUtils::ShouldSnapToGrid(mFrame)) {
aOutOrigin->Round();
}
return GetResultingTransformMatrix(mFrame, nsPoint(0, 0), scale,
INCLUDE_PERSPECTIVE);
}
return GetTransform().GetMatrix();
}
MOZ_ASSERT(!mHasTransformGetter);
float scale = mFrame->PresContext()->AppUnitsPerDevPixel();
// Don't include perspective transform, or the offset to origin, since
// nsDisplayPerspective will handle both of those.
return GetResultingTransformMatrix(mFrame, nsPoint(), scale, 0);
}
const Matrix4x4& nsDisplayTransform::GetAccumulatedPreserved3DTransform(
nsDisplayListBuilder* aBuilder) {
MOZ_ASSERT(!mFrame->Extend3DContext() || IsLeafOf3DContext());
if (!IsLeafOf3DContext()) {
return GetTransform().GetMatrix();
}
if (!mTransformPreserves3D) {
const nsIFrame* establisher; // Establisher of the 3D rendering context.
for (establisher = mFrame;
establisher && establisher->Combines3DTransformWithAncestors();
establisher =
establisher->GetClosestFlattenedTreeAncestorPrimaryFrame()) {
}
const nsIFrame* establisherReference = aBuilder->FindReferenceFrameFor(
nsLayoutUtils::GetCrossDocParentFrameInProcess(establisher));
nsPoint offset = establisher->GetOffsetToCrossDoc(establisherReference);
float scale = mFrame->PresContext()->AppUnitsPerDevPixel();
uint32_t flags =
INCLUDE_PRESERVE3D_ANCESTORS | INCLUDE_PERSPECTIVE | OFFSET_BY_ORIGIN;
mTransformPreserves3D = MakeUnique<Matrix4x4>(
GetResultingTransformMatrix(mFrame, offset, scale, flags));
}
return *mTransformPreserves3D;
}
bool nsDisplayTransform::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
// We want to make sure we don't pollute the transform property in the WR
// stacking context by including the position of this frame (relative to the
// parent reference frame). We need to keep those separate; the position of
// this frame goes into the stacking context bounds while the transform goes
// into the transform.
LayoutDevicePoint position;
Matrix4x4 newTransformMatrix = GetTransformForRendering(&position);
gfx::Matrix4x4* transformForSC = &newTransformMatrix;
if (newTransformMatrix.IsIdentity()) {
// If the transform is an identity transform, strip it out so that WR
// doesn't turn this stacking context into a reference frame, as it
// affects positioning.
transformForSC = nullptr;
// In ChooseScaleAndSetTransform, we round the offset from the reference
// frame used to adjust the transform, if there is no transform, or it
// is just a translation. We need to do the same here.
if (nsLayoutUtils::ShouldSnapToGrid(mFrame)) {
position.Round();
}
}
auto key = wr::SpatialKey(uint64_t(mFrame), GetPerFrameKey(),
wr::SpatialKeyKind::Transform);
// We don't send animations for transform separator display items.
uint64_t animationsId =
mIsTransformSeparator
? 0
: AddAnimationsForWebRender(
this, aManager, aDisplayListBuilder,
IsPartialPrerender() ? Some(position) : Nothing());
wr::WrAnimationProperty prop{wr::WrAnimationType::Transform, animationsId,
key};
nsDisplayTransform* deferredTransformItem = nullptr;
if (ShouldDeferTransform()) {
// If it has perspective, we create a new scroll data via the
// UpdateScrollData call because that scenario is more complex. Otherwise,
// if we don't contain any ASRs then just stash the transform on the
// StackingContextHelper and apply it to any scroll data that are created
// inside this nsDisplayTransform.
deferredTransformItem = this;
}
// Determine if we're possibly animated (= would need an active layer in FLB).
bool animated = !mIsTransformSeparator &&
ActiveLayerTracker::IsTransformMaybeAnimated(Frame());
wr::StackingContextParams params;
params.mBoundTransform = &newTransformMatrix;
params.animation = animationsId ? &prop : nullptr;
if (mWrapsBackdropFilter) {
params.flags |= wr::StackingContextFlags::WRAPS_BACKDROP_FILTER;
}
if (mForceIsolation) {
params.flags |= wr::StackingContextFlags::FORCED_ISOLATION;
}
wr::WrTransformInfo transform_info;
if (transformForSC) {
transform_info.transform = wr::ToLayoutTransform(newTransformMatrix);
transform_info.key = key;
params.mTransformPtr = &transform_info;
} else {
params.mTransformPtr = nullptr;
}
params.prim_flags = !BackfaceIsHidden()
? wr::PrimitiveFlags::IS_BACKFACE_VISIBLE
: wr::PrimitiveFlags{0};
params.paired_with_perspective = mHasAssociatedPerspective;
params.mDeferredTransformItem = deferredTransformItem;
params.mAnimated = animated;
// Determine if we would have to rasterize any items in local raster space
// (i.e. disable subpixel AA). We don't always need to rasterize locally even
// if the stacking context is possibly animated (at the cost of potentially
// some false negatives with respect to will-change handling), so we pass in
// this determination separately to accurately match with when FLB would
// normally disable subpixel AA.
params.mRasterizeLocally = animated && Frame()->HasAnimationOfTransform();
params.SetPreserve3D(mFrame->Extend3DContext() && !mIsTransformSeparator);
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
LayoutDeviceSize boundsSize = LayoutDeviceSize::FromAppUnits(
mChildBounds.Size(), mFrame->PresContext()->AppUnitsPerDevPixel());
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params, LayoutDeviceRect(position, boundsSize));
aManager->CommandBuilder().CreateWebRenderCommandsFromDisplayList(
GetChildren(), this, aDisplayListBuilder, sc, aBuilder, aResources);
return true;
}
bool nsDisplayTransform::UpdateScrollData(
WebRenderScrollData* aData, WebRenderLayerScrollData* aLayerData) {
if (ShouldDeferTransform()) {
// This case is handled in CreateWebRenderCommands by stashing the transform
// on the stacking context.
return false;
}
if (aLayerData) {
aLayerData->SetTransform(GetTransform().GetMatrix());
aLayerData->SetTransformIsPerspective(mFrame->ChildrenHavePerspective());
}
return true;
}
bool nsDisplayTransform::ShouldSkipTransform(
nsDisplayListBuilder* aBuilder) const {
return (aBuilder->RootReferenceFrame() == mFrame) &&
aBuilder->IsForGenerateGlyphMask();
}
void nsDisplayTransform::Collect3DTransformLeaves(
nsDisplayListBuilder* aBuilder, nsTArray<nsDisplayTransform*>& aLeaves) {
if (!IsParticipating3DContext() || IsLeafOf3DContext()) {
aLeaves.AppendElement(this);
return;
}
FlattenedDisplayListIterator iter(aBuilder, &mChildren);
while (iter.HasNext()) {
nsDisplayItem* item = iter.GetNextItem();
if (item->GetType() == DisplayItemType::TYPE_PERSPECTIVE) {
auto* perspective = static_cast<nsDisplayPerspective*>(item);
if (!perspective->GetChildren()->GetTop()) {
continue;
}
item = perspective->GetChildren()->GetTop();
}
if (item->GetType() != DisplayItemType::TYPE_TRANSFORM) {
gfxCriticalError() << "Invalid child item within 3D transform of type: "
<< item->Name();
continue;
}
static_cast<nsDisplayTransform*>(item)->Collect3DTransformLeaves(aBuilder,
aLeaves);
}
}
static RefPtr<gfx::Path> BuildPathFromPolygon(const RefPtr<DrawTarget>& aDT,
const gfx::Polygon& aPolygon) {
MOZ_ASSERT(!aPolygon.IsEmpty());
RefPtr<PathBuilder> pathBuilder = aDT->CreatePathBuilder();
const nsTArray<Point4D>& points = aPolygon.GetPoints();
pathBuilder->MoveTo(points[0].As2DPoint());
for (size_t i = 1; i < points.Length(); ++i) {
pathBuilder->LineTo(points[i].As2DPoint());
}
pathBuilder->Close();
return pathBuilder->Finish();
}
void nsDisplayTransform::CollectSorted3DTransformLeaves(
nsDisplayListBuilder* aBuilder, nsTArray<TransformPolygon>& aLeaves) {
std::list<TransformPolygon> inputLayers;
nsTArray<nsDisplayTransform*> leaves;
Collect3DTransformLeaves(aBuilder, leaves);
for (nsDisplayTransform* item : leaves) {
auto bounds = LayoutDeviceRect::FromAppUnits(
item->mChildBounds, item->mFrame->PresContext()->AppUnitsPerDevPixel());
Matrix4x4 transform = item->GetAccumulatedPreserved3DTransform(aBuilder);
if (!IsFrameVisible(item->mFrame, transform)) {
continue;
}
gfx::Polygon polygon =
gfx::Polygon::FromRect(gfx::Rect(bounds.ToUnknownRect()));
polygon.TransformToScreenSpace(transform);
if (polygon.GetPoints().Length() >= 3) {
inputLayers.push_back(TransformPolygon(item, std::move(polygon)));
}
}
if (inputLayers.empty()) {
return;
}
BSPTree<nsDisplayTransform> tree(inputLayers);
nsTArray<TransformPolygon> orderedLayers(tree.GetDrawOrder());
for (TransformPolygon& polygon : orderedLayers) {
Matrix4x4 inverse =
polygon.data->GetAccumulatedPreserved3DTransform(aBuilder).Inverse();
MOZ_ASSERT(polygon.geometry);
polygon.geometry->TransformToLayerSpace(inverse);
}
aLeaves = std::move(orderedLayers);
}
void nsDisplayTransform::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
Paint(aBuilder, aCtx, Nothing());
}
void nsDisplayTransform::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx,
const Maybe<gfx::Polygon>& aPolygon) {
if (IsParticipating3DContext() && !IsLeafOf3DContext()) {
MOZ_ASSERT(!aPolygon);
nsTArray<TransformPolygon> leaves;
CollectSorted3DTransformLeaves(aBuilder, leaves);
for (TransformPolygon& item : leaves) {
item.data->Paint(aBuilder, aCtx, item.geometry);
}
return;
}
gfxContextMatrixAutoSaveRestore saveMatrix(aCtx);
Matrix4x4 trans = ShouldSkipTransform(aBuilder)
? Matrix4x4()
: GetAccumulatedPreserved3DTransform(aBuilder);
if (!IsFrameVisible(mFrame, trans)) {
return;
}
Matrix trans2d;
if (trans.CanDraw2D(&trans2d)) {
aCtx->Multiply(ThebesMatrix(trans2d));
if (aPolygon) {
RefPtr<gfx::Path> path =
BuildPathFromPolygon(aCtx->GetDrawTarget(), *aPolygon);
aCtx->GetDrawTarget()->PushClip(path);
}
GetChildren()->Paint(aBuilder, aCtx,
mFrame->PresContext()->AppUnitsPerDevPixel());
if (aPolygon) {
aCtx->GetDrawTarget()->PopClip();
}
return;
}
// TODO: Implement 3d transform handling, including plane splitting and
// sorting. See BasicCompositor.
auto pixelBounds = LayoutDeviceRect::FromAppUnitsToOutside(
mChildBounds, mFrame->PresContext()->AppUnitsPerDevPixel());
RefPtr<DrawTarget> untransformedDT =
gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
IntSize(pixelBounds.Width(), pixelBounds.Height()),
SurfaceFormat::B8G8R8A8, true);
if (!untransformedDT || !untransformedDT->IsValid()) {
return;
}
untransformedDT->SetTransform(
Matrix::Translation(-Point(pixelBounds.X(), pixelBounds.Y())));
gfxContext groupTarget(untransformedDT, /* aPreserveTransform */ true);
if (aPolygon) {
RefPtr<gfx::Path> path =
BuildPathFromPolygon(aCtx->GetDrawTarget(), *aPolygon);
aCtx->GetDrawTarget()->PushClip(path);
}
GetChildren()->Paint(aBuilder, &groupTarget,
mFrame->PresContext()->AppUnitsPerDevPixel());
if (aPolygon) {
aCtx->GetDrawTarget()->PopClip();
}
RefPtr<SourceSurface> untransformedSurf = untransformedDT->Snapshot();
trans.PreTranslate(pixelBounds.X(), pixelBounds.Y(), 0);
aCtx->GetDrawTarget()->Draw3DTransformedSurface(untransformedSurf, trans);
}
bool nsDisplayTransform::MayBeAnimated(nsDisplayListBuilder* aBuilder) const {
// If EffectCompositor::HasAnimationsForCompositor() is true then we can
// completely bypass the main thread for this animation, so it is always
// worthwhile.
// For ActiveLayerTracker::IsTransformAnimated() cases the main thread is
// already involved so there is less to be gained.
// Therefore we check that the *post-transform* bounds of this item are
// big enough to justify an active layer.
return EffectCompositor::HasAnimationsForCompositor(
mFrame, DisplayItemType::TYPE_TRANSFORM) ||
(ActiveLayerTracker::IsTransformAnimated(aBuilder, mFrame));
}
nsRect nsDisplayTransform::TransformUntransformedBounds(
nsDisplayListBuilder* aBuilder, const Matrix4x4Flagged& aMatrix) const {
const nsRect untransformedBounds = GetUntransformedBounds(aBuilder);
// GetTransform always operates in dev pixels.
const float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
return nsLayoutUtils::MatrixTransformRect(untransformedBounds, aMatrix,
factor);
}
/**
* Returns the bounds for this transform. The bounds are calculated during
* display list building and merging, see |nsDisplayTransform::UpdateBounds()|.
*/
nsRect nsDisplayTransform::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
return mBounds;
}
void nsDisplayTransform::ComputeBounds(nsDisplayListBuilder* aBuilder) {
MOZ_ASSERT(mFrame->Extend3DContext() || IsLeafOf3DContext());
/* Some transforms can get empty bounds in 2D, but might get transformed again
* and get non-empty bounds. A simple example of this would be a 180 degree
* rotation getting applied twice.
* We should not depend on transforming bounds level by level.
*
* This function collects the bounds of this transform and stores it in
* nsDisplayListBuilder. If this is not a leaf of a 3D context, we recurse
* down and include the bounds of the child transforms.
* The bounds are transformed with the accumulated transformation matrix up to
* the 3D context root coordinate space.
*/
nsDisplayListBuilder::AutoAccumulateTransform accTransform(aBuilder);
accTransform.Accumulate(GetTransform().GetMatrix());
// Do not dive into another 3D context.
if (!IsLeafOf3DContext()) {
for (nsDisplayItem* i : *GetChildren()) {
i->DoUpdateBoundsPreserves3D(aBuilder);
}
}
/* The child transforms that extend 3D context further will have empty bounds,
* so the untransformed bounds here is the bounds of all the non-preserve-3d
* content under this transform.
*/
const nsRect rect = TransformUntransformedBounds(
aBuilder, accTransform.GetCurrentTransform());
aBuilder->AccumulateRect(rect);
}
void nsDisplayTransform::DoUpdateBoundsPreserves3D(
nsDisplayListBuilder* aBuilder) {
MOZ_ASSERT(mFrame->Combines3DTransformWithAncestors() ||
IsTransformSeparator());
// Updating is not going through to child 3D context.
ComputeBounds(aBuilder);
}
void nsDisplayTransform::UpdateBounds(nsDisplayListBuilder* aBuilder) {
UpdateUntransformedBounds(aBuilder);
if (IsTransformSeparator()) {
MOZ_ASSERT(GetTransform().IsIdentity());
mBounds = mChildBounds;
return;
}
if (mFrame->Extend3DContext()) {
if (!Combines3DTransformWithAncestors()) {
// The transform establishes a 3D context. |UpdateBoundsFor3D()| will
// collect the bounds from the child transforms.
UpdateBoundsFor3D(aBuilder);
} else {
// With nested 3D transforms, the 2D bounds might not be useful.
mBounds = nsRect();
}
return;
}
MOZ_ASSERT(!mFrame->Extend3DContext());
// We would like to avoid calculating 2D bounds here for nested 3D transforms,
// but mix-blend-mode relies on having bounds set. See bug 1556956.
// A stand-alone transform.
mBounds = TransformUntransformedBounds(aBuilder, GetTransform());
}
void nsDisplayTransform::UpdateBoundsFor3D(nsDisplayListBuilder* aBuilder) {
MOZ_ASSERT(mFrame->Extend3DContext() &&
!mFrame->Combines3DTransformWithAncestors() &&
!IsTransformSeparator());
// Always start updating from an establisher of a 3D rendering context.
nsDisplayListBuilder::AutoAccumulateRect accRect(aBuilder);
nsDisplayListBuilder::AutoAccumulateTransform accTransform(aBuilder);
accTransform.StartRoot();
ComputeBounds(aBuilder);
mBounds = aBuilder->GetAccumulatedRect();
}
void nsDisplayTransform::UpdateUntransformedBounds(
nsDisplayListBuilder* aBuilder) {
mChildBounds = GetChildren()->GetClippedBoundsWithRespectToASR(
aBuilder, mActiveScrolledRoot);
}
#ifdef DEBUG_HIT
# include <time.h>
#endif
/* HitTest does some fun stuff with matrix transforms to obtain the answer. */
void nsDisplayTransform::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect, HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
if (aState->mGatheringPreserves3DLeaves) {
GetChildren()->HitTest(aBuilder, aRect, aState, aOutFrames);
return;
}
/* Here's how this works:
* 1. Get the matrix. If it's singular, abort (clearly we didn't hit
* anything).
* 2. Invert the matrix.
* 3. Use it to transform the rect into the correct space.
* 4. Pass that rect down through to the list's version of HitTest.
*/
// GetTransform always operates in dev pixels.
float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
Matrix4x4 matrix = GetAccumulatedPreserved3DTransform(aBuilder);
if (!IsFrameVisible(mFrame, matrix)) {
return;
}
const bool oldHitOccludingItem = aState->mHitOccludingItem;
/* We want to go from transformed-space to regular space.
* Thus we have to invert the matrix, which normally does
* the reverse operation (e.g. regular->transformed)
*/
/* Now, apply the transform and pass it down the channel. */
matrix.Invert();
nsRect resultingRect;
// Magic width/height indicating we're hit testing a point, not a rect
const bool testingPoint = aRect.width == 1 && aRect.height == 1;
if (testingPoint) {
Point4D point =
matrix.ProjectPoint(Point(NSAppUnitsToFloatPixels(aRect.x, factor),
NSAppUnitsToFloatPixels(aRect.y, factor)));
if (!point.HasPositiveWCoord()) {
return;
}
Point point2d = point.As2DPoint();
resultingRect =
nsRect(NSFloatPixelsToAppUnits(float(point2d.x), factor),
NSFloatPixelsToAppUnits(float(point2d.y), factor), 1, 1);
} else {
Rect originalRect(NSAppUnitsToFloatPixels(aRect.x, factor),
NSAppUnitsToFloatPixels(aRect.y, factor),
NSAppUnitsToFloatPixels(aRect.width, factor),
NSAppUnitsToFloatPixels(aRect.height, factor));
Rect childGfxBounds(NSAppUnitsToFloatPixels(mChildBounds.x, factor),
NSAppUnitsToFloatPixels(mChildBounds.y, factor),
NSAppUnitsToFloatPixels(mChildBounds.width, factor),
NSAppUnitsToFloatPixels(mChildBounds.height, factor));
Rect rect = matrix.ProjectRectBounds(originalRect, childGfxBounds);
resultingRect =
nsRect(NSFloatPixelsToAppUnits(float(rect.X()), factor),
NSFloatPixelsToAppUnits(float(rect.Y()), factor),
NSFloatPixelsToAppUnits(float(rect.Width()), factor),
NSFloatPixelsToAppUnits(float(rect.Height()), factor));
}
if (resultingRect.IsEmpty()) {
return;
}
#ifdef DEBUG_HIT
printf("Frame: %p\n", dynamic_cast<void*>(mFrame));
printf(" Untransformed point: (%f, %f)\n", resultingRect.X(),
resultingRect.Y());
uint32_t originalFrameCount = aOutFrames.Length();
#endif
const bool savedTransformHasBackfaceVisible =
aState->mTransformHasBackfaceVisible;
if (IsLeafOf3DContext()) {
aState->mTransformHasBackfaceVisible = matrix.IsBackfaceVisible();
}
GetChildren()->HitTest(aBuilder, resultingRect, aState, aOutFrames);
if (IsLeafOf3DContext()) {
aState->mTransformHasBackfaceVisible = savedTransformHasBackfaceVisible;
}
if (aState->mHitOccludingItem && !testingPoint && !mBounds.Contains(aRect)) {
MOZ_ASSERT(aBuilder->HitTestIsForVisibility());
// We're hit-testing a rect that's bigger than our child bounds, but
// resultingRect is clipped by our bounds (in ProjectRectBounds above), so
// we can't stop hit-testing altogether.
//
// FIXME(emilio): I think this means that theoretically we might include
// some frames fully behind other transformed-but-opaque frames? Then again
// that's our pre-existing behavior for other untransformed content that
// doesn't fill the whole rect. To be fully correct I think we'd need proper
// "known occluded region" tracking, but that might be overkill for our
// purposes here.
aState->mHitOccludingItem = oldHitOccludingItem;
}
#ifdef DEBUG_HIT
if (originalFrameCount != aOutFrames.Length())
printf(" Hit! Time: %f, first frame: %p\n", static_cast<double>(clock()),
dynamic_cast<void*>(aOutFrames.ElementAt(0)));
printf("=== end of hit test ===\n");
#endif
}
float nsDisplayTransform::GetHitDepthAtPoint(nsDisplayListBuilder* aBuilder,
const nsPoint& aPoint) {
// GetTransform always operates in dev pixels.
float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
Matrix4x4 matrix = GetAccumulatedPreserved3DTransform(aBuilder);
NS_ASSERTION(IsFrameVisible(mFrame, matrix),
"We can't have hit a frame that isn't visible!");
Matrix4x4 inverse = matrix;
inverse.Invert();
// Compute the value z so that (aPoint.x, aPoint.y, z, 1) gets transformed by
// inverse to the z=0 plane. This is the same thing that
// Matrix4x4Typed::ProjectPoint does, but we are only interested in the z
// value, not the projected point, thus we extract the formula here, look
// there for how this equation is determined.
// https://searchfox.org/mozilla-central/rev/bd4d1cd1ca3037e6dc8d4081a4303824880b1b45/gfx/2d/Matrix.h#724
return -(NSAppUnitsToFloatPixels(aPoint.x, factor) * inverse._13 +
NSAppUnitsToFloatPixels(aPoint.y, factor) * inverse._23 +
inverse._43) /
inverse._33;
}
/* The transform is opaque iff the transform consists solely of scales and
* translations and if the underlying content is opaque. Thus if the transform
* is of the form
*
* |a c e|
* |b d f|
* |0 0 1|
*
* We need b and c to be zero.
*
* We also need to check whether the underlying opaque content completely fills
* our visible rect. We use UntransformRect which expands to the axis-aligned
* bounding rect, but that's OK since if
* mStoredList.GetVisibleRect().Contains(untransformedVisible), then it
* certainly contains the actual (non-axis-aligned) untransformed rect.
*/
nsRegion nsDisplayTransform::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
nsRect untransformedVisible;
if (!UntransformBuildingRect(aBuilder, &untransformedVisible)) {
return nsRegion();
}
const Matrix4x4Flagged& matrix = GetTransform();
Matrix matrix2d;
if (!matrix.Is2D(&matrix2d) || !matrix2d.PreservesAxisAlignedRectangles()) {
return nsRegion();
}
nsRegion result;
const nsRect bounds = GetUntransformedBounds(aBuilder);
const nsRegion opaque =
::mozilla::GetOpaqueRegion(aBuilder, GetChildren(), bounds);
if (opaque.Contains(untransformedVisible)) {
bool tmpSnap;
result = GetBuildingRect().Intersect(GetBounds(aBuilder, &tmpSnap));
}
return result;
}
nsRect nsDisplayTransform::GetComponentAlphaBounds(
nsDisplayListBuilder* aBuilder) const {
if (GetChildren()->GetComponentAlphaBounds(aBuilder).IsEmpty()) {
return nsRect();
}
bool snap;
return GetBounds(aBuilder, &snap);
}
/* TransformRect takes in as parameters a rectangle (in app space) and returns
* the smallest rectangle (in app space) containing the transformed image of
* that rectangle. That is, it takes the four corners of the rectangle,
* transforms them according to the matrix associated with the specified frame,
* then returns the smallest rectangle containing the four transformed points.
*
* @param aUntransformedBounds The rectangle (in app units) to transform.
* @param aFrame The frame whose transformation should be applied.
* @param aOrigin The delta from the frame origin to the coordinate space origin
* @return The smallest rectangle containing the image of the transformed
* rectangle.
*/
nsRect nsDisplayTransform::TransformRect(const nsRect& aUntransformedBounds,
const nsIFrame* aFrame,
TransformReferenceBox& aRefBox) {
MOZ_ASSERT(aFrame, "Can't take the transform based on a null frame!");
float factor = aFrame->PresContext()->AppUnitsPerDevPixel();
FrameTransformProperties props(aFrame, aRefBox, factor);
return nsLayoutUtils::MatrixTransformRect(
aUntransformedBounds,
GetResultingTransformMatrixInternal(
props, aRefBox, nsPoint(), factor,
kTransformRectFlags & ~OFFSET_BY_ORIGIN),
factor);
}
bool nsDisplayTransform::UntransformRect(const nsRect& aTransformedBounds,
const nsRect& aChildBounds,
const nsIFrame* aFrame,
nsRect* aOutRect) {
MOZ_ASSERT(aFrame, "Can't take the transform based on a null frame!");
float factor = aFrame->PresContext()->AppUnitsPerDevPixel();
Matrix4x4 transform = GetResultingTransformMatrix(
aFrame, nsPoint(), factor, kTransformRectFlags & ~OFFSET_BY_ORIGIN);
return UntransformRect(aTransformedBounds, aChildBounds, transform, factor,
aOutRect);
}
bool nsDisplayTransform::UntransformRect(const nsRect& aTransformedBounds,
const nsRect& aChildBounds,
const Matrix4x4& aMatrix,
float aAppUnitsPerPixel,
nsRect* aOutRect) {
Maybe<Matrix4x4> inverse = aMatrix.MaybeInverse();
if (inverse.isNothing()) {
return false;
}
RectDouble result(
NSAppUnitsToFloatPixels(aTransformedBounds.x, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(aTransformedBounds.y, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(aTransformedBounds.width, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(aTransformedBounds.height, aAppUnitsPerPixel));
RectDouble childGfxBounds(
NSAppUnitsToFloatPixels(aChildBounds.x, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(aChildBounds.y, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(aChildBounds.width, aAppUnitsPerPixel),
NSAppUnitsToFloatPixels(aChildBounds.height, aAppUnitsPerPixel));
result = inverse->ProjectRectBounds(result, childGfxBounds);
*aOutRect = nsLayoutUtils::RoundGfxRectToAppRect(result, aAppUnitsPerPixel);
return true;
}
bool nsDisplayTransform::UntransformRect(nsDisplayListBuilder* aBuilder,
const nsRect& aRect,
nsRect* aOutRect) const {
if (GetTransform().IsSingular()) {
return false;
}
// GetTransform always operates in dev pixels.
float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
RectDouble result(NSAppUnitsToFloatPixels(aRect.x, factor),
NSAppUnitsToFloatPixels(aRect.y, factor),
NSAppUnitsToFloatPixels(aRect.width, factor),
NSAppUnitsToFloatPixels(aRect.height, factor));
nsRect childBounds = GetUntransformedBounds(aBuilder);
RectDouble childGfxBounds(
NSAppUnitsToFloatPixels(childBounds.x, factor),
NSAppUnitsToFloatPixels(childBounds.y, factor),
NSAppUnitsToFloatPixels(childBounds.width, factor),
NSAppUnitsToFloatPixels(childBounds.height, factor));
/* We want to untransform the matrix, so invert the transformation first! */
result = GetInverseTransform().ProjectRectBounds(result, childGfxBounds);
*aOutRect = nsLayoutUtils::RoundGfxRectToAppRect(result, factor);
return true;
}
void nsDisplayTransform::WriteDebugInfo(std::stringstream& aStream) {
aStream << GetTransform().GetMatrix();
if (IsTransformSeparator()) {
aStream << " transform-separator";
}
if (IsLeafOf3DContext()) {
aStream << " 3d-context-leaf";
}
if (mFrame->Extend3DContext()) {
aStream << " extends-3d-context";
}
if (mFrame->Combines3DTransformWithAncestors()) {
aStream << " combines-3d-with-ancestors";
}
aStream << " prerender(";
switch (mPrerenderDecision) {
case PrerenderDecision::No:
aStream << "no";
break;
case PrerenderDecision::Partial:
aStream << "partial";
break;
case PrerenderDecision::Full:
aStream << "full";
break;
}
aStream << ")";
aStream << " childrenBuildingRect" << mChildrenBuildingRect;
}
nsDisplayPerspective::nsDisplayPerspective(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
nsDisplayList* aList)
: nsPaintedDisplayItem(aBuilder, aFrame), mList(aBuilder) {
mList.AppendToTop(aList);
MOZ_ASSERT(mList.Length() == 1);
MOZ_ASSERT(mList.GetTop()->GetType() == DisplayItemType::TYPE_TRANSFORM);
}
void nsDisplayPerspective::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
// Just directly recurse into children, since we'll include the persepctive
// value in any nsDisplayTransform children.
GetChildren()->Paint(aBuilder, aCtx,
mFrame->PresContext()->AppUnitsPerDevPixel());
}
nsRegion nsDisplayPerspective::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
if (!GetChildren()->GetTop()) {
*aSnap = false;
return nsRegion();
}
return GetChildren()->GetTop()->GetOpaqueRegion(aBuilder, aSnap);
}
bool nsDisplayPerspective::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
float appUnitsPerPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
Matrix4x4 perspectiveMatrix;
DebugOnly<bool> hasPerspective = nsDisplayTransform::ComputePerspectiveMatrix(
mFrame, appUnitsPerPixel, perspectiveMatrix);
MOZ_ASSERT(hasPerspective, "Why did we create nsDisplayPerspective?");
/*
* ClipListToRange can remove our child after we were created.
*/
if (!GetChildren()->GetTop()) {
return false;
}
/*
* The resulting matrix is still in the coordinate space of the transformed
* frame. Append a translation to the reference frame coordinates.
*/
nsDisplayTransform* transform =
static_cast<nsDisplayTransform*>(GetChildren()->GetTop());
Point3D newOrigin =
Point3D(NSAppUnitsToFloatPixels(transform->ToReferenceFrame().x,
appUnitsPerPixel),
NSAppUnitsToFloatPixels(transform->ToReferenceFrame().y,
appUnitsPerPixel),
0.0f);
Point3D roundedOrigin(NS_round(newOrigin.x), NS_round(newOrigin.y), 0);
perspectiveMatrix.PostTranslate(roundedOrigin);
nsIFrame* perspectiveFrame =
mFrame->GetClosestFlattenedTreeAncestorPrimaryFrame();
// Passing true here is always correct, since perspective always combines
// transforms with the descendants. However that'd make WR do a lot of work
// that it doesn't really need to do if there aren't other transforms forming
// part of the 3D context.
//
// WR knows how to treat perspective in that case, so the only thing we need
// to do is to ensure we pass true when we're involved in a 3d context in any
// other way via the transform-style property on either the transformed frame
// or the perspective frame in order to not confuse WR's preserve-3d code in
// very awful ways.
bool preserve3D =
mFrame->Extend3DContext() || perspectiveFrame->Extend3DContext();
wr::StackingContextParams params;
wr::WrTransformInfo transform_info;
transform_info.transform = wr::ToLayoutTransform(perspectiveMatrix);
transform_info.key = wr::SpatialKey(uint64_t(mFrame), GetPerFrameKey(),
wr::SpatialKeyKind::Perspective);
params.mTransformPtr = &transform_info;
params.reference_frame_kind = wr::WrReferenceFrameKind::Perspective;
params.prim_flags = !BackfaceIsHidden()
? wr::PrimitiveFlags::IS_BACKFACE_VISIBLE
: wr::PrimitiveFlags{0};
params.SetPreserve3D(preserve3D);
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
Maybe<uint64_t> scrollingRelativeTo;
for (const auto* asr = GetActiveScrolledRoot(); asr; asr = asr->mParent) {
// In OOP documents, the root scrollable frame of the in-process root
// document is always active, so using IsAncestorFrameCrossDocInProcess
// should be fine here.
if (ScrollContainerFrame* scrollFrame = asr->ScrollFrameOrNull()) {
if (nsLayoutUtils::IsAncestorFrameCrossDocInProcess(
scrollFrame->GetScrolledFrame(), perspectiveFrame)) {
scrollingRelativeTo.emplace(asr->GetViewId());
break;
}
}
}
// We put the perspective reference frame wrapping the transformed frame,
// even though there may be arbitrarily nested scroll frames in between.
//
// We need to know how many ancestor scroll-frames are we nested in, in order
// for the async scrolling code in WebRender to calculate the right
// transformation for the perspective contents.
params.scrolling_relative_to = scrollingRelativeTo.ptrOr(nullptr);
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params);
aManager->CommandBuilder().CreateWebRenderCommandsFromDisplayList(
GetChildren(), this, aDisplayListBuilder, sc, aBuilder, aResources);
return true;
}
nsDisplayText::nsDisplayText(nsDisplayListBuilder* aBuilder,
nsTextFrame* aFrame)
: nsPaintedDisplayItem(aBuilder, aFrame),
mVisIStartEdge(0),
mVisIEndEdge(0) {
MOZ_COUNT_CTOR(nsDisplayText);
mBounds = mFrame->InkOverflowRectRelativeToSelf() + ToReferenceFrame();
// Bug 748228
mBounds.Inflate(mFrame->PresContext()->AppUnitsPerDevPixel());
mVisibleRect = aBuilder->GetVisibleRect() +
aBuilder->GetCurrentFrameOffsetToReferenceFrame();
}
bool nsDisplayText::CanApplyOpacity(WebRenderLayerManager* aManager,
nsDisplayListBuilder* aBuilder) const {
auto* f = static_cast<nsTextFrame*>(mFrame);
if (f->IsSelected()) {
return false;
}
const nsStyleText* textStyle = f->StyleText();
if (textStyle->HasTextShadow()) {
return false;
}
nsTextFrame::TextDecorations decorations;
f->GetTextDecorations(f->PresContext(), nsTextFrame::eResolvedColors,
decorations);
return !decorations.HasDecorationLines();
}
void nsDisplayText::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
AUTO_PROFILER_LABEL("nsDisplayText::Paint", GRAPHICS);
// We don't pass mVisibleRect here, since this can be called from within
// the WebRender fallback painting path, and we don't want to issue
// recorded commands that are dependent on the visible/building rect.
RenderToContext(aCtx, aBuilder, GetPaintRect(aBuilder, aCtx));
auto* textFrame = static_cast<nsTextFrame*>(mFrame);
LCPTextFrameHelper::MaybeUnionTextFrame(textFrame,
mBounds - ToReferenceFrame());
}
bool nsDisplayText::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
auto* f = static_cast<nsTextFrame*>(mFrame);
auto appUnitsPerDevPixel = f->PresContext()->AppUnitsPerDevPixel();
nsRect bounds = f->WebRenderBounds() + ToReferenceFrame();
// Bug 748228
bounds.Inflate(appUnitsPerDevPixel);
if (bounds.IsEmpty()) {
return true;
}
// For large font sizes, punt to a blob image, to avoid the blurry rendering
// that results from WR clamping the glyph size used for rasterization.
//
// (See FONT_SIZE_LIMIT in webrender/src/glyph_rasterizer/mod.rs.)
//
// This is not strictly accurate, as final used font sizes might not be the
// same as claimed by the fontGroup's style.size (eg: due to font-size-adjust
// altering the used size of the font actually used).
// It also fails to consider how transforms might affect the device-font-size
// that webrender uses (and clamps).
// But it should be near enough for practical purposes; the limitations just
// mean we might sometimes end up with webrender still applying some bitmap
// scaling, or bail out when we didn't really need to.
constexpr float kWebRenderFontSizeLimit = 320.0;
f->EnsureTextRun(nsTextFrame::eInflated);
gfxTextRun* textRun = f->GetTextRun(nsTextFrame::eInflated);
if (textRun &&
textRun->GetFontGroup()->GetStyle()->size > kWebRenderFontSizeLimit) {
return false;
}
gfx::Point deviceOffset =
LayoutDevicePoint::FromAppUnits(bounds.TopLeft(), appUnitsPerDevPixel)
.ToUnknownPoint();
// Clipping the bounds to the PaintRect (factoring in what's covered by parent
// frames) lets us early reject a bunch of things.
nsRect visible = mVisibleRect;
// Add the "source rect" area from which the given shadows could intersect
// with mVisibleRect, and which therefore needs to included in the paint
// operation, to the `visible` rect that we will use to limit the bounds of
// what we send to the renderer.
auto addShadowSourceToVisible = [&](Span<const StyleSimpleShadow> aShadows) {
for (const auto& shadow : aShadows) {
nsRect sourceRect = mVisibleRect;
// Negate the offsets, because we're looking for the "source" rect that
// could cast a shadow into the visible rect, rather than a "target" area
// onto which the visible rect would cast a shadow.
sourceRect.MoveBy(-shadow.horizontal.ToAppUnits(),
-shadow.vertical.ToAppUnits());
// Inflate to account for the shadow blur.
sourceRect.Inflate(nsContextBoxBlur::GetBlurRadiusMargin(
shadow.blur.ToAppUnits(), appUnitsPerDevPixel));
visible.OrWith(sourceRect);
}
};
// Shadows can translate things back into view, so we enlarge the notional
// "visible" rect to ensure we don't skip painting relevant parts that might
// cast a shadow within the visible area.
addShadowSourceToVisible(f->StyleText()->mTextShadow.AsSpan());
// Similarly for shadows that may be cast by ::selection.
if (f->IsSelected()) {
nsTextPaintStyle textPaint(f);
Span<const StyleSimpleShadow> shadows;
f->GetSelectionTextShadow(SelectionType::eNormal, textPaint, &shadows);
addShadowSourceToVisible(shadows);
}
// Inflate a little extra to allow for potential antialiasing "blur".
visible.Inflate(3 * appUnitsPerDevPixel);
bounds = bounds.Intersect(visible);
gfxContext* textDrawer = aBuilder.GetTextContext(aResources, aSc, aManager,
this, bounds, deviceOffset);
LCPTextFrameHelper::MaybeUnionTextFrame(f, bounds - ToReferenceFrame());
aBuilder.StartGroup(this);
RenderToContext(textDrawer, aDisplayListBuilder, mVisibleRect,
aBuilder.GetInheritedOpacity(), true);
const bool result = textDrawer->GetTextDrawer()->Finish();
if (result) {
aBuilder.FinishGroup();
} else {
aBuilder.CancelGroup(true);
}
return result;
}
void nsDisplayText::RenderToContext(gfxContext* aCtx,
nsDisplayListBuilder* aBuilder,
const nsRect& aVisibleRect, float aOpacity,
bool aIsRecording) {
nsTextFrame* f = static_cast<nsTextFrame*>(mFrame);
// Add 1 pixel of dirty area around mVisibleRect to allow us to paint
// antialiased pixels beyond the measured text extents.
// This is temporary until we do this in the actual calculation of text
// extents.
auto A2D = mFrame->PresContext()->AppUnitsPerDevPixel();
LayoutDeviceRect extraVisible =
LayoutDeviceRect::FromAppUnits(aVisibleRect, A2D);
extraVisible.Inflate(1);
gfxRect pixelVisible(extraVisible.x, extraVisible.y, extraVisible.width,
extraVisible.height);
pixelVisible.Inflate(2);
pixelVisible.RoundOut();
gfxClipAutoSaveRestore autoSaveClip(aCtx);
if (!aBuilder->IsForGenerateGlyphMask() && !aIsRecording) {
autoSaveClip.Clip(pixelVisible);
}
NS_ASSERTION(mVisIStartEdge >= 0, "illegal start edge");
NS_ASSERTION(mVisIEndEdge >= 0, "illegal end edge");
gfxContextMatrixAutoSaveRestore matrixSR;
nsPoint framePt = ToReferenceFrame();
if (f->Style()->IsTextCombined()) {
auto [offset, scale] = f->GetTextCombineOffsetAndScale();
gfxTextRun* textRun = f->GetTextRun(nsTextFrame::eInflated);
bool rtl = textRun && textRun->IsRightToLeft();
if (rtl) {
framePt.x -= offset;
} else {
framePt.x += offset;
}
if (scale != 1.0f) {
if (auto* textDrawer = aCtx->GetTextDrawer()) {
// WebRender doesn't support scaling text like this yet
textDrawer->FoundUnsupportedFeature();
return;
}
matrixSR.SetContext(aCtx);
// Setup matrix to compress text for text-combine-upright if
// necessary. This is done here because we want selection be
// compressed at the same time as text.
gfxPoint pt = nsLayoutUtils::PointToGfxPoint(framePt, A2D);
if (rtl) {
pt.x += gfxFloat(f->GetSize().width) / A2D;
}
gfxMatrix mat = aCtx->CurrentMatrixDouble()
.PreTranslate(pt)
.PreScale(scale, 1.0)
.PreTranslate(-pt);
aCtx->SetMatrixDouble(mat);
}
}
nsTextFrame::PaintTextParams params(aCtx);
params.framePt = gfx::Point(framePt.x, framePt.y);
params.dirtyRect = extraVisible;
if (aBuilder->IsForGenerateGlyphMask()) {
params.state = nsTextFrame::PaintTextParams::GenerateTextMask;
} else {
params.state = nsTextFrame::PaintTextParams::PaintText;
}
f->PaintText(params, mVisIStartEdge, mVisIEndEdge, ToReferenceFrame(),
f->IsSelected(), aOpacity);
}
// This could go to nsDisplayListInvalidation.h, but
// |nsTextFrame::TextDecorations| requires including of nsTextFrame.h which
// would produce circular dependencies.
class nsDisplayTextGeometry : public nsDisplayItemGenericGeometry {
public:
nsDisplayTextGeometry(nsDisplayText* aItem, nsDisplayListBuilder* aBuilder)
: nsDisplayItemGenericGeometry(aItem, aBuilder),
mVisIStartEdge(aItem->VisIStartEdge()),
mVisIEndEdge(aItem->VisIEndEdge()) {
nsTextFrame* f = static_cast<nsTextFrame*>(aItem->Frame());
f->GetTextDecorations(f->PresContext(), nsTextFrame::eResolvedColors,
mDecorations);
}
/**
* We store the computed text decorations here since they are
* computed using style data from parent frames. Any changes to these
* styles will only invalidate the parent frame and not this frame.
*/
nsTextFrame::TextDecorations mDecorations;
nscoord mVisIStartEdge;
nscoord mVisIEndEdge;
};
nsDisplayItemGeometry* nsDisplayText::AllocateGeometry(
nsDisplayListBuilder* aBuilder) {
return new nsDisplayTextGeometry(this, aBuilder);
}
void nsDisplayText::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
const nsDisplayTextGeometry* geometry =
static_cast<const nsDisplayTextGeometry*>(aGeometry);
nsTextFrame* f = static_cast<nsTextFrame*>(mFrame);
nsTextFrame::TextDecorations decorations;
f->GetTextDecorations(f->PresContext(), nsTextFrame::eResolvedColors,
decorations);
bool snap;
const nsRect& newRect = geometry->mBounds;
nsRect oldRect = GetBounds(aBuilder, &snap);
if (decorations != geometry->mDecorations ||
mVisIStartEdge != geometry->mVisIStartEdge ||
mVisIEndEdge != geometry->mVisIEndEdge ||
!oldRect.IsEqualInterior(newRect) ||
!geometry->mBorderRect.IsEqualInterior(GetBorderRect())) {
aInvalidRegion->Or(oldRect, newRect);
}
}
void nsDisplayText::WriteDebugInfo(std::stringstream& aStream) {
#ifdef DEBUG
aStream << " (\"";
nsTextFrame* f = static_cast<nsTextFrame*>(mFrame);
nsCString buf;
f->ToCString(buf);
aStream << buf.get() << "\")";
#endif
}
nsDisplayEffectsBase::nsDisplayEffectsBase(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, bool aClearClipChain)
: nsDisplayWrapList(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType, aClearClipChain) {
MOZ_COUNT_CTOR(nsDisplayEffectsBase);
}
nsDisplayEffectsBase::nsDisplayEffectsBase(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
nsDisplayList* aList)
: nsDisplayWrapList(aBuilder, aFrame, aList) {
MOZ_COUNT_CTOR(nsDisplayEffectsBase);
}
nsRegion nsDisplayEffectsBase::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
*aSnap = false;
return nsRegion();
}
void nsDisplayEffectsBase::HitTest(nsDisplayListBuilder* aBuilder,
const nsRect& aRect, HitTestState* aState,
nsTArray<nsIFrame*>* aOutFrames) {
nsPoint rectCenter(aRect.x + aRect.width / 2, aRect.y + aRect.height / 2);
if (SVGIntegrationUtils::HitTestFrameForEffects(
mFrame, rectCenter - ToReferenceFrame())) {
mList.HitTest(aBuilder, aRect, aState, aOutFrames);
}
}
gfxRect nsDisplayEffectsBase::BBoxInUserSpace() const {
return SVGUtils::GetBBox(mFrame);
}
gfxPoint nsDisplayEffectsBase::UserSpaceOffset() const {
return SVGUtils::FrameSpaceInCSSPxToUserSpaceOffset(mFrame);
}
void nsDisplayEffectsBase::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
const auto* geometry =
static_cast<const nsDisplaySVGEffectGeometry*>(aGeometry);
bool snap;
nsRect bounds = GetBounds(aBuilder, &snap);
if (geometry->mFrameOffsetToReferenceFrame != ToReferenceFrame() ||
geometry->mUserSpaceOffset != UserSpaceOffset() ||
!geometry->mBBox.IsEqualInterior(BBoxInUserSpace())) {
// Filter and mask output can depend on the location of the frame's user
// space and on the frame's BBox. We need to invalidate if either of these
// change relative to the reference frame.
// Invalidations from our inactive layer manager are not enough to catch
// some of these cases because filters can produce output even if there's
// nothing in the filter input.
aInvalidRegion->Or(bounds, geometry->mBounds);
}
}
bool nsDisplayEffectsBase::ValidateSVGFrame() {
if (mFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT)) {
ISVGDisplayableFrame* svgFrame = do_QueryFrame(mFrame);
if (!svgFrame) {
return false;
}
if (auto* svgElement = SVGElement::FromNode(mFrame->GetContent())) {
// The SVG spec says only to draw filters if the element
// has valid dimensions.
return svgElement->HasValidDimensions();
}
return false;
}
return true;
}
using PaintFramesParams = SVGIntegrationUtils::PaintFramesParams;
static void ComputeMaskGeometry(PaintFramesParams& aParams) {
// Properties are added lazily and may have been removed by a restyle, so
// make sure all applicable ones are set again.
nsIFrame* firstFrame =
nsLayoutUtils::FirstContinuationOrIBSplitSibling(aParams.frame);
const nsStyleSVGReset* svgReset = firstFrame->StyleSVGReset();
nsTArray<SVGMaskFrame*> maskFrames;
// XXX check return value?
SVGObserverUtils::GetAndObserveMasks(firstFrame, &maskFrames);
if (maskFrames.Length() == 0) {
return;
}
gfxContext& ctx = aParams.ctx;
nsIFrame* frame = aParams.frame;
nsPoint offsetToUserSpace =
nsLayoutUtils::ComputeOffsetToUserSpace(aParams.builder, aParams.frame);
auto cssToDevScale = frame->PresContext()->CSSToDevPixelScale();
int32_t appUnitsPerDevPixel = frame->PresContext()->AppUnitsPerDevPixel();
gfxPoint devPixelOffsetToUserSpace =
nsLayoutUtils::PointToGfxPoint(offsetToUserSpace, appUnitsPerDevPixel);
gfxContextMatrixAutoSaveRestore matSR(&ctx);
ctx.SetMatrixDouble(
ctx.CurrentMatrixDouble().PreTranslate(devPixelOffsetToUserSpace));
// Convert boaderArea and dirtyRect to user space.
nsRect userSpaceBorderArea = aParams.borderArea - offsetToUserSpace;
nsRect userSpaceDirtyRect = aParams.dirtyRect - offsetToUserSpace;
// Union all mask layer rectangles in user space.
LayoutDeviceRect maskInUserSpace;
for (size_t i = 0; i < maskFrames.Length(); i++) {
SVGMaskFrame* maskFrame = maskFrames[i];
LayoutDeviceRect currentMaskSurfaceRect;
if (maskFrame) {
auto rect = maskFrame->GetMaskArea(aParams.frame);
currentMaskSurfaceRect =
CSSRect::FromUnknownRect(ToRect(rect)) * cssToDevScale;
} else {
nsCSSRendering::ImageLayerClipState clipState;
nsCSSRendering::GetImageLayerClip(
svgReset->mMask.mLayers[i], frame, *frame->StyleBorder(),
userSpaceBorderArea, userSpaceDirtyRect,
/* aWillPaintBorder = */ false, appUnitsPerDevPixel, &clipState);
currentMaskSurfaceRect = LayoutDeviceRect::FromUnknownRect(
ToRect(clipState.mDirtyRectInDevPx));
}
maskInUserSpace = maskInUserSpace.Union(currentMaskSurfaceRect);
}
if (!maskInUserSpace.IsEmpty()) {
aParams.maskRect = Some(maskInUserSpace);
} else {
aParams.maskRect = Nothing();
}
}
nsDisplayMasksAndClipPaths::nsDisplayMasksAndClipPaths(
nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aActiveScrolledRoot,
ContainerASRType aContainerASRType, bool aWrapsBackdropFilter,
bool aForceIsolation)
: nsDisplayEffectsBase(aBuilder, aFrame, aList, aActiveScrolledRoot,
aContainerASRType, /* aClearClipChain = */ true),
mWrapsBackdropFilter(aWrapsBackdropFilter),
mForceIsolation(aForceIsolation) {
MOZ_COUNT_CTOR(nsDisplayMasksAndClipPaths);
nsPresContext* presContext = mFrame->PresContext();
uint32_t flags =
aBuilder->GetBackgroundPaintFlags() | nsCSSRendering::PAINTBG_MASK_IMAGE;
const nsStyleSVGReset* svgReset = aFrame->StyleSVGReset();
NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, svgReset->mMask) {
const auto& layer = svgReset->mMask.mLayers[i];
if (!layer.mImage.IsResolved()) {
continue;
}
const nsRect& borderArea = mFrame->GetRectRelativeToSelf();
// NOTE(emilio): We only care about the dest rect so we don't bother
// computing a clip.
bool isTransformedFixed = false;
nsBackgroundLayerState state = nsCSSRendering::PrepareImageLayer(
presContext, aFrame, flags, borderArea, borderArea, layer,
&isTransformedFixed);
mDestRects.AppendElement(state.mDestArea);
}
}
static bool CanMergeDisplayMaskFrame(nsIFrame* aFrame) {
// Do not merge items for box-decoration-break:clone elements,
// since each box should have its own mask in that case.
if (aFrame->StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone) {
return false;
}
// Do not merge if either frame has a mask. Continuation frames should apply
// the mask independently (just like nsDisplayBackgroundImage).
if (aFrame->StyleSVGReset()->HasMask()) {
return false;
}
return true;
}
bool nsDisplayMasksAndClipPaths::CanMerge(const nsDisplayItem* aItem) const {
// Items for the same content element should be merged into a single
// compositing group.
if (!HasDifferentFrame(aItem) || !HasSameTypeAndClip(aItem) ||
!HasSameContent(aItem)) {
return false;
}
return CanMergeDisplayMaskFrame(mFrame) &&
CanMergeDisplayMaskFrame(aItem->Frame());
}
bool nsDisplayMasksAndClipPaths::IsValidMask() {
if (!ValidateSVGFrame()) {
return false;
}
return SVGUtils::DetermineMaskUsage(mFrame, false).UsingMaskOrClipPath();
}
bool nsDisplayMasksAndClipPaths::PaintMask(nsDisplayListBuilder* aBuilder,
gfxContext* aMaskContext,
bool aHandleOpacity,
bool* aMaskPainted) {
MOZ_ASSERT(aMaskContext->GetDrawTarget()->GetFormat() == SurfaceFormat::A8);
imgDrawingParams imgParams(aBuilder->GetImageDecodeFlags());
nsRect borderArea = nsRect(ToReferenceFrame(), mFrame->GetSize());
PaintFramesParams params(*aMaskContext, mFrame, mBounds, borderArea, aBuilder,
aHandleOpacity, imgParams);
ComputeMaskGeometry(params);
bool maskIsComplete = false;
bool painted = SVGIntegrationUtils::PaintMask(params, maskIsComplete);
if (aMaskPainted) {
*aMaskPainted = painted;
}
return maskIsComplete &&
(imgParams.result == ImgDrawResult::SUCCESS ||
imgParams.result == ImgDrawResult::SUCCESS_NOT_COMPLETE ||
imgParams.result == ImgDrawResult::WRONG_SIZE);
}
void nsDisplayMasksAndClipPaths::ComputeInvalidationRegion(
nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
nsRegion* aInvalidRegion) const {
nsDisplayEffectsBase::ComputeInvalidationRegion(aBuilder, aGeometry,
aInvalidRegion);
const auto* geometry =
static_cast<const nsDisplayMasksAndClipPathsGeometry*>(aGeometry);
bool snap;
nsRect bounds = GetBounds(aBuilder, &snap);
if (mDestRects.Length() != geometry->mDestRects.Length()) {
aInvalidRegion->Or(bounds, geometry->mBounds);
} else {
for (size_t i = 0; i < mDestRects.Length(); i++) {
if (!mDestRects[i].IsEqualInterior(geometry->mDestRects[i])) {
aInvalidRegion->Or(bounds, geometry->mBounds);
break;
}
}
}
}
void nsDisplayMasksAndClipPaths::PaintWithContentsPaintCallback(
nsDisplayListBuilder* aBuilder, gfxContext* aCtx,
const std::function<void()>& aPaintChildren) {
// Clip the drawing target by mVisibleRect, which contains the visible
// region of the target frame and its out-of-flow and inflow descendants.
Rect bounds = NSRectToRect(GetPaintRect(aBuilder, aCtx),
mFrame->PresContext()->AppUnitsPerDevPixel());
bounds.RoundOut();
gfxClipAutoSaveRestore autoSaveClip(aCtx);
autoSaveClip.Clip(bounds);
imgDrawingParams imgParams(aBuilder->GetImageDecodeFlags());
nsRect borderArea = nsRect(ToReferenceFrame(), mFrame->GetSize());
PaintFramesParams params(*aCtx, mFrame, GetPaintRect(aBuilder, aCtx),
borderArea, aBuilder, false, imgParams);
ComputeMaskGeometry(params);
SVGIntegrationUtils::PaintMaskAndClipPath(params, aPaintChildren);
}
void nsDisplayMasksAndClipPaths::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
if (!IsValidMask()) {
return;
}
PaintWithContentsPaintCallback(aBuilder, aCtx, [&] {
GetChildren()->Paint(aBuilder, aCtx,
mFrame->PresContext()->AppUnitsPerDevPixel());
});
}
static Maybe<wr::WrClipChainId> CreateSimpleClipRegion(
const nsDisplayMasksAndClipPaths& aDisplayItem,
wr::DisplayListBuilder& aBuilder) {
nsIFrame* frame = aDisplayItem.Frame();
const auto* style = frame->StyleSVGReset();
MOZ_ASSERT(style->HasClipPath() || style->HasMask());
if (!SVGUtils::DetermineMaskUsage(frame, false).IsSimpleClipShape()) {
return Nothing();
}
const auto& clipPath = style->mClipPath;
const auto& shape = *clipPath.AsShape()._0;
auto appUnitsPerDevPixel = frame->PresContext()->AppUnitsPerDevPixel();
const nsRect refBox =
nsLayoutUtils::ComputeClipPathGeometryBox(frame, clipPath.AsShape()._1);
wr::WrClipId clipId{};
switch (shape.tag) {
case StyleBasicShape::Tag::Rect: {
const nsRect rect =
ShapeUtils::ComputeInsetRect(shape.AsRect().rect, refBox) +
aDisplayItem.ToReferenceFrame();
nsRectCornerRadii radii;
if (ShapeUtils::ComputeRectRadii(shape.AsRect().round, refBox, rect,
radii)) {
clipId = aBuilder.DefineRoundedRectClip(
Nothing(),
wr::ToComplexClipRegion(rect, radii, appUnitsPerDevPixel));
} else {
clipId = aBuilder.DefineRectClip(
Nothing(), wr::ToLayoutRect(LayoutDeviceRect::FromAppUnits(
rect, appUnitsPerDevPixel)));
}
break;
}
case StyleBasicShape::Tag::Ellipse:
case StyleBasicShape::Tag::Circle: {
nsPoint center = ShapeUtils::ComputeCircleOrEllipseCenter(shape, refBox);
nsSize radii;
if (shape.IsEllipse()) {
radii = ShapeUtils::ComputeEllipseRadii(shape, center, refBox);
} else {
nscoord radius = ShapeUtils::ComputeCircleRadius(shape, center, refBox);
radii = {radius, radius};
}
nsRect ellipseRect(aDisplayItem.ToReferenceFrame() + center -
nsPoint(radii.width, radii.height),
radii * 2);
nsRectCornerRadii ellipseRadii;
for (const auto corner : AllPhysicalHalfCorners()) {
ellipseRadii[corner] =
HalfCornerIsX(corner) ? radii.width : radii.height;
}
clipId = aBuilder.DefineRoundedRectClip(
Nothing(), wr::ToComplexClipRegion(ellipseRect, ellipseRadii,
appUnitsPerDevPixel));
break;
}
default:
// Please don't add more exceptions, try to find a way to define the clip
// without using a mask image.
//
// And if you _really really_ need to add an exception, add it to
// SVGUtils::DetermineMaskUsage
MOZ_ASSERT_UNREACHABLE("Unhandled shape id?");
return Nothing();
}
wr::WrClipChainId clipChainId = aBuilder.DefineClipChain({clipId}, true);
return Some(clipChainId);
}
static void FillPolygonDataForDisplayItem(
const nsDisplayMasksAndClipPaths& aDisplayItem,
nsTArray<wr::LayoutPoint>& aPoints, wr::FillRule& aFillRule) {
nsIFrame* frame = aDisplayItem.Frame();
const auto* style = frame->StyleSVGReset();
bool isPolygon = style->HasClipPath() && style->mClipPath.IsShape() &&
style->mClipPath.AsShape()._0->IsPolygon();
if (!isPolygon) {
return;
}
const auto& clipPath = style->mClipPath;
const auto& shape = *clipPath.AsShape()._0;
const nsRect refBox =
nsLayoutUtils::ComputeClipPathGeometryBox(frame, clipPath.AsShape()._1);
// We only fill polygon data for polygons that are below a complexity
// limit.
nsTArray<nsPoint> vertices =
ShapeUtils::ComputePolygonVertices(shape, refBox);
if (vertices.Length() > wr::POLYGON_CLIP_VERTEX_MAX) {
return;
}
auto appUnitsPerDevPixel = frame->PresContext()->AppUnitsPerDevPixel();
for (size_t i = 0; i < vertices.Length(); ++i) {
wr::LayoutPoint point = wr::ToLayoutPoint(
LayoutDevicePoint::FromAppUnits(vertices[i], appUnitsPerDevPixel));
aPoints.AppendElement(point);
}
aFillRule = (shape.AsPolygon().fill == StyleFillRule::Nonzero)
? wr::FillRule::Nonzero
: wr::FillRule::Evenodd;
}
static Maybe<wr::WrClipChainId> CreateWRClipPathAndMasks(
nsDisplayMasksAndClipPaths* aDisplayItem, const LayoutDeviceRect& aBounds,
wr::IpcResourceUpdateQueue& aResources, wr::DisplayListBuilder& aBuilder,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
if (auto clip = CreateSimpleClipRegion(*aDisplayItem, aBuilder)) {
return clip;
}
Maybe<wr::ImageMask> mask = aManager->CommandBuilder().BuildWrMaskImage(
aDisplayItem, aBuilder, aResources, aSc, aDisplayListBuilder, aBounds);
if (!mask) {
return Nothing();
}
// We couldn't create a simple clip region, but before we create an image
// mask clip, see if we can get a polygon clip to add to it.
nsTArray<wr::LayoutPoint> points;
wr::FillRule fillRule = wr::FillRule::Nonzero;
FillPolygonDataForDisplayItem(*aDisplayItem, points, fillRule);
wr::WrClipId clipId =
aBuilder.DefineImageMaskClip(mask.ref(), points, fillRule);
wr::WrClipChainId clipChainId = aBuilder.DefineClipChain({clipId}, true);
return Some(clipChainId);
}
bool nsDisplayMasksAndClipPaths::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
bool snap;
auto appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
nsRect displayBounds = GetBounds(aDisplayListBuilder, &snap);
LayoutDeviceRect bounds =
LayoutDeviceRect::FromAppUnits(displayBounds, appUnitsPerDevPixel);
Maybe<wr::WrClipChainId> clip = CreateWRClipPathAndMasks(
this, bounds, aResources, aBuilder, aSc, aManager, aDisplayListBuilder);
float oldOpacity = aBuilder.GetInheritedOpacity();
Maybe<StackingContextHelper> layer;
const StackingContextHelper* sc = &aSc;
if (clip) {
// Create a new stacking context to attach the mask to, ensuring the mask is
// applied to the aggregate, and not the individual elements.
// The stacking context shouldn't have any offset.
bounds.MoveTo(0, 0);
Maybe<float> opacity =
(SVGUtils::DetermineMaskUsage(mFrame, false).IsSimpleClipShape() &&
aBuilder.GetInheritedOpacity() != 1.0f)
? Some(aBuilder.GetInheritedOpacity())
: Nothing();
wr::StackingContextParams params;
params.clip = wr::WrStackingContextClip::ClipChain(clip->id);
params.opacity = opacity.ptrOr(nullptr);
if (mForceIsolation) {
params.flags |= wr::StackingContextFlags::FORCED_ISOLATION;
}
if (mWrapsBackdropFilter) {
params.flags |= wr::StackingContextFlags::WRAPS_BACKDROP_FILTER;
}
layer.emplace(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder, params,
bounds);
sc = layer.ptr();
}
aBuilder.SetInheritedOpacity(1.0f);
const DisplayItemClipChain* oldClipChain = aBuilder.GetInheritedClipChain();
aBuilder.SetInheritedClipChain(nullptr);
CreateWebRenderCommandsNewClipListOption(aBuilder, aResources, *sc, aManager,
aDisplayListBuilder, layer.isSome());
aBuilder.SetInheritedOpacity(oldOpacity);
aBuilder.SetInheritedClipChain(oldClipChain);
return true;
}
Maybe<nsRect> nsDisplayMasksAndClipPaths::GetClipWithRespectToASR(
nsDisplayListBuilder* aBuilder, const ActiveScrolledRoot* aASR) const {
if (const DisplayItemClip* clip =
DisplayItemClipChain::ClipForASR(GetClipChain(), aASR)) {
return Some(clip->GetClipRect());
}
// This item does not have a clip with respect to |aASR|. However, we
// might still have finite bounds with respect to |aASR|. Check our
// children.
nsDisplayList* childList = GetSameCoordinateSystemChildren();
if (childList) {
return Some(childList->GetClippedBoundsWithRespectToASR(aBuilder, aASR));
}
#ifdef DEBUG
NS_ASSERTION(false, "item should have finite clip with respect to aASR");
#endif
return Nothing();
}
#ifdef MOZ_DUMP_PAINTING
void nsDisplayMasksAndClipPaths::PrintEffects(nsACString& aTo) {
nsIFrame* firstFrame =
nsLayoutUtils::FirstContinuationOrIBSplitSibling(mFrame);
bool first = true;
aTo += " effects=(";
SVGClipPathFrame* clipPathFrame;
// XXX Check return value?
SVGObserverUtils::GetAndObserveClipPath(firstFrame, &clipPathFrame);
if (clipPathFrame) {
if (!first) {
aTo += ", ";
}
aTo += nsPrintfCString(
"clip(%s)", clipPathFrame->IsTrivial() ? "trivial" : "non-trivial");
first = false;
} else if (mFrame->StyleSVGReset()->HasClipPath()) {
if (!first) {
aTo += ", ";
}
aTo += "clip(basic-shape)";
first = false;
}
nsTArray<SVGMaskFrame*> masks;
// XXX check return value?
SVGObserverUtils::GetAndObserveMasks(firstFrame, &masks);
if (!masks.IsEmpty() && masks[0]) {
if (!first) {
aTo += ", ";
}
aTo += "mask";
}
aTo += ")";
}
#endif
bool nsDisplayBackdropFilters::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
WrFiltersHolder wrFilters;
const ComputedStyle& style = mStyle ? *mStyle : *mFrame->Style();
auto filterChain = style.StyleEffects()->mBackdropFilters.AsSpan();
// Try building a CSS filter chain
WrFiltersStatus status = SVGIntegrationUtils::CreateWebRenderCSSFilters(
filterChain, mFrame, wrFilters);
if (status == WrFiltersStatus::BLOB_FALLBACK) {
// If the filters are too complex for CSS filters, try SVG filters
auto offsetForSVGFilters =
nsLayoutUtils::ComputeOffsetToUserSpace(aDisplayListBuilder, mFrame);
status = SVGIntegrationUtils::BuildWebRenderFilters(
mFrame, filterChain, StyleFilterType::BackdropFilter, wrFilters,
offsetForSVGFilters);
}
if (status == WrFiltersStatus::BLOB_FALLBACK) {
// TODO: If painting backdrop-filters on the content side is implemented,
// consider returning false to fall back to that.
wrFilters = {};
}
if (status == WrFiltersStatus::UNSUPPORTED) {
wrFilters = {};
}
nsCSSRendering::ImageLayerClipState clip;
nsCSSRendering::GetImageLayerClip(
style.StyleBackground()->BottomLayer(), mFrame, *style.StyleBorder(),
mBackdropRect, mBackdropRect, false,
mFrame->PresContext()->AppUnitsPerDevPixel(), &clip);
LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
mBackdropRect, mFrame->PresContext()->AppUnitsPerDevPixel());
wr::ComplexClipRegion region =
wr::ToComplexClipRegion(clip.mBGClipArea, clip.mRadii,
mFrame->PresContext()->AppUnitsPerDevPixel());
aBuilder.PushBackdropFilter(wr::ToLayoutRect(bounds), region,
wrFilters.filters, wrFilters.filter_datas,
!BackfaceIsHidden());
wr::StackingContextParams params;
params.clip =
wr::WrStackingContextClip::ClipChain(aBuilder.CurrentClipChainId());
params.flags = wr::StackingContextFlags::FORCED_ISOLATION;
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params);
nsDisplayWrapList::CreateWebRenderCommands(aBuilder, aResources, sc, aManager,
aDisplayListBuilder);
return true;
}
void nsDisplayBackdropFilters::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
// TODO: Implement backdrop filters
GetChildren()->Paint(aBuilder, aCtx,
mFrame->PresContext()->AppUnitsPerDevPixel());
}
nsRect nsDisplayBackdropFilters::GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) const {
nsRect childBounds = nsDisplayWrapList::GetBounds(aBuilder, aSnap);
*aSnap = false;
return mBackdropRect.Union(childBounds);
}
/* static */
nsDisplayFilters::nsDisplayFilters(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList,
nsIFrame* aStyleFrame,
bool aWrapsBackdropFilter)
: nsDisplayEffectsBase(aBuilder, aFrame, aList),
mStyle(aFrame == aStyleFrame ? nullptr : aStyleFrame->Style()),
mEffectsBounds(aFrame->InkOverflowRectRelativeToSelf()),
mWrapsBackdropFilter(aWrapsBackdropFilter) {
MOZ_COUNT_CTOR(nsDisplayFilters);
mVisibleRect = aBuilder->GetVisibleRect() +
aBuilder->GetCurrentFrameOffsetToReferenceFrame();
}
void nsDisplayFilters::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
PaintWithContentsPaintCallback(aBuilder, aCtx, [&](gfxContext* aContext) {
GetChildren()->Paint(aBuilder, aContext,
mFrame->PresContext()->AppUnitsPerDevPixel());
});
}
void nsDisplayFilters::PaintWithContentsPaintCallback(
nsDisplayListBuilder* aBuilder, gfxContext* aCtx,
const std::function<void(gfxContext* aContext)>& aPaintChildren) {
imgDrawingParams imgParams(aBuilder->GetImageDecodeFlags());
nsRect borderArea = nsRect(ToReferenceFrame(), mFrame->GetSize());
PaintFramesParams params(*aCtx, mFrame, mVisibleRect, borderArea, aBuilder,
false, imgParams);
gfxPoint userSpaceToFrameSpaceOffset =
SVGIntegrationUtils::GetOffsetToUserSpaceInDevPx(mFrame, params);
auto filterChain = mStyle ? mStyle->StyleEffects()->mFilters.AsSpan()
: mFrame->StyleEffects()->mFilters.AsSpan();
SVGIntegrationUtils::PaintFilter(
params, filterChain,
[&](gfxContext& aContext, imgDrawingParams&, const gfxMatrix*,
const nsIntRect*) {
gfxContextMatrixAutoSaveRestore autoSR(&aContext);
aContext.SetMatrixDouble(aContext.CurrentMatrixDouble().PreTranslate(
-userSpaceToFrameSpaceOffset));
aPaintChildren(&aContext);
});
}
bool nsDisplayFilters::CanCreateWebRenderCommands() const {
return SVGIntegrationUtils::CanCreateWebRenderFiltersForFrame(mFrame);
}
bool nsDisplayFilters::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
WrFiltersHolder wrFilters;
const ComputedStyle& style = mStyle ? *mStyle : *mFrame->Style();
auto filterChain = style.StyleEffects()->mFilters.AsSpan();
// Try building a CSS filter chain
WrFiltersStatus status = SVGIntegrationUtils::CreateWebRenderCSSFilters(
filterChain, mFrame, wrFilters);
if (status == WrFiltersStatus::BLOB_FALLBACK) {
// Try building an SVG filter graph
auto offsetForSVGFilters =
nsLayoutUtils::ComputeOffsetToUserSpace(aDisplayListBuilder, mFrame);
status = SVGIntegrationUtils::BuildWebRenderFilters(
mFrame, filterChain, StyleFilterType::Filter, wrFilters,
offsetForSVGFilters);
if (status == WrFiltersStatus::BLOB_FALLBACK && mStyle) {
// TODO(bug 1769223): Support fallback filters in the root code-path,
// perhaps. For now treat it the same way as invalid filters.
status = WrFiltersStatus::UNSUPPORTED;
}
}
switch (status) {
case WrFiltersStatus::BLOB_FALLBACK:
// Draw using fallback.
return false;
case WrFiltersStatus::UNSUPPORTED:
// https://drafts.fxtf.org/filter-effects/#typedef-filter-url:
//
// If the filter references a non-existent object or the referenced
// object is not a filter element, then the whole filter chain is
// ignored. No filter is applied to the object.
//
// Note that other engines have a weird discrepancy between SVG and HTML
// content here, but the spec is clear.
wrFilters = {};
break;
case WrFiltersStatus::DISABLED_FOR_PERFORMANCE:
// SVG spec allows us to drop the entire filter graph if it contains too
// many filters to render or other performance considerations.
wrFilters = {};
break;
case WrFiltersStatus::CHAIN:
case WrFiltersStatus::SVGFE:
// Filter the image using the wrFilters produced above.
break;
}
uint64_t clipChainId;
if (wrFilters.post_filters_clip) {
auto devPxRect = LayoutDeviceRect::FromAppUnits(
wrFilters.post_filters_clip.value() + ToReferenceFrame(),
mFrame->PresContext()->AppUnitsPerDevPixel());
auto clipId =
aBuilder.DefineRectClip(Nothing(), wr::ToLayoutRect(devPxRect));
clipChainId = aBuilder.DefineClipChain({clipId}, true).id;
} else {
clipChainId = aBuilder.CurrentClipChainId();
}
wr::WrStackingContextClip clip =
wr::WrStackingContextClip::ClipChain(clipChainId);
float opacity = aBuilder.GetInheritedOpacity();
aBuilder.SetInheritedOpacity(1.0f);
const DisplayItemClipChain* oldClipChain = aBuilder.GetInheritedClipChain();
aBuilder.SetInheritedClipChain(nullptr);
wr::StackingContextParams params;
params.mFilters = std::move(wrFilters.filters);
params.mFilterDatas = std::move(wrFilters.filter_datas);
params.opacity = opacity != 1.0f ? &opacity : nullptr;
params.clip = clip;
if (mWrapsBackdropFilter) {
params.flags |= wr::StackingContextFlags::WRAPS_BACKDROP_FILTER;
}
StackingContextHelper sc(aSc, GetActiveScrolledRoot(), mFrame, this, aBuilder,
params);
nsDisplayEffectsBase::CreateWebRenderCommands(aBuilder, aResources, sc,
aManager, aDisplayListBuilder);
aBuilder.SetInheritedOpacity(opacity);
aBuilder.SetInheritedClipChain(oldClipChain);
return true;
}
#ifdef MOZ_DUMP_PAINTING
void nsDisplayFilters::PrintEffects(nsACString& aTo) {
nsIFrame* firstFrame =
nsLayoutUtils::FirstContinuationOrIBSplitSibling(mFrame);
bool first = true;
aTo += " effects=(";
// We may exist for a mix of CSS filter functions and/or references to SVG
// filters. If we have invalid references to SVG filters then we paint
// nothing, but otherwise we will apply one or more filters.
if (SVGObserverUtils::GetAndObserveFilters(firstFrame, nullptr) !=
SVGObserverUtils::eHasRefsSomeInvalid) {
if (!first) {
aTo += ", ";
}
aTo += "filter";
}
aTo += ")";
}
#endif
nsDisplaySVGWrapper::nsDisplaySVGWrapper(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList)
: nsDisplayWrapList(aBuilder, aFrame, aList) {
MOZ_COUNT_CTOR(nsDisplaySVGWrapper);
}
bool nsDisplaySVGWrapper::ShouldFlattenAway(nsDisplayListBuilder* aBuilder) {
return !aBuilder->GetWidgetLayerManager();
}
bool nsDisplaySVGWrapper::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
return CreateWebRenderCommandsNewClipListOption(
aBuilder, aResources, aSc, aManager, aDisplayListBuilder, false);
}
nsDisplayForeignObject::nsDisplayForeignObject(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
nsDisplayList* aList)
: nsDisplayWrapList(aBuilder, aFrame, aList) {
MOZ_COUNT_CTOR(nsDisplayForeignObject);
}
bool nsDisplayForeignObject::ShouldFlattenAway(nsDisplayListBuilder* aBuilder) {
return !aBuilder->GetWidgetLayerManager();
}
bool nsDisplayForeignObject::CreateWebRenderCommands(
wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
const StackingContextHelper& aSc, RenderRootStateManager* aManager,
nsDisplayListBuilder* aDisplayListBuilder) {
AutoRestore<bool> restoreDoGrouping(aManager->CommandBuilder().mDoGrouping);
aManager->CommandBuilder().mDoGrouping = false;
return CreateWebRenderCommandsNewClipListOption(
aBuilder, aResources, aSc, aManager, aDisplayListBuilder, false);
}
void nsDisplayLink::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
auto appPerDev = mFrame->PresContext()->AppUnitsPerDevPixel();
aCtx->GetDrawTarget()->Link(
mLinkURI.get(), mLinkDest.get(),
NSRectToRect(GetPaintRect(aBuilder, aCtx), appPerDev));
}
void nsDisplayDestination::Paint(nsDisplayListBuilder* aBuilder,
gfxContext* aCtx) {
auto appPerDev = mFrame->PresContext()->AppUnitsPerDevPixel();
aCtx->GetDrawTarget()->Destination(
mDestinationName.get(),
NSPointToPoint(GetPaintRect(aBuilder, aCtx).TopLeft(), appPerDev));
}
void nsDisplayListCollection::SerializeWithCorrectZOrder(
nsDisplayList* aOutResultList, nsIContent* aContent) {
// Sort PositionedDescendants() in CSS 'z-order' order. The list is already
// in content document order and SortByZOrder is a stable sort which
// guarantees that boxes produced by the same element are placed together
// in the sort. Consider a position:relative inline element that breaks
// across lines and has absolutely positioned children; all the abs-pos
// children should be z-ordered after all the boxes for the position:relative
// element itself.
PositionedDescendants()->SortByZOrder();
// Now follow the rules of http://www.w3.org/TR/CSS21/zindex.html
// 1,2: backgrounds and borders
aOutResultList->AppendToTop(BorderBackground());
// 3: negative z-index children.
for (auto* item : PositionedDescendants()->TakeItems()) {
if (item->ZIndex() < 0) {
aOutResultList->AppendToTop(item);
} else {
PositionedDescendants()->AppendToTop(item);
}
}
// 4: block backgrounds
aOutResultList->AppendToTop(BlockBorderBackgrounds());
// 5: floats
aOutResultList->AppendToTop(Floats());
// 7: general content
aOutResultList->AppendToTop(Content());
// 7.5: outlines, in content tree order. We need to sort by content order
// because an element with outline that breaks and has children with outline
// might have placed child outline items between its own outline items.
// The element's outline items need to all come before any child outline
// items.
if (aContent) {
Outlines()->SortByContentOrder(aContent);
}
aOutResultList->AppendToTop(Outlines());
// 8, 9: non-negative z-index children
aOutResultList->AppendToTop(PositionedDescendants());
}
uint32_t PaintTelemetry::sPaintLevel = 0;
PaintTelemetry::AutoRecordPaint::AutoRecordPaint() {
// Don't record nested paints.
if (sPaintLevel++ > 0) {
return;
}
mStart = TimeStamp::Now();
}
PaintTelemetry::AutoRecordPaint::~AutoRecordPaint() {
MOZ_ASSERT(sPaintLevel != 0);
if (--sPaintLevel > 0) {
return;
}
// If we're in multi-process mode, don't include paint times for the parent
// process.
if (gfxVars::BrowserTabsRemoteAutostart() && XRE_IsParentProcess()) {
return;
}
// Record the total time.
mozilla::glean::gfx_content::paint_time.AccumulateRawDuration(
TimeStamp::Now() - mStart);
}
static nsIFrame* GetSelfOrPlaceholderFor(nsIFrame* aFrame) {
if (aFrame->HasAnyStateBits(NS_FRAME_IS_PUSHED_FLOAT)) {
return aFrame;
}
if (aFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
!aFrame->GetPrevInFlow()) {
return aFrame->GetPlaceholderFrame();
}
return aFrame;
}
static nsIFrame* GetAncestorFor(nsIFrame* aFrame) {
nsIFrame* f = GetSelfOrPlaceholderFor(aFrame);
MOZ_ASSERT(f);
return nsLayoutUtils::GetCrossDocParentFrameInProcess(f);
}
nsDisplayListBuilder::AutoBuildingDisplayList::AutoBuildingDisplayList(
nsDisplayListBuilder* aBuilder, nsIFrame* aForChild,
const nsRect& aVisibleRect, const nsRect& aDirtyRect,
const bool aIsTransformed)
: mBuilder(aBuilder),
mPrevFrame(aBuilder->mCurrentFrame),
mPrevReferenceFrame(aBuilder->mCurrentReferenceFrame),
mPrevOffset(aBuilder->mCurrentOffsetToReferenceFrame),
mPrevAdditionalOffset(aBuilder->mAdditionalOffset),
mPrevVisibleRect(aBuilder->mVisibleRect),
mPrevDirtyRect(aBuilder->mDirtyRect),
mPrevCompositorHitTestInfo(aBuilder->mCompositorHitTestInfo),
mPrevAncestorHasApzAwareEventHandler(
aBuilder->mAncestorHasApzAwareEventHandler),
mPrevBuildingInvisibleItems(aBuilder->mBuildingInvisibleItems),
mPrevInInvalidSubtree(aBuilder->mInInvalidSubtree) {
// If the last AutoBuildingDisplayList on the stack that we created was for
// this same frame then we are already up to date and can skip this work (this
// happens eg when BuildDisplayListForChild calls
// BuildDisplayListForStackingContext).
if (aForChild != mPrevFrame) {
if (aIsTransformed) {
aBuilder->mCurrentOffsetToReferenceFrame =
aBuilder->AdditionalOffset().refOr(nsPoint());
aBuilder->mCurrentReferenceFrame = aForChild;
} else if (aBuilder->mCurrentFrame == aForChild->GetParent()) {
aBuilder->mCurrentOffsetToReferenceFrame += aForChild->GetPosition();
} else {
aBuilder->mCurrentReferenceFrame = aBuilder->FindReferenceFrameFor(
aForChild, &aBuilder->mCurrentOffsetToReferenceFrame);
}
}
// If aForChild is being visited from a frame other than it's ancestor frame,
// mInInvalidSubtree will need to be recalculated the slow way.
if (aForChild == mPrevFrame || GetAncestorFor(aForChild) == mPrevFrame) {
aBuilder->mInInvalidSubtree =
aBuilder->mInInvalidSubtree || aForChild->IsFrameModified();
} else {
aBuilder->mInInvalidSubtree = AnyContentAncestorModified(aForChild);
}
aBuilder->mCurrentFrame = aForChild;
aBuilder->mVisibleRect = aVisibleRect;
aBuilder->mDirtyRect =
aBuilder->mInInvalidSubtree ? aVisibleRect : aDirtyRect;
}
} // namespace mozilla
|