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
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
* (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc.
* All rights reserved.
* Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include <math.h>
#include <algorithm>
#include <utility>
#include "base/memory/values_equivalent.h"
#include "cc/input/scroll_snap_data.h"
#include "third_party/blink/public/platform/web_theme_engine.h"
#include "third_party/blink/public/strings/grit/blink_strings.h"
#include "third_party/blink/renderer/core/css/properties/longhands.h"
#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/focus_params.h"
#include "third_party/blink/renderer/core/dom/scroll_marker_group_pseudo_element.h"
#include "third_party/blink/renderer/core/dom/scroll_marker_pseudo_element.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/ime/input_method_controller.h"
#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/forms/html_button_element.h"
#include "third_party/blink/renderer/core/html/forms/html_field_set_element.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_legend_element.h"
#include "third_party/blink/renderer/core/html/forms/html_opt_group_element.h"
#include "third_party/blink/renderer/core/html/forms/html_option_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_utils.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/core/layout/anchor_position_scroll_data.h"
#include "third_party/blink/renderer/core/layout/box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/constraint_space.h"
#include "third_party/blink/renderer/core/layout/constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/custom/custom_layout_child.h"
#include "third_party/blink/renderer/core/layout/custom/layout_custom.h"
#include "third_party/blink/renderer/core/layout/custom/layout_worklet.h"
#include "third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.h"
#include "third_party/blink/renderer/core/layout/custom_scrollbar.h"
#include "third_party/blink/renderer/core/layout/disable_layout_side_effects_scope.h"
#include "third_party/blink/renderer/core/layout/forms/layout_fieldset.h"
#include "third_party/blink/renderer/core/layout/forms/layout_text_control.h"
#include "third_party/blink/renderer/core/layout/fragmentation_utils.h"
#include "third_party/blink/renderer/core/layout/geometry/box_strut.h"
#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/inline/inline_cursor.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_object_inlines.h"
#include "third_party/blink/renderer/core/layout/layout_result.h"
#include "third_party/blink/renderer/core/layout/layout_utils.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/legacy_layout_tree_walking.h"
#include "third_party/blink/renderer/core/layout/length_utils.h"
#include "third_party/blink/renderer/core/layout/logical_box_fragment.h"
#include "third_party/blink/renderer/core/layout/measure_cache.h"
#include "third_party/blink/renderer/core/layout/shapes/shape_outside_info.h"
#include "third_party/blink/renderer/core/layout/table/layout_table.h"
#include "third_party/blink/renderer/core/layout/table/layout_table_cell.h"
#include "third_party/blink/renderer/core/layout/text_utils.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/core/page/autoscroll_controller.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/box_paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/contoured_border_geometry.h"
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/outline_painter.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer_size.h"
#include "third_party/blink/renderer/core/scroll/scroll_into_view_util.h"
#include "third_party/blink/renderer/core/style/computed_style_base_constants.h"
#include "third_party/blink/renderer/core/style/shadow_list.h"
#include "third_party/blink/renderer/core/style/style_overflow_clip_margin.h"
#include "third_party/blink/renderer/platform/geometry/contoured_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_rounded_rect.h"
#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/geometry/physical_offset.h"
#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/theme/web_theme_engine_helper.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"
#include "ui/gfx/geometry/quad_f.h"
#include "ui/gfx/geometry/rect_conversions.h"
namespace blink {
using mojom::blink::FormControlType;
// Used by flexible boxes when flexing this element and by table cells.
typedef WTF::HashMap<const LayoutBox*, LayoutUnit> OverrideSizeMap;
// Size of border belt for autoscroll. When mouse pointer in border belt,
// autoscroll is started.
#if BUILDFLAG(IS_IOS)
static constexpr int kAutoscrollBeltSizeInDIPs = 20;
// Size of border bottom belt for autoscroll on iOS. When users drag the right
// handle of selection on iOS, the Y value of point that passed from
// BETextInput's autoscrollToPoint is smaller that the Y value that users touch.
static constexpr int kAutoscrollBeltSizeInDIPsBottom = 60;
#else
// TODO(crbug.com/398066579): Figure out if these can be in DIPs.
static constexpr int kAutoscrollBeltSize = 20;
static constexpr int kAutoscrollBeltSizeBottom = 20;
#endif // BUILDFLAG(IS_IOS)
static const unsigned kBackgroundObscurationTestMaxDepth = 4;
struct SameSizeAsLayoutBox : public LayoutBoxModelObject {
union {
DeprecatedLayoutPoint a;
PhysicalOffset b;
} frame_location_;
PhysicalSize frame_size_;
PhysicalSize previous_size;
MinMaxSizes intrinsic_logical_widths;
Member<void*> min_max_sizes_cache;
Member<void*> cache;
HeapVector<Member<const LayoutResult>, 1> layout_results;
wtf_size_t first_fragment_item_index_;
Member<void*> members[2];
};
ASSERT_SIZE(LayoutBox, SameSizeAsLayoutBox);
namespace {
LayoutUnit TextAreaIntrinsicInlineSize(const HTMLTextAreaElement& textarea,
const LayoutBox& box) {
// Always add the scrollbar thickness for 'overflow:auto'.
const auto& style = box.StyleRef();
int scrollbar_thickness = 0;
if (style.OverflowBlockDirection() == EOverflow::kScroll ||
style.OverflowBlockDirection() == EOverflow::kAuto) {
scrollbar_thickness = layout_text_control::ScrollbarThickness(box);
}
return LayoutUnit(ceilf(layout_text_control::GetAvgCharWidth(style) *
textarea.cols())) +
scrollbar_thickness;
}
LayoutUnit TextFieldIntrinsicInlineSize(const HTMLInputElement& input,
const LayoutBox& box) {
int factor;
const bool includes_decoration = input.SizeShouldIncludeDecoration(factor);
if (factor <= 0)
factor = 20;
const float char_width = layout_text_control::GetAvgCharWidth(box.StyleRef());
float float_result = char_width * factor;
float max_char_width = 0.f;
const Font* font = box.StyleRef().GetFont();
if (layout_text_control::HasValidAvgCharWidth(*font)) {
max_char_width = font->PrimaryFont()->MaxCharWidth();
}
// For text inputs, IE adds some extra width.
if (max_char_width > char_width)
float_result += max_char_width - char_width;
LayoutUnit result(ceilf(float_result));
if (includes_decoration) {
const auto* spin_button =
To<HTMLElement>(input.UserAgentShadowRoot()->getElementById(
shadow_element_names::kIdSpinButton));
if (LayoutBox* spin_box =
spin_button ? spin_button->GetLayoutBox() : nullptr) {
const Length& logical_width = spin_box->StyleRef().LogicalWidth();
result += spin_box->BorderAndPaddingInlineSize();
// Since the width of spin_box is not calculated yet,
// spin_box->LogicalWidth() returns 0. Use the computed logical
// width instead.
if (logical_width.IsPercent()) {
const float value = logical_width.Percent();
if (value != 100.f) {
result += result * value / (100.f - value);
}
} else if (logical_width.IsFixed()) {
result += logical_width.Pixels();
}
}
}
return result;
}
LayoutUnit TextAreaIntrinsicBlockSize(const HTMLTextAreaElement& textarea,
const LayoutBox& box) {
// Only add the scrollbar thickness for 'overflow: scroll'.
int scrollbar_thickness = 0;
if (box.StyleRef().OverflowInlineDirection() == EOverflow::kScroll) {
scrollbar_thickness = layout_text_control::ScrollbarThickness(box);
}
const auto* inner_editor = textarea.InnerEditorElement();
const auto* reference_box =
inner_editor ? inner_editor->GetLayoutBox() : nullptr;
if (RuntimeEnabledFeatures::TextareaMultipleIfcsEnabled() && reference_box &&
reference_box->FirstChildBox()) {
reference_box = reference_box->FirstChildBox();
}
const LayoutUnit line_height =
reference_box ? reference_box->FirstLineHeight() : box.FirstLineHeight();
return line_height * textarea.rows() + scrollbar_thickness;
}
LayoutUnit TextFieldIntrinsicBlockSize(const HTMLInputElement& input,
const LayoutBox& box) {
const auto* inner_editor = input.InnerEditorElement();
// inner_editor's LayoutBox can be nullptr because web authors can set
// display:none to ::-webkit-textfield-decoration-container element.
const LayoutBox& target_box = (inner_editor && inner_editor->GetLayoutBox())
? *inner_editor->GetLayoutBox()
: box;
return target_box.FirstLineHeight();
}
LayoutUnit FileUploadControlIntrinsicInlineSize(const HTMLInputElement& input,
const LayoutBox& box) {
// This should match to margin-inline-end of ::-webkit-file-upload-button UA
// style.
constexpr int kAfterButtonSpacing = 4;
// Figure out how big the filename space needs to be for a given number of
// characters (using "0" as the nominal character).
constexpr int kDefaultWidthNumChars = 34;
constexpr UChar kCharacter = '0';
const String character_as_string = String(base::span_from_ref(kCharacter));
const float min_default_label_width =
kDefaultWidthNumChars *
ComputeTextWidth(character_as_string, box.StyleRef());
const String label =
input.GetLocale().QueryString(IDS_FORM_FILE_NO_FILE_LABEL);
float default_label_width = ComputeTextWidth(label, box.StyleRef());
if (HTMLInputElement* button = input.UploadButton()) {
if (auto* button_box = button->GetLayoutBox()) {
const ComputedStyle& button_style = button_box->StyleRef();
WritingMode mode = button_style.GetWritingMode();
ConstraintSpaceBuilder builder(mode, button_style.GetWritingDirection(),
/* is_new_fc */ true);
LayoutUnit max = BlockNode(button_box)
.ComputeMinMaxSizes(mode, SizeType::kIntrinsic,
builder.ToConstraintSpace())
.sizes.max_size;
default_label_width +=
max + (kAfterButtonSpacing * box.StyleRef().EffectiveZoom());
}
}
return LayoutUnit(
ceilf(std::max(min_default_label_width, default_label_width)));
}
LayoutUnit SliderIntrinsicInlineSize(const LayoutBox& box) {
constexpr int kDefaultTrackLength = 129;
return LayoutUnit(kDefaultTrackLength * box.StyleRef().EffectiveZoom());
}
LogicalSize ThemePartIntrinsicSize(const LayoutBox& box,
WebThemeEngine::Part part) {
const auto& style = box.StyleRef();
PhysicalSize size(
WebThemeEngineHelper::GetNativeThemeEngine()->GetSize(part));
size.Scale(style.EffectiveZoom());
return ToLogicalSize(size, style.GetWritingMode());
}
LayoutUnit ListBoxDefaultItemHeight(const LayoutBox& box) {
constexpr int kDefaultPaddingBottom = 1;
const SimpleFontData* font_data = box.StyleRef().GetFont()->PrimaryFont();
if (!font_data)
return LayoutUnit();
return LayoutUnit(font_data->GetFontMetrics().Height() +
kDefaultPaddingBottom);
}
// TODO(crbug.com/1040826): This function is written in LayoutObject API
// so that this works in both of the legacy layout and LayoutNG. We
// should have LayoutNG-specific code.
LayoutUnit ListBoxItemBlockSize(const HTMLSelectElement& select,
const LayoutBox& box) {
const auto& items = select.GetListItems();
if (items.empty() || box.ShouldApplySizeContainment())
return ListBoxDefaultItemHeight(box);
LayoutUnit max_block_size;
for (Element* element : items) {
if (auto* optgroup = DynamicTo<HTMLOptGroupElement>(element))
element = &optgroup->OptGroupLabelElement();
LayoutUnit item_block_size;
if (auto* layout_box = element->GetLayoutBox()) {
item_block_size = box.StyleRef().IsHorizontalWritingMode()
? layout_box->Size().height
: layout_box->Size().width;
} else {
item_block_size = ListBoxDefaultItemHeight(box);
}
max_block_size = std::max(max_block_size, item_block_size);
}
return max_block_size;
}
LayoutUnit MenuListIntrinsicInlineSize(const HTMLSelectElement& select,
const LayoutBox& box) {
const ComputedStyle& style = box.StyleRef();
float max_option_width = 0;
if (!box.ShouldApplySizeContainment()) {
for (const auto& option : select.GetOptionList()) {
String text =
style.ApplyTextTransform(option.TextIndentedToRespectGroupLabel());
// We apply SELECT's style, not OPTION's style because max_option_width is
// used to determine intrinsic width of the menulist box.
max_option_width =
std::max(max_option_width, ComputeTextWidth(text, style));
}
}
LayoutTheme& theme = LayoutTheme::GetTheme();
int paddings = theme.PopupInternalPaddingStart(style) +
theme.PopupInternalPaddingEnd(box.GetFrame(), style);
return LayoutUnit(ceilf(max_option_width)) + LayoutUnit(paddings);
}
LayoutUnit MenuListIntrinsicBlockSize(const HTMLSelectElement& select,
const LayoutBox& box) {
if (!box.StyleRef().HasEffectiveAppearance())
return kIndefiniteSize;
const SimpleFontData* font_data = box.StyleRef().GetFont()->PrimaryFont();
DCHECK(font_data);
const LayoutBox* inner_box = select.InnerElement().GetLayoutBox();
return (font_data ? font_data->GetFontMetrics().Height() : 0) +
(inner_box ? inner_box->BorderAndPaddingBlockSize() : LayoutUnit());
}
#if DCHECK_IS_ON()
void CheckDidAddFragment(const LayoutBox& box,
const PhysicalBoxFragment& new_fragment,
wtf_size_t new_fragment_index = kNotFound) {
// If |HasFragmentItems|, |ChildrenInline()| should be true.
// |HasFragmentItems| uses this condition to optimize .
if (new_fragment.HasItems())
DCHECK(box.ChildrenInline());
wtf_size_t index = 0;
for (const PhysicalBoxFragment& fragment : box.PhysicalFragments()) {
DCHECK_EQ(fragment.IsFirstForNode(), index == 0);
if (const FragmentItems* fragment_items = fragment.Items()) {
fragment_items->CheckAllItemsAreValid();
}
// Don't check past the fragment just added. Those entries may be invalid at
// this point.
if (index == new_fragment_index)
break;
++index;
}
}
#else
inline void CheckDidAddFragment(const LayoutBox& box,
const PhysicalBoxFragment& fragment,
wtf_size_t new_fragment_index = kNotFound) {}
#endif
// Applies the overflow clip to |result|. For any axis that is clipped, |result|
// is reset to |no_overflow_rect|. If neither axis is clipped, nothing is
// changed.
void ApplyOverflowClip(OverflowClipAxes overflow_clip_axes,
const PhysicalRect& no_overflow_rect,
PhysicalRect& result) {
if (overflow_clip_axes & kOverflowClipX) {
result.SetX(no_overflow_rect.X());
result.SetWidth(no_overflow_rect.Width());
}
if (overflow_clip_axes & kOverflowClipY) {
result.SetY(no_overflow_rect.Y());
result.SetHeight(no_overflow_rect.Height());
}
}
int HypotheticalScrollbarThickness(const LayoutBox& box,
ScrollbarOrientation scrollbar_orientation,
bool should_include_overlay_thickness) {
box.CheckIsNotDestroyed();
if (PaintLayerScrollableArea* scrollable_area = box.GetScrollableArea()) {
return scrollable_area->HypotheticalScrollbarThickness(
scrollbar_orientation, should_include_overlay_thickness);
} else {
Page* page = box.GetFrame()->GetPage();
ScrollbarTheme& theme = page->GetScrollbarTheme();
if (theme.UsesOverlayScrollbars() && !should_include_overlay_thickness) {
return 0;
} else {
ChromeClient& chrome_client = page->GetChromeClient();
Document& document = box.GetDocument();
float scale_from_dip =
chrome_client.WindowToViewportScalar(document.GetFrame(), 1.0f);
return theme.ScrollbarThickness(scale_from_dip,
box.StyleRef().UsedScrollbarWidth());
}
}
}
void RecalcFragmentScrollableOverflow(RecalcScrollableOverflowResult& result,
const PhysicalFragment& fragment) {
for (const auto& child : fragment.PostLayoutChildren()) {
if (child->GetLayoutObject()) {
if (const auto* box = DynamicTo<PhysicalBoxFragment>(child.get())) {
if (LayoutBox* owner_box = box->MutableOwnerLayoutBox())
result.Unite(owner_box->RecalcScrollableOverflow());
}
} else {
// We enter this branch when the |child| is a fragmentainer.
RecalcFragmentScrollableOverflow(result, *child.get());
}
}
}
} // namespace
LayoutBoxRareData::LayoutBoxRareData()
: spanner_placeholder_(nullptr),
// TODO(rego): We should store these based on physical direction.
has_override_containing_block_content_logical_width_(false),
has_previous_content_box_rect_(false) {}
void LayoutBoxRareData::Trace(Visitor* visitor) const {
visitor->Trace(spanner_placeholder_);
visitor->Trace(layout_child_);
}
LayoutBox::LayoutBox(ContainerNode* node) : LayoutBoxModelObject(node) {
if (blink::IsA<HTMLLegendElement>(node))
SetIsHTMLLegendElement();
}
void LayoutBox::Trace(Visitor* visitor) const {
visitor->Trace(min_max_sizes_cache_);
visitor->Trace(measure_cache_);
visitor->Trace(layout_results_);
visitor->Trace(overflow_);
visitor->Trace(rare_data_);
LayoutBoxModelObject::Trace(visitor);
}
LayoutBox::~LayoutBox() = default;
PaintLayerType LayoutBox::LayerTypeRequired() const {
NOT_DESTROYED();
if (IsStacked() || HasHiddenBackface() ||
(StyleRef().SpecifiesColumns() && !IsLayoutNGObject()))
return kNormalPaintLayer;
if (HasNonVisibleOverflow() && !IsLayoutReplaced()) {
return kOverflowClipPaintLayer;
}
return kNoPaintLayer;
}
void LayoutBox::WillBeDestroyed() {
NOT_DESTROYED();
ClearOverrideContainingBlockContentSize();
ShapeOutsideInfo::RemoveInfo(*this);
if (!DocumentBeingDestroyed()) {
DisassociatePhysicalFragments();
}
if (Style() && StyleRef().HasOutOfFlowPosition()) {
if (auto* display_locks = DisplayLocksAffectedByAnchors()) {
NotifyContainingDisplayLocksForAnchorPositioning(display_locks, nullptr);
}
}
LayoutBoxModelObject::WillBeDestroyed();
}
void LayoutBox::DisassociatePhysicalFragments() {
NOT_DESTROYED();
if (FirstInlineFragmentItemIndex()) {
FragmentItems::LayoutObjectWillBeDestroyed(*this);
ClearFirstInlineFragmentItemIndex();
}
if (measure_cache_) {
measure_cache_->LayoutObjectWillBeDestroyed();
}
for (auto result : layout_results_)
result->GetPhysicalFragment().LayoutObjectWillBeDestroyed();
}
void LayoutBox::InsertedIntoTree() {
NOT_DESTROYED();
LayoutBoxModelObject::InsertedIntoTree();
AddCustomLayoutChildIfNeeded();
}
void LayoutBox::WillBeRemovedFromTree() {
NOT_DESTROYED();
ClearCustomLayoutChild();
LayoutBoxModelObject::WillBeRemovedFromTree();
}
void LayoutBox::StyleWillChange(StyleDifference diff,
const ComputedStyle& new_style) {
NOT_DESTROYED();
const ComputedStyle* old_style = Style();
if (old_style) {
if (IsDocumentElement() || IsBody()) {
// The background of the root element or the body element could propagate
// up to the canvas. Just dirty the entire canvas when our style changes
// substantially.
if (diff.NeedsNormalPaintInvalidation() || diff.NeedsLayout()) {
View()->SetShouldDoFullPaintInvalidation();
}
}
// When a layout hint happens and an object's position style changes, we
// have to do a layout to dirty the layout tree using the old position
// value now.
if (diff.NeedsFullLayout() && Parent()) {
bool will_move_out_of_ifc = false;
if (old_style->GetPosition() != new_style.GetPosition()) {
if (!old_style->HasOutOfFlowPosition() &&
new_style.HasOutOfFlowPosition()) {
// We're about to go out of flow. Before that takes place, we need to
// mark the current containing block chain for preferred widths
// recalculation.
SetNeedsLayoutAndIntrinsicWidthsRecalc(
layout_invalidation_reason::kStyleChange);
// Grid placement is different for out-of-flow elements, so if the
// containing block is a grid, dirty the grid's placement. The
// converse (going from out of flow to in flow) is handled in
// LayoutBox::UpdateGridPositionAfterStyleChange.
LayoutBlock* containing_block = ContainingBlock();
if (containing_block && containing_block->IsLayoutGrid()) {
containing_block->SetGridPlacementDirty(true);
}
// Out of flow are not part of |FragmentItems|, and that further
// changes including destruction cannot be tracked. We need to mark it
// is moved out from this IFC.
will_move_out_of_ifc = true;
} else {
MarkContainerChainForLayout();
}
if (old_style->GetPosition() == EPosition::kStatic) {
SetShouldDoFullPaintInvalidation();
} else if (new_style.HasOutOfFlowPosition()) {
Parent()->SetChildNeedsLayout();
}
}
bool will_become_inflow = false;
if ((old_style->IsFloating() || old_style->HasOutOfFlowPosition()) &&
!new_style.IsFloating() && !new_style.HasOutOfFlowPosition()) {
// As a float or OOF, this object may have been part of an inline
// formatting context, but that's definitely no longer the case.
will_become_inflow = true;
will_move_out_of_ifc = true;
}
if (will_move_out_of_ifc && FirstInlineFragmentItemIndex()) {
FragmentItems::LayoutObjectWillBeMoved(*this);
ClearFirstInlineFragmentItemIndex();
}
if (will_become_inflow)
SetIsInLayoutNGInlineFormattingContext(false);
}
// FIXME: This branch runs when !oldStyle, which means that layout was never
// called so what's the point in invalidating the whole view that we never
// painted?
} else if (IsBody()) {
View()->SetShouldDoFullPaintInvalidation();
}
LayoutBoxModelObject::StyleWillChange(diff, new_style);
}
void LayoutBox::StyleDidChange(StyleDifference diff,
const ComputedStyle* old_style) {
NOT_DESTROYED();
LayoutBoxModelObject::StyleDidChange(diff, old_style);
// Reflection works through PaintLayer. Some child classes e.g. LayoutSVGBlock
// don't create layers and ignore reflections.
if (HasReflection() && !HasLayer())
SetHasReflection(false);
if (auto* parent_flow_block = DynamicTo<LayoutBlockFlow>(Parent())) {
if (IsFloatingOrOutOfFlowPositioned() && old_style &&
!old_style->IsFloating() && !old_style->HasOutOfFlowPosition()) {
// Note that |parent_flow_block| may have been destroyed after this call.
parent_flow_block->ChildBecameFloatingOrOutOfFlow(this);
}
}
SetOverflowClipAxes(ComputeOverflowClipAxes());
// If our zoom factor changes and we have a defined scrollLeft/Top, we need to
// adjust that value into the new zoomed coordinate space. Note that the new
// scroll offset may be outside the normal min/max range of the scrollable
// area, which is weird but OK, because the scrollable area will update its
// min/max in updateAfterLayout().
const ComputedStyle& new_style = StyleRef();
if (IsScrollContainer() && old_style &&
old_style->EffectiveZoom() != new_style.EffectiveZoom()) {
PaintLayerScrollableArea* scrollable_area = GetScrollableArea();
DCHECK(scrollable_area);
// We use GetScrollOffset() rather than ScrollPosition(), because scroll
// offset is the distance from the beginning of flow for the box, which is
// the dimension we want to preserve.
ScrollOffset offset = scrollable_area->GetScrollOffset();
if (!offset.IsZero()) {
offset.Scale(new_style.EffectiveZoom() / old_style->EffectiveZoom());
scrollable_area->SetScrollOffsetUnconditionally(offset);
}
}
if (old_style && old_style->IsScrollContainer() != IsScrollContainer()) {
if (auto* layer = EnclosingLayer())
layer->ScrollContainerStatusChanged();
}
UpdateShapeOutsideInfoAfterStyleChange(*Style(), old_style);
UpdateGridPositionAfterStyleChange(old_style);
if (old_style) {
// Regular column content (i.e. non-spanners) have a hook into the flow
// thread machinery before (StyleWillChange()) and after (here in
// StyleDidChange()) the style has changed. Column spanners, on the other
// hand, only have a hook here. The LayoutMultiColumnSpannerPlaceholder code
// will do all the necessary things, including removing it as a spanner, if
// it should no longer be one. Therefore, make sure that we skip
// FlowThreadDescendantStyleDidChange() in such cases, as that might trigger
// a duplicate flow thread insertion notification, if the spanner no longer
// is a spanner.
if (LayoutMultiColumnSpannerPlaceholder* placeholder =
SpannerPlaceholder()) {
placeholder->LayoutObjectInFlowThreadStyleDidChange(old_style);
}
UpdateScrollSnapMappingAfterStyleChange(*old_style);
if (ShouldClipOverflowAlongEitherAxis()) {
// The overflow clip paint property depends on border sizes through
// overflowClipRect(), and border radii, so we update properties on
// border size or radii change.
//
// For some controls, it depends on paddings.
if (!old_style->BorderSizeEquals(new_style) ||
diff.BorderRadiusChanged() ||
(HasControlClip() && !old_style->PaddingEqual(new_style))) {
SetNeedsPaintPropertyUpdate();
}
}
if (old_style->OverscrollBehaviorX() != new_style.OverscrollBehaviorX() ||
old_style->OverscrollBehaviorY() != new_style.OverscrollBehaviorY()) {
SetNeedsPaintPropertyUpdate();
}
if (old_style->OverflowX() != new_style.OverflowX() ||
old_style->OverflowY() != new_style.OverflowY()) {
SetNeedsPaintPropertyUpdate();
}
if (old_style->OverflowClipMargin() != new_style.OverflowClipMargin())
SetNeedsPaintPropertyUpdate();
if (IsInLayoutNGInlineFormattingContext() && IsAtomicInlineLevel() &&
old_style->Direction() != new_style.Direction()) {
SetNeedsCollectInlines();
}
if (IsBackgroundAttachmentFixedObject() &&
new_style.BackgroundLayers().Clip() !=
old_style->BackgroundLayers().Clip()) {
SetNeedsPaintPropertyUpdate();
}
}
// Update the script style map, from the new computed style.
if (IsCustomItem())
GetCustomLayoutChild()->styleMap()->UpdateStyle(GetDocument(), StyleRef());
// Non-atomic inlines should be LayoutInline or LayoutText, not LayoutBox.
DCHECK(!IsInline() || IsAtomicInlineLevel());
}
void LayoutBox::UpdateShapeOutsideInfoAfterStyleChange(
const ComputedStyle& style,
const ComputedStyle* old_style) {
NOT_DESTROYED();
const ShapeValue* shape_outside = style.ShapeOutside();
const ShapeValue* old_shape_outside =
old_style ? old_style->ShapeOutside()
: ComputedStyleInitialValues::InitialShapeOutside();
const Length& shape_margin = style.ShapeMargin();
const Length& old_shape_margin =
old_style ? old_style->ShapeMargin()
: ComputedStyleInitialValues::InitialShapeMargin();
float shape_image_threshold = style.ShapeImageThreshold();
float old_shape_image_threshold =
old_style ? old_style->ShapeImageThreshold()
: ComputedStyleInitialValues::InitialShapeImageThreshold();
// FIXME: A future optimization would do a deep comparison for equality. (bug
// 100811)
if (shape_outside == old_shape_outside && shape_margin == old_shape_margin &&
shape_image_threshold == old_shape_image_threshold)
return;
if (!shape_outside)
ShapeOutsideInfo::RemoveInfo(*this);
else
ShapeOutsideInfo::EnsureInfo(*this).MarkShapeAsDirty();
if (!IsFloating()) {
return;
}
if (shape_outside || shape_outside != old_shape_outside) {
if (auto* containing_block = ContainingBlock()) {
containing_block->SetChildNeedsLayout();
}
}
}
namespace {
bool GridStyleChanged(const ComputedStyle* old_style,
const ComputedStyle& current_style) {
return old_style->GridColumnStart() != current_style.GridColumnStart() ||
old_style->GridColumnEnd() != current_style.GridColumnEnd() ||
old_style->GridRowStart() != current_style.GridRowStart() ||
old_style->GridRowEnd() != current_style.GridRowEnd() ||
old_style->Order() != current_style.Order() ||
old_style->HasOutOfFlowPosition() !=
current_style.HasOutOfFlowPosition();
}
bool AlignmentChanged(const ComputedStyle* old_style,
const ComputedStyle& current_style) {
return old_style->AlignSelf() != current_style.AlignSelf() ||
old_style->JustifySelf() != current_style.JustifySelf();
}
} // namespace
void LayoutBox::UpdateGridPositionAfterStyleChange(
const ComputedStyle* old_style) {
NOT_DESTROYED();
if (!old_style)
return;
LayoutObject* parent = Parent();
const bool was_out_of_flow = old_style->HasOutOfFlowPosition();
const bool is_out_of_flow = StyleRef().HasOutOfFlowPosition();
LayoutBlock* containing_block = ContainingBlock();
if ((containing_block && containing_block->IsLayoutGrid()) &&
GridStyleChanged(old_style, StyleRef())) {
// Out-of-flow items do not impact grid placement.
// TODO(kschmi): Scope this so that it only dirties the grid when track
// sizing depends on grid item sizes.
if (!was_out_of_flow || !is_out_of_flow)
containing_block->SetGridPlacementDirty(true);
// For out-of-flow elements with grid container as containing block, we need
// to run the entire algorithm to place and size them correctly. As a
// result, we trigger a full layout for GridNG.
if (is_out_of_flow) {
containing_block->SetNeedsLayout(layout_invalidation_reason::kGridChanged,
kMarkContainerChain);
}
}
// GridNG computes static positions for out-of-flow elements at layout time,
// with alignment offsets baked in. So if alignment changes, we need to
// schedule a layout.
if (is_out_of_flow && parent && AlignmentChanged(old_style, StyleRef())) {
parent->SetNeedsLayout(
layout_invalidation_reason::kOutOfFlowAlignmentChanged,
kMarkContainerChain);
}
}
void LayoutBox::UpdateScrollSnapMappingAfterStyleChange(
const ComputedStyle& old_style) {
NOT_DESTROYED();
DCHECK(Style());
// scroll-snap-type and scroll-padding invalidate the snap container.
if (old_style.GetScrollSnapType() != StyleRef().GetScrollSnapType() ||
old_style.ScrollPaddingBottom() != StyleRef().ScrollPaddingBottom() ||
old_style.ScrollPaddingLeft() != StyleRef().ScrollPaddingLeft() ||
old_style.ScrollPaddingTop() != StyleRef().ScrollPaddingTop() ||
old_style.ScrollPaddingRight() != StyleRef().ScrollPaddingRight()) {
if (!NeedsLayout() && IsScrollContainer()) {
GetScrollableArea()->EnqueueForSnapUpdateIfNeeded();
}
}
// scroll-snap-align invalidates layout as we need to propagate the
// snap-areas up the fragment-tree.
if (old_style.GetScrollSnapAlign() != StyleRef().GetScrollSnapAlign()) {
if (auto* containing_block = ContainingBlock()) {
containing_block->SetNeedsLayout(layout_invalidation_reason::kStyleChange,
kMarkContainerChain);
}
}
auto SnapAreaDidChange = [&]() {
auto* snap_container = ContainingScrollContainer();
if (snap_container && !snap_container->NeedsLayout()) {
snap_container->GetScrollableArea()->EnqueueForSnapUpdateIfNeeded();
}
};
// scroll-snap-stop and scroll-margin invalidate the snap area.
if (old_style.ScrollSnapStop() != StyleRef().ScrollSnapStop() ||
old_style.ScrollMarginBottom() != StyleRef().ScrollMarginBottom() ||
old_style.ScrollMarginLeft() != StyleRef().ScrollMarginLeft() ||
old_style.ScrollMarginTop() != StyleRef().ScrollMarginTop() ||
old_style.ScrollMarginRight() != StyleRef().ScrollMarginRight()) {
SnapAreaDidChange();
}
// Transform invalidates the snap area.
if (old_style.Transform() != StyleRef().Transform())
SnapAreaDidChange();
}
bool LayoutBox::ShouldBeHandledAsFloating(const ComputedStyle& style) const {
NOT_DESTROYED();
return style.IsFloating() &&
ToPositionedState(style.GetPosition()) != kIsOutOfFlowPositioned &&
!style.IsInsideDisplayIgnoringFloatingChildren();
}
void LayoutBox::UpdateFromStyle() {
NOT_DESTROYED();
LayoutBoxModelObject::UpdateFromStyle();
const ComputedStyle& style_to_use = StyleRef();
SetFloating(ShouldBeHandledAsFloating(style_to_use));
SetHasTransformRelatedProperty(
IsSVGChild() ? style_to_use.HasTransformRelatedPropertyForSVG()
: style_to_use.HasTransformRelatedProperty());
SetHasReflection(style_to_use.BoxReflect());
bool should_clip_overflow = (!StyleRef().IsOverflowVisibleAlongBothAxes() ||
ShouldApplyPaintContainment()) &&
RespectsCSSOverflow();
if (should_clip_overflow != HasNonVisibleOverflow()) {
// The overflow clip paint property depends on whether overflow clip is
// present so we need to update paint properties if this changes.
SetNeedsPaintPropertyUpdate();
if (Layer())
Layer()->SetNeedsCompositingInputsUpdate();
}
SetHasNonVisibleOverflow(should_clip_overflow);
}
void LayoutBox::LayoutSubtreeRoot() {
NOT_DESTROYED();
// Our own style may have changed which would disqualify us as a layout root
// (e.g. our containment/writing-mode/formatting-context status/etc changed).
// Skip subtree layout, and ensure our container chain needs layout.
if (SelfNeedsFullLayout()) {
MarkContainerChainForLayout();
return;
}
const auto* previous_result = GetSingleCachedLayoutResult();
DCHECK(previous_result);
const auto& space = previous_result->GetConstraintSpaceForCaching();
DCHECK_EQ(space.GetWritingMode(), StyleRef().GetWritingMode());
const LayoutResult* result = BlockNode(this).Layout(space);
GetDocument().GetFrame()->GetInputMethodController().DidLayoutSubtree(*this);
if (IsOutOfFlowPositioned()) {
result->CopyMutableOutOfFlowData(*previous_result);
}
// Even if we are a subtree layout root we need to mark our containing-block
// for layout if:
// - Our baselines have shifted.
// - We've propagated any layout-objects (which affect our container chain).
//
// NOTE: We could weaken the constraints in ObjectIsRelayoutBoundary, and use
// this technique to detect size-changes, etc if we wanted to expand this
// optimization.
const auto& previous_fragment =
To<PhysicalBoxFragment>(previous_result->GetPhysicalFragment());
const auto& fragment = To<PhysicalBoxFragment>(result->GetPhysicalFragment());
if (previous_fragment.FirstBaseline() != fragment.FirstBaseline() ||
previous_fragment.LastBaseline() != fragment.LastBaseline() ||
fragment.HasPropagatedLayoutObjects()) {
if (auto* containing_block = ContainingBlock()) {
containing_block->SetNeedsLayout(
layout_invalidation_reason::kChildChanged, kMarkContainerChain);
}
}
}
// ClientWidth and ClientHeight represent the interior of an object excluding
// border and scrollbar.
DISABLE_CFI_PERF
LayoutUnit LayoutBox::ClientWidth() const {
NOT_DESTROYED();
// We need to clamp negative values. This function may be called during layout
// before frame_size_ gets the final proper value. Another reason: While
// border side values are currently limited to 2^20px (a recent change in the
// code), if this limit is raised again in the future, we'd have ill effects
// of saturated arithmetic otherwise.
LayoutUnit width = Size().width;
if (CanSkipComputeScrollbars()) {
return (width - BorderLeft() - BorderRight()).ClampNegativeToZero();
} else {
return (width - BorderLeft() - BorderRight() -
ComputeScrollbarsInternal(kClampToContentBox).HorizontalSum())
.ClampNegativeToZero();
}
}
DISABLE_CFI_PERF
LayoutUnit LayoutBox::ClientHeight() const {
NOT_DESTROYED();
// We need to clamp negative values. This function can be called during layout
// before frame_size_ gets the final proper value. The scrollbar may be wider
// than the padding box. Another reason: While border side values are
// currently limited to 2^20px (a recent change in the code), if this limit is
// raised again in the future, we'd have ill effects of saturated arithmetic
// otherwise.
LayoutUnit height = Size().height;
if (CanSkipComputeScrollbars()) {
return (height - BorderTop() - BorderBottom()).ClampNegativeToZero();
} else {
return (height - BorderTop() - BorderBottom() -
ComputeScrollbarsInternal(kClampToContentBox).VerticalSum())
.ClampNegativeToZero();
}
}
LayoutUnit LayoutBox::ClientWidthFrom(LayoutUnit width) const {
NOT_DESTROYED();
if (CanSkipComputeScrollbars()) {
return (width - BorderLeft() - BorderRight()).ClampNegativeToZero();
} else {
return (width - BorderLeft() - BorderRight() -
ComputeScrollbarsInternal(kClampToContentBox).HorizontalSum())
.ClampNegativeToZero();
}
}
LayoutUnit LayoutBox::ClientHeightFrom(LayoutUnit height) const {
NOT_DESTROYED();
if (CanSkipComputeScrollbars()) {
return (height - BorderTop() - BorderBottom()).ClampNegativeToZero();
} else {
return (height - BorderTop() - BorderBottom() -
ComputeScrollbarsInternal(kClampToContentBox).VerticalSum())
.ClampNegativeToZero();
}
}
LayoutUnit LayoutBox::ClientWidthWithTableSpecialBehavior() const {
NOT_DESTROYED();
// clientWidth/Height is the visual portion of the box content, not including
// borders or scroll bars, but includes padding. And per
// https://www.w3.org/TR/CSS2/tables.html#model,
// table wrapper box is a principal block box that contains the table box
// itself and any caption boxes, and table grid box is a block-level box that
// contains the table's internal table boxes. When table's border is specified
// in CSS, the border is added to table grid box, not table wrapper box.
// Currently, Blink doesn't have table wrapper box, and we are supposed to
// retrieve clientWidth/Height from table wrapper box, not table grid box. So
// when we retrieve clientWidth/Height, it includes table's border size.
if (IsTable())
return ClientWidth() + BorderLeft() + BorderRight();
return ClientWidth();
}
LayoutUnit LayoutBox::ClientHeightWithTableSpecialBehavior() const {
NOT_DESTROYED();
// clientWidth/Height is the visual portion of the box content, not including
// borders or scroll bars, but includes padding. And per
// https://www.w3.org/TR/CSS2/tables.html#model,
// table wrapper box is a principal block box that contains the table box
// itself and any caption boxes, and table grid box is a block-level box that
// contains the table's internal table boxes. When table's border is specified
// in CSS, the border is added to table grid box, not table wrapper box.
// Currently, Blink doesn't have table wrapper box, and we are supposed to
// retrieve clientWidth/Height from table wrapper box, not table grid box. So
// when we retrieve clientWidth/Height, it includes table's border size.
if (IsTable())
return ClientHeight() + BorderTop() + BorderBottom();
return ClientHeight();
}
LayoutUnit LayoutBox::OffsetWidth() const {
NOT_DESTROYED();
if (RuntimeEnabledFeatures::LayoutBoxVisualLocationEnabled()) {
return LayoutBoxModelObject::OffsetWidth();
}
return Size().width;
}
LayoutUnit LayoutBox::OffsetHeight() const {
NOT_DESTROYED();
if (RuntimeEnabledFeatures::LayoutBoxVisualLocationEnabled()) {
return LayoutBoxModelObject::OffsetHeight();
}
return Size().height;
}
bool LayoutBox::UsesOverlayScrollbars() const {
NOT_DESTROYED();
if (StyleRef().HasCustomScrollbarStyle(DynamicTo<Element>(GetNode()))) {
return false;
}
if (GetFrame()->GetPage()->GetScrollbarTheme().UsesOverlayScrollbars())
return true;
return false;
}
LayoutUnit LayoutBox::ScrollWidth() const {
NOT_DESTROYED();
if (IsScrollContainer())
return GetScrollableArea()->ScrollWidth();
if (StyleRef().IsScrollbarGutterStable() &&
StyleRef().OverflowBlockDirection() == EOverflow::kHidden) {
if (auto* scrollable_area = GetScrollableArea())
return scrollable_area->ScrollWidth();
else
return ScrollableOverflowRect().Width();
}
// For objects with scrollable overflow, this matches IE.
PhysicalRect overflow_rect = ScrollableOverflowRect();
if (!StyleRef().GetWritingDirection().IsFlippedX()) {
return std::max(ClientWidth(), overflow_rect.Right() - BorderLeft());
}
return ClientWidth() -
std::min(LayoutUnit(), overflow_rect.X() - BorderLeft());
}
LayoutUnit LayoutBox::ScrollHeight() const {
NOT_DESTROYED();
if (IsScrollContainer())
return GetScrollableArea()->ScrollHeight();
if (StyleRef().IsScrollbarGutterStable() &&
StyleRef().OverflowBlockDirection() == EOverflow::kHidden) {
if (auto* scrollable_area = GetScrollableArea())
return scrollable_area->ScrollHeight();
else
return ScrollableOverflowRect().Height();
}
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
return std::max(ClientHeight(),
ScrollableOverflowRect().Bottom() - BorderTop());
}
PhysicalBoxStrut LayoutBox::MarginBoxOutsets() const {
NOT_DESTROYED();
if (PhysicalFragmentCount()) {
// We get margin data from the first physical fragment. Margins are
// per-LayoutBox data, and we don't need to take care of block
// fragmentation.
return GetPhysicalFragment(0)->Margins();
}
return PhysicalBoxStrut();
}
LayoutBlock* LayoutBox::GetScrollMarkerGroup() {
NOT_DESTROYED();
if (Style()->ScrollMarkerGroup() == EScrollMarkerGroup::kNone) {
return nullptr;
}
LayoutBox* content_box = ContentLayoutBox();
if (!content_box || (!content_box->IsScrollContainer() &&
!content_box->IsDocumentElement())) {
return nullptr;
}
if (auto* element = DynamicTo<Element>(GetNode())) {
PseudoElement* pseudo =
element->GetPseudoElement(kPseudoIdScrollMarkerGroupBefore);
if (!pseudo) {
pseudo = element->GetPseudoElement(kPseudoIdScrollMarkerGroupAfter);
}
if (pseudo) {
return To<LayoutBlock>(pseudo->GetLayoutObject());
}
}
return nullptr;
}
LayoutBlock* LayoutBox::ScrollerFromScrollMarkerGroup() const {
NOT_DESTROYED();
DCHECK(IsScrollMarkerGroup());
auto* pseudo_element = DynamicTo<PseudoElement>(GetNode());
if (const Element* originating_element = pseudo_element->parentElement()) {
return DynamicTo<LayoutBlock>(
originating_element->GetLayoutBoxForScrolling());
}
return nullptr;
}
void LayoutBox::QuadsInAncestorInternal(Vector<gfx::QuadF>& quads,
const LayoutBoxModelObject* ancestor,
MapCoordinatesFlags mode) const {
NOT_DESTROYED();
if (RuntimeEnabledFeatures::LayoutBoxVisualLocationEnabled()) {
const PhysicalBoxFragment* first_fragment = nullptr;
for (const PhysicalBoxFragment& fragment : PhysicalFragments()) {
// Calculate the offset relatively to the first fragment, which in turn
// will be mapped correctly to the ancestor.
PhysicalOffset offset;
if (!first_fragment) {
first_fragment = &fragment;
} else {
offset = fragment.OffsetFromRootFragmentationContext() -
first_fragment->OffsetFromRootFragmentationContext();
}
PhysicalRect rect(offset, fragment.Size());
quads.push_back(LocalRectToAncestorQuad(rect, ancestor, mode));
}
return;
}
if (LayoutFlowThread* flow_thread = FlowThreadContainingBlock()) {
flow_thread->QuadsInAncestorForDescendant(*this, quads, ancestor, mode);
return;
}
quads.push_back(
LocalRectToAncestorQuad(PhysicalBorderBoxRect(), ancestor, mode));
}
gfx::RectF LayoutBox::LocalBoundingBoxRectForAccessibility() const {
NOT_DESTROYED();
PhysicalSize size = Size();
return gfx::RectF(0, 0, size.width.ToFloat(), size.height.ToFloat());
}
void LayoutBox::UpdateAfterLayout() {
NOT_DESTROYED();
SetNeedsOverflowRecalc(OverflowRecalcType::kOnlyVisualOverflowRecalc);
SetScrollableOverflowFromLayoutResults();
if (IsLayoutView() && !GetDocument().Printing()) {
// Unlike every other layer, the root PaintLayer takes its size from the
// layout viewport size. The call to AdjustViewSize() will update the
// frame's contents size, which will also update the page's minimum scale
// factor. The call to ResizeAfterLayout() will calculate the layout
// viewport size based on the page minimum scale factor, and then update the
// LocalFrameView with the new size.
LocalFrame& frame = GetFrameView()->GetFrame();
GetFrameView()->AdjustViewSize();
if (frame.IsMainFrame()) {
frame.GetChromeClient().ResizeAfterLayout();
}
if (IsScrollContainer()) {
GetScrollableArea()->ClampScrollOffsetAfterOverflowChange();
}
}
// Transform-origin depends on box size, so we need to update the layer
// transform after layout.
if (HasLayer()) {
Layer()->UpdateTransform();
Layer()->UpdateScrollingAfterLayout();
}
GetFrame()->GetInputMethodController().DidUpdateLayout(*this);
if (IsPositioned())
GetFrame()->GetInputMethodController().DidLayoutSubtree(*this);
if (StyleRef().HasColumnRule() && IsFragmentationContextRoot()) {
// Issue full invalidation, in case the number of column rules have changed.
ClearNeedsLayoutWithFullPaintInvalidation();
} else {
ClearNeedsLayout();
}
if (auto* block_flow = DynamicTo<LayoutBlockFlow>(this)) {
// TODO(crbug.com/371802475): Get rid of this. The special anonymous objects
// created (but not really used anymore) for multicol layout are not laid
// out, and need to be cleared manually, to avoid DCHECK failures.
if (LayoutMultiColumnFlowThread* flow_thread =
block_flow->MultiColumnFlowThread()) {
for (LayoutBox* column_box = flow_thread->FirstMultiColumnBox();
column_box; column_box = column_box->NextSiblingMultiColumnBox()) {
column_box->ClearNeedsLayout();
}
flow_thread->ClearNeedsLayout();
}
}
// We should notify the display lock that we've done layout on self, and if
// it's not blocked, on children.
if (auto* context = GetDisplayLockContext()) {
if (!ChildLayoutBlockedByDisplayLock()) {
context->DidLayoutChildren();
}
}
}
LayoutUnit LayoutBox::OverrideIntrinsicContentInlineSize() const {
NOT_DESTROYED();
// We only override a size contained dimension.
if (!ShouldApplyInlineSizeContainment()) {
return kIndefiniteSize;
}
const auto& style = StyleRef();
const StyleIntrinsicLength& intrinsic_length =
style.ContainIntrinsicInlineSize();
if (intrinsic_length.HasAuto()) {
const auto* context = GetDisplayLockContext();
if (context && context->IsLocked()) {
if (const auto* elem = DynamicTo<Element>(GetNode())) {
if (const auto inline_size = elem->LastRememberedInlineSize()) {
// ResizeObserverSize is adjusted to be in CSS space, we need to
// adjust it back to Layout space by applying the effective zoom.
return LayoutUnit::FromFloatRound(*inline_size *
style.EffectiveZoom());
}
}
}
}
if (const auto& length = intrinsic_length.GetLength()) {
DCHECK(length->IsFixed());
return LayoutUnit(length->Pixels());
}
return kIndefiniteSize;
}
LayoutUnit LayoutBox::OverrideIntrinsicContentBlockSize() const {
NOT_DESTROYED();
// We only override a size contained dimension.
if (!ShouldApplyBlockSizeContainment()) {
return kIndefiniteSize;
}
const auto& style = StyleRef();
const StyleIntrinsicLength& intrinsic_length =
style.ContainIntrinsicBlockSize();
if (intrinsic_length.HasAuto()) {
const auto* context = GetDisplayLockContext();
if (context && context->IsLocked()) {
if (const auto* elem = DynamicTo<Element>(GetNode())) {
if (const auto inline_size = elem->LastRememberedBlockSize()) {
// ResizeObserverSize is adjusted to be in CSS space, we need to
// adjust it back to Layout space by applying the effective zoom.
return LayoutUnit::FromFloatRound(*inline_size *
style.EffectiveZoom());
}
}
}
}
if (const auto& length = intrinsic_length.GetLength()) {
DCHECK(length->IsFixed());
return LayoutUnit(length->Pixels());
}
return kIndefiniteSize;
}
LayoutUnit LayoutBox::DefaultIntrinsicContentInlineSize() const {
NOT_DESTROYED();
if (!IsA<Element>(GetNode()))
return kIndefiniteSize;
const Element& element = *To<Element>(GetNode());
const bool apply_fixed_size = StyleRef().ApplyControlFixedSize(&element);
const auto* select = DynamicTo<HTMLSelectElement>(element);
if (select && select->UsesMenuList() &&
StyleRef().EffectiveAppearance() != AppearanceValue::kBaseSelect)
[[unlikely]] {
return apply_fixed_size ? MenuListIntrinsicInlineSize(*select, *this)
: kIndefiniteSize;
}
const auto* input = DynamicTo<HTMLInputElement>(element);
if (input) [[unlikely]] {
if (input->IsTextField() && apply_fixed_size) {
return TextFieldIntrinsicInlineSize(*input, *this);
}
FormControlType type = input->FormControlType();
if (type == FormControlType::kInputFile && apply_fixed_size) {
return FileUploadControlIntrinsicInlineSize(*input, *this);
}
if (type == FormControlType::kInputRange) {
return SliderIntrinsicInlineSize(*this);
}
auto effective_appearance = StyleRef().EffectiveAppearance();
if (effective_appearance == AppearanceValue::kCheckbox) {
return ThemePartIntrinsicSize(*this, WebThemeEngine::kPartCheckbox)
.inline_size;
}
if (effective_appearance == AppearanceValue::kRadio) {
return ThemePartIntrinsicSize(*this, WebThemeEngine::kPartRadio)
.inline_size;
}
return kIndefiniteSize;
}
const auto* textarea = DynamicTo<HTMLTextAreaElement>(element);
if (textarea && apply_fixed_size) [[unlikely]] {
return TextAreaIntrinsicInlineSize(*textarea, *this);
}
if (IsSliderContainer(element))
return SliderIntrinsicInlineSize(*this);
return kIndefiniteSize;
}
LayoutUnit LayoutBox::DefaultIntrinsicContentBlockSize() const {
NOT_DESTROYED();
auto effective_appearance = StyleRef().EffectiveAppearance();
if (effective_appearance == AppearanceValue::kCheckbox) {
return ThemePartIntrinsicSize(*this, WebThemeEngine::kPartCheckbox)
.block_size;
}
if (effective_appearance == AppearanceValue::kRadio) {
return ThemePartIntrinsicSize(*this, WebThemeEngine::kPartRadio).block_size;
}
if (!StyleRef().ApplyControlFixedSize(GetNode())) {
return kIndefiniteSize;
}
if (const auto* select = DynamicTo<HTMLSelectElement>(GetNode())) {
if (!select->UsesMenuList()) {
// TODO(crbug.com/357649033): Consider not doing this when in base
// appearance mode by using a presentational style for the size attribute
// instead.
return ListBoxItemBlockSize(*select, *this) * select->ListBoxSize() -
ComputeLogicalScrollbars().BlockSum();
} else if (effective_appearance != AppearanceValue::kBaseSelect) {
return MenuListIntrinsicBlockSize(*select, *this);
}
}
if (IsTextField()) {
return TextFieldIntrinsicBlockSize(*To<HTMLInputElement>(GetNode()), *this);
}
if (IsTextArea()) {
return TextAreaIntrinsicBlockSize(*To<HTMLTextAreaElement>(GetNode()),
*this);
}
return kIndefiniteSize;
}
LogicalRect LayoutBox::LogicalRectInContainer() const {
NOT_DESTROYED();
return LocationContainer()->CreateWritingModeConverter().ToLogical(
PhysicalRect(PhysicalLocation(), Size()));
}
gfx::QuadF LayoutBox::AbsoluteContentQuad(MapCoordinatesFlags flags) const {
NOT_DESTROYED();
PhysicalRect rect = PhysicalContentBoxRect();
return LocalRectToAbsoluteQuad(rect, flags);
}
PhysicalRect LayoutBox::PhysicalBackgroundRect(
BackgroundRectType rect_type) const {
NOT_DESTROYED();
// If the background transfers to view, the used background of this object
// is transparent.
if (rect_type == kBackgroundKnownOpaqueRect && BackgroundTransfersToView())
return PhysicalRect();
std::optional<EFillBox> background_box;
Color background_color = ResolveColor(GetCSSPropertyBackgroundColor());
// Find the largest background rect of the given opaqueness.
for (const FillLayer* cur = &(StyleRef().BackgroundLayers()); cur;
cur = cur->Next()) {
EFillBox current_clip = cur->Clip();
if (rect_type == kBackgroundKnownOpaqueRect) {
if (current_clip == EFillBox::kText)
continue;
if (cur->GetBlendMode() != BlendMode::kNormal ||
cur->Composite() != kCompositeSourceOver)
continue;
bool layer_known_opaque = false;
// Check if the image is opaque and fills the clip.
if (const StyleImage* image = cur->GetImage()) {
if ((cur->Repeat().x == EFillRepeat::kRepeatFill ||
cur->Repeat().x == EFillRepeat::kRoundFill) &&
(cur->Repeat().y == EFillRepeat::kRepeatFill ||
cur->Repeat().y == EFillRepeat::kRoundFill) &&
image->KnownToBeOpaque(GetDocument(), StyleRef())) {
layer_known_opaque = true;
}
}
// The background color is painted into the last layer.
if (!cur->Next() && background_color.IsOpaque()) {
layer_known_opaque = true;
}
// If neither the image nor the color are opaque then skip this layer.
if (!layer_known_opaque)
continue;
} else {
// Ignore invisible background layers for kBackgroundPaintedExtent.
DCHECK_EQ(rect_type, kBackgroundPaintedExtent);
if (!cur->GetImage() &&
(cur->Next() || background_color.IsFullyTransparent())) {
continue;
}
// A content-box clipped fill layer can be scrolled into the padding box
// of the overflow container.
if (current_clip == EFillBox::kContent &&
cur->Attachment() == EFillAttachment::kLocal) {
current_clip = EFillBox::kPadding;
}
}
// Restrict clip if attachment is local.
if (current_clip == EFillBox::kBorder &&
cur->Attachment() == EFillAttachment::kLocal)
current_clip = EFillBox::kPadding;
background_box = background_box
? EnclosingFillBox(*background_box, current_clip)
: current_clip;
}
if (!background_box)
return PhysicalRect();
if (*background_box == EFillBox::kText) {
DCHECK_NE(rect_type, kBackgroundKnownOpaqueRect);
*background_box = EFillBox::kBorder;
}
if (rect_type == kBackgroundPaintedExtent &&
*background_box == EFillBox::kBorder &&
BackgroundClipBorderBoxIsEquivalentToPaddingBox()) {
*background_box = EFillBox::kPadding;
}
switch (*background_box) {
case EFillBox::kBorder:
return PhysicalBorderBoxRect();
case EFillBox::kPadding:
return PhysicalPaddingBoxRect();
case EFillBox::kContent:
return PhysicalContentBoxRect();
default:
NOTREACHED();
}
}
void LayoutBox::AddOutlineRects(OutlineRectCollector& collector,
OutlineInfo* info,
const PhysicalOffset& additional_offset,
OutlineType) const {
NOT_DESTROYED();
collector.AddRect(PhysicalRect(additional_offset, Size()));
if (info)
*info = OutlineInfo::GetFromStyle(StyleRef());
}
bool LayoutBox::CanResize() const {
NOT_DESTROYED();
// We need a special case for <iframe> because they never have
// hasOverflowClip(). However, they do "implicitly" clip their contents, so
// we want to allow resizing them also.
return (IsScrollContainer() || IsLayoutIFrame()) && StyleRef().HasResize();
}
bool LayoutBox::HasScrollbarGutters(ScrollbarOrientation orientation) const {
NOT_DESTROYED();
if (StyleRef().IsScrollbarGutterAuto())
return false;
DCHECK(StyleRef().IsScrollbarGutterStable());
// Scrollbar-gutter propagates to the viewport
// (see:|StyleResolver::PropagateStyleToViewport|).
if (orientation == kVerticalScrollbar) {
EOverflow overflow = StyleRef().OverflowY();
return StyleRef().IsHorizontalWritingMode() &&
(overflow == EOverflow::kAuto || overflow == EOverflow::kScroll ||
overflow == EOverflow::kHidden) &&
!UsesOverlayScrollbars() &&
GetNode() != GetDocument().ViewportDefiningElement();
} else {
EOverflow overflow = StyleRef().OverflowX();
return !StyleRef().IsHorizontalWritingMode() &&
(overflow == EOverflow::kAuto || overflow == EOverflow::kScroll ||
overflow == EOverflow::kHidden) &&
!UsesOverlayScrollbars() &&
GetNode() != GetDocument().ViewportDefiningElement();
}
}
PhysicalBoxStrut LayoutBox::ComputeScrollbarsInternal(
ShouldClampToContentBox clamp_to_content_box,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior,
ShouldIncludeScrollbarGutter include_scrollbar_gutter) const {
NOT_DESTROYED();
PhysicalBoxStrut scrollbars;
PaintLayerScrollableArea* scrollable_area = GetScrollableArea();
if (include_scrollbar_gutter == kIncludeScrollbarGutter &&
HasScrollbarGutters(kVerticalScrollbar)) {
LayoutUnit gutter_size = LayoutUnit(HypotheticalScrollbarThickness(
*this, kVerticalScrollbar, /* include_overlay_thickness */ true));
if (ShouldPlaceVerticalScrollbarOnLeft()) {
scrollbars.left = gutter_size;
if (StyleRef().IsScrollbarGutterBothEdges())
scrollbars.right = gutter_size;
} else {
scrollbars.right = gutter_size;
if (StyleRef().IsScrollbarGutterBothEdges())
scrollbars.left = gutter_size;
}
} else if (scrollable_area) {
if (ShouldPlaceVerticalScrollbarOnLeft()) {
scrollbars.left = LayoutUnit(scrollable_area->VerticalScrollbarWidth(
overlay_scrollbar_clip_behavior));
} else {
scrollbars.right = LayoutUnit(scrollable_area->VerticalScrollbarWidth(
overlay_scrollbar_clip_behavior));
}
}
if (include_scrollbar_gutter == kIncludeScrollbarGutter &&
HasScrollbarGutters(kHorizontalScrollbar)) {
LayoutUnit gutter_size = LayoutUnit(
HypotheticalScrollbarThickness(*this, kHorizontalScrollbar,
/* include_overlay_thickness */ true));
scrollbars.bottom = gutter_size;
if (StyleRef().IsScrollbarGutterBothEdges())
scrollbars.top = gutter_size;
} else if (scrollable_area) {
scrollbars.bottom = LayoutUnit(scrollable_area->HorizontalScrollbarHeight(
overlay_scrollbar_clip_behavior));
}
// Use the width of the vertical scrollbar, unless it's larger than the
// logical width of the content box, in which case we'll use that instead.
// Scrollbar handling is quite bad in such situations, and this code here
// is just to make sure that left-hand scrollbars don't mess up
// scrollWidth. For the full story, visit http://crbug.com/724255.
if (scrollbars.left > 0 && clamp_to_content_box == kClampToContentBox) {
LayoutUnit max_width = Size().width - BorderAndPaddingWidth();
scrollbars.left =
std::min(scrollbars.left, max_width.ClampNegativeToZero());
}
return scrollbars;
}
void LayoutBox::Autoscroll(const PhysicalOffset& position_in_root_frame) {
NOT_DESTROYED();
LocalFrame* frame = GetFrame();
if (!frame)
return;
LocalFrameView* frame_view = frame->View();
if (!frame_view)
return;
PhysicalOffset absolute_position =
frame_view->ConvertFromRootFrame(position_in_root_frame);
mojom::blink::ScrollIntoViewParamsPtr params =
scroll_into_view_util::CreateScrollIntoViewParams(
ScrollAlignment::ToEdgeIfNeeded(), ScrollAlignment::ToEdgeIfNeeded(),
mojom::blink::ScrollType::kUser);
scroll_into_view_util::ScrollRectToVisible(
*this,
PhysicalRect(absolute_position,
PhysicalSize(LayoutUnit(1), LayoutUnit(1))),
std::move(params));
}
// If specified point is outside the border-belt-excluded box (the border box
// inset by the autoscroll activation threshold), returned offset denotes
// direction of scrolling.
PhysicalOffset LayoutBox::CalculateAutoscrollDirection(
const gfx::PointF& point_in_root_frame) const {
NOT_DESTROYED();
if (!GetFrame())
return PhysicalOffset();
LocalFrameView* frame_view = GetFrame()->View();
if (!frame_view)
return PhysicalOffset();
#if BUILDFLAG(IS_IOS)
float autoscroll_belt_size_in_viewport =
frame_view->GetChromeClient()->WindowToViewportScalar(
GetFrame(), kAutoscrollBeltSizeInDIPs);
float autoscroll_belt_size_for_bottom_in_viewport =
frame_view->GetChromeClient()->WindowToViewportScalar(
GetFrame(), kAutoscrollBeltSizeInDIPsBottom);
#else
float autoscroll_belt_size_in_viewport = kAutoscrollBeltSize;
float autoscroll_belt_size_for_bottom_in_viewport = kAutoscrollBeltSizeBottom;
#endif // BUILDFLAG(IS_IOS)
PhysicalRect absolute_scrolling_box(AbsoluteBoundingBoxRect());
// Exclude scrollbars so the border belt (activation area) starts from the
// scrollbar-content edge rather than the window edge.
ExcludeScrollbars(absolute_scrolling_box,
kExcludeOverlayScrollbarSizeForHitTesting);
PhysicalRect belt_box =
View()->GetFrameView()->ConvertToRootFrame(absolute_scrolling_box);
LayoutUnit autoscroll_belt_size_layout_unit =
LayoutUnit(autoscroll_belt_size_in_viewport);
belt_box.ContractEdges(
autoscroll_belt_size_layout_unit, autoscroll_belt_size_layout_unit,
LayoutUnit(autoscroll_belt_size_for_bottom_in_viewport),
autoscroll_belt_size_layout_unit);
gfx::PointF point = point_in_root_frame;
if (point.x() < belt_box.X())
point.Offset(-autoscroll_belt_size_in_viewport, 0);
else if (point.x() > belt_box.Right())
point.Offset(autoscroll_belt_size_in_viewport, 0);
if (point.y() < belt_box.Y())
point.Offset(0, -autoscroll_belt_size_in_viewport);
else if (point.y() > belt_box.Bottom())
point.Offset(0, autoscroll_belt_size_for_bottom_in_viewport);
return PhysicalOffset::FromVector2dFRound(point - point_in_root_frame);
}
LayoutBox* LayoutBox::FindAutoscrollable(LayoutObject* layout_object,
bool is_middle_click_autoscroll) {
while (layout_object && !(layout_object->IsBox() &&
To<LayoutBox>(layout_object)->IsUserScrollable())) {
// Do not start selection-based autoscroll when the node is inside a
// fixed-position element.
if (!is_middle_click_autoscroll && layout_object->IsBox() &&
To<LayoutBox>(layout_object)->IsFixedToView()) {
return nullptr;
}
if (!layout_object->Parent() &&
layout_object->GetNode() == layout_object->GetDocument() &&
layout_object->GetDocument().LocalOwner()) {
layout_object =
layout_object->GetDocument().LocalOwner()->GetLayoutObject();
} else {
layout_object = layout_object->Parent();
}
}
return DynamicTo<LayoutBox>(layout_object);
}
bool LayoutBox::HasHorizontallyScrollableAncestor(LayoutObject* layout_object) {
while (layout_object) {
if (layout_object->IsBox() &&
To<LayoutBox>(layout_object)->HasScrollableOverflowX())
return true;
// Scroll is not propagating.
if (layout_object->StyleRef().OverscrollBehaviorX() !=
EOverscrollBehavior::kAuto)
break;
if (!layout_object->Parent() &&
layout_object->GetNode() == layout_object->GetDocument() &&
layout_object->GetDocument().LocalOwner()) {
layout_object =
layout_object->GetDocument().LocalOwner()->GetLayoutObject();
} else {
layout_object = layout_object->Parent();
}
}
return false;
}
gfx::Vector2d LayoutBox::OriginAdjustmentForScrollbars() const {
NOT_DESTROYED();
if (CanSkipComputeScrollbars())
return gfx::Vector2d();
PhysicalBoxStrut scrollbars = ComputeScrollbarsInternal(kClampToContentBox);
return gfx::Vector2d(scrollbars.left.ToInt(), scrollbars.top.ToInt());
}
gfx::Point LayoutBox::ScrollOrigin() const {
NOT_DESTROYED();
return GetScrollableArea() ? GetScrollableArea()->ScrollOrigin()
: gfx::Point();
}
PhysicalOffset LayoutBox::ScrolledContentOffset() const {
NOT_DESTROYED();
DCHECK(IsScrollContainer());
DCHECK(GetScrollableArea());
return PhysicalOffset::FromVector2dFFloor(
GetScrollableArea()->GetScrollOffset());
}
gfx::Vector2d LayoutBox::PixelSnappedScrolledContentOffset() const {
NOT_DESTROYED();
DCHECK(IsScrollContainer());
DCHECK(GetScrollableArea());
return GetScrollableArea()->ScrollOffsetInt();
}
PhysicalRect LayoutBox::ClippingRect(const PhysicalOffset& location) const {
NOT_DESTROYED();
PhysicalRect result(InfiniteIntRect());
if (ShouldClipOverflowAlongEitherAxis())
result = OverflowClipRect(location);
if (HasClip())
result.Intersect(ClipRect(location));
return result;
}
gfx::PointF LayoutBox::PerspectiveOrigin(const PhysicalSize* size) const {
NOT_DESTROYED();
if (!HasTransformRelatedProperty())
return gfx::PointF();
// Use the |size| parameter instead of |Size()| if present.
gfx::SizeF float_size = size ? gfx::SizeF(*size) : gfx::SizeF(Size());
return PointForLengthPoint(StyleRef().PerspectiveOrigin(), float_size);
}
bool LayoutBox::MapVisualRectToContainer(
const LayoutObject* container_object,
const PhysicalOffset& container_offset,
const LayoutObject* ancestor,
VisualRectFlags visual_rect_flags,
TransformState& transform_state) const {
NOT_DESTROYED();
bool container_preserve_3d = container_object->StyleRef().Preserves3D() &&
container_object == NearestAncestorForElement();
TransformState::TransformAccumulation accumulation =
container_preserve_3d ? TransformState::kAccumulateTransform
: TransformState::kFlattenTransform;
// If there is no transform on this box, adjust for container offset and
// container scrolling, then apply container clip.
if (!ShouldUseTransformFromContainer(container_object)) {
transform_state.Move(container_offset, accumulation);
if (container_object->IsBox() && container_object != ancestor &&
!To<LayoutBox>(container_object)
->MapContentsRectToBoxSpace(transform_state, accumulation, *this,
visual_rect_flags)) {
return false;
}
return true;
}
// Otherwise, do the following:
// 1. Expand for pixel snapping.
// 2. Generate transformation matrix combining, in this order
// a) transform,
// b) container offset,
// c) container scroll offset,
// d) perspective applied by container.
// 3. Apply transform Transform+flattening.
// 4. Apply container clip.
// 1. Expand for pixel snapping.
// Use EnclosingBoundingBox because we cannot properly compute pixel
// snapping for painted elements within the transform since we don't know
// the desired subpixel accumulation at this point, and the transform may
// include a scale. This only makes sense for non-preserve3D.
//
// TODO(dbaron): Does the flattening here need to be done for the
// early return case above as well?
// (Why is this flattening needed in addition to the flattening done by
// using TransformState::kAccumulateTransform?)
if (!StyleRef().Preserves3D()) {
transform_state.Flatten();
transform_state.SetQuad(gfx::QuadF(gfx::RectF(
gfx::ToEnclosingRect(transform_state.LastPlanarQuad().BoundingBox()))));
}
// 2. Generate transformation matrix.
// a) Transform.
gfx::Transform transform;
if (Layer() && Layer()->Transform())
transform.PreConcat(Layer()->CurrentTransform());
// b) Container offset.
transform.PostTranslate(container_offset.left.ToFloat(),
container_offset.top.ToFloat());
// c) Container scroll offset.
if (container_object->IsBox() && container_object != ancestor &&
To<LayoutBox>(container_object)->ContainedContentsScroll(*this)) {
PhysicalOffset offset(
-To<LayoutBox>(container_object)->ScrolledContentOffset());
transform.PostTranslate(offset.left, offset.top);
}
bool has_perspective = container_object && container_object->HasLayer() &&
container_object->StyleRef().HasPerspective();
if (has_perspective && container_object != NearestAncestorForElement()) {
has_perspective = false;
if (StyleRef().Preserves3D() || transform.Creates3d()) {
UseCounter::Count(GetDocument(),
WebFeature::kDifferentPerspectiveCBOrParent);
}
}
// d) Perspective applied by container.
if (has_perspective) {
// Perspective on the container affects us, so we have to factor it in here.
DCHECK(container_object->HasLayer());
gfx::PointF perspective_origin;
if (const auto* container_box = DynamicTo<LayoutBox>(container_object))
perspective_origin = container_box->PerspectiveOrigin();
gfx::Transform perspective_matrix;
perspective_matrix.ApplyPerspectiveDepth(
container_object->StyleRef().UsedPerspective());
perspective_matrix.ApplyTransformOrigin(perspective_origin.x(),
perspective_origin.y(), 0);
transform = perspective_matrix * transform;
}
// 3. Apply transform and flatten.
transform_state.ApplyTransform(transform, accumulation);
if (!container_preserve_3d)
transform_state.Flatten();
// 4. Apply container clip.
if (container_object->IsBox() && container_object != ancestor &&
container_object->HasClipRelatedProperty()) {
return To<LayoutBox>(container_object)
->ApplyBoxClips(transform_state, accumulation, visual_rect_flags);
}
return true;
}
bool LayoutBox::MapContentsRectToBoxSpace(
TransformState& transform_state,
TransformState::TransformAccumulation accumulation,
const LayoutObject& contents,
VisualRectFlags visual_rect_flags) const {
NOT_DESTROYED();
if (!HasClipRelatedProperty())
return true;
if (ContainedContentsScroll(contents))
transform_state.Move(-ScrolledContentOffset());
return ApplyBoxClips(transform_state, accumulation, visual_rect_flags);
}
bool LayoutBox::ContainedContentsScroll(const LayoutObject& contents) const {
NOT_DESTROYED();
if (IsA<LayoutView>(this) &&
contents.StyleRef().GetPosition() == EPosition::kFixed) {
return false;
}
return IsScrollContainer();
}
bool LayoutBox::ApplyBoxClips(
TransformState& transform_state,
TransformState::TransformAccumulation accumulation,
VisualRectFlags visual_rect_flags) const {
NOT_DESTROYED();
// This won't work fully correctly for fixed-position elements, who should
// receive CSS clip but for whom the current object is not in the containing
// block chain.
PhysicalRect clip_rect = ClippingRect(PhysicalOffset());
transform_state.Flatten();
PhysicalRect rect(
gfx::ToEnclosingRect(transform_state.LastPlanarQuad().BoundingBox()));
bool does_intersect;
if (visual_rect_flags & kEdgeInclusive) {
does_intersect = rect.InclusiveIntersect(clip_rect);
} else {
rect.Intersect(clip_rect);
does_intersect = !rect.IsEmpty();
}
transform_state.SetQuad(gfx::QuadF(gfx::RectF(rect)));
return does_intersect;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
LayoutUnit LayoutBox::OverrideContainingBlockContentLogicalWidth() const {
NOT_DESTROYED();
DCHECK(HasOverrideContainingBlockContentLogicalWidth());
return rare_data_->override_containing_block_content_logical_width_;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
bool LayoutBox::HasOverrideContainingBlockContentLogicalWidth() const {
NOT_DESTROYED();
return rare_data_ &&
rare_data_->has_override_containing_block_content_logical_width_;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
void LayoutBox::SetOverrideContainingBlockContentLogicalWidth(
LayoutUnit logical_width) {
NOT_DESTROYED();
DCHECK_GE(logical_width, LayoutUnit(-1));
EnsureRareData().override_containing_block_content_logical_width_ =
logical_width;
EnsureRareData().has_override_containing_block_content_logical_width_ = true;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
void LayoutBox::ClearOverrideContainingBlockContentSize() {
NOT_DESTROYED();
if (!rare_data_)
return;
EnsureRareData().has_override_containing_block_content_logical_width_ = false;
}
bool LayoutBox::HitTestAllPhases(HitTestResult& result,
const HitTestLocation& hit_test_location,
const PhysicalOffset& accumulated_offset) {
NOT_DESTROYED();
if (!MayIntersect(result, hit_test_location, accumulated_offset))
return false;
return LayoutObject::HitTestAllPhases(result, hit_test_location,
accumulated_offset);
}
bool LayoutBox::HitTestOverflowControl(
HitTestResult& result,
const HitTestLocation& hit_test_location,
const PhysicalOffset& adjusted_location) const {
NOT_DESTROYED();
auto* scrollable_area = GetScrollableArea();
if (!scrollable_area)
return false;
if (!VisibleToHitTestRequest(result.GetHitTestRequest()))
return false;
PhysicalOffset local_point = hit_test_location.Point() - adjusted_location;
if (!scrollable_area->HitTestOverflowControls(result,
ToRoundedPoint(local_point)))
return false;
UpdateHitTestResult(result, local_point);
return result.AddNodeToListBasedTestResult(
NodeForHitTest(), hit_test_location) == kStopHitTesting;
}
bool LayoutBox::NodeAtPoint(HitTestResult& result,
const HitTestLocation& hit_test_location,
const PhysicalOffset& accumulated_offset,
HitTestPhase phase) {
NOT_DESTROYED();
if (!MayIntersect(result, hit_test_location, accumulated_offset))
return false;
if (phase == HitTestPhase::kForeground && !HasSelfPaintingLayer() &&
HitTestOverflowControl(result, hit_test_location, accumulated_offset))
return true;
bool skip_children = (result.GetHitTestRequest().GetStopNode() == this) ||
ChildPaintBlockedByDisplayLock();
if (!skip_children && ShouldClipOverflowAlongEitherAxis()) {
// PaintLayer::HitTestFragmentsWithPhase() checked the fragments'
// foreground rect for intersection if a layer is self painting,
// so only do the overflow clip check here for non-self-painting layers.
if (!HasSelfPaintingLayer() &&
!hit_test_location.Intersects(OverflowClipRect(
accumulated_offset, kExcludeOverlayScrollbarSizeForHitTesting))) {
skip_children = true;
}
if (!skip_children && StyleRef().HasBorderRadius()) {
PhysicalRect bounds_rect(accumulated_offset, Size());
skip_children = !hit_test_location.Intersects(
ContouredBorderGeometry::PixelSnappedContouredInnerBorder(
StyleRef(), bounds_rect));
}
}
if (!skip_children &&
HitTestChildren(result, hit_test_location, accumulated_offset, phase)) {
return true;
}
if (StyleRef().HasBorderRadius() &&
HitTestClippedOutByBorder(hit_test_location, accumulated_offset))
return false;
// Now hit test ourselves.
if (IsInSelfHitTestingPhase(phase) &&
VisibleToHitTestRequest(result.GetHitTestRequest())) {
PhysicalRect bounds_rect;
if (result.GetHitTestRequest().IsHitTestVisualOverflow()) [[unlikely]] {
bounds_rect = VisualOverflowRectIncludingFilters();
} else {
bounds_rect = PhysicalBorderBoxRect();
}
bounds_rect.Move(accumulated_offset);
if (hit_test_location.Intersects(bounds_rect)) {
UpdateHitTestResult(result,
hit_test_location.Point() - accumulated_offset);
if (result.AddNodeToListBasedTestResult(NodeForHitTest(),
hit_test_location,
bounds_rect) == kStopHitTesting)
return true;
}
}
return false;
}
bool LayoutBox::HitTestChildren(HitTestResult& result,
const HitTestLocation& hit_test_location,
const PhysicalOffset& accumulated_offset,
HitTestPhase phase) {
NOT_DESTROYED();
for (LayoutObject* child = SlowLastChild(); child;
child = child->PreviousSibling()) {
if (child->HasLayer() &&
To<LayoutBoxModelObject>(child)->Layer()->IsSelfPaintingLayer())
continue;
PhysicalOffset child_accumulated_offset = accumulated_offset;
if (auto* box = DynamicTo<LayoutBox>(child))
child_accumulated_offset += box->PhysicalLocation(this);
if (child->NodeAtPoint(result, hit_test_location, child_accumulated_offset,
phase))
return true;
}
return false;
}
bool LayoutBox::HitTestClippedOutByBorder(
const HitTestLocation& hit_test_location,
const PhysicalOffset& border_box_location) const {
NOT_DESTROYED();
PhysicalRect border_rect = PhysicalBorderBoxRect();
border_rect.Move(border_box_location);
return !hit_test_location.Intersects(
ContouredBorderGeometry::PixelSnappedContouredBorder(StyleRef(),
border_rect));
}
void LayoutBox::Paint(const PaintInfo& paint_info) const {
NOT_DESTROYED();
NOTREACHED();
}
PhysicalRect LayoutBox::BackgroundPaintedExtent() const {
NOT_DESTROYED();
return PhysicalBackgroundRect(kBackgroundPaintedExtent);
}
bool LayoutBox::BackgroundIsKnownToBeOpaqueInRect(
const PhysicalRect& local_rect) const {
NOT_DESTROYED();
// If the element has appearance, it might be painted by theme.
// We cannot be sure if theme paints the background opaque.
// In this case it is safe to not assume opaqueness.
// FIXME: May be ask theme if it paints opaque.
if (StyleRef().HasEffectiveAppearance())
return false;
// FIXME: Check the opaqueness of background images.
// FIXME: Use rounded rect if border radius is present.
if (StyleRef().HasBorderRadius())
return false;
if (HasClipPath())
return false;
if (StyleRef().HasBlendMode())
return false;
return PhysicalBackgroundRect(kBackgroundKnownOpaqueRect)
.Contains(local_rect);
}
// Note that callers are responsible for checking
// ChildPaintBlockedByDisplayLock(), since that is a property of the parent
// rather than of the child.
static bool IsCandidateForOpaquenessTest(const LayoutBox& child_box) {
// Skip all layers to simplify ForegroundIsKnownToBeOpaqueInRect(). This
// covers cases of clipped, transformed, translucent, composited, etc.
if (child_box.HasLayer())
return false;
const ComputedStyle& child_style = child_box.StyleRef();
if (child_style.Visibility() != EVisibility::kVisible ||
child_style.ShapeOutside()) {
return false;
}
if (child_box.Size().IsZero())
return false;
// A replaced element with border-radius always clips the content.
if (child_box.IsLayoutReplaced() && child_style.HasBorderRadius())
return false;
return true;
}
bool LayoutBox::ForegroundIsKnownToBeOpaqueInRect(
const PhysicalRect& local_rect,
unsigned max_depth_to_test) const {
NOT_DESTROYED();
if (!max_depth_to_test)
return false;
if (ChildPaintBlockedByDisplayLock())
return false;
for (LayoutObject* child = SlowFirstChild(); child;
child = child->NextSibling()) {
// We do not bother checking descendants of |LayoutInline|, including
// block-in-inline, because the cost of checking them overweights the
// benefits.
if (!child->IsBox())
continue;
auto* child_box = To<LayoutBox>(child);
if (!IsCandidateForOpaquenessTest(*child_box))
continue;
DCHECK(!child_box->IsPositioned());
PhysicalRect child_local_rect = local_rect;
child_local_rect.Move(-child_box->PhysicalLocation());
if (child_local_rect.Y() < 0 || child_local_rect.X() < 0) {
// If there is unobscured area above/left of a static positioned box then
// the rect is probably not covered. This can cause false-negative in
// non-horizontal-tb writing mode but is allowed.
return false;
}
if (child_local_rect.Bottom() > child_box->Size().height ||
child_local_rect.Right() > child_box->Size().width) {
continue;
}
if (RuntimeEnabledFeatures::CompositeBGColorAnimationEnabled() &&
child->Style()->HasCurrentBackgroundColorAnimation()) {
return false;
}
if (child_box->BackgroundIsKnownToBeOpaqueInRect(child_local_rect))
return true;
if (child_box->ForegroundIsKnownToBeOpaqueInRect(child_local_rect,
max_depth_to_test - 1))
return true;
}
return false;
}
DISABLE_CFI_PERF
bool LayoutBox::ComputeBackgroundIsKnownToBeObscured() const {
NOT_DESTROYED();
if (ScrollsOverflow())
return false;
// Test to see if the children trivially obscure the background.
if (!StyleRef().HasBackground())
return false;
// Root background painting is special.
if (IsA<LayoutView>(this))
return false;
if (StyleRef().BoxShadow())
return false;
if (IsFragmented()) {
// The code here doesn't really understand fragmentation, but rather works
// in the stitched-fragments coordinate system (pretending that there's no
// block fragmentation, imagining that all fragments are laid out in a tall
// continuous strip after oneanother).
return false;
}
return ForegroundIsKnownToBeOpaqueInRect(BackgroundPaintedExtent(),
kBackgroundObscurationTestMaxDepth);
}
void LayoutBox::ImageChanged(WrappedImagePtr image,
CanDeferInvalidation defer) {
NOT_DESTROYED();
bool is_box_reflect_image =
(StyleRef().BoxReflect() && StyleRef().BoxReflect()->Mask().GetImage() &&
StyleRef().BoxReflect()->Mask().GetImage()->Data() == image);
if (is_box_reflect_image && HasLayer()) {
Layer()->SetFilterOnEffectNodeDirty();
SetNeedsPaintPropertyUpdate();
}
// TODO(chrishtr): support delayed paint invalidation for animated border
// images.
if ((StyleRef().BorderImage().GetImage() &&
StyleRef().BorderImage().GetImage()->Data() == image) ||
(StyleRef().MaskBoxImage().GetImage() &&
StyleRef().MaskBoxImage().GetImage()->Data() == image) ||
is_box_reflect_image) {
SetShouldDoFullPaintInvalidationWithoutLayoutChange(
PaintInvalidationReason::kImage);
} else {
for (const FillLayer* layer = &StyleRef().MaskLayers(); layer;
layer = layer->Next()) {
if (layer->GetImage() && image == layer->GetImage()->Data()) {
SetShouldDoFullPaintInvalidationWithoutLayoutChange(
PaintInvalidationReason::kImage);
if (layer->GetImage()->IsMaskSource() && IsSVGChild()) {
// Since an invalid <mask> reference does not yield a paint property
// on SVG content (see CSSMaskPainter), we need to update paint
// properties when such a reference changes.
SetNeedsPaintPropertyUpdate();
}
break;
}
}
}
if (!BackgroundTransfersToView()) {
for (const FillLayer* layer = &StyleRef().BackgroundLayers(); layer;
layer = layer->Next()) {
if (layer->GetImage() && image == layer->GetImage()->Data()) {
bool maybe_animated =
layer->GetImage()->CachedImage() &&
layer->GetImage()->CachedImage()->GetImage() &&
layer->GetImage()->CachedImage()->GetImage()->MaybeAnimated();
if (defer == CanDeferInvalidation::kYes && maybe_animated)
SetMayNeedPaintInvalidationAnimatedBackgroundImage();
else
SetBackgroundNeedsFullPaintInvalidation();
break;
}
}
}
ShapeValue* shape_outside_value = StyleRef().ShapeOutside();
if (!GetFrameView()->IsInPerformLayout() && IsFloating() &&
shape_outside_value && shape_outside_value->GetImage() &&
shape_outside_value->GetImage()->Data() == image) {
ShapeOutsideInfo& info = ShapeOutsideInfo::EnsureInfo(*this);
if (!info.IsComputingShape()) {
info.MarkShapeAsDirty();
if (auto* containing_block = ContainingBlock()) {
containing_block->SetChildNeedsLayout();
}
}
}
}
ResourcePriority LayoutBox::ComputeResourcePriority() const {
NOT_DESTROYED();
PhysicalRect view_bounds = ViewRect();
PhysicalRect object_bounds = PhysicalContentBoxRect();
// TODO(japhet): Is this IgnoreTransforms correct? Would it be better to use
// the visual rect (which has ancestor clips and transforms applied)? Should
// we map to the top-level viewport instead of the current (sub) frame?
object_bounds.Move(LocalToAbsolutePoint(PhysicalOffset(), kIgnoreTransforms));
// The object bounds might be empty right now, so intersects will fail since
// it doesn't deal with empty rects. Use PhysicalRect::Contains in that case.
bool is_visible;
if (!object_bounds.IsEmpty())
is_visible = view_bounds.Intersects(object_bounds);
else
is_visible = view_bounds.Contains(object_bounds);
PhysicalRect screen_rect;
if (!object_bounds.IsEmpty()) {
screen_rect = view_bounds;
screen_rect.Intersect(object_bounds);
}
int screen_area = 0;
if (!screen_rect.IsEmpty() && is_visible)
screen_area = (screen_rect.Width() * screen_rect.Height()).ToInt();
return ResourcePriority(
is_visible ? ResourcePriority::kVisible : ResourcePriority::kNotVisible,
screen_area);
}
void LayoutBox::LocationChanged() {
NOT_DESTROYED();
// The location may change because of layout of other objects. Should check
// this object for paint invalidation.
if (!NeedsLayout())
SetShouldCheckForPaintInvalidation();
}
void LayoutBox::SizeChanged() {
NOT_DESTROYED();
SetScrollableAreaSizeChanged(true);
// The size may change because of layout of other objects. Should check this
// object for paint invalidation.
if (!NeedsLayout())
SetShouldCheckForPaintInvalidation();
// In flipped blocks writing mode, our children can change physical location,
// but their flipped location remains the same.
if (HasFlippedBlocksWritingMode()) {
if (ChildrenInline())
SetSubtreeShouldDoFullPaintInvalidation();
else
SetSubtreeShouldCheckForPaintInvalidation();
}
}
bool LayoutBox::IntersectsVisibleViewport() const {
NOT_DESTROYED();
LayoutView* layout_view = View();
while (auto* owner = layout_view->GetFrame()->OwnerLayoutObject()) {
layout_view = owner->View();
}
// If this is the outermost LayoutView then it will always intersect. (`rect`
// will be the viewport in that case.)
if (this == layout_view) {
return true;
}
PhysicalRect rect = VisualOverflowRect();
MapToVisualRectInAncestorSpace(layout_view, rect);
return rect.Intersects(PhysicalRect(
layout_view->GetFrameView()->GetScrollableArea()->VisibleContentRect()));
}
void LayoutBox::EnsureIsReadyForPaintInvalidation() {
NOT_DESTROYED();
LayoutBoxModelObject::EnsureIsReadyForPaintInvalidation();
bool new_obscured = ComputeBackgroundIsKnownToBeObscured();
if (BackgroundIsKnownToBeObscured() != new_obscured) {
SetBackgroundIsKnownToBeObscured(new_obscured);
SetBackgroundNeedsFullPaintInvalidation();
}
if (MayNeedPaintInvalidationAnimatedBackgroundImage() &&
!BackgroundIsKnownToBeObscured()) {
SetBackgroundNeedsFullPaintInvalidation();
SetShouldDelayFullPaintInvalidation();
}
if (ShouldDelayFullPaintInvalidation() && IntersectsVisibleViewport()) {
// Do regular full paint invalidation if the object with delayed paint
// invalidation is on screen.
ClearShouldDelayFullPaintInvalidation();
DCHECK(ShouldDoFullPaintInvalidation());
}
}
void LayoutBox::InvalidatePaint(const PaintInvalidatorContext& context) const {
NOT_DESTROYED();
BoxPaintInvalidator(*this, context).InvalidatePaint();
}
void LayoutBox::ClearPaintFlags() {
NOT_DESTROYED();
LayoutObject::ClearPaintFlags();
if (auto* scrollable_area = GetScrollableArea()) {
if (auto* scrollbar =
DynamicTo<CustomScrollbar>(scrollable_area->HorizontalScrollbar()))
scrollbar->ClearPaintFlags();
if (auto* scrollbar =
DynamicTo<CustomScrollbar>(scrollable_area->VerticalScrollbar()))
scrollbar->ClearPaintFlags();
}
}
PhysicalRect LayoutBox::OverflowClipRect(
const PhysicalOffset& location,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior) const {
NOT_DESTROYED();
PhysicalRect clip_rect;
if (IsEffectiveRootScroller()) {
// If this box is the effective root scroller, use the viewport clipping
// rect since it will account for the URL bar correctly which the border
// box does not. We can do this because the effective root scroller is
// restricted such that it exactly fills the viewport. See
// RootScrollerController::IsValidRootScroller()
clip_rect = PhysicalRect(location, View()->ViewRect().size);
} else {
clip_rect = PhysicalBorderBoxRect();
clip_rect.Contract(BorderOutsets());
clip_rect.Move(location);
// Videos need to be pre-snapped so that they line up with the
// display_rect and can enable hardware overlays.
// Embedded objects are always sized to fit the content rect, but they
// could overflow by 1px due to pre-snapping. Adjust clip rect to
// match pre-snapped box as a special case.
if (IsVideo() || IsLayoutEmbeddedContent())
clip_rect = LayoutReplaced::PreSnappedRectForPersistentSizing(clip_rect);
if (HasNonVisibleOverflow()) {
const auto overflow_clip = GetOverflowClipAxes();
if (overflow_clip != kOverflowClipBothAxis) {
ApplyVisibleOverflowToClipRect(overflow_clip, clip_rect);
} else if (ShouldApplyOverflowClipMargin()) {
switch (StyleRef().OverflowClipMargin()->GetReferenceBox()) {
case StyleOverflowClipMargin::ReferenceBox::kBorderBox:
clip_rect.Expand(BorderOutsets());
break;
case StyleOverflowClipMargin::ReferenceBox::kPaddingBox:
break;
case StyleOverflowClipMargin::ReferenceBox::kContentBox:
clip_rect.Contract(PaddingOutsets());
break;
}
clip_rect.Inflate(StyleRef().OverflowClipMargin()->GetMargin());
}
}
}
if (IsScrollContainer()) {
// The additional gutters created by scrollbar-gutter don't occlude the
// content underneath, so they should not be clipped out here.
// See https://crbug.com/710214
ExcludeScrollbars(clip_rect, overlay_scrollbar_clip_behavior,
kExcludeScrollbarGutter);
}
if (IsA<HTMLInputElement>(GetNode())) [[unlikely]] {
// We only apply a clip to <input> buttons, and not regular <button>s.
if (IsTextField() || IsInputButton()) {
DCHECK(HasControlClip());
PhysicalRect control_clip = PhysicalPaddingBoxRect();
control_clip.Move(location);
clip_rect.Intersect(control_clip);
}
} else if (IsMenuList()) [[unlikely]] {
DCHECK(HasControlClip());
PhysicalRect control_clip = PhysicalContentBoxRect();
control_clip.Move(location);
clip_rect.Intersect(control_clip);
} else {
DCHECK(!HasControlClip());
}
return clip_rect;
}
bool LayoutBox::HasControlClip() const {
NOT_DESTROYED();
if (IsTextField() || IsMenuList() || IsInputButton()) [[unlikely]] {
return true;
}
return false;
}
void LayoutBox::ExcludeScrollbars(
PhysicalRect& rect,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior,
ShouldIncludeScrollbarGutter include_scrollbar_gutter) const {
NOT_DESTROYED();
if (CanSkipComputeScrollbars())
return;
PhysicalBoxStrut scrollbars = ComputeScrollbarsInternal(
kDoNotClampToContentBox, overlay_scrollbar_clip_behavior,
include_scrollbar_gutter);
rect.offset.top += scrollbars.top;
rect.offset.left += scrollbars.left;
rect.size.width -= scrollbars.HorizontalSum();
rect.size.height -= scrollbars.VerticalSum();
rect.size.ClampNegativeToZero();
}
PhysicalRect LayoutBox::ClipRect(const PhysicalOffset& location) const {
NOT_DESTROYED();
PhysicalRect clip_rect(location, Size());
LayoutUnit width = Size().width;
LayoutUnit height = Size().height;
if (!StyleRef().ClipLeft().IsAuto()) {
LayoutUnit c = ValueForLength(StyleRef().ClipLeft(), width);
clip_rect.offset.left += c;
clip_rect.size.width -= c;
}
if (!StyleRef().ClipRight().IsAuto()) {
clip_rect.size.width -=
width - ValueForLength(StyleRef().ClipRight(), width);
}
if (!StyleRef().ClipTop().IsAuto()) {
LayoutUnit c = ValueForLength(StyleRef().ClipTop(), height);
clip_rect.offset.top += c;
clip_rect.size.height -= c;
}
if (!StyleRef().ClipBottom().IsAuto()) {
clip_rect.size.height -=
height - ValueForLength(StyleRef().ClipBottom(), height);
}
return clip_rect;
}
LayoutUnit LayoutBox::ContainingBlockLogicalHeightForRelPositioned() const {
NOT_DESTROYED();
DCHECK(IsRelPositioned());
// TODO(ikilpatrick): This is resolving percentages against incorrectly if
// the container is an inline.
auto* cb = To<LayoutBoxModelObject>(Container());
return ContainingBlockLogicalHeightForPositioned(cb) -
cb->PaddingLogicalHeight();
}
LayoutUnit LayoutBox::ContainingBlockLogicalWidthForContent() const {
NOT_DESTROYED();
if (HasOverrideContainingBlockContentLogicalWidth())
return OverrideContainingBlockContentLogicalWidth();
LayoutBlock* cb = ContainingBlock();
if (IsOutOfFlowPositioned())
return cb->ClientLogicalWidth();
return cb->AvailableLogicalWidth();
}
PhysicalOffset LayoutBox::OffsetFromContainerInternal(
const LayoutObject* o,
MapCoordinatesFlags mode) const {
NOT_DESTROYED();
DCHECK_EQ(o, Container());
PhysicalOffset offset = PhysicalLocation();
if (NeedsAnchorPositionScrollAdjustment()) {
offset += AnchorPositionScrollTranslationOffset();
}
return offset + LayoutBoxModelObject::OffsetFromContainerInternal(o, mode);
}
bool LayoutBox::HasInlineFragments() const {
NOT_DESTROYED();
return first_fragment_item_index_;
}
void LayoutBox::ClearFirstInlineFragmentItemIndex() {
NOT_DESTROYED();
CHECK(IsInLayoutNGInlineFormattingContext()) << *this;
first_fragment_item_index_ = 0u;
}
void LayoutBox::SetFirstInlineFragmentItemIndex(wtf_size_t index) {
NOT_DESTROYED();
CHECK(IsInLayoutNGInlineFormattingContext()) << *this;
DCHECK_NE(index, 0u);
first_fragment_item_index_ = index;
}
void LayoutBox::InLayoutNGInlineFormattingContextWillChange(bool new_value) {
NOT_DESTROYED();
if (IsInLayoutNGInlineFormattingContext())
ClearFirstInlineFragmentItemIndex();
}
bool LayoutBox::PhysicalFragmentList::MayHaveFragmentItems() const {
return !IsEmpty() && front().IsInlineFormattingContext();
}
bool LayoutBox::PhysicalFragmentList::SlowHasFragmentItems() const {
for (const PhysicalBoxFragment& fragment : *this) {
if (fragment.HasItems())
return true;
}
return false;
}
wtf_size_t LayoutBox::PhysicalFragmentList::IndexOf(
const PhysicalBoxFragment& fragment) const {
wtf_size_t index = 0;
for (const auto& result : layout_results_) {
if (&result->GetPhysicalFragment() == &fragment) {
return index;
}
++index;
}
return kNotFound;
}
bool LayoutBox::PhysicalFragmentList::Contains(
const PhysicalBoxFragment& fragment) const {
return IndexOf(fragment) != kNotFound;
}
void LayoutBox::AddMeasureLayoutResult(const LayoutResult* result) {
NOT_DESTROYED();
// Ensure the given result is valid for the measure cache.
if (result->Status() != LayoutResult::kSuccess) {
return;
}
if (result->GetConstraintSpaceForCaching().CacheSlot() !=
LayoutResultCacheSlot::kMeasure) {
return;
}
DCHECK(
To<PhysicalBoxFragment>(result->GetPhysicalFragment()).IsOnlyForNode());
if (!measure_cache_) {
measure_cache_ = MakeGarbageCollected<MeasureCache>();
}
// Clear out old measure results if we need non-simplifed layout.
if (NeedsLayout() && !NeedsSimplifiedLayoutOnly()) {
measure_cache_->Clear();
}
measure_cache_->Add(result);
}
void LayoutBox::SetCachedLayoutResult(const LayoutResult* result,
wtf_size_t index) {
NOT_DESTROYED();
if (result->GetConstraintSpaceForCaching().CacheSlot() ==
LayoutResultCacheSlot::kMeasure) {
DCHECK(!result->GetPhysicalFragment().GetBreakToken());
DCHECK(
To<PhysicalBoxFragment>(result->GetPhysicalFragment()).IsOnlyForNode());
DCHECK_EQ(index, 0u);
// We don't early return here, when setting the "measure" result we also
// set the "layout" result.
if (measure_cache_) {
measure_cache_->InvalidateItems();
}
AddMeasureLayoutResult(result);
if (IsTableCell()) {
To<LayoutTableCell>(this)->InvalidateLayoutResultCacheAfterMeasure();
}
} else {
// We have a "layout" result, and we may need to clear the old "measure"
// result if we needed non-simplified layout.
if (NeedsLayout() && !NeedsSimplifiedLayoutOnly()) {
if (measure_cache_) {
measure_cache_->Clear();
}
}
}
// If we're about to cache a layout result that is different than the measure
// result, mark the measure result's fragment as no longer having valid
// children. It can still be used to query information about this box's
// fragment from the measure pass, but children might be out of sync with the
// latest version of the tree.
if (measure_cache_) {
measure_cache_->SetFragmentChildrenInvalid(result);
}
SetLayoutResult(result, index);
}
void LayoutBox::SetLayoutResult(const LayoutResult* result, wtf_size_t index) {
NOT_DESTROYED();
DCHECK_EQ(result->Status(), LayoutResult::kSuccess);
const auto& box_fragment =
To<PhysicalBoxFragment>(result->GetPhysicalFragment());
if (index != WTF::kNotFound && layout_results_.size() > index) {
if (layout_results_.size() > index + 1) {
// If we have reached the end, remove surplus results from previous
// layout.
//
// Note: When an OOF is fragmented, we wait to lay it out at the
// fragmentation context root. If the OOF lives above a column spanner,
// though, we may lay it out early to make sure the OOF contributes to the
// correct column block-size. Thus, if an item broke as a result of a
// spanner, remove subsequent sibling items so that OOFs don't try to
// access old fragments.
//
// Additionally, if an outer multicol has a spanner break, we may try
// to access old fragments of the inner multicol if it hasn't completed
// layout yet. Remove subsequent multicol fragments to avoid OOFs from
// trying to access old fragments.
//
// TODO(layout-dev): Other solutions to handling interactions between OOFs
// and spanner breaks may need to be considered.
if (!box_fragment.GetBreakToken() ||
box_fragment.GetBreakToken()->IsCausedByColumnSpanner() ||
box_fragment.IsFragmentationContextRoot()) {
// Before forgetting any old fragments and their items, we need to clear
// associations.
if (box_fragment.IsInlineFormattingContext())
FragmentItems::ClearAssociatedFragments(this);
ShrinkLayoutResults(index + 1);
}
}
ReplaceLayoutResult(std::move(result), index);
return;
}
DCHECK(index == layout_results_.size() || index == kNotFound);
AppendLayoutResult(result);
if (!box_fragment.GetBreakToken()) {
FinalizeLayoutResults();
}
}
void LayoutBox::AppendLayoutResult(const LayoutResult* result) {
NOT_DESTROYED();
const auto& fragment = To<PhysicalBoxFragment>(result->GetPhysicalFragment());
// |layout_results_| is particularly critical when side effects are disabled.
DCHECK(!DisableLayoutSideEffectsScope::IsDisabled());
layout_results_.push_back(std::move(result));
InvalidateCachedGeometry();
CheckDidAddFragment(*this, fragment);
}
void LayoutBox::ReplaceLayoutResult(const LayoutResult* result,
wtf_size_t index) {
NOT_DESTROYED();
DCHECK_LE(index, layout_results_.size());
const LayoutResult* old_result = layout_results_[index];
if (old_result == result)
return;
const auto& fragment = To<PhysicalBoxFragment>(result->GetPhysicalFragment());
const auto& old_fragment = old_result->GetPhysicalFragment();
bool got_new_fragment = &old_fragment != &fragment;
if (got_new_fragment) {
if (HasFragmentItems()) {
if (!index)
InvalidateItems(*old_result);
FragmentItems::ClearAssociatedFragments(this);
}
// We are about to replace a fragment, and the size may have changed. The
// inline-size and total stitched block-size may still remain unchanged,
// though, and pre-paint can only detect changes in the total stitched
// size. So this is our last chance to detect any size changes at the
// fragment itself. Only do this if we're fragmented, though. Otherwise
// leave it to pre-paint to figure out if invalidation is really required,
// since it's fine to just check the stitched sizes when not fragmented.
// Unconditionally requiring full paint invalidation at size changes may be
// unnecessary and expensive.
if (layout_results_.size() > 1 && fragment.Size() != old_fragment.Size()) {
SetShouldDoFullPaintInvalidation();
}
}
// |layout_results_| is particularly critical when side effects are disabled.
DCHECK(!DisableLayoutSideEffectsScope::IsDisabled());
layout_results_[index] = std::move(result);
InvalidateCachedGeometry();
CheckDidAddFragment(*this, fragment, index);
if (got_new_fragment && !fragment.GetBreakToken()) {
// If this is the last result, the results vector better agree on that.
DCHECK_EQ(index, layout_results_.size() - 1);
FinalizeLayoutResults();
}
}
void LayoutBox::FinalizeLayoutResults() {
NOT_DESTROYED();
DCHECK(!layout_results_.empty());
DCHECK(!layout_results_.back()->GetPhysicalFragment().GetBreakToken());
#if EXPENSIVE_DCHECKS_ARE_ON()
CheckMayHaveFragmentItems();
#endif
// If we've added all the results we were going to, and the node establishes
// an inline formatting context, we have some finalization to do.
if (HasFragmentItems()) {
FragmentItems::FinalizeAfterLayout(layout_results_,
*To<LayoutBlockFlow>(this));
}
}
void LayoutBox::RebuildFragmentTreeSpine() {
NOT_DESTROYED();
DCHECK(PhysicalFragmentCount());
// If this box has an associated layout-result, rebuild the spine of the
// fragment-tree to ensure consistency.
LayoutBox* container = this;
while (container && container->PhysicalFragmentCount() &&
!container->NeedsLayout()) {
for (auto& result : container->layout_results_)
result = LayoutResult::CloneWithPostLayoutFragments(*result);
if (MeasureCache* measure_cache = container->measure_cache_) {
// In case any of the now-replaced cached results above were in fact
// measure-results (see how SetCachedLayoutResult() may write into both
// the measure cache and the layout results vector), the measure results
// are now outdated. Remove them.
measure_cache->Clear();
}
container = container->ContainingNGBox();
}
if (container && container->NeedsLayout()) {
// We stopped walking upwards because this container needs layout. This
// typically means that updating the associated layout results is waste of
// time, since we're probably going to lay it out anyway. However, in some
// cases the container is going to hit the cache and therefore not perform
// actual layout. If this happens, we need to update the layout results at
// that point.
container->SetHasBrokenSpine();
}
}
void LayoutBox::ShrinkLayoutResults(wtf_size_t results_to_keep) {
NOT_DESTROYED();
DCHECK_GE(layout_results_.size(), results_to_keep);
// Invalidate if inline |DisplayItemClient|s will be destroyed.
for (wtf_size_t i = results_to_keep; i < layout_results_.size(); i++)
InvalidateItems(*layout_results_[i]);
// |layout_results_| is particularly critical when side effects are disabled.
DCHECK(!DisableLayoutSideEffectsScope::IsDisabled());
layout_results_.Shrink(results_to_keep);
InvalidateCachedGeometry();
}
#if EXPENSIVE_DCHECKS_ARE_ON()
void LayoutBox::CheckMayHaveFragmentItems() const {
NOT_DESTROYED();
if (!MayHaveFragmentItems()) {
DCHECK(!PhysicalFragments().SlowHasFragmentItems());
}
}
#endif
void LayoutBox::InvalidateCachedGeometry() {
NOT_DESTROYED();
SetHasValidCachedGeometry(false);
if (auto* block_flow = DynamicTo<LayoutBlockFlow>(this)) {
if (auto* flow_thread = block_flow->MultiColumnFlowThread()) {
flow_thread->SetHasValidCachedGeometry(false);
for (auto* sibling = flow_thread->NextSiblingBox(); sibling;
sibling = sibling->NextSiblingBox()) {
sibling->SetHasValidCachedGeometry(false);
}
}
}
}
// static
void LayoutBox::InvalidateItems(const LayoutResult& result) {
// Invalidate if inline |DisplayItemClient|s will be destroyed.
const auto& box_fragment =
To<PhysicalBoxFragment>(result.GetPhysicalFragment());
if (!box_fragment.HasItems())
return;
ObjectPaintInvalidator(*box_fragment.GetLayoutObject())
.SlowSetPaintingLayerNeedsRepaint();
}
const LayoutResult* LayoutBox::GetCachedLayoutResult(
const BlockBreakToken* break_token) const {
NOT_DESTROYED();
wtf_size_t index = FragmentIndex(break_token);
if (index >= layout_results_.size())
return nullptr;
const LayoutResult* result = layout_results_[index];
DCHECK(!result->GetPhysicalFragment().IsLayoutObjectDestroyedOrMoved() ||
BeingDestroyed());
return result;
}
const LayoutResult* LayoutBox::GetCachedMeasureResult(
const ConstraintSpace& space,
std::optional<FragmentGeometry>* fragment_geometry) const {
NOT_DESTROYED();
if (!measure_cache_) {
return nullptr;
}
// If we've already had an actual layout pass, and the node fragmented, we
// cannot reliably re-use the measure result. What we want to avoid here is
// simplified layout inside a measure-result, as that would descend into a
// fragment subtree generated by actual (fragmented) layout, which is
// invalid. But it seems safer to stop such attempts here, so that we don't
// hand out results that may cause problems if we end up with simplified
// layout inside.
if (!layout_results_.empty()) {
const PhysicalBoxFragment* first_fragment = GetPhysicalFragment(0);
if (first_fragment->GetBreakToken()) {
return nullptr;
}
}
return measure_cache_
? measure_cache_->Find(BlockNode(const_cast<LayoutBox*>(this)),
space, fragment_geometry)
: nullptr;
}
const LayoutResult* LayoutBox::GetSingleCachedLayoutResult() const {
DCHECK_LE(layout_results_.size(), 1u);
return GetCachedLayoutResult(nullptr);
}
const LayoutResult* LayoutBox::GetSingleCachedMeasureResultForTesting() const {
NOT_DESTROYED();
return measure_cache_ ? measure_cache_->GetLastForTesting() : nullptr;
}
const LayoutResult* LayoutBox::GetLayoutResult(wtf_size_t i) const {
NOT_DESTROYED();
return layout_results_[i].Get();
}
const PhysicalBoxFragment&
LayoutBox::PhysicalFragmentList::Iterator::operator*() const {
return To<PhysicalBoxFragment>((*iterator_)->GetPhysicalFragment());
}
const PhysicalBoxFragment& LayoutBox::PhysicalFragmentList::front() const {
return To<PhysicalBoxFragment>(
layout_results_.front()->GetPhysicalFragment());
}
const PhysicalBoxFragment& LayoutBox::PhysicalFragmentList::back() const {
return To<PhysicalBoxFragment>(layout_results_.back()->GetPhysicalFragment());
}
const FragmentData* LayoutBox::FragmentDataFromPhysicalFragment(
const PhysicalBoxFragment& physical_fragment) const {
NOT_DESTROYED();
return &FragmentList().at(BoxFragmentIndex(physical_fragment));
}
void LayoutBox::SetSpannerPlaceholder(
LayoutMultiColumnSpannerPlaceholder& placeholder) {
NOT_DESTROYED();
// Not expected to change directly from one spanner to another.
CHECK(!rare_data_ || !rare_data_->spanner_placeholder_);
EnsureRareData().spanner_placeholder_ = &placeholder;
}
void LayoutBox::ClearSpannerPlaceholder() {
NOT_DESTROYED();
if (!rare_data_)
return;
rare_data_->spanner_placeholder_ = nullptr;
}
bool LayoutBox::IsValidColumnSpanner() const {
NOT_DESTROYED();
// Note that this function may be called in many circumstances, such as before
// it is inserted into the tree, and even as part of calculating the
// containing block. Be careful.
DCHECK_EQ(StyleRef().GetColumnSpan(), EColumnSpan::kAll);
if (!RuntimeEnabledFeatures::FlowThreadLessEnabled()) {
return SpannerPlaceholder();
}
if (!Parent() || !IsInsideMulticol()) {
return false;
}
// The spec says that column-span only applies to in-flow block-level
// elements.
if (ShouldBeHandledAsInline() || ShouldBeHandledAsFloating() ||
ToPositionedState() == kIsOutOfFlowPositioned) {
return false;
}
// This looks like a spanner, but if we're inside something unbreakable or
// something that establishes a new formatting context, it's not to be treated
// as one.
for (const LayoutBox* ancestor = Parent()->EnclosingBox(); ancestor;
ancestor = ancestor->ContainingBlock()) {
if (ancestor->IsMulticolContainer()) {
return true;
}
const auto* ancestor_block_flow = DynamicTo<LayoutBlockFlow>(ancestor);
if (!ancestor_block_flow) {
// Needs to be in a block-flow container, and not e.g. a table.
return false;
}
// Make sure that there's nothing about this ancestor that prevents `this`
// from becoming a column spanner. We require the ancestor to participate in
// the block formatting context established by the multicol container
// (i.e. that there are no formatting contexts in-between). Transforms are
// also forbidden, since they insist on being in the containing block chain
// for everything inside, which will easily conflict with a spanners's need
// to have the multicol container as its direct containing block.
if (ancestor_block_flow->IsMonolithic() ||
ancestor_block_flow->CreatesNewFormattingContext() ||
ancestor_block_flow->CanContainFixedPositionObjects()) {
return false;
}
DCHECK(!ancestor->IsColumnSpanAll());
}
return false;
}
void LayoutBox::InflateVisualRectForFilterUnderContainer(
TransformState& transform_state,
const LayoutObject& container,
const LayoutBoxModelObject* ancestor_to_stop_at) const {
NOT_DESTROYED();
transform_state.Flatten();
// Apply visual overflow caused by reflections and filters defined on objects
// between this object and container (not included) or ancestorToStopAt
// (included).
PhysicalOffset offset_from_container = OffsetFromContainer(&container);
transform_state.Move(offset_from_container);
for (LayoutObject* parent = Parent(); parent && parent != container;
parent = parent->Parent()) {
if (parent->IsBox()) {
// Convert rect into coordinate space of parent to apply parent's
// reflection and filter.
PhysicalOffset parent_offset = parent->OffsetFromAncestor(&container);
transform_state.Move(-parent_offset);
To<LayoutBox>(parent)->InflateVisualRectForFilter(transform_state);
transform_state.Move(parent_offset);
}
if (parent == ancestor_to_stop_at)
break;
}
transform_state.Move(-offset_from_container);
}
bool LayoutBox::MapToVisualRectInAncestorSpaceInternal(
const LayoutBoxModelObject* ancestor,
TransformState& transform_state,
VisualRectFlags visual_rect_flags) const {
NOT_DESTROYED();
if (ancestor == this)
return true;
if (!(visual_rect_flags & kIgnoreFilters)) {
InflateVisualRectForFilter(transform_state);
}
AncestorSkipInfo skip_info(ancestor, true);
LayoutObject* container = Container(&skip_info);
if (!container)
return true;
PhysicalOffset container_offset;
if (auto* box = DynamicTo<LayoutBox>(container)) {
container_offset += PhysicalLocation(box);
} else {
container_offset += PhysicalLocation();
}
if (IsStickyPositioned()) {
container_offset += StickyPositionOffset();
} else if (NeedsAnchorPositionScrollAdjustment()) [[unlikely]] {
container_offset += AnchorPositionScrollTranslationOffset();
}
if (skip_info.FilterSkipped() && !(visual_rect_flags & kIgnoreFilters)) {
InflateVisualRectForFilterUnderContainer(transform_state, *container,
ancestor);
}
if (!MapVisualRectToContainer(container, container_offset, ancestor,
visual_rect_flags, transform_state))
return false;
if (skip_info.AncestorSkipped()) {
bool preserve3D = container->StyleRef().Preserves3D();
TransformState::TransformAccumulation accumulation =
preserve3D ? TransformState::kAccumulateTransform
: TransformState::kFlattenTransform;
// If the ancestor is below the container, then we need to map the rect into
// ancestor's coordinates.
PhysicalOffset ancestor_container_offset =
ancestor->OffsetFromAncestor(container);
transform_state.Move(-ancestor_container_offset, accumulation);
return true;
}
if (IsFixedPositioned() && container == ancestor && container->IsLayoutView())
transform_state.Move(To<LayoutView>(container)->OffsetForFixedPosition());
return container->MapToVisualRectInAncestorSpaceInternal(
ancestor, transform_state, visual_rect_flags);
}
void LayoutBox::InflateVisualRectForFilter(
TransformState& transform_state) const {
NOT_DESTROYED();
if (!Layer() || !Layer()->PaintsWithFilters())
return;
transform_state.Flatten();
PhysicalRect rect = PhysicalRect::EnclosingRect(
transform_state.LastPlanarQuad().BoundingBox());
transform_state.SetQuad(
gfx::QuadF(gfx::RectF(Layer()->MapRectForFilter(rect))));
}
LayoutUnit LayoutBox::ContainingBlockLogicalHeightForPositioned(
const LayoutBoxModelObject* containing_block) const {
NOT_DESTROYED();
// Use viewport as container for top-level fixed-position elements.
const auto* view = DynamicTo<LayoutView>(containing_block);
if (StyleRef().GetPosition() == EPosition::kFixed && view &&
!GetDocument().Printing()) {
if (LocalFrameView* frame_view = view->GetFrameView()) {
// Don't use visibleContentRect since the PaintLayer's size has not been
// set yet.
gfx::Size viewport_size =
frame_view->LayoutViewport()->ExcludeScrollbars(frame_view->Size());
return LayoutUnit(containing_block->IsHorizontalWritingMode()
? viewport_size.height()
: viewport_size.width());
}
}
if (containing_block->IsBox())
return To<LayoutBox>(containing_block)->ClientLogicalHeight();
DCHECK(containing_block->IsLayoutInline());
DCHECK(containing_block->CanContainOutOfFlowPositionedElement(
StyleRef().GetPosition()));
const auto* flow = To<LayoutInline>(containing_block);
// If the containing block is empty, return a height of 0.
if (!flow->HasInlineFragments())
return LayoutUnit();
LayoutUnit height_result;
auto bounding_box_size = flow->PhysicalLinesBoundingBox().size;
if (containing_block->IsHorizontalWritingMode())
height_result = bounding_box_size.height;
else
height_result = bounding_box_size.width;
height_result -= (containing_block->BorderBlockStart() +
containing_block->BorderBlockEnd());
return height_result;
}
PhysicalRect LayoutBox::LocalCaretRect(int caret_offset) const {
NOT_DESTROYED();
// VisiblePositions at offsets inside containers either a) refer to the
// positions before/after those containers (tables and select elements) or
// b) refer to the position inside an empty block.
// They never refer to children.
// FIXME: Paint the carets inside empty blocks differently than the carets
// before/after elements.
LayoutUnit caret_width = GetFrameView()->CaretWidth();
LogicalSize size(LogicalWidth(), LogicalHeight());
LayoutUnit caret_block_size = size.block_size;
// If height of box is smaller than font height, use the latter one,
// otherwise the caret might become invisible.
//
// Also, if the box is not an atomic inline-level element, always use the font
// height. This prevents the "big caret" bug described in:
// <rdar://problem/3777804> Deleting all content in a document can result in
// giant tall-as-window insertion point
//
// FIXME: ignoring :first-line, missing good reason to take care of
const SimpleFontData* font_data = StyleRef().GetFont()->PrimaryFont();
LayoutUnit font_height =
LayoutUnit(font_data ? font_data->GetFontMetrics().Height() : 0);
if (font_height > size.block_size || (!IsAtomicInlineLevel() && !IsTable())) {
caret_block_size = font_height;
}
// FIXME: Border/padding should be added for all elements but this workaround
// is needed because we use offsets inside an "atomic" element to represent
// positions before and after the element in deprecated editing offsets.
bool apply_border_padding =
GetNode() &&
!(EditingIgnoresContent(*GetNode()) || IsDisplayInsideTable(GetNode()));
WritingDirectionMode writing_direction = Style()->GetWritingDirection();
LogicalOffset offset;
LayoutUnit content_inline_size = size.inline_size;
if (apply_border_padding) {
BoxStrut border_padding = (BorderOutsets() + PaddingOutsets())
.ConvertToLogical(writing_direction);
offset.inline_offset = border_padding.inline_start;
offset.block_offset = border_padding.block_start;
content_inline_size -= border_padding.InlineSum();
}
if (caret_offset) {
offset.inline_offset += content_inline_size - caret_width;
}
LogicalRect rect(offset, LogicalSize(caret_width, caret_block_size));
return WritingModeConverter(writing_direction, Size()).ToPhysical(rect);
}
PositionWithAffinity LayoutBox::PositionForPointInFragments(
const PhysicalOffset& target) const {
NOT_DESTROYED();
DCHECK_GE(GetDocument().Lifecycle().GetState(),
DocumentLifecycle::kPrePaintClean);
DCHECK_GT(PhysicalFragmentCount(), 0u);
if (PhysicalFragmentCount() == 1) {
const PhysicalBoxFragment* fragment = GetPhysicalFragment(0);
return fragment->PositionForPoint(target);
}
// When |this| is block fragmented, find the closest fragment.
const PhysicalBoxFragment* closest_fragment = nullptr;
PhysicalOffset closest_fragment_offset;
LayoutUnit shortest_square_distance = LayoutUnit::Max();
for (const PhysicalBoxFragment& fragment : PhysicalFragments()) {
// If |fragment| contains |target|, call its |PositionForPoint|.
const PhysicalOffset fragment_offset = fragment.OffsetFromOwnerLayoutBox();
const PhysicalSize distance =
PhysicalRect(fragment_offset, fragment.Size()).DistanceAsSize(target);
if (distance.IsZero())
return fragment.PositionForPoint(target - fragment_offset);
// Otherwise find the closest fragment.
const LayoutUnit square_distance =
distance.width * distance.width + distance.height * distance.height;
if (square_distance < shortest_square_distance || !closest_fragment) {
shortest_square_distance = square_distance;
closest_fragment = &fragment;
closest_fragment_offset = fragment_offset;
}
}
DCHECK(closest_fragment);
return closest_fragment->PositionForPoint(target - closest_fragment_offset);
}
DISABLE_CFI_PERF
bool LayoutBox::ShouldBeConsideredAsReplaced() const {
NOT_DESTROYED();
if (IsAtomicInlineLevel())
return true;
// We need to detect all types of objects that should be treated as replaced.
// Callers of this method will use the result for various things, such as
// determining how to size the object, or whether it needs to avoid adjacent
// floats, just like objects that establish a new formatting context.
// IsAtomicInlineLevel() will not catch all the cases. Objects may be
// block-level and still replaced, and we cannot deduce this from the
// LayoutObject type. Checkboxes and radio buttons are such examples. We need
// to check the Element type. This also applies to images, since we may have
// created a block-flow LayoutObject for the ALT text (which still counts as
// replaced).
auto* element = DynamicTo<Element>(GetNode());
if (!element)
return false;
if (element->IsFormControlElement()) {
// Form control elements are generally replaced objects. Fieldsets are not,
// though. A fieldset is (almost) a regular block container, and should be
// treated as such.
return !IsA<HTMLFieldSetElement>(element);
}
return IsA<HTMLImageElement>(element);
}
// Children of LayoutCustom object's are only considered "items" when it has a
// loaded algorithm.
bool LayoutBox::IsCustomItem() const {
NOT_DESTROYED();
auto* parent_layout_box = DynamicTo<LayoutCustom>(Parent());
return parent_layout_box && parent_layout_box->IsLoaded();
}
PhysicalBoxStrut LayoutBox::ComputeVisualEffectOverflowOutsets() {
NOT_DESTROYED();
const ComputedStyle& style = StyleRef();
DCHECK(style.HasVisualOverflowingEffect());
PhysicalBoxStrut outsets = style.BoxDecorationOutsets();
if (style.HasOutline()) {
OutlineInfo info;
Vector<PhysicalRect> outline_rects =
OutlineRects(&info, PhysicalOffset(),
style.OutlineRectsShouldIncludeBlockInkOverflow());
PhysicalRect rect = UnionRect(outline_rects);
bool outline_affected = rect.size != Size();
SetOutlineMayBeAffectedByDescendants(outline_affected);
rect.Inflate(LayoutUnit(OutlinePainter::OutlineOutsetExtent(style, info)));
outsets.Unite(PhysicalBoxStrut(-rect.Y(), rect.Right() - Size().width,
rect.Bottom() - Size().height, -rect.X()));
}
return outsets;
}
bool LayoutBox::HasTopOverflow() const {
NOT_DESTROYED();
// Early-return for the major case.
if (IsHorizontalWritingMode()) {
return false;
}
switch (StyleRef().GetWritingMode()) {
case WritingMode::kHorizontalTb:
return false;
case WritingMode::kSidewaysLr:
return StyleRef().IsLeftToRightDirection();
case WritingMode::kVerticalLr:
case WritingMode::kVerticalRl:
case WritingMode::kSidewaysRl:
return !StyleRef().IsLeftToRightDirection();
}
}
bool LayoutBox::HasLeftOverflow() const {
NOT_DESTROYED();
// Early-return for the major case.
if (IsHorizontalWritingMode()) {
return !StyleRef().IsLeftToRightDirection();
}
switch (StyleRef().GetWritingMode()) {
case WritingMode::kHorizontalTb:
return !StyleRef().IsLeftToRightDirection();
case WritingMode::kVerticalLr:
case WritingMode::kSidewaysLr:
return false;
case WritingMode::kVerticalRl:
case WritingMode::kSidewaysRl:
return true;
}
}
void LayoutBox::SetScrollableOverflowFromLayoutResults() {
NOT_DESTROYED();
ClearSelfNeedsScrollableOverflowRecalc();
ClearChildNeedsScrollableOverflowRecalc();
if (overflow_) {
overflow_->scrollable_overflow.reset();
}
if (IsLayoutReplaced()) {
return;
}
const WritingMode writing_mode = StyleRef().GetWritingMode();
std::optional<PhysicalRect> scrollable_overflow;
LayoutUnit consumed_block_size;
LayoutUnit fragment_width_sum;
// Iterate over all the fragments and unite their individual
// scrollable-overflow to determine the final scrollable-overflow.
for (const auto& layout_result : layout_results_) {
const auto& fragment =
To<PhysicalBoxFragment>(layout_result->GetPhysicalFragment());
// In order to correctly unite the overflow, we need to shift an individual
// fragment's scrollable-overflow by previously consumed block-size so far.
PhysicalOffset offset_adjust;
switch (writing_mode) {
case WritingMode::kHorizontalTb:
offset_adjust = {LayoutUnit(), consumed_block_size};
break;
case WritingMode::kVerticalRl:
case WritingMode::kSidewaysRl:
// For flipped-blocks writing-modes, we build the total overflow rect
// from right-to-left (adding with negative offsets). At the end we
// need to make the origin relative to the LHS, so we add the total
// fragment width.
fragment_width_sum += fragment.Size().width;
offset_adjust = {-fragment.Size().width - consumed_block_size,
LayoutUnit()};
break;
case WritingMode::kVerticalLr:
case WritingMode::kSidewaysLr:
offset_adjust = {consumed_block_size, LayoutUnit()};
break;
default:
NOTREACHED();
}
PhysicalRect fragment_scrollable_overflow = fragment.ScrollableOverflow();
fragment_scrollable_overflow.offset += offset_adjust;
// If we are the first fragment just set the scrollable-overflow.
if (!scrollable_overflow) {
scrollable_overflow = fragment_scrollable_overflow;
} else {
scrollable_overflow->UniteEvenIfEmpty(fragment_scrollable_overflow);
}
if (const auto* break_token = fragment.GetBreakToken()) {
// The legacy engine doesn't understand our concept of repeated
// fragments. Stop now. The overflow rectangle will represent the
// fragment(s) generated under the first repeated root.
if (break_token->IsRepeated())
break;
consumed_block_size = break_token->ConsumedBlockSize();
}
}
if (!scrollable_overflow) {
return;
}
if (IsFlippedBlocksWritingMode(writing_mode)) {
scrollable_overflow->offset.left += fragment_width_sum;
}
if (scrollable_overflow->IsEmpty() ||
PhysicalPaddingBoxRect().Contains(*scrollable_overflow)) {
return;
}
DCHECK(!ScrollableOverflowIsSet());
if (!overflow_)
overflow_ = MakeGarbageCollected<BoxOverflowModel>();
overflow_->scrollable_overflow.emplace(*scrollable_overflow);
}
RecalcScrollableOverflowResult LayoutBox::RecalcScrollableOverflowNG() {
NOT_DESTROYED();
RecalcScrollableOverflowResult child_result;
// Don't attempt to rebuild the fragment tree or recalculate
// scrollable-overflow, layout will do this for us.
if (NeedsLayout())
return RecalcScrollableOverflowResult();
if (ChildNeedsScrollableOverflowRecalc()) {
child_result = RecalcChildScrollableOverflowNG();
}
bool should_recalculate_scrollable_overflow =
SelfNeedsScrollableOverflowRecalc() ||
child_result.scrollable_overflow_changed;
bool rebuild_fragment_tree = child_result.rebuild_fragment_tree;
bool scrollable_overflow_changed = false;
if (rebuild_fragment_tree || should_recalculate_scrollable_overflow) {
for (auto& layout_result : layout_results_) {
const auto& fragment =
To<PhysicalBoxFragment>(layout_result->GetPhysicalFragment());
std::optional<PhysicalRect> scrollable_overflow;
// Recalculate our scrollable-overflow if a child had its
// scrollable-overflow changed, or if we are marked as dirty.
if (should_recalculate_scrollable_overflow) {
const PhysicalRect old_scrollable_overflow =
fragment.ScrollableOverflow();
const bool has_block_fragmentation =
layout_result->GetConstraintSpaceForCaching()
.HasBlockFragmentation();
#if DCHECK_IS_ON()
PhysicalBoxFragment::AllowPostLayoutScope allow_post_layout_scope;
#endif
const PhysicalRect new_scrollable_overflow =
ScrollableOverflowCalculator::
RecalculateScrollableOverflowForFragment(
fragment, has_block_fragmentation);
// Set the appropriate flags if the scrollable-overflow changed.
if (old_scrollable_overflow != new_scrollable_overflow) {
scrollable_overflow = new_scrollable_overflow;
scrollable_overflow_changed = true;
rebuild_fragment_tree = true;
}
}
if (scrollable_overflow) {
fragment.GetMutableForStyleRecalc().SetScrollableOverflow(
*scrollable_overflow);
}
}
SetScrollableOverflowFromLayoutResults();
}
if (scrollable_overflow_changed && IsScrollContainer()) {
Layer()->GetScrollableArea()->UpdateAfterOverflowRecalc();
}
// Only indicate to our parent that our scrollable overflow changed if we
// have:
// - No layout containment applied.
// - No clipping (in both axes).
scrollable_overflow_changed = scrollable_overflow_changed &&
!ShouldApplyLayoutContainment() &&
!ShouldClipOverflowAlongBothAxis();
return {scrollable_overflow_changed, rebuild_fragment_tree};
}
RecalcScrollableOverflowResult LayoutBox::RecalcChildScrollableOverflowNG() {
NOT_DESTROYED();
DCHECK(ChildNeedsScrollableOverflowRecalc());
ClearChildNeedsScrollableOverflowRecalc();
#if DCHECK_IS_ON()
// We use PostLayout methods to navigate the fragment tree and reach the
// corresponding LayoutObjects, so we need to use AllowPostLayoutScope here.
PhysicalBoxFragment::AllowPostLayoutScope allow_post_layout_scope;
#endif
RecalcScrollableOverflowResult result;
for (auto& layout_result : layout_results_) {
const auto& fragment =
To<PhysicalBoxFragment>(layout_result->GetPhysicalFragment());
if (fragment.HasItems()) {
for (InlineCursor cursor(fragment); cursor; cursor.MoveToNext()) {
const PhysicalBoxFragment* child =
cursor.Current()->PostLayoutBoxFragment();
if (!child || !child->GetLayoutObject()->IsBox())
continue;
result.Unite(
child->MutableOwnerLayoutBox()->RecalcScrollableOverflow());
}
}
RecalcFragmentScrollableOverflow(result, fragment);
}
return result;
}
void LayoutBox::AddSelfVisualOverflow(const PhysicalRect& rect) {
NOT_DESTROYED();
if (rect.IsEmpty())
return;
PhysicalRect border_box = PhysicalBorderBoxRect();
if (border_box.Contains(rect))
return;
if (!VisualOverflowIsSet()) {
if (!overflow_)
overflow_ = MakeGarbageCollected<BoxOverflowModel>();
overflow_->visual_overflow.emplace(border_box);
}
overflow_->visual_overflow->AddSelfVisualOverflow(rect);
}
void LayoutBox::AddContentsVisualOverflow(const PhysicalRect& rect) {
NOT_DESTROYED();
if (rect.IsEmpty())
return;
// If hasOverflowClip() we always save contents visual overflow because we
// need it
// e.g. to determine whether to apply rounded corner clip on contents.
// Otherwise we save contents visual overflow only if it overflows the border
// box.
PhysicalRect border_box = PhysicalBorderBoxRect();
if (!HasNonVisibleOverflow() && border_box.Contains(rect))
return;
if (!VisualOverflowIsSet()) {
if (!overflow_)
overflow_ = MakeGarbageCollected<BoxOverflowModel>();
overflow_->visual_overflow.emplace(border_box);
}
overflow_->visual_overflow->AddContentsVisualOverflow(rect);
}
void LayoutBox::UpdateHasSubpixelVisualEffectOutsets(
const PhysicalBoxStrut& outsets) {
NOT_DESTROYED();
if (!VisualOverflowIsSet()) {
return;
}
overflow_->visual_overflow->SetHasSubpixelVisualEffectOutsets(
!outsets.top.IsInteger() || !outsets.right.IsInteger() ||
!outsets.bottom.IsInteger() || !outsets.left.IsInteger());
}
void LayoutBox::SetVisualOverflow(const PhysicalRect& self,
const PhysicalRect& contents) {
NOT_DESTROYED();
ClearVisualOverflow();
AddSelfVisualOverflow(self);
AddContentsVisualOverflow(contents);
if (!VisualOverflowIsSet())
return;
const PhysicalRect overflow_rect =
overflow_->visual_overflow->SelfVisualOverflowRect();
const PhysicalSize box_size = Size();
const PhysicalBoxStrut outsets(
-overflow_rect.Y(), overflow_rect.Right() - box_size.width,
overflow_rect.Bottom() - box_size.height, -overflow_rect.X());
UpdateHasSubpixelVisualEffectOutsets(outsets);
// |OutlineMayBeAffectedByDescendants| is set whenever outline style
// changes. Update to the actual value here.
const ComputedStyle& style = StyleRef();
if (style.HasOutline()) {
const LayoutUnit outline_extent(OutlinePainter::OutlineOutsetExtent(
style, OutlineInfo::GetFromStyle(style)));
SetOutlineMayBeAffectedByDescendants(
outsets.top != outline_extent || outsets.right != outline_extent ||
outsets.bottom != outline_extent || outsets.left != outline_extent);
}
}
void LayoutBox::ClearVisualOverflow() {
NOT_DESTROYED();
if (overflow_)
overflow_->visual_overflow.reset();
// overflow_ will be reset by MutableForPainting::ClearPreviousOverflowData()
// if we don't need it to store previous overflow data.
}
bool LayoutBox::CanUseFragmentsForVisualOverflow() const {
NOT_DESTROYED();
// TODO(crbug.com/1144203): Legacy, or no-fragments-objects such as
// table-column. What to do with them is TBD.
if (!PhysicalFragmentCount())
return false;
const PhysicalBoxFragment& fragment = *GetPhysicalFragment(0);
if (!fragment.CanUseFragmentsForInkOverflow())
return false;
return true;
}
// Copy visual overflow from |PhysicalFragments()|.
void LayoutBox::CopyVisualOverflowFromFragments() {
NOT_DESTROYED();
DCHECK(CanUseFragmentsForVisualOverflow());
const PhysicalRect previous_visual_overflow =
VisualOverflowRectAllowingUnset();
CopyVisualOverflowFromFragmentsWithoutInvalidations();
const PhysicalRect visual_overflow = VisualOverflowRect();
if (visual_overflow == previous_visual_overflow)
return;
SetShouldCheckForPaintInvalidation();
}
void LayoutBox::CopyVisualOverflowFromFragmentsWithoutInvalidations() {
NOT_DESTROYED();
DCHECK(CanUseFragmentsForVisualOverflow());
if (!PhysicalFragmentCount()) [[unlikely]] {
DCHECK(IsLayoutTableCol());
ClearVisualOverflow();
return;
}
if (PhysicalFragmentCount() == 1) {
const PhysicalBoxFragment& fragment = *GetPhysicalFragment(0);
DCHECK(fragment.CanUseFragmentsForInkOverflow());
if (!fragment.HasInkOverflow()) {
ClearVisualOverflow();
return;
}
SetVisualOverflow(fragment.SelfInkOverflowRect(),
fragment.ContentsInkOverflowRect());
return;
}
// When block-fragmented, stitch visual overflows from all fragments.
const LayoutBlock* cb = ContainingBlock();
DCHECK(cb);
const WritingMode writing_mode = cb->StyleRef().GetWritingMode();
bool has_overflow = false;
PhysicalRect self_rect;
PhysicalRect contents_rect;
const PhysicalBoxFragment* last_fragment = nullptr;
for (const PhysicalBoxFragment& fragment : PhysicalFragments()) {
DCHECK(fragment.CanUseFragmentsForInkOverflow());
if (!fragment.HasInkOverflow()) {
last_fragment = &fragment;
continue;
}
has_overflow = true;
PhysicalRect fragment_self_rect = fragment.SelfInkOverflowRect();
PhysicalRect fragment_contents_rect = fragment.ContentsInkOverflowRect();
// Stitch this fragment to the bottom of the last one in horizontal
// writing mode, or to the right in vertical. Flipped blocks is handled
// later, after the loop.
if (last_fragment) {
const BlockBreakToken* break_token = last_fragment->GetBreakToken();
DCHECK(break_token);
const LayoutUnit block_offset = break_token->ConsumedBlockSize();
if (blink::IsHorizontalWritingMode(writing_mode)) {
fragment_self_rect.offset.top += block_offset;
fragment_contents_rect.offset.top += block_offset;
} else {
fragment_self_rect.offset.left += block_offset;
fragment_contents_rect.offset.left += block_offset;
}
}
last_fragment = &fragment;
self_rect.Unite(fragment_self_rect);
contents_rect.Unite(fragment_contents_rect);
// The legacy engine doesn't understand our concept of repeated
// fragments. Stop now. The overflow rectangle will represent the
// fragment(s) generated under the first repeated root.
if (fragment.GetBreakToken() && fragment.GetBreakToken()->IsRepeated()) {
break;
}
}
if (!has_overflow) {
ClearVisualOverflow();
return;
}
SetVisualOverflow(self_rect, contents_rect);
}
DISABLE_CFI_PERF
bool LayoutBox::HasUnsplittableScrollingOverflow() const {
NOT_DESTROYED();
// Fragmenting scrollbars is only problematic in interactive media, e.g.
// multicol on a screen. If we're printing, which is non-interactive media, we
// should allow objects with non-visible overflow to be paginated as normally.
if (GetDocument().Printing())
return false;
// Treat any scrollable container as monolithic.
return IsScrollContainer();
}
bool LayoutBox::IsMonolithic() const {
NOT_DESTROYED();
// TODO(almaher): Don't consider a writing mode root monolitic if
// IsFlexibleBox(). The breakability should be handled at the item
// level. (Likely same for Table and Grid).
if (ShouldBeConsideredAsReplaced() || HasUnsplittableScrollingOverflow() ||
(Parent() && IsWritingModeRoot()) ||
(IsFixedPositioned() && GetDocument().Printing() &&
IsA<LayoutView>(Container())) ||
ShouldApplySizeContainment() || IsFrameSet() ||
StyleRef().HasLineClamp() || IsScrollMarkerGroup()) {
return true;
}
return false;
}
LayoutUnit LayoutBox::FirstLineHeight() const {
NOT_DESTROYED();
if (IsAtomicInlineLevel()) {
return FirstLineStyle()->IsHorizontalWritingMode()
? MarginHeight() + Size().height
: MarginWidth() + Size().width;
}
return LayoutUnit();
}
PhysicalBoxStrut LayoutBox::BorderOutsetsForClipping() const {
NOT_DESTROYED();
auto padding_box = -BorderOutsets();
if (!ShouldApplyOverflowClipMargin())
return padding_box;
PhysicalBoxStrut overflow_clip_margin;
switch (StyleRef().OverflowClipMargin()->GetReferenceBox()) {
case StyleOverflowClipMargin::ReferenceBox::kBorderBox:
break;
case StyleOverflowClipMargin::ReferenceBox::kPaddingBox:
overflow_clip_margin = padding_box;
break;
case StyleOverflowClipMargin::ReferenceBox::kContentBox:
overflow_clip_margin = padding_box - PaddingOutsets();
break;
}
return overflow_clip_margin.Inflate(
StyleRef().OverflowClipMargin()->GetMargin());
}
PhysicalRect LayoutBox::VisualOverflowRect() const {
NOT_DESTROYED();
DCHECK(!IsLayoutMultiColumnSet());
if (!VisualOverflowIsSet())
return PhysicalBorderBoxRect();
const PhysicalRect& self_visual_overflow_rect =
overflow_->visual_overflow->SelfVisualOverflowRect();
if (HasMask()) {
return self_visual_overflow_rect;
}
const OverflowClipAxes overflow_clip_axes = GetOverflowClipAxes();
if (ShouldApplyOverflowClipMargin()) {
// We should apply overflow clip margin only if we clip overflow on both
// axis.
DCHECK_EQ(overflow_clip_axes, kOverflowClipBothAxis);
const PhysicalRect& contents_visual_overflow_rect =
overflow_->visual_overflow->ContentsVisualOverflowRect();
if (!contents_visual_overflow_rect.IsEmpty()) {
PhysicalRect result = PhysicalBorderBoxRect();
PhysicalBoxStrut outsets = BorderOutsetsForClipping();
result.ExpandEdges(outsets.top, outsets.right, outsets.bottom,
outsets.left);
result.Intersect(contents_visual_overflow_rect);
result.Unite(self_visual_overflow_rect);
return result;
}
}
if (overflow_clip_axes == kOverflowClipBothAxis)
return self_visual_overflow_rect;
PhysicalRect result =
overflow_->visual_overflow->ContentsVisualOverflowRect();
result.Unite(self_visual_overflow_rect);
ApplyOverflowClip(overflow_clip_axes, self_visual_overflow_rect, result);
return result;
}
#if DCHECK_IS_ON()
PhysicalRect LayoutBox::VisualOverflowRectAllowingUnset() const {
NOT_DESTROYED();
InkOverflow::ReadUnsetAsNoneScope read_unset_as_none;
return VisualOverflowRect();
}
void LayoutBox::CheckIsVisualOverflowComputed() const {
NOT_DESTROYED();
// TODO(crbug.com/1205708): There are still too many failures. Disable the
// the check for now. Need to investigate the reason.
return;
/*
if (InkOverflow::ReadUnsetAsNoneScope::IsActive())
return;
if (!CanUseFragmentsForVisualOverflow())
return;
// TODO(crbug.com/1203402): MathML needs some more work.
if (IsMathML())
return;
for (const PhysicalBoxFragment& fragment : PhysicalFragments())
DCHECK(fragment.IsInkOverflowComputed());
*/
}
#endif
PhysicalOffset LayoutBox::OffsetPoint(const Element* parent) const {
NOT_DESTROYED();
return AdjustedPositionRelativeTo(PhysicalLocation(), parent);
}
LayoutUnit LayoutBox::OffsetLeft(const Element* parent) const {
NOT_DESTROYED();
return OffsetPoint(parent).left;
}
LayoutUnit LayoutBox::OffsetTop(const Element* parent) const {
NOT_DESTROYED();
return OffsetPoint(parent).top;
}
PhysicalSize LayoutBox::Size() const {
NOT_DESTROYED();
if (!HasValidCachedGeometry()) {
// const_cast in order to update the cached value.
const_cast<LayoutBox*>(this)->SetHasValidCachedGeometry(true);
const_cast<LayoutBox*>(this)->frame_size_ = ComputeSize();
}
return frame_size_;
}
PhysicalSize LayoutBox::ComputeSize() const {
NOT_DESTROYED();
const auto& results = GetLayoutResults();
if (results.size() == 0) {
return PhysicalSize();
}
const auto& first_fragment = results[0]->GetPhysicalFragment();
if (results.size() == 1u) {
return first_fragment.Size();
}
WritingModeConverter converter(first_fragment.Style().GetWritingDirection());
const BlockBreakToken* previous_break_token = nullptr;
LogicalSize size;
for (const auto& result : results) {
const auto& physical_fragment =
To<PhysicalBoxFragment>(result->GetPhysicalFragment());
LogicalSize fragment_logical_size =
converter.ToLogical(physical_fragment.Size());
if (physical_fragment.IsFirstForNode()) {
// Inline-size will only be set at the first fragment. Subsequent
// fragments may have different inline-size (either because fragmentainer
// inline-size is variable, or e.g. because available inline-size is
// affected by floats). The legacy engine doesn't handle variable
// inline-size (since it doesn't really understand fragmentation). This
// means that things like offsetWidth won't work correctly (since that's
// still being handled by the legacy engine), but at least layout,
// painting and hit-testing will be correct.
size = fragment_logical_size;
} else {
DCHECK(previous_break_token);
size.block_size = fragment_logical_size.block_size +
previous_break_token->ConsumedBlockSize();
}
previous_break_token = physical_fragment.GetBreakToken();
// Continue in order to update logical height, unless this fragment is
// past the block-end of the generating node (happens with overflow) or
// is a repeated one.
if (!previous_break_token || previous_break_token->IsRepeated() ||
previous_break_token->IsAtBlockEnd()) {
break;
}
}
return converter.ToPhysical(size);
}
LayoutBox* LayoutBox::LocationContainer() const {
NOT_DESTROYED();
// A non-root SVG object derived from LayoutBox doesn't have a meaningful
// location container.
if (IsSVGChild()) {
return nullptr;
}
// The box's location is relative to its containing box.
LayoutObject* container = Container();
while (container && !container->IsBox())
container = container->Container();
return To<LayoutBox>(container);
}
ShapeOutsideInfo* LayoutBox::GetShapeOutsideInfo() const {
NOT_DESTROYED();
return ShapeOutsideInfo::Info(*this);
}
CustomLayoutChild* LayoutBox::GetCustomLayoutChild() const {
NOT_DESTROYED();
DCHECK(rare_data_);
DCHECK(rare_data_->layout_child_);
return rare_data_->layout_child_.Get();
}
void LayoutBox::AddCustomLayoutChildIfNeeded() {
NOT_DESTROYED();
if (!IsCustomItem())
return;
const AtomicString& name = Parent()->StyleRef().DisplayLayoutCustomName();
LayoutWorklet* worklet = LayoutWorklet::From(*GetDocument().domWindow());
const CSSLayoutDefinition* definition =
worklet->Proxy()->FindDefinition(name);
// If there isn't a definition yet, the web developer defined layout isn't
// loaded yet (or is invalid). The layout tree will get re-attached when
// loaded, so don't bother creating a script representation of this node yet.
if (!definition)
return;
EnsureRareData().layout_child_ =
MakeGarbageCollected<CustomLayoutChild>(*definition, BlockNode(this));
}
void LayoutBox::ClearCustomLayoutChild() {
NOT_DESTROYED();
if (!rare_data_)
return;
if (rare_data_->layout_child_)
rare_data_->layout_child_->ClearLayoutNode();
rare_data_->layout_child_ = nullptr;
}
PhysicalRect LayoutBox::DebugRect() const {
NOT_DESTROYED();
return PhysicalRect(PhysicalLocation(), Size());
}
OverflowClipAxes LayoutBox::ComputeOverflowClipAxes() const {
NOT_DESTROYED();
if (ShouldApplyPaintContainment() || HasControlClip())
return kOverflowClipBothAxis;
if (!RespectsCSSOverflow() || !HasNonVisibleOverflow())
return kNoOverflowClip;
if (IsScrollContainer())
return kOverflowClipBothAxis;
return (StyleRef().OverflowX() == EOverflow::kVisible ? kNoOverflowClip
: kOverflowClipX) |
(StyleRef().OverflowY() == EOverflow::kVisible ? kNoOverflowClip
: kOverflowClipY);
}
void LayoutBox::MutableForPainting::SavePreviousOverflowData() {
if (!GetLayoutBox().overflow_)
GetLayoutBox().overflow_ = MakeGarbageCollected<BoxOverflowModel>();
auto& previous_overflow = GetLayoutBox().overflow_->previous_overflow_data;
if (!previous_overflow)
previous_overflow.emplace();
previous_overflow->previous_scrollable_overflow_rect =
GetLayoutBox().ScrollableOverflowRect();
previous_overflow->previous_visual_overflow_rect =
GetLayoutBox().VisualOverflowRect();
previous_overflow->previous_self_visual_overflow_rect =
GetLayoutBox().SelfVisualOverflowRect();
}
void LayoutBox::MutableForPainting::SetPreviousGeometryForLayoutShiftTracking(
const PhysicalOffset& paint_offset,
const PhysicalSize& size,
const PhysicalRect& visual_overflow_rect) {
FirstFragment().SetPaintOffset(paint_offset);
GetLayoutBox().previous_size_ = size;
if (PhysicalRect(PhysicalOffset(), size).Contains(visual_overflow_rect))
return;
if (!GetLayoutBox().overflow_)
GetLayoutBox().overflow_ = MakeGarbageCollected<BoxOverflowModel>();
auto& previous_overflow = GetLayoutBox().overflow_->previous_overflow_data;
if (!previous_overflow)
previous_overflow.emplace();
previous_overflow->previous_visual_overflow_rect = visual_overflow_rect;
// Other previous rects don't matter because they are used for paint
// invalidation and we always do full paint invalidation on reattachment.
}
void LayoutBox::MutableForPainting::UpdateBackgroundPaintLocation(
bool needs_root_element_group) {
GetLayoutBox().SetBackgroundPaintLocation(
GetLayoutBox().ComputeBackgroundPaintLocation(needs_root_element_group));
}
RasterEffectOutset LayoutBox::VisualRectOutsetForRasterEffects() const {
NOT_DESTROYED();
// If the box has subpixel visual effect outsets, as the visual effect may be
// painted along the pixel-snapped border box, the pixels on the anti-aliased
// edge of the effect may overflow the calculated visual rect. Expand visual
// rect by one pixel in the case.
return VisualOverflowIsSet() &&
overflow_->visual_overflow->HasSubpixelVisualEffectOutsets()
? RasterEffectOutset::kWholePixel
: RasterEffectOutset::kNone;
}
TextDirection LayoutBox::ResolvedDirection() const {
NOT_DESTROYED();
if (IsInline() && IsAtomicInlineLevel() &&
IsInLayoutNGInlineFormattingContext()) {
InlineCursor cursor;
cursor.MoveTo(*this);
if (cursor) {
return cursor.Current().ResolvedDirection();
}
}
return StyleRef().Direction();
}
void LayoutBox::OverrideTickmarks(Vector<gfx::Rect> tickmarks) {
NOT_DESTROYED();
GetScrollableArea()->SetTickmarksOverride(std::move(tickmarks));
InvalidatePaintForTickmarks();
}
void LayoutBox::InvalidatePaintForTickmarks() {
NOT_DESTROYED();
ScrollableArea* scrollable_area = GetScrollableArea();
if (!scrollable_area)
return;
Scrollbar* scrollbar = scrollable_area->VerticalScrollbar();
if (!scrollbar)
return;
scrollbar->SetNeedsPaintInvalidation(static_cast<ScrollbarPart>(~kThumbPart));
}
static bool HasInsetBoxShadow(const ComputedStyle& style) {
if (!style.BoxShadow())
return false;
for (const ShadowData& shadow : style.BoxShadow()->Shadows()) {
if (shadow.Style() == ShadowStyle::kInset)
return true;
}
return false;
}
// If all borders and scrollbars are opaque, then background-clip: border-box
// is equivalent to background-clip: padding-box.
bool LayoutBox::BackgroundClipBorderBoxIsEquivalentToPaddingBox() const {
NOT_DESTROYED();
const auto* scrollable_area = GetScrollableArea();
if (scrollable_area) {
if (auto* scrollbar = scrollable_area->HorizontalScrollbar()) {
if (!scrollbar->IsOverlayScrollbar() && !scrollbar->IsOpaque()) {
return false;
}
}
if (auto* scrollbar = scrollable_area->VerticalScrollbar()) {
if (!scrollbar->IsOverlayScrollbar() && !scrollbar->IsOpaque()) {
return false;
}
}
}
if (StyleRef().BorderTopWidth() &&
(!ResolveColor(GetCSSPropertyBorderTopColor()).IsOpaque() ||
StyleRef().BorderTopStyle() != EBorderStyle::kSolid)) {
return false;
}
if (StyleRef().BorderRightWidth() &&
(!ResolveColor(GetCSSPropertyBorderRightColor()).IsOpaque() ||
StyleRef().BorderRightStyle() != EBorderStyle::kSolid)) {
return false;
}
if (StyleRef().BorderBottomWidth() &&
(!ResolveColor(GetCSSPropertyBorderBottomColor()).IsOpaque() ||
StyleRef().BorderBottomStyle() != EBorderStyle::kSolid)) {
return false;
}
if (StyleRef().BorderLeftWidth() &&
(!ResolveColor(GetCSSPropertyBorderLeftColor()).IsOpaque() ||
StyleRef().BorderLeftStyle() != EBorderStyle::kSolid)) {
return false;
}
if (!StyleRef().IsScrollbarGutterAuto()) {
return false;
}
return true;
}
BackgroundPaintLocation LayoutBox::ComputeBackgroundPaintLocation(
bool needs_root_element_group) const {
NOT_DESTROYED();
bool may_have_scrolling_layers_without_scrolling = IsA<LayoutView>(this);
const auto* scrollable_area = GetScrollableArea();
bool scrolls_overflow = scrollable_area && scrollable_area->ScrollsOverflow();
if (!scrolls_overflow && !may_have_scrolling_layers_without_scrolling)
return kBackgroundPaintInBorderBoxSpace;
if (IsA<LayoutView>(this)) {
if (needs_root_element_group) {
// We must paint background in the contents space to apply the root
// element effects.
return kBackgroundPaintInContentsSpace;
}
if (GetDocument().GetSettings()->GetLCDTextPreference() ==
LCDTextPreference::kStronglyPreferred) {
// If we care about LCD text, paint root backgrounds into scrolling
// contents layer even if style suggests otherwise.
return kBackgroundPaintInContentsSpace;
}
}
// Inset box shadow is painted in the scrolling area above the background, and
// it doesn't scroll, so the background can only be painted in the main layer.
if (HasInsetBoxShadow(StyleRef()))
return kBackgroundPaintInBorderBoxSpace;
// For simplicity, assume any border image can have inset, like the above.
if (StyleRef().BorderImage().GetImage()) {
return kBackgroundPaintInBorderBoxSpace;
}
// Assume optimistically that the background can be painted in the scrolling
// contents until we find otherwise.
BackgroundPaintLocation paint_location = kBackgroundPaintInContentsSpace;
Color background_color = ResolveColor(GetCSSPropertyBackgroundColor());
const FillLayer* layer = &(StyleRef().BackgroundLayers());
for (; layer; layer = layer->Next()) {
if (layer->Attachment() == EFillAttachment::kLocal)
continue;
// The background color is either the only background or it's the
// bottommost value from the background property (see final-bg-layer in
// https://drafts.csswg.org/css-backgrounds/#the-background).
if (!layer->GetImage() && !layer->Next() &&
!background_color.IsFullyTransparent() &&
StyleRef().IsScrollbarGutterAuto()) {
// Solid color layers with an effective background clip of the padding box
// can be treated as local.
EFillBox clip = layer->Clip();
if (clip == EFillBox::kPadding)
continue;
// A border box can be treated as a padding box if the border is opaque or
// there is no border and we don't have custom scrollbars.
if (clip == EFillBox::kBorder) {
if (BackgroundClipBorderBoxIsEquivalentToPaddingBox())
continue;
// If we have an opaque background color, we can safely paint it into
// both the scrolling contents layer and the graphics layer to preserve
// LCD text. The background color is either the only background or
// behind background-attachment:local images (ensured by previous
// iterations of the loop). For the latter case, the first paint of the
// images doesn't matter because it will be covered by the second paint
// of the opaque color.
if (background_color.IsOpaque()) {
paint_location = kBackgroundPaintInBothSpaces;
continue;
}
} else if (clip == EFillBox::kContent &&
StyleRef().PaddingTop().IsZero() &&
StyleRef().PaddingLeft().IsZero() &&
StyleRef().PaddingRight().IsZero() &&
StyleRef().PaddingBottom().IsZero()) {
// A content fill box can be treated as a padding fill box if there is
// no padding.
continue;
}
}
return kBackgroundPaintInBorderBoxSpace;
}
// It can't paint in the scrolling contents because it has different 3d
// context than the scrolling contents.
if (!StyleRef().Preserves3D() && Parent() &&
Parent()->StyleRef().Preserves3D()) {
return kBackgroundPaintInBorderBoxSpace;
}
return paint_location;
}
bool LayoutBox::ComputeCanCompositeBackgroundAttachmentFixed() const {
NOT_DESTROYED();
DCHECK(IsBackgroundAttachmentFixedObject());
if (GetDocument().GetSettings()->GetLCDTextPreference() ==
LCDTextPreference::kStronglyPreferred) {
return false;
}
// The fixed attachment background must be the only background layer.
if (StyleRef().BackgroundLayers().Next() ||
StyleRef().BackgroundLayers().Clip() == EFillBox::kText) {
return false;
}
// To support box shadow, we'll need to paint the outset and inset box
// shadows in separate display items in case there are outset box shadow,
// background, inset box shadow and border in paint order.
if (StyleRef().BoxShadow()) {
return false;
}
// The theme may paint the background differently for an appearance.
if (StyleRef().HasEffectiveAppearance()) {
return false;
}
// For now the BackgroundClip paint property node doesn't support rounded
// corners. If we want to support this, we need to ensure
// - there is no obvious bleeding issues, and
// - both the fast path and the slow path of composited rounded clip work.
if (StyleRef().HasBorderRadius()) {
return false;
}
return true;
}
bool LayoutBox::IsFixedToView(
const LayoutObject* container_for_fixed_position) const {
NOT_DESTROYED();
if (!IsFixedPositioned())
return false;
const auto* container = container_for_fixed_position;
if (!container)
container = Container();
else
DCHECK_EQ(container, Container());
return container->IsLayoutView();
}
PhysicalRect LayoutBox::ComputeStickyConstrainingRect() const {
NOT_DESTROYED();
DCHECK(IsScrollContainer());
PhysicalRect constraining_rect(OverflowClipRect(PhysicalOffset()));
constraining_rect.Move(PhysicalOffset(-BorderLeft() + PaddingLeft(),
-BorderTop() + PaddingTop()));
constraining_rect.ContractEdges(LayoutUnit(), PaddingLeft() + PaddingRight(),
PaddingTop() + PaddingBottom(), LayoutUnit());
// Subtract off the scroll origin to move into scrolling content space.
constraining_rect.Move(-PhysicalOffset(ScrollOrigin()));
return constraining_rect;
}
AnchorPositionScrollData* LayoutBox::GetAnchorPositionScrollData() const {
NOT_DESTROYED();
if (Element* element = DynamicTo<Element>(GetNode())) {
return element->GetAnchorPositionScrollData();
}
return nullptr;
}
bool LayoutBox::NeedsAnchorPositionScrollAdjustment() const {
NOT_DESTROYED();
if (auto* data = GetAnchorPositionScrollData()) {
return data->NeedsScrollAdjustment();
}
return false;
}
bool LayoutBox::AnchorPositionScrollAdjustmentAfectedByViewportScrolling()
const {
NOT_DESTROYED();
if (auto* data = GetAnchorPositionScrollData()) {
return data->NeedsScrollAdjustment() &&
data->IsAffectedByViewportScrolling();
}
return false;
}
PhysicalOffset LayoutBox::AnchorPositionScrollTranslationOffset() const {
NOT_DESTROYED();
if (auto* data = GetAnchorPositionScrollData()) {
return data->TranslationAsPhysicalOffset();
}
return PhysicalOffset();
}
namespace {
template <typename Function>
void ForEachAnchorQueryOnContainer(const LayoutBox& box, Function func) {
const LayoutObject* container = box.Container();
if (container->IsLayoutBlock()) {
for (const PhysicalBoxFragment& fragment :
To<LayoutBlock>(container)->PhysicalFragments()) {
if (const PhysicalAnchorQuery* anchor_query = fragment.AnchorQuery()) {
func(*anchor_query);
}
}
return;
}
// Now the container is an inline box that's also an abspos containing block.
CHECK(container->IsLayoutInline());
const LayoutInline* inline_container = To<LayoutInline>(container);
if (!inline_container->HasInlineFragments()) {
return;
}
InlineCursor cursor;
cursor.MoveTo(*container);
for (; cursor; cursor.MoveToNextForSameLayoutObject()) {
if (const PhysicalBoxFragment* fragment = cursor.Current().BoxFragment()) {
if (const PhysicalAnchorQuery* anchor_query = fragment->AnchorQuery()) {
func(*anchor_query);
}
}
}
}
#if EXPENSIVE_DCHECKS_ARE_ON()
template <typename Function>
void AssertSameDataOnLayoutResults(
const LayoutBox::LayoutResultList& layout_results,
Function func) {
// When an out-of-flow box is fragmented, the position fallback results on all
// fragments should be the same.
for (wtf_size_t i = 1; i < layout_results.size(); ++i) {
DCHECK(func(layout_results[i]) == func(layout_results[i - 1]));
}
}
#endif
} // namespace
const LayoutObject* LayoutBox::FindTargetAnchor(
const ScopedCSSName& anchor_name) const {
NOT_DESTROYED();
if (!IsOutOfFlowPositioned()) {
return nullptr;
}
AnchorScopedName* anchor_scoped_name = ToAnchorScopedName(anchor_name, *this);
// Go through the already built PhysicalAnchorQuery to avoid tree traversal.
const LayoutObject* anchor = nullptr;
auto search_for_anchor = [&](const PhysicalAnchorQuery& anchor_query) {
if (const LayoutObject* current =
anchor_query.AnchorLayoutObject(*this, anchor_scoped_name)) {
if (!anchor ||
(anchor != current && anchor->IsBeforeInPreOrder(*current))) {
anchor = current;
}
}
};
ForEachAnchorQueryOnContainer(*this, search_for_anchor);
return anchor;
}
const LayoutObject* LayoutBox::AcceptableImplicitAnchor() const {
NOT_DESTROYED();
if (!IsOutOfFlowPositioned()) {
return nullptr;
}
Element* element = DynamicTo<Element>(GetNode());
Element* anchor_element =
element ? element->ImplicitAnchorElement() : nullptr;
LayoutObject* anchor_layout_object =
anchor_element ? anchor_element->GetLayoutObject() : nullptr;
if (!anchor_layout_object) {
return nullptr;
}
// Go through the already built PhysicalAnchorQuery to avoid tree traversal.
bool is_acceptable_anchor = false;
auto validate_anchor = [&](const PhysicalAnchorQuery& anchor_query) {
if (anchor_query.AnchorLayoutObject(*this, anchor_element)) {
is_acceptable_anchor = true;
}
};
ForEachAnchorQueryOnContainer(*this, validate_anchor);
return is_acceptable_anchor ? anchor_layout_object : nullptr;
}
const HeapVector<NonOverflowingScrollRange>*
LayoutBox::NonOverflowingScrollRanges() const {
NOT_DESTROYED();
const auto& layout_results = GetLayoutResults();
if (layout_results.empty()) {
return nullptr;
}
// We only need to check the first fragment, because when the box is
// fragmented, position fallback results are duplicated on all fragments.
#if EXPENSIVE_DCHECKS_ARE_ON()
for (wtf_size_t i = 1; i < layout_results.size(); ++i) {
DCHECK(base::ValuesEquivalent(
layout_results[i]->NonOverflowingScrollRanges(),
layout_results[i - 1]->NonOverflowingScrollRanges()));
}
#endif
return layout_results.front()->NonOverflowingScrollRanges();
}
const BoxStrut& LayoutBox::OutOfFlowInsetsForGetComputedStyle() const {
NOT_DESTROYED();
const auto& layout_results = GetLayoutResults();
// We should call this function only after the node is laid out.
CHECK(layout_results.size());
// We only need to check the first fragment, because when the box is
// fragmented, insets are duplicated on all fragments.
#if EXPENSIVE_DCHECKS_ARE_ON()
AssertSameDataOnLayoutResults(layout_results, [](const auto& result) {
return result->OutOfFlowInsetsForGetComputedStyle();
});
#endif
return GetLayoutResults().front()->OutOfFlowInsetsForGetComputedStyle();
}
Element* LayoutBox::AccessibilityAnchor() const {
NOT_DESTROYED();
const auto& layout_results = GetLayoutResults();
if (layout_results.empty()) {
return nullptr;
}
return layout_results.front()->AccessibilityAnchor();
}
const GCedHeapHashSet<Member<Element>>*
LayoutBox::DisplayLocksAffectedByAnchors() const {
NOT_DESTROYED();
const auto& layout_results = GetLayoutResults();
if (layout_results.empty()) {
return nullptr;
}
return layout_results.front()->DisplayLocksAffectedByAnchors();
}
void LayoutBox::NotifyContainingDisplayLocksForAnchorPositioning(
const GCedHeapHashSet<Member<Element>>*
past_display_locks_affected_by_anchors,
const GCedHeapHashSet<Member<Element>>* display_locks_affected_by_anchors)
const {
NOT_DESTROYED();
auto notify_display_locks =
[](const GCedHeapHashSet<Member<Element>>* display_locks) {
if (!display_locks) {
return;
}
for (auto& display_lock_element : *display_locks) {
display_lock_element->GetDisplayLockContext()
->SetAnchorPositioningRenderStateMayHaveChanged();
}
};
notify_display_locks(past_display_locks_affected_by_anchors);
notify_display_locks(display_locks_affected_by_anchors);
}
bool LayoutBox::NeedsAnchorPositionScrollAdjustmentInX() const {
NOT_DESTROYED();
const auto& layout_results = GetLayoutResults();
if (layout_results.empty()) {
return false;
}
// We only need to check the first fragment, because when the box is
// fragmented, position fallback results are duplicated on all fragments.
#if EXPENSIVE_DCHECKS_ARE_ON()
AssertSameDataOnLayoutResults(layout_results, [](const auto& result) {
return result->NeedsAnchorPositionScrollAdjustmentInX();
});
#endif
return layout_results.front()->NeedsAnchorPositionScrollAdjustmentInX();
}
bool LayoutBox::NeedsAnchorPositionScrollAdjustmentInY() const {
NOT_DESTROYED();
const auto& layout_results = GetLayoutResults();
if (layout_results.empty()) {
return false;
}
// We only need to check the first fragment, because when the box is
// fragmented, position fallback results are duplicated on all fragments.
#if EXPENSIVE_DCHECKS_ARE_ON()
AssertSameDataOnLayoutResults(layout_results, [](const auto& result) {
return result->NeedsAnchorPositionScrollAdjustmentInY();
});
#endif
return layout_results.front()->NeedsAnchorPositionScrollAdjustmentInY();
}
WritingModeConverter LayoutBox::CreateWritingModeConverter() const {
NOT_DESTROYED();
return WritingModeConverter({Style()->GetWritingMode(), TextDirection::kLtr},
Size());
}
PhysicalOffset LayoutBox::PhysicalLocation(
const LayoutBox* location_container) const {
NOT_DESTROYED();
if (RuntimeEnabledFeatures::LayoutBoxVisualLocationEnabled()) {
return frame_location_.physical_offset;
}
return DeprecatedPhysicalLocationInternal(
location_container ? location_container : LocationContainer());
}
PhysicalRect LayoutBox::BoundingBoxRelativeToFirstFragment() const {
NOT_DESTROYED();
PhysicalRect bounding_rect;
const PhysicalBoxFragment* first_fragment = nullptr;
for (const PhysicalBoxFragment& fragment : PhysicalFragments()) {
PhysicalOffset offset;
if (!first_fragment) {
first_fragment = &fragment;
} else {
offset = fragment.OffsetFromRootFragmentationContext() -
first_fragment->OffsetFromRootFragmentationContext();
}
PhysicalRect fragment_rect(offset, fragment.Size());
bounding_rect.UniteEvenIfEmpty(fragment_rect);
if (const BlockBreakToken* break_token = fragment.GetBreakToken()) {
if (break_token->IsAtBlockEnd()) {
// Ignore subsequent fragments that are just there to hold overflowing
// children.
break;
}
}
}
return bounding_rect;
}
bool LayoutBox::IsReadingFlowContainer() const {
NOT_DESTROYED();
if (!RuntimeEnabledFeatures::CSSReadingFlowEnabled()) {
return false;
}
const ComputedStyle& style = StyleRef();
switch (style.ReadingFlow()) {
case EReadingFlow::kNormal:
return false;
case EReadingFlow::kFlexVisual:
case EReadingFlow::kFlexFlow:
return IsFlexibleBox();
case EReadingFlow::kGridRows:
case EReadingFlow::kGridColumns:
case EReadingFlow::kGridOrder:
return IsLayoutGrid();
case EReadingFlow::kSourceOrder:
return IsLayoutBlock() || IsFlexibleBox() || IsLayoutGrid();
}
return false;
}
const HeapVector<Member<Node>>& LayoutBox::ReadingFlowNodes() const {
NOT_DESTROYED();
if (const auto* nodes = GetPhysicalFragment(0)->ReadingFlowNodes()) {
return *nodes;
}
using HolderType = DisallowNewWrapper<HeapVector<Member<Node>>>;
DEFINE_STATIC_LOCAL(Persistent<HolderType>, empty_vector,
(MakeGarbageCollected<HolderType>()));
return empty_vector->Value();
}
} // namespace blink
|