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
|
/*
* Copyright (C) 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/layout/LayoutGrid.h"
#include "core/frame/UseCounter.h"
#include "core/layout/LayoutState.h"
#include "core/layout/TextAutosizer.h"
#include "core/paint/GridPainter.h"
#include "core/paint/PaintLayer.h"
#include "core/style/ComputedStyle.h"
#include "core/style/GridArea.h"
#include "platform/LengthFunctions.h"
#include "wtf/PtrUtil.h"
#include <algorithm>
#include <memory>
namespace blink {
static const int infinity = -1;
class GridItemWithSpan;
size_t LayoutGrid::Grid::numTracks(GridTrackSizingDirection direction) const {
if (direction == ForRows)
return m_grid.size();
return m_grid.size() ? m_grid[0].size() : 0;
}
void LayoutGrid::Grid::ensureGridSize(size_t maximumRowSize,
size_t maximumColumnSize) {
DCHECK(maximumRowSize <= kGridMaxTracks * 2);
DCHECK(maximumColumnSize <= kGridMaxTracks * 2);
const size_t oldRowSize = numTracks(ForRows);
if (maximumRowSize > oldRowSize) {
m_grid.grow(maximumRowSize);
for (size_t row = oldRowSize; row < numTracks(ForRows); ++row)
m_grid[row].grow(numTracks(ForColumns));
}
if (maximumColumnSize > numTracks(ForColumns)) {
for (size_t row = 0; row < numTracks(ForRows); ++row)
m_grid[row].grow(maximumColumnSize);
}
}
void LayoutGrid::Grid::insert(LayoutBox& child, const GridArea& area) {
DCHECK(area.rows.isTranslatedDefinite() &&
area.columns.isTranslatedDefinite());
ensureGridSize(area.rows.endLine(), area.columns.endLine());
for (const auto& row : area.rows) {
for (const auto& column : area.columns)
m_grid[row][column].push_back(&child);
}
setGridItemArea(child, area);
}
void LayoutGrid::Grid::setSmallestTracksStart(int rowStart, int columnStart) {
m_smallestRowStart = rowStart;
m_smallestColumnStart = columnStart;
}
int LayoutGrid::Grid::smallestTrackStart(
GridTrackSizingDirection direction) const {
return direction == ForRows ? m_smallestRowStart : m_smallestColumnStart;
}
GridArea LayoutGrid::Grid::gridItemArea(const LayoutBox& item) const {
DCHECK(m_gridItemArea.contains(&item));
return m_gridItemArea.get(&item);
}
void LayoutGrid::Grid::setGridItemArea(const LayoutBox& item, GridArea area) {
m_gridItemArea.set(&item, area);
}
size_t LayoutGrid::Grid::gridItemPaintOrder(const LayoutBox& item) const {
return m_gridItemsIndexesMap.get(&item);
}
void LayoutGrid::Grid::setGridItemPaintOrder(const LayoutBox& item,
size_t order) {
m_gridItemsIndexesMap.set(&item, order);
}
#if DCHECK_IS_ON()
bool LayoutGrid::Grid::hasAnyGridItemPaintOrder() const {
return !m_gridItemsIndexesMap.isEmpty();
}
#endif
void LayoutGrid::Grid::setAutoRepeatTracks(size_t autoRepeatRows,
size_t autoRepeatColumns) {
DCHECK_GE(static_cast<unsigned>(kGridMaxTracks),
numTracks(ForRows) + autoRepeatRows);
DCHECK_GE(static_cast<unsigned>(kGridMaxTracks),
numTracks(ForColumns) + autoRepeatColumns);
m_autoRepeatRows = autoRepeatRows;
m_autoRepeatColumns = autoRepeatColumns;
}
size_t LayoutGrid::Grid::autoRepeatTracks(
GridTrackSizingDirection direction) const {
return direction == ForRows ? m_autoRepeatRows : m_autoRepeatColumns;
}
void LayoutGrid::Grid::setAutoRepeatEmptyColumns(
std::unique_ptr<OrderedTrackIndexSet> autoRepeatEmptyColumns) {
m_autoRepeatEmptyColumns = std::move(autoRepeatEmptyColumns);
}
void LayoutGrid::Grid::setAutoRepeatEmptyRows(
std::unique_ptr<OrderedTrackIndexSet> autoRepeatEmptyRows) {
m_autoRepeatEmptyRows = std::move(autoRepeatEmptyRows);
}
bool LayoutGrid::Grid::hasAutoRepeatEmptyTracks(
GridTrackSizingDirection direction) const {
return direction == ForColumns ? !!m_autoRepeatEmptyColumns
: !!m_autoRepeatEmptyRows;
}
bool LayoutGrid::Grid::isEmptyAutoRepeatTrack(
GridTrackSizingDirection direction,
size_t line) const {
DCHECK(hasAutoRepeatEmptyTracks(direction));
return autoRepeatEmptyTracks(direction)->contains(line);
}
LayoutGrid::OrderedTrackIndexSet* LayoutGrid::Grid::autoRepeatEmptyTracks(
GridTrackSizingDirection direction) const {
DCHECK(hasAutoRepeatEmptyTracks(direction));
return direction == ForColumns ? m_autoRepeatEmptyColumns.get()
: m_autoRepeatEmptyRows.get();
}
GridSpan LayoutGrid::Grid::gridItemSpan(
const LayoutBox& gridItem,
GridTrackSizingDirection direction) const {
GridArea area = gridItemArea(gridItem);
return direction == ForColumns ? area.columns : area.rows;
}
void LayoutGrid::Grid::setHasAnyOrthogonalGridItem(
bool hasAnyOrthogonalGridItem) {
m_hasAnyOrthogonalGridItem = hasAnyOrthogonalGridItem;
}
void LayoutGrid::Grid::setNeedsItemsPlacement(bool needsItemsPlacement) {
m_needsItemsPlacement = needsItemsPlacement;
if (!needsItemsPlacement) {
m_grid.shrinkToFit();
return;
}
m_grid.resize(0);
m_gridItemArea.clear();
m_gridItemsIndexesMap.clear();
m_hasAnyOrthogonalGridItem = false;
m_smallestRowStart = 0;
m_smallestColumnStart = 0;
m_autoRepeatColumns = 0;
m_autoRepeatRows = 0;
m_autoRepeatEmptyColumns = nullptr;
m_autoRepeatEmptyRows = nullptr;
}
class GridTrack {
public:
GridTrack() : m_infinitelyGrowable(false) {}
LayoutUnit baseSize() const {
DCHECK(isGrowthLimitBiggerThanBaseSize());
return m_baseSize;
}
LayoutUnit growthLimit() const {
DCHECK(isGrowthLimitBiggerThanBaseSize());
DCHECK(!m_growthLimitCap || m_growthLimitCap.value() >= m_growthLimit ||
m_baseSize >= m_growthLimitCap.value());
return m_growthLimit;
}
void setBaseSize(LayoutUnit baseSize) {
m_baseSize = baseSize;
ensureGrowthLimitIsBiggerThanBaseSize();
}
void setGrowthLimit(LayoutUnit growthLimit) {
m_growthLimit =
growthLimit == infinity
? growthLimit
: std::min(growthLimit, m_growthLimitCap.value_or(growthLimit));
ensureGrowthLimitIsBiggerThanBaseSize();
}
bool infiniteGrowthPotential() const {
return growthLimitIsInfinite() || m_infinitelyGrowable;
}
LayoutUnit plannedSize() const { return m_plannedSize; }
void setPlannedSize(const LayoutUnit& plannedSize) {
ASSERT(plannedSize >= 0 || plannedSize == infinity);
m_plannedSize = plannedSize;
}
LayoutUnit sizeDuringDistribution() const { return m_sizeDuringDistribution; }
void setSizeDuringDistribution(const LayoutUnit& sizeDuringDistribution) {
DCHECK_GE(sizeDuringDistribution, 0);
DCHECK(growthLimitIsInfinite() || growthLimit() >= sizeDuringDistribution);
m_sizeDuringDistribution = sizeDuringDistribution;
}
void growSizeDuringDistribution(const LayoutUnit& sizeDuringDistribution) {
DCHECK_GE(sizeDuringDistribution, 0);
m_sizeDuringDistribution += sizeDuringDistribution;
}
bool infinitelyGrowable() const { return m_infinitelyGrowable; }
void setInfinitelyGrowable(bool infinitelyGrowable) {
m_infinitelyGrowable = infinitelyGrowable;
}
void setGrowthLimitCap(Optional<LayoutUnit> growthLimitCap) {
DCHECK(!growthLimitCap || *growthLimitCap >= 0);
m_growthLimitCap = growthLimitCap;
}
Optional<LayoutUnit> growthLimitCap() const { return m_growthLimitCap; }
private:
bool growthLimitIsInfinite() const { return m_growthLimit == infinity; }
bool isGrowthLimitBiggerThanBaseSize() const {
return growthLimitIsInfinite() || m_growthLimit >= m_baseSize;
}
void ensureGrowthLimitIsBiggerThanBaseSize() {
if (m_growthLimit != infinity && m_growthLimit < m_baseSize)
m_growthLimit = m_baseSize;
}
LayoutUnit m_baseSize;
LayoutUnit m_growthLimit;
LayoutUnit m_plannedSize;
LayoutUnit m_sizeDuringDistribution;
Optional<LayoutUnit> m_growthLimitCap;
bool m_infinitelyGrowable;
};
struct ContentAlignmentData {
STACK_ALLOCATED();
public:
ContentAlignmentData(){};
ContentAlignmentData(LayoutUnit position, LayoutUnit distribution)
: positionOffset(position), distributionOffset(distribution) {}
bool isValid() { return positionOffset >= 0 && distributionOffset >= 0; }
LayoutUnit positionOffset = LayoutUnit(-1);
LayoutUnit distributionOffset = LayoutUnit(-1);
};
enum TrackSizeRestriction {
AllowInfinity,
ForbidInfinity,
};
class LayoutGrid::GridIterator {
WTF_MAKE_NONCOPYABLE(GridIterator);
public:
// |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
// GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd
// column.
GridIterator(const Grid& grid,
GridTrackSizingDirection direction,
size_t fixedTrackIndex,
size_t varyingTrackIndex = 0)
: m_grid(grid.m_grid),
m_direction(direction),
m_rowIndex((direction == ForColumns) ? varyingTrackIndex
: fixedTrackIndex),
m_columnIndex((direction == ForColumns) ? fixedTrackIndex
: varyingTrackIndex),
m_childIndex(0) {
DCHECK(!m_grid.isEmpty());
DCHECK(!m_grid[0].isEmpty());
DCHECK(m_rowIndex < m_grid.size());
DCHECK(m_columnIndex < m_grid[0].size());
}
LayoutBox* nextGridItem() {
DCHECK(!m_grid.isEmpty());
DCHECK(!m_grid[0].isEmpty());
size_t& varyingTrackIndex =
(m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
const size_t endOfVaryingTrackIndex =
(m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
const GridCell& children = m_grid[m_rowIndex][m_columnIndex];
if (m_childIndex < children.size())
return children[m_childIndex++];
m_childIndex = 0;
}
return nullptr;
}
bool checkEmptyCells(size_t rowSpan, size_t columnSpan) const {
DCHECK(!m_grid.isEmpty());
DCHECK(!m_grid[0].isEmpty());
// Ignore cells outside current grid as we will grow it later if needed.
size_t maxRows = std::min(m_rowIndex + rowSpan, m_grid.size());
size_t maxColumns = std::min(m_columnIndex + columnSpan, m_grid[0].size());
// This adds a O(N^2) behavior that shouldn't be a big deal as we expect
// spanning areas to be small.
for (size_t row = m_rowIndex; row < maxRows; ++row) {
for (size_t column = m_columnIndex; column < maxColumns; ++column) {
const GridCell& children = m_grid[row][column];
if (!children.isEmpty())
return false;
}
}
return true;
}
std::unique_ptr<GridArea> nextEmptyGridArea(size_t fixedTrackSpan,
size_t varyingTrackSpan) {
DCHECK(!m_grid.isEmpty());
DCHECK(!m_grid[0].isEmpty());
ASSERT(fixedTrackSpan >= 1 && varyingTrackSpan >= 1);
size_t rowSpan =
(m_direction == ForColumns) ? varyingTrackSpan : fixedTrackSpan;
size_t columnSpan =
(m_direction == ForColumns) ? fixedTrackSpan : varyingTrackSpan;
size_t& varyingTrackIndex =
(m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
const size_t endOfVaryingTrackIndex =
(m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
if (checkEmptyCells(rowSpan, columnSpan)) {
std::unique_ptr<GridArea> result = WTF::wrapUnique(
new GridArea(GridSpan::translatedDefiniteGridSpan(
m_rowIndex, m_rowIndex + rowSpan),
GridSpan::translatedDefiniteGridSpan(
m_columnIndex, m_columnIndex + columnSpan)));
// Advance the iterator to avoid an infinite loop where we would return
// the same grid area over and over.
++varyingTrackIndex;
return result;
}
}
return nullptr;
}
private:
const GridAsMatrix& m_grid;
GridTrackSizingDirection m_direction;
size_t m_rowIndex;
size_t m_columnIndex;
size_t m_childIndex;
};
struct LayoutGrid::GridSizingData {
WTF_MAKE_NONCOPYABLE(GridSizingData);
STACK_ALLOCATED();
public:
GridSizingData(size_t gridColumnCount, size_t gridRowCount, Grid& grid)
: columnTracks(gridColumnCount), rowTracks(gridRowCount), m_grid(grid) {}
Vector<GridTrack> columnTracks;
Vector<GridTrack> rowTracks;
Vector<size_t> contentSizedTracksIndex;
// Performance optimization: hold onto these Vectors until the end of Layout
// to avoid repeated malloc / free.
Vector<GridTrack*> filteredTracks;
Vector<GridItemWithSpan> itemsSortedByIncreasingSpan;
Vector<GridTrack*> growBeyondGrowthLimitsTracks;
LayoutUnit& freeSpace(GridTrackSizingDirection direction) {
return direction == ForColumns ? freeSpaceForColumns : freeSpaceForRows;
}
LayoutUnit availableSpace() const { return m_availableSpace; }
void setAvailableSpace(LayoutUnit availableSpace) {
m_availableSpace = availableSpace;
}
SizingOperation sizingOperation{TrackSizing};
enum SizingState {
ColumnSizingFirstIteration,
RowSizingFirstIteration,
ColumnSizingSecondIteration,
RowSizingSecondIteration
};
SizingState sizingState{ColumnSizingFirstIteration};
void nextState() {
switch (sizingState) {
case ColumnSizingFirstIteration:
sizingState = RowSizingFirstIteration;
return;
case RowSizingFirstIteration:
sizingState = ColumnSizingSecondIteration;
return;
case ColumnSizingSecondIteration:
sizingState = RowSizingSecondIteration;
return;
case RowSizingSecondIteration:
sizingState = ColumnSizingFirstIteration;
return;
}
NOTREACHED();
sizingState = ColumnSizingFirstIteration;
}
bool isValidTransition(GridTrackSizingDirection direction) const {
switch (sizingState) {
case ColumnSizingFirstIteration:
case ColumnSizingSecondIteration:
return direction == ForColumns;
case RowSizingFirstIteration:
case RowSizingSecondIteration:
return direction == ForRows;
}
NOTREACHED();
return false;
}
Grid& grid() const { return m_grid; }
private:
LayoutUnit freeSpaceForColumns{};
LayoutUnit freeSpaceForRows{};
// No need to store one per direction as it will be only used for computations
// during each axis track sizing. It's cached here because we need it to
// compute relative sizes.
LayoutUnit m_availableSpace;
Grid& m_grid;
};
struct GridItemsSpanGroupRange {
Vector<GridItemWithSpan>::iterator rangeStart;
Vector<GridItemWithSpan>::iterator rangeEnd;
};
LayoutGrid::LayoutGrid(Element* element) : LayoutBlock(element), m_grid(this) {
ASSERT(!childrenInline());
if (!isAnonymous())
UseCounter::count(document(), UseCounter::CSSGridLayout);
}
LayoutGrid::~LayoutGrid() {}
LayoutGrid* LayoutGrid::createAnonymous(Document* document) {
LayoutGrid* layoutGrid = new LayoutGrid(nullptr);
layoutGrid->setDocumentForAnonymous(document);
return layoutGrid;
}
void LayoutGrid::addChild(LayoutObject* newChild, LayoutObject* beforeChild) {
LayoutBlock::addChild(newChild, beforeChild);
// The grid needs to be recomputed as it might contain auto-placed items that
// will change their position.
dirtyGrid();
}
void LayoutGrid::removeChild(LayoutObject* child) {
LayoutBlock::removeChild(child);
// The grid needs to be recomputed as it might contain auto-placed items that
// will change their position.
dirtyGrid();
}
void LayoutGrid::styleDidChange(StyleDifference diff,
const ComputedStyle* oldStyle) {
LayoutBlock::styleDidChange(diff, oldStyle);
if (!oldStyle)
return;
// FIXME: The following checks could be narrowed down if we kept track of
// which type of grid items we have:
// - explicit grid size changes impact negative explicitely positioned and
// auto-placed grid items.
// - named grid lines only impact grid items with named grid lines.
// - auto-flow changes only impacts auto-placed children.
if (explicitGridDidResize(*oldStyle) ||
namedGridLinesDefinitionDidChange(*oldStyle) ||
oldStyle->getGridAutoFlow() != styleRef().getGridAutoFlow() ||
(diff.needsLayout() && (styleRef().gridAutoRepeatColumns().size() ||
styleRef().gridAutoRepeatRows().size())))
dirtyGrid();
}
bool LayoutGrid::explicitGridDidResize(const ComputedStyle& oldStyle) const {
return oldStyle.gridTemplateColumns().size() !=
styleRef().gridTemplateColumns().size() ||
oldStyle.gridTemplateRows().size() !=
styleRef().gridTemplateRows().size() ||
oldStyle.namedGridAreaColumnCount() !=
styleRef().namedGridAreaColumnCount() ||
oldStyle.namedGridAreaRowCount() !=
styleRef().namedGridAreaRowCount() ||
oldStyle.gridAutoRepeatColumns().size() !=
styleRef().gridAutoRepeatColumns().size() ||
oldStyle.gridAutoRepeatRows().size() !=
styleRef().gridAutoRepeatRows().size();
}
bool LayoutGrid::namedGridLinesDefinitionDidChange(
const ComputedStyle& oldStyle) const {
return oldStyle.namedGridRowLines() != styleRef().namedGridRowLines() ||
oldStyle.namedGridColumnLines() != styleRef().namedGridColumnLines();
}
LayoutUnit LayoutGrid::computeTrackBasedLogicalHeight(
const GridSizingData& sizingData) const {
LayoutUnit logicalHeight;
for (const auto& row : sizingData.rowTracks)
logicalHeight += row.baseSize();
logicalHeight +=
guttersSize(sizingData.grid(), ForRows, 0, sizingData.rowTracks.size(),
sizingData.sizingOperation);
return logicalHeight;
}
void LayoutGrid::computeTrackSizesForDefiniteSize(
GridTrackSizingDirection direction,
GridSizingData& sizingData,
LayoutUnit availableSpace) const {
DCHECK(sizingData.isValidTransition(direction));
sizingData.setAvailableSpace(availableSpace);
sizingData.freeSpace(direction) =
availableSpace - guttersSize(sizingData.grid(), direction, 0,
sizingData.grid().numTracks(direction),
sizingData.sizingOperation);
sizingData.sizingOperation = TrackSizing;
LayoutUnit baseSizes, growthLimits;
computeUsedBreadthOfGridTracks(direction, sizingData, baseSizes,
growthLimits);
ASSERT(tracksAreWiderThanMinTrackBreadth(direction, sizingData));
sizingData.nextState();
}
void LayoutGrid::repeatTracksSizingIfNeeded(GridSizingData& sizingData,
LayoutUnit availableSpaceForColumns,
LayoutUnit availableSpaceForRows) {
DCHECK(sizingData.sizingState > GridSizingData::RowSizingFirstIteration);
// In orthogonal flow cases column track's size is determined by using the
// computed row track's size, which it was estimated during the first cycle of
// the sizing algorithm.
// Hence we need to repeat computeUsedBreadthOfGridTracks for both, columns
// and rows, to determine the final values.
// TODO (lajava): orthogonal flows is just one of the cases which may require
// a new cycle of the sizing algorithm; there may be more. In addition, not
// all the cases with orthogonal flows require this extra cycle; we need a
// more specific condition to detect whether child's min-content contribution
// has changed or not.
if (sizingData.grid().hasAnyOrthogonalGridItem()) {
computeTrackSizesForDefiniteSize(ForColumns, sizingData,
availableSpaceForColumns);
computeTrackSizesForDefiniteSize(ForRows, sizingData,
availableSpaceForRows);
}
}
void LayoutGrid::layoutBlock(bool relayoutChildren) {
ASSERT(needsLayout());
// We cannot perform a simplifiedLayout() on a dirty grid that
// has positioned items to be laid out.
if (!relayoutChildren &&
(!m_grid.needsItemsPlacement() || !posChildNeedsLayout()) &&
simplifiedLayout())
return;
SubtreeLayoutScope layoutScope(*this);
{
// LayoutState needs this deliberate scope to pop before updating scroll
// information (which may trigger relayout).
LayoutState state(*this);
LayoutSize previousSize = size();
// We need to clear both own and containingBlock override sizes to
// ensure we get the same result when grid's intrinsic size is
// computed again in the updateLogicalWidth call bellow.
if (sizesLogicalWidthToFitContent(styleRef().logicalWidth()) ||
styleRef().logicalWidth().isIntrinsicOrAuto()) {
for (auto* child = firstInFlowChildBox(); child;
child = child->nextInFlowSiblingBox()) {
if (!isOrthogonalChild(*child))
continue;
child->clearOverrideSize();
child->clearContainingBlockOverrideSize();
child->forceLayout();
}
}
updateLogicalWidth();
m_hasDefiniteLogicalHeight = hasDefiniteLogicalHeight();
TextAutosizer::LayoutScope textAutosizerLayoutScope(this, &layoutScope);
placeItemsOnGrid(m_grid, TrackSizing);
GridSizingData sizingData(numTracks(ForColumns, m_grid),
numTracks(ForRows, m_grid), m_grid);
// 1- First, the track sizing algorithm is used to resolve the sizes of the
// grid columns.
// At this point the logical width is always definite as the above call to
// updateLogicalWidth() properly resolves intrinsic sizes. We cannot do the
// same for heights though because many code paths inside
// updateLogicalHeight() require a previous call to setLogicalHeight() to
// resolve heights properly (like for positioned items for example).
LayoutUnit availableSpaceForColumns = availableLogicalWidth();
computeTrackSizesForDefiniteSize(ForColumns, sizingData,
availableSpaceForColumns);
// 2- Next, the track sizing algorithm resolves the sizes of the grid rows,
// using the grid column sizes calculated in the previous step.
if (cachedHasDefiniteLogicalHeight()) {
computeTrackSizesForDefiniteSize(
ForRows, sizingData,
availableLogicalHeight(ExcludeMarginBorderPadding));
} else {
computeTrackSizesForIndefiniteSize(
ForRows, sizingData, m_minContentHeight, m_maxContentHeight);
sizingData.nextState();
sizingData.sizingOperation = TrackSizing;
}
LayoutUnit trackBasedLogicalHeight =
computeTrackBasedLogicalHeight(sizingData) +
borderAndPaddingLogicalHeight() + scrollbarLogicalHeight();
setLogicalHeight(trackBasedLogicalHeight);
LayoutUnit oldClientAfterEdge = clientLogicalBottom();
updateLogicalHeight();
// Once grid's indefinite height is resolved, we can compute the
// available free space for Content Alignment.
if (!cachedHasDefiniteLogicalHeight())
sizingData.freeSpace(ForRows) = logicalHeight() - trackBasedLogicalHeight;
// 3- If the min-content contribution of any grid items have changed based
// on the row sizes calculated in step 2, steps 1 and 2 are repeated with
// the new min-content contribution (once only).
repeatTracksSizingIfNeeded(sizingData, availableSpaceForColumns,
contentLogicalHeight());
// Grid container should have the minimum height of a line if it's editable.
// That doesn't affect track sizing though.
if (hasLineIfEmpty())
setLogicalHeight(
std::max(logicalHeight(), minimumLogicalHeightForEmptyLine()));
applyStretchAlignmentToTracksIfNeeded(ForColumns, sizingData);
applyStretchAlignmentToTracksIfNeeded(ForRows, sizingData);
layoutGridItems(sizingData);
if (size() != previousSize)
relayoutChildren = true;
layoutPositionedObjects(relayoutChildren || isDocumentElement());
computeOverflow(oldClientAfterEdge);
}
updateLayerTransformAfterLayout();
updateAfterLayout();
clearNeedsLayout();
}
LayoutUnit LayoutGrid::gridGapForDirection(
GridTrackSizingDirection direction,
SizingOperation sizingOperation) const {
LayoutUnit availableSize;
const Length& gap = direction == ForColumns ? styleRef().gridColumnGap()
: styleRef().gridRowGap();
if (sizingOperation == TrackSizing && gap.isPercent())
availableSize = direction == ForColumns
? availableLogicalWidth()
: availableLogicalHeightForPercentageComputation();
// TODO(rego): Maybe we could cache the computed percentage as a performance
// improvement.
return valueForLength(gap, availableSize);
}
LayoutUnit LayoutGrid::guttersSize(const Grid& grid,
GridTrackSizingDirection direction,
size_t startLine,
size_t span,
SizingOperation sizingOperation) const {
if (span <= 1)
return LayoutUnit();
LayoutUnit gap = gridGapForDirection(direction, sizingOperation);
// Fast path, no collapsing tracks.
if (!grid.hasAutoRepeatEmptyTracks(direction))
return gap * (span - 1);
// If there are collapsing tracks we need to be sure that gutters are properly
// collapsed. Apart from that, if we have a collapsed track in the edges of
// the span we're considering, we need to move forward (or backwards) in order
// to know whether the collapsed tracks reach the end of the grid (so the gap
// becomes 0) or there is a non empty track before that.
LayoutUnit gapAccumulator;
size_t endLine = startLine + span;
for (size_t line = startLine; line < endLine - 1; ++line) {
if (!grid.isEmptyAutoRepeatTrack(direction, line))
gapAccumulator += gap;
}
// The above loop adds one extra gap for trailing collapsed tracks.
if (gapAccumulator && grid.isEmptyAutoRepeatTrack(direction, endLine - 1)) {
DCHECK_GE(gapAccumulator, gap);
gapAccumulator -= gap;
}
// If the startLine is the start line of a collapsed track we need to go
// backwards till we reach a non collapsed track. If we find a non collapsed
// track we need to add that gap.
if (startLine && grid.isEmptyAutoRepeatTrack(direction, startLine)) {
size_t nonEmptyTracksBeforeStartLine = startLine;
auto begin = grid.autoRepeatEmptyTracks(direction)->begin();
for (auto it = begin; *it != startLine; ++it) {
DCHECK(nonEmptyTracksBeforeStartLine);
--nonEmptyTracksBeforeStartLine;
}
if (nonEmptyTracksBeforeStartLine)
gapAccumulator += gap;
}
// If the endLine is the end line of a collapsed track we need to go forward
// till we reach a non collapsed track. If we find a non collapsed track we
// need to add that gap.
if (grid.isEmptyAutoRepeatTrack(direction, endLine - 1)) {
size_t nonEmptyTracksAfterEndLine = grid.numTracks(direction) - endLine;
auto currentEmptyTrack =
grid.autoRepeatEmptyTracks(direction)->find(endLine - 1);
auto endEmptyTrack = grid.autoRepeatEmptyTracks(direction)->end();
// HashSet iterators do not implement operator- so we have to manually
// iterate to know the number of remaining empty tracks.
for (auto it = ++currentEmptyTrack; it != endEmptyTrack; ++it) {
DCHECK(nonEmptyTracksAfterEndLine);
--nonEmptyTracksAfterEndLine;
}
if (nonEmptyTracksAfterEndLine)
gapAccumulator += gap;
}
return gapAccumulator;
}
void LayoutGrid::computeIntrinsicLogicalWidths(
LayoutUnit& minLogicalWidth,
LayoutUnit& maxLogicalWidth) const {
Grid grid(this);
placeItemsOnGrid(grid, IntrinsicSizeComputation);
GridSizingData sizingData(numTracks(ForColumns, grid),
numTracks(ForRows, grid), grid);
computeTrackSizesForIndefiniteSize(ForColumns, sizingData, minLogicalWidth,
maxLogicalWidth);
LayoutUnit scrollbarWidth = LayoutUnit(scrollbarLogicalWidth());
minLogicalWidth += scrollbarWidth;
maxLogicalWidth += scrollbarWidth;
}
void LayoutGrid::computeTrackSizesForIndefiniteSize(
GridTrackSizingDirection direction,
GridSizingData& sizingData,
LayoutUnit& minIntrinsicSize,
LayoutUnit& maxIntrinsicSize) const {
DCHECK(sizingData.isValidTransition(direction));
sizingData.setAvailableSpace(LayoutUnit());
sizingData.freeSpace(direction) = LayoutUnit();
sizingData.sizingOperation = IntrinsicSizeComputation;
computeUsedBreadthOfGridTracks(direction, sizingData, minIntrinsicSize,
maxIntrinsicSize);
size_t numberOfTracks = direction == ForColumns
? sizingData.columnTracks.size()
: sizingData.rowTracks.size();
LayoutUnit totalGuttersSize =
guttersSize(sizingData.grid(), direction, 0, numberOfTracks,
sizingData.sizingOperation);
minIntrinsicSize += totalGuttersSize;
maxIntrinsicSize += totalGuttersSize;
#if DCHECK_IS_ON()
DCHECK(tracksAreWiderThanMinTrackBreadth(direction, sizingData));
#endif
}
LayoutUnit LayoutGrid::computeIntrinsicLogicalContentHeightUsing(
const Length& logicalHeightLength,
LayoutUnit intrinsicContentHeight,
LayoutUnit borderAndPadding) const {
if (logicalHeightLength.isMinContent())
return m_minContentHeight;
if (logicalHeightLength.isMaxContent())
return m_maxContentHeight;
if (logicalHeightLength.isFitContent()) {
if (m_minContentHeight == -1 || m_maxContentHeight == -1)
return LayoutUnit(-1);
LayoutUnit fillAvailableExtent =
containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
return std::min<LayoutUnit>(
m_maxContentHeight, std::max(m_minContentHeight, fillAvailableExtent));
}
if (logicalHeightLength.isFillAvailable())
return containingBlock()->availableLogicalHeight(
ExcludeMarginBorderPadding) -
borderAndPadding;
ASSERT_NOT_REACHED();
return LayoutUnit();
}
static inline double normalizedFlexFraction(const GridTrack& track,
double flexFactor) {
return track.baseSize() / std::max<double>(1, flexFactor);
}
void LayoutGrid::computeUsedBreadthOfGridTracks(
GridTrackSizingDirection direction,
GridSizingData& sizingData,
LayoutUnit& baseSizesWithoutMaximization,
LayoutUnit& growthLimitsWithoutMaximization) const {
LayoutUnit& freeSpace = sizingData.freeSpace(direction);
const LayoutUnit initialFreeSpace = freeSpace;
Vector<GridTrack>& tracks = (direction == ForColumns)
? sizingData.columnTracks
: sizingData.rowTracks;
Vector<size_t> flexibleSizedTracksIndex;
sizingData.contentSizedTracksIndex.shrink(0);
// Grid gutters were removed from freeSpace by the caller, but we must use
// them to compute relative (i.e. percentages) sizes.
LayoutUnit maxSize = sizingData.availableSpace().clampNegativeToZero();
bool hasDefiniteFreeSpace = sizingData.sizingOperation == TrackSizing;
// 1. Initialize per Grid track variables.
for (size_t i = 0; i < tracks.size(); ++i) {
GridTrack& track = tracks[i];
GridTrackSize trackSize = gridTrackSize(direction, i, sizingData);
track.setBaseSize(computeUsedBreadthOfMinLength(trackSize, maxSize));
track.setGrowthLimit(
computeUsedBreadthOfMaxLength(trackSize, track.baseSize(), maxSize));
track.setInfinitelyGrowable(false);
if (trackSize.isFitContent()) {
GridLength gridLength = trackSize.fitContentTrackBreadth();
if (!gridLength.hasPercentage() || hasDefiniteFreeSpace)
track.setGrowthLimitCap(valueForLength(gridLength.length(), maxSize));
}
if (trackSize.isContentSized())
sizingData.contentSizedTracksIndex.push_back(i);
if (trackSize.maxTrackBreadth().isFlex())
flexibleSizedTracksIndex.push_back(i);
}
// 2. Resolve content-based TrackSizingFunctions.
if (!sizingData.contentSizedTracksIndex.isEmpty())
resolveContentBasedTrackSizingFunctions(direction, sizingData);
baseSizesWithoutMaximization = growthLimitsWithoutMaximization = LayoutUnit();
for (auto& track : tracks) {
ASSERT(!track.infiniteGrowthPotential());
baseSizesWithoutMaximization += track.baseSize();
growthLimitsWithoutMaximization += track.growthLimit();
// The growth limit caps must be cleared now in order to properly sort
// tracks by growth potential on an eventual "Maximize Tracks".
track.setGrowthLimitCap(WTF::nullopt);
}
freeSpace = initialFreeSpace - baseSizesWithoutMaximization;
if (hasDefiniteFreeSpace && freeSpace <= 0)
return;
// 3. Grow all Grid tracks in GridTracks from their baseSize up to their
// growthLimit value until freeSpace is exhausted.
const size_t tracksSize = tracks.size();
if (hasDefiniteFreeSpace) {
Vector<GridTrack*> tracksForDistribution(tracksSize);
for (size_t i = 0; i < tracksSize; ++i) {
tracksForDistribution[i] = tracks.data() + i;
tracksForDistribution[i]->setPlannedSize(
tracksForDistribution[i]->baseSize());
}
distributeSpaceToTracks<MaximizeTracks>(tracksForDistribution, nullptr,
sizingData, freeSpace);
for (auto* track : tracksForDistribution)
track->setBaseSize(track->plannedSize());
} else {
for (auto& track : tracks)
track.setBaseSize(track.growthLimit());
}
if (flexibleSizedTracksIndex.isEmpty())
return;
// 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
double flexFraction = 0;
if (hasDefiniteFreeSpace) {
flexFraction = findFlexFactorUnitSize(
tracks, GridSpan::translatedDefiniteGridSpan(0, tracks.size()),
direction, initialFreeSpace, sizingData);
} else {
for (const auto& trackIndex : flexibleSizedTracksIndex) {
flexFraction = std::max(
flexFraction, normalizedFlexFraction(
tracks[trackIndex],
gridTrackSize(direction, trackIndex, sizingData)
.maxTrackBreadth()
.flex()));
}
const Grid& grid = sizingData.grid();
if (grid.hasGridItems()) {
for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
GridIterator iterator(grid, direction, flexibleSizedTracksIndex[i]);
while (LayoutBox* gridItem = iterator.nextGridItem()) {
const GridSpan& span = grid.gridItemSpan(*gridItem, direction);
// Do not include already processed items.
if (i > 0 && span.startLine() <= flexibleSizedTracksIndex[i - 1])
continue;
flexFraction =
std::max(flexFraction,
findFlexFactorUnitSize(
tracks, span, direction,
maxContentForChild(*gridItem, direction, sizingData),
sizingData));
}
}
}
}
LayoutUnit totalGrowth;
Vector<LayoutUnit> increments;
increments.grow(flexibleSizedTracksIndex.size());
computeFlexSizedTracksGrowth(direction, tracks, flexibleSizedTracksIndex,
flexFraction, increments, totalGrowth,
sizingData);
// We only need to redo the flex fraction computation for indefinite heights
// (definite sizes are already constrained by min/max sizes). Regarding
// widths, they are always definite at layout time so we shouldn't ever have
// to do this.
if (!hasDefiniteFreeSpace && direction == ForRows) {
auto minSize = computeContentLogicalHeight(
MinSize, styleRef().logicalMinHeight(), LayoutUnit(-1));
auto maxSize = computeContentLogicalHeight(
MaxSize, styleRef().logicalMaxHeight(), LayoutUnit(-1));
// Redo the flex fraction computation using min|max-height as definite
// available space in case the total height is smaller than min-height or
// larger than max-height.
LayoutUnit rowsSize =
totalGrowth + computeTrackBasedLogicalHeight(sizingData);
bool checkMinSize = minSize && rowsSize < minSize;
bool checkMaxSize = maxSize != -1 && rowsSize > maxSize;
if (checkMinSize || checkMaxSize) {
LayoutUnit freeSpace = checkMaxSize ? maxSize : LayoutUnit(-1);
freeSpace = std::max(freeSpace, minSize) -
guttersSize(sizingData.grid(), ForRows, 0,
sizingData.grid().numTracks(ForRows),
sizingData.sizingOperation);
flexFraction = findFlexFactorUnitSize(
tracks, GridSpan::translatedDefiniteGridSpan(0, tracks.size()),
ForRows, freeSpace, sizingData);
totalGrowth = LayoutUnit(0);
computeFlexSizedTracksGrowth(ForRows, tracks, flexibleSizedTracksIndex,
flexFraction, increments, totalGrowth,
sizingData);
}
}
size_t i = 0;
for (auto trackIndex : flexibleSizedTracksIndex) {
auto& track = tracks[trackIndex];
if (LayoutUnit increment = increments[i++])
track.setBaseSize(track.baseSize() + increment);
}
freeSpace -= totalGrowth;
growthLimitsWithoutMaximization += totalGrowth;
}
void LayoutGrid::computeFlexSizedTracksGrowth(
GridTrackSizingDirection direction,
Vector<GridTrack>& tracks,
const Vector<size_t>& flexibleSizedTracksIndex,
double flexFraction,
Vector<LayoutUnit>& increments,
LayoutUnit& totalGrowth,
const GridSizingData& sizingData) const {
size_t numFlexTracks = flexibleSizedTracksIndex.size();
DCHECK_EQ(increments.size(), numFlexTracks);
for (size_t i = 0; i < numFlexTracks; ++i) {
size_t trackIndex = flexibleSizedTracksIndex[i];
auto trackSize = gridTrackSize(direction, trackIndex, sizingData);
DCHECK(trackSize.maxTrackBreadth().isFlex());
LayoutUnit oldBaseSize = tracks[trackIndex].baseSize();
LayoutUnit newBaseSize =
std::max(oldBaseSize,
LayoutUnit(flexFraction * trackSize.maxTrackBreadth().flex()));
increments[i] = newBaseSize - oldBaseSize;
totalGrowth += increments[i];
}
}
LayoutUnit LayoutGrid::computeUsedBreadthOfMinLength(
const GridTrackSize& trackSize,
LayoutUnit maxSize) const {
const GridLength& gridLength = trackSize.minTrackBreadth();
if (gridLength.isFlex())
return LayoutUnit();
const Length& trackLength = gridLength.length();
if (trackLength.isSpecified())
return valueForLength(trackLength, maxSize);
ASSERT(trackLength.isMinContent() || trackLength.isAuto() ||
trackLength.isMaxContent());
return LayoutUnit();
}
LayoutUnit LayoutGrid::computeUsedBreadthOfMaxLength(
const GridTrackSize& trackSize,
LayoutUnit usedBreadth,
LayoutUnit maxSize) const {
const GridLength& gridLength = trackSize.maxTrackBreadth();
if (gridLength.isFlex())
return usedBreadth;
const Length& trackLength = gridLength.length();
if (trackLength.isSpecified())
return valueForLength(trackLength, maxSize);
ASSERT(trackLength.isMinContent() || trackLength.isAuto() ||
trackLength.isMaxContent());
return LayoutUnit(infinity);
}
double LayoutGrid::computeFlexFactorUnitSize(
const Vector<GridTrack>& tracks,
GridTrackSizingDirection direction,
double flexFactorSum,
LayoutUnit& leftOverSpace,
const Vector<size_t, 8>& flexibleTracksIndexes,
const GridSizingData& sizingData,
std::unique_ptr<TrackIndexSet> tracksToTreatAsInflexible) const {
// We want to avoid the effect of flex factors sum below 1 making the factor
// unit size to grow exponentially.
double hypotheticalFactorUnitSize =
leftOverSpace / std::max<double>(1, flexFactorSum);
// product of the hypothetical "flex factor unit" and any flexible track's
// "flex factor" must be grater than such track's "base size".
std::unique_ptr<TrackIndexSet> additionalTracksToTreatAsInflexible =
std::move(tracksToTreatAsInflexible);
bool validFlexFactorUnit = true;
for (auto index : flexibleTracksIndexes) {
if (additionalTracksToTreatAsInflexible &&
additionalTracksToTreatAsInflexible->contains(index))
continue;
LayoutUnit baseSize = tracks[index].baseSize();
double flexFactor =
gridTrackSize(direction, index, sizingData).maxTrackBreadth().flex();
// treating all such tracks as inflexible.
if (baseSize > hypotheticalFactorUnitSize * flexFactor) {
leftOverSpace -= baseSize;
flexFactorSum -= flexFactor;
if (!additionalTracksToTreatAsInflexible)
additionalTracksToTreatAsInflexible = WTF::makeUnique<TrackIndexSet>();
additionalTracksToTreatAsInflexible->add(index);
validFlexFactorUnit = false;
}
}
if (!validFlexFactorUnit) {
return computeFlexFactorUnitSize(
tracks, direction, flexFactorSum, leftOverSpace, flexibleTracksIndexes,
sizingData, std::move(additionalTracksToTreatAsInflexible));
}
return hypotheticalFactorUnitSize;
}
double LayoutGrid::findFlexFactorUnitSize(
const Vector<GridTrack>& tracks,
const GridSpan& tracksSpan,
GridTrackSizingDirection direction,
LayoutUnit leftOverSpace,
const GridSizingData& sizingData) const {
if (leftOverSpace <= 0)
return 0;
double flexFactorSum = 0;
Vector<size_t, 8> flexibleTracksIndexes;
for (const auto& trackIndex : tracksSpan) {
GridTrackSize trackSize = gridTrackSize(direction, trackIndex, sizingData);
if (!trackSize.maxTrackBreadth().isFlex()) {
leftOverSpace -= tracks[trackIndex].baseSize();
} else {
flexibleTracksIndexes.push_back(trackIndex);
flexFactorSum += trackSize.maxTrackBreadth().flex();
}
}
// The function is not called if we don't have <flex> grid tracks
ASSERT(!flexibleTracksIndexes.isEmpty());
return computeFlexFactorUnitSize(tracks, direction, flexFactorSum,
leftOverSpace, flexibleTracksIndexes,
sizingData);
}
static bool hasOverrideContainingBlockContentSizeForChild(
const LayoutBox& child,
GridTrackSizingDirection direction) {
return direction == ForColumns
? child.hasOverrideContainingBlockLogicalWidth()
: child.hasOverrideContainingBlockLogicalHeight();
}
static LayoutUnit overrideContainingBlockContentSizeForChild(
const LayoutBox& child,
GridTrackSizingDirection direction) {
return direction == ForColumns
? child.overrideContainingBlockContentLogicalWidth()
: child.overrideContainingBlockContentLogicalHeight();
}
static void setOverrideContainingBlockContentSizeForChild(
LayoutBox& child,
GridTrackSizingDirection direction,
LayoutUnit size) {
if (direction == ForColumns)
child.setOverrideContainingBlockContentLogicalWidth(size);
else
child.setOverrideContainingBlockContentLogicalHeight(size);
}
static bool shouldClearOverrideContainingBlockContentSizeForChild(
const LayoutBox& child,
GridTrackSizingDirection direction) {
if (direction == ForColumns)
return child.hasRelativeLogicalWidth() ||
child.styleRef().logicalWidth().isIntrinsicOrAuto();
return child.hasRelativeLogicalHeight() ||
child.styleRef().logicalHeight().isIntrinsicOrAuto();
}
const GridTrackSize& LayoutGrid::rawGridTrackSize(
GridTrackSizingDirection direction,
size_t translatedIndex,
const GridSizingData& sizingData) const {
bool isRowAxis = direction == ForColumns;
const Vector<GridTrackSize>& trackStyles =
isRowAxis ? styleRef().gridTemplateColumns()
: styleRef().gridTemplateRows();
const Vector<GridTrackSize>& autoRepeatTrackStyles =
isRowAxis ? styleRef().gridAutoRepeatColumns()
: styleRef().gridAutoRepeatRows();
const Vector<GridTrackSize>& autoTrackStyles =
isRowAxis ? styleRef().gridAutoColumns() : styleRef().gridAutoRows();
size_t insertionPoint = isRowAxis
? styleRef().gridAutoRepeatColumnsInsertionPoint()
: styleRef().gridAutoRepeatRowsInsertionPoint();
size_t autoRepeatTracksCount = sizingData.grid().autoRepeatTracks(direction);
// We should not use GridPositionsResolver::explicitGridXXXCount() for this
// because the explicit grid might be larger than the number of tracks in
// grid-template-rows|columns (if grid-template-areas is specified for
// example).
size_t explicitTracksCount = trackStyles.size() + autoRepeatTracksCount;
int untranslatedIndexAsInt =
translatedIndex + sizingData.grid().smallestTrackStart(direction);
size_t autoTrackStylesSize = autoTrackStyles.size();
if (untranslatedIndexAsInt < 0) {
int index = untranslatedIndexAsInt % static_cast<int>(autoTrackStylesSize);
// We need to traspose the index because the first negative implicit line
// will get the last defined auto track and so on.
index += index ? autoTrackStylesSize : 0;
return autoTrackStyles[index];
}
size_t untranslatedIndex = static_cast<size_t>(untranslatedIndexAsInt);
if (untranslatedIndex >= explicitTracksCount)
return autoTrackStyles[(untranslatedIndex - explicitTracksCount) %
autoTrackStylesSize];
if (LIKELY(!autoRepeatTracksCount) || untranslatedIndex < insertionPoint)
return trackStyles[untranslatedIndex];
if (untranslatedIndex < (insertionPoint + autoRepeatTracksCount)) {
size_t autoRepeatLocalIndex = untranslatedIndexAsInt - insertionPoint;
return autoRepeatTrackStyles[autoRepeatLocalIndex %
autoRepeatTrackStyles.size()];
}
return trackStyles[untranslatedIndex - autoRepeatTracksCount];
}
GridTrackSize LayoutGrid::gridTrackSize(
GridTrackSizingDirection direction,
size_t translatedIndex,
const GridSizingData& sizingData) const {
// Collapse empty auto repeat tracks if auto-fit.
if (sizingData.grid().hasAutoRepeatEmptyTracks(direction) &&
sizingData.grid().isEmptyAutoRepeatTrack(direction, translatedIndex))
return {Length(Fixed), LengthTrackSizing};
const GridTrackSize& trackSize =
rawGridTrackSize(direction, translatedIndex, sizingData);
if (trackSize.isFitContent())
return trackSize;
GridLength minTrackBreadth = trackSize.minTrackBreadth();
GridLength maxTrackBreadth = trackSize.maxTrackBreadth();
// If the logical width/height of the grid container is indefinite, percentage
// values are treated as <auto>.
if (minTrackBreadth.hasPercentage() || maxTrackBreadth.hasPercentage()) {
// For the inline axis this only happens when we're computing the intrinsic
// sizes (AvailableSpaceIndefinite).
if ((sizingData.sizingOperation == IntrinsicSizeComputation) ||
(direction == ForRows && !cachedHasDefiniteLogicalHeight())) {
if (minTrackBreadth.hasPercentage())
minTrackBreadth = Length(Auto);
if (maxTrackBreadth.hasPercentage())
maxTrackBreadth = Length(Auto);
}
}
// Flex sizes are invalid as a min sizing function. However we still can have
// a flexible |minTrackBreadth| if the track had a flex size directly (e.g.
// "1fr"), the spec says that in this case it implies an automatic minimum.
if (minTrackBreadth.isFlex())
minTrackBreadth = Length(Auto);
return GridTrackSize(minTrackBreadth, maxTrackBreadth);
}
bool LayoutGrid::isOrthogonalChild(const LayoutBox& child) const {
return child.isHorizontalWritingMode() != isHorizontalWritingMode();
}
LayoutUnit LayoutGrid::logicalHeightForChild(LayoutBox& child,
GridSizingData& sizingData) const {
GridTrackSizingDirection childBlockDirection =
flowAwareDirectionForChild(child, ForRows);
// If |child| has a relative logical height, we shouldn't let it override its
// intrinsic height, which is what we are interested in here. Thus we need to
// set the block-axis override size to -1 (no possible resolution).
if (shouldClearOverrideContainingBlockContentSizeForChild(child, ForRows)) {
setOverrideContainingBlockContentSizeForChild(child, childBlockDirection,
LayoutUnit(-1));
child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
}
// We need to clear the stretched height to properly compute logical height
// during layout.
if (child.needsLayout())
child.clearOverrideLogicalContentHeight();
child.layoutIfNeeded();
return child.logicalHeight() + child.marginLogicalHeight();
}
GridTrackSizingDirection LayoutGrid::flowAwareDirectionForChild(
const LayoutBox& child,
GridTrackSizingDirection direction) const {
return !isOrthogonalChild(child)
? direction
: (direction == ForColumns ? ForRows : ForColumns);
}
LayoutUnit LayoutGrid::minSizeForChild(LayoutBox& child,
GridTrackSizingDirection direction,
GridSizingData& sizingData) const {
GridTrackSizingDirection childInlineDirection =
flowAwareDirectionForChild(child, ForColumns);
bool isRowAxis = direction == childInlineDirection;
const Length& childSize = isRowAxis ? child.styleRef().logicalWidth()
: child.styleRef().logicalHeight();
const Length& childMinSize = isRowAxis ? child.styleRef().logicalMinWidth()
: child.styleRef().logicalMinHeight();
bool overflowIsVisible =
isRowAxis
? child.styleRef().overflowInlineDirection() == EOverflow::Visible
: child.styleRef().overflowBlockDirection() == EOverflow::Visible;
if (!childSize.isAuto() || (childMinSize.isAuto() && overflowIsVisible))
return minContentForChild(child, direction, sizingData);
bool overrideSizeHasChanged =
updateOverrideContainingBlockContentSizeForChild(
child, childInlineDirection, sizingData);
if (isRowAxis) {
LayoutUnit marginLogicalWidth =
sizingData.sizingOperation == TrackSizing
? computeMarginLogicalSizeForChild(InlineDirection, child)
: marginIntrinsicLogicalWidthForChild(child);
return child.computeLogicalWidthUsing(
MinSize, childMinSize,
overrideContainingBlockContentSizeForChild(child,
childInlineDirection),
this) +
marginLogicalWidth;
}
if (overrideSizeHasChanged &&
(direction != ForColumns ||
sizingData.sizingOperation != IntrinsicSizeComputation))
child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
child.layoutIfNeeded();
return child.computeLogicalHeightUsing(MinSize, childMinSize,
child.intrinsicLogicalHeight()) +
child.marginLogicalHeight() + child.scrollbarLogicalHeight();
}
bool LayoutGrid::updateOverrideContainingBlockContentSizeForChild(
LayoutBox& child,
GridTrackSizingDirection direction,
GridSizingData& sizingData) const {
LayoutUnit overrideSize =
gridAreaBreadthForChild(child, direction, sizingData);
if (hasOverrideContainingBlockContentSizeForChild(child, direction) &&
overrideContainingBlockContentSizeForChild(child, direction) ==
overrideSize)
return false;
setOverrideContainingBlockContentSizeForChild(child, direction, overrideSize);
return true;
}
DISABLE_CFI_PERF
LayoutUnit LayoutGrid::minContentForChild(LayoutBox& child,
GridTrackSizingDirection direction,
GridSizingData& sizingData) const {
GridTrackSizingDirection childInlineDirection =
flowAwareDirectionForChild(child, ForColumns);
if (direction == childInlineDirection) {
// If |child| has a relative logical width, we shouldn't let it override its
// intrinsic width, which is what we are interested in here. Thus we need to
// set the inline-axis override size to -1 (no possible resolution).
if (shouldClearOverrideContainingBlockContentSizeForChild(child,
ForColumns))
setOverrideContainingBlockContentSizeForChild(child, childInlineDirection,
LayoutUnit(-1));
// FIXME: It's unclear if we should return the intrinsic width or the
// preferred width.
// See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
LayoutUnit marginLogicalWidth =
child.needsLayout()
? computeMarginLogicalSizeForChild(InlineDirection, child)
: child.marginLogicalWidth();
return child.minPreferredLogicalWidth() + marginLogicalWidth;
}
// All orthogonal flow boxes were already laid out during an early layout
// phase performed in FrameView::performLayout.
// It's true that grid track sizing was not completed at that time and it may
// afffect the final height of a grid item, but since it's forbidden to
// perform a layout during intrinsic width computation, we have to use that
// computed height for now.
if (direction == ForColumns &&
sizingData.sizingOperation == IntrinsicSizeComputation) {
DCHECK(isOrthogonalChild(child));
return child.logicalHeight() + child.marginLogicalHeight();
}
if (updateOverrideContainingBlockContentSizeForChild(
child, childInlineDirection, sizingData))
child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
return logicalHeightForChild(child, sizingData);
}
DISABLE_CFI_PERF
LayoutUnit LayoutGrid::maxContentForChild(LayoutBox& child,
GridTrackSizingDirection direction,
GridSizingData& sizingData) const {
GridTrackSizingDirection childInlineDirection =
flowAwareDirectionForChild(child, ForColumns);
if (direction == childInlineDirection) {
// If |child| has a relative logical width, we shouldn't let it override its
// intrinsic width, which is what we are interested in here. Thus we need to
// set the inline-axis override size to -1 (no possible resolution).
if (shouldClearOverrideContainingBlockContentSizeForChild(child,
ForColumns))
setOverrideContainingBlockContentSizeForChild(child, childInlineDirection,
LayoutUnit(-1));
// FIXME: It's unclear if we should return the intrinsic width or the
// preferred width.
// See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
LayoutUnit marginLogicalWidth =
child.needsLayout()
? computeMarginLogicalSizeForChild(InlineDirection, child)
: child.marginLogicalWidth();
return child.maxPreferredLogicalWidth() + marginLogicalWidth;
}
// All orthogonal flow boxes were already laid out during an early layout
// phase performed in FrameView::performLayout.
// It's true that grid track sizing was not completed at that time and it may
// afffect the final height of a grid item, but since it's forbidden to
// perform a layout during intrinsic width computation, we have to use that
// computed height for now.
if (direction == ForColumns &&
sizingData.sizingOperation == IntrinsicSizeComputation) {
DCHECK(isOrthogonalChild(child));
return child.logicalHeight() + child.marginLogicalHeight();
}
if (updateOverrideContainingBlockContentSizeForChild(
child, childInlineDirection, sizingData))
child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
return logicalHeightForChild(child, sizingData);
}
// We're basically using a class instead of a std::pair because of accessing
// gridItem() or getGridSpan() is much more self-explanatory that using .first
// or .second members in the pair. Having a std::pair<LayoutBox*, size_t>
// does not work either because we still need the GridSpan so we'd have to add
// an extra hash lookup for each item at the beginning of
// LayoutGrid::resolveContentBasedTrackSizingFunctionsForItems().
class GridItemWithSpan {
public:
GridItemWithSpan(LayoutBox& gridItem, const GridSpan& gridSpan)
: m_gridItem(&gridItem), m_gridSpan(gridSpan) {}
LayoutBox& gridItem() const { return *m_gridItem; }
GridSpan getGridSpan() const { return m_gridSpan; }
bool operator<(const GridItemWithSpan other) const {
return m_gridSpan.integerSpan() < other.m_gridSpan.integerSpan();
}
private:
LayoutBox* m_gridItem;
GridSpan m_gridSpan;
};
bool LayoutGrid::spanningItemCrossesFlexibleSizedTracks(
const GridSpan& span,
GridTrackSizingDirection direction,
const GridSizingData& sizingData) const {
for (const auto& trackPosition : span) {
const GridTrackSize& trackSize =
gridTrackSize(direction, trackPosition, sizingData);
if (trackSize.minTrackBreadth().isFlex() ||
trackSize.maxTrackBreadth().isFlex())
return true;
}
return false;
}
void LayoutGrid::resolveContentBasedTrackSizingFunctions(
GridTrackSizingDirection direction,
GridSizingData& sizingData) const {
sizingData.itemsSortedByIncreasingSpan.shrink(0);
const Grid& grid = sizingData.grid();
if (grid.hasGridItems()) {
HashSet<LayoutBox*> itemsSet;
for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
GridIterator iterator(grid, direction, trackIndex);
GridTrack& track = (direction == ForColumns)
? sizingData.columnTracks[trackIndex]
: sizingData.rowTracks[trackIndex];
while (LayoutBox* gridItem = iterator.nextGridItem()) {
if (itemsSet.add(gridItem).isNewEntry) {
const GridSpan& span = grid.gridItemSpan(*gridItem, direction);
if (span.integerSpan() == 1) {
resolveContentBasedTrackSizingFunctionsForNonSpanningItems(
direction, span, *gridItem, track, sizingData);
} else if (!spanningItemCrossesFlexibleSizedTracks(span, direction,
sizingData)) {
sizingData.itemsSortedByIncreasingSpan.push_back(
GridItemWithSpan(*gridItem, span));
}
}
}
}
std::sort(sizingData.itemsSortedByIncreasingSpan.begin(),
sizingData.itemsSortedByIncreasingSpan.end());
}
auto it = sizingData.itemsSortedByIncreasingSpan.begin();
auto end = sizingData.itemsSortedByIncreasingSpan.end();
while (it != end) {
GridItemsSpanGroupRange spanGroupRange = {it,
std::upper_bound(it, end, *it)};
resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMinimums>(
direction, sizingData, spanGroupRange);
resolveContentBasedTrackSizingFunctionsForItems<
ResolveContentBasedMinimums>(direction, sizingData, spanGroupRange);
resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMinimums>(
direction, sizingData, spanGroupRange);
resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMaximums>(
direction, sizingData, spanGroupRange);
resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMaximums>(
direction, sizingData, spanGroupRange);
it = spanGroupRange.rangeEnd;
}
for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
GridTrack& track = (direction == ForColumns)
? sizingData.columnTracks[trackIndex]
: sizingData.rowTracks[trackIndex];
if (track.growthLimit() == infinity)
track.setGrowthLimit(track.baseSize());
}
}
void LayoutGrid::resolveContentBasedTrackSizingFunctionsForNonSpanningItems(
GridTrackSizingDirection direction,
const GridSpan& span,
LayoutBox& gridItem,
GridTrack& track,
GridSizingData& sizingData) const {
const size_t trackPosition = span.startLine();
GridTrackSize trackSize = gridTrackSize(direction, trackPosition, sizingData);
if (trackSize.hasMinContentMinTrackBreadth())
track.setBaseSize(std::max(
track.baseSize(), minContentForChild(gridItem, direction, sizingData)));
else if (trackSize.hasMaxContentMinTrackBreadth())
track.setBaseSize(std::max(
track.baseSize(), maxContentForChild(gridItem, direction, sizingData)));
else if (trackSize.hasAutoMinTrackBreadth())
track.setBaseSize(std::max(
track.baseSize(), minSizeForChild(gridItem, direction, sizingData)));
if (trackSize.hasMinContentMaxTrackBreadth()) {
track.setGrowthLimit(
std::max(track.growthLimit(),
minContentForChild(gridItem, direction, sizingData)));
} else if (trackSize.hasMaxContentOrAutoMaxTrackBreadth()) {
LayoutUnit growthLimit =
maxContentForChild(gridItem, direction, sizingData);
if (trackSize.isFitContent())
growthLimit =
std::min(growthLimit,
valueForLength(trackSize.fitContentTrackBreadth().length(),
sizingData.availableSpace()));
track.setGrowthLimit(std::max(track.growthLimit(), growthLimit));
}
}
static LayoutUnit trackSizeForTrackSizeComputationPhase(
TrackSizeComputationPhase phase,
const GridTrack& track,
TrackSizeRestriction restriction) {
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
case ResolveMaxContentMinimums:
case MaximizeTracks:
return track.baseSize();
case ResolveIntrinsicMaximums:
case ResolveMaxContentMaximums:
const LayoutUnit& growthLimit = track.growthLimit();
if (restriction == AllowInfinity)
return growthLimit;
return growthLimit == infinity ? track.baseSize() : growthLimit;
}
ASSERT_NOT_REACHED();
return track.baseSize();
}
static bool shouldProcessTrackForTrackSizeComputationPhase(
TrackSizeComputationPhase phase,
const GridTrackSize& trackSize) {
switch (phase) {
case ResolveIntrinsicMinimums:
return trackSize.hasIntrinsicMinTrackBreadth();
case ResolveContentBasedMinimums:
return trackSize.hasMinOrMaxContentMinTrackBreadth();
case ResolveMaxContentMinimums:
return trackSize.hasMaxContentMinTrackBreadth();
case ResolveIntrinsicMaximums:
return trackSize.hasIntrinsicMaxTrackBreadth();
case ResolveMaxContentMaximums:
return trackSize.hasMaxContentOrAutoMaxTrackBreadth();
case MaximizeTracks:
ASSERT_NOT_REACHED();
return false;
}
ASSERT_NOT_REACHED();
return false;
}
static bool trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(
TrackSizeComputationPhase phase,
const GridTrackSize& trackSize) {
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
return trackSize
.hasAutoOrMinContentMinTrackBreadthAndIntrinsicMaxTrackBreadth();
case ResolveMaxContentMinimums:
return trackSize
.hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth();
case ResolveIntrinsicMaximums:
case ResolveMaxContentMaximums:
return true;
case MaximizeTracks:
ASSERT_NOT_REACHED();
return false;
}
ASSERT_NOT_REACHED();
return false;
}
static void markAsInfinitelyGrowableForTrackSizeComputationPhase(
TrackSizeComputationPhase phase,
GridTrack& track) {
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
case ResolveMaxContentMinimums:
return;
case ResolveIntrinsicMaximums:
if (trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity) ==
infinity &&
track.plannedSize() != infinity)
track.setInfinitelyGrowable(true);
return;
case ResolveMaxContentMaximums:
if (track.infinitelyGrowable())
track.setInfinitelyGrowable(false);
return;
case MaximizeTracks:
ASSERT_NOT_REACHED();
return;
}
ASSERT_NOT_REACHED();
}
static void updateTrackSizeForTrackSizeComputationPhase(
TrackSizeComputationPhase phase,
GridTrack& track) {
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveContentBasedMinimums:
case ResolveMaxContentMinimums:
track.setBaseSize(track.plannedSize());
return;
case ResolveIntrinsicMaximums:
case ResolveMaxContentMaximums:
track.setGrowthLimit(track.plannedSize());
return;
case MaximizeTracks:
ASSERT_NOT_REACHED();
return;
}
ASSERT_NOT_REACHED();
}
LayoutUnit LayoutGrid::currentItemSizeForTrackSizeComputationPhase(
TrackSizeComputationPhase phase,
LayoutBox& gridItem,
GridTrackSizingDirection direction,
GridSizingData& sizingData) const {
switch (phase) {
case ResolveIntrinsicMinimums:
case ResolveIntrinsicMaximums:
return minSizeForChild(gridItem, direction, sizingData);
case ResolveContentBasedMinimums:
return minContentForChild(gridItem, direction, sizingData);
case ResolveMaxContentMinimums:
case ResolveMaxContentMaximums:
return maxContentForChild(gridItem, direction, sizingData);
case MaximizeTracks:
ASSERT_NOT_REACHED();
return LayoutUnit();
}
ASSERT_NOT_REACHED();
return LayoutUnit();
}
template <TrackSizeComputationPhase phase>
void LayoutGrid::resolveContentBasedTrackSizingFunctionsForItems(
GridTrackSizingDirection direction,
GridSizingData& sizingData,
const GridItemsSpanGroupRange& gridItemsWithSpan) const {
Vector<GridTrack>& tracks = (direction == ForColumns)
? sizingData.columnTracks
: sizingData.rowTracks;
for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
GridTrack& track = tracks[trackIndex];
track.setPlannedSize(
trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity));
}
for (auto it = gridItemsWithSpan.rangeStart; it != gridItemsWithSpan.rangeEnd;
++it) {
GridItemWithSpan& gridItemWithSpan = *it;
ASSERT(gridItemWithSpan.getGridSpan().integerSpan() > 1);
const GridSpan& itemSpan = gridItemWithSpan.getGridSpan();
sizingData.growBeyondGrowthLimitsTracks.shrink(0);
sizingData.filteredTracks.shrink(0);
LayoutUnit spanningTracksSize;
for (const auto& trackPosition : itemSpan) {
GridTrackSize trackSize =
gridTrackSize(direction, trackPosition, sizingData);
GridTrack& track = (direction == ForColumns)
? sizingData.columnTracks[trackPosition]
: sizingData.rowTracks[trackPosition];
spanningTracksSize +=
trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
if (!shouldProcessTrackForTrackSizeComputationPhase(phase, trackSize))
continue;
sizingData.filteredTracks.push_back(&track);
if (trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(
phase, trackSize))
sizingData.growBeyondGrowthLimitsTracks.push_back(&track);
}
if (sizingData.filteredTracks.isEmpty())
continue;
spanningTracksSize +=
guttersSize(sizingData.grid(), direction, itemSpan.startLine(),
itemSpan.integerSpan(), sizingData.sizingOperation);
LayoutUnit extraSpace =
currentItemSizeForTrackSizeComputationPhase(
phase, gridItemWithSpan.gridItem(), direction, sizingData) -
spanningTracksSize;
extraSpace = extraSpace.clampNegativeToZero();
auto& tracksToGrowBeyondGrowthLimits =
sizingData.growBeyondGrowthLimitsTracks.isEmpty()
? sizingData.filteredTracks
: sizingData.growBeyondGrowthLimitsTracks;
distributeSpaceToTracks<phase>(sizingData.filteredTracks,
&tracksToGrowBeyondGrowthLimits, sizingData,
extraSpace);
}
for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
GridTrack& track = tracks[trackIndex];
markAsInfinitelyGrowableForTrackSizeComputationPhase(phase, track);
updateTrackSizeForTrackSizeComputationPhase(phase, track);
}
}
static bool sortByGridTrackGrowthPotential(const GridTrack* track1,
const GridTrack* track2) {
// This check ensures that we respect the irreflexivity property of the strict
// weak ordering required by std::sort(forall x: NOT x < x).
bool track1HasInfiniteGrowthPotentialWithoutCap =
track1->infiniteGrowthPotential() && !track1->growthLimitCap();
bool track2HasInfiniteGrowthPotentialWithoutCap =
track2->infiniteGrowthPotential() && !track2->growthLimitCap();
if (track1HasInfiniteGrowthPotentialWithoutCap &&
track2HasInfiniteGrowthPotentialWithoutCap)
return false;
if (track1HasInfiniteGrowthPotentialWithoutCap ||
track2HasInfiniteGrowthPotentialWithoutCap)
return track2HasInfiniteGrowthPotentialWithoutCap;
LayoutUnit track1Limit =
track1->growthLimitCap().value_or(track1->growthLimit());
LayoutUnit track2Limit =
track2->growthLimitCap().value_or(track2->growthLimit());
return (track1Limit - track1->baseSize()) <
(track2Limit - track2->baseSize());
}
static void clampGrowthShareIfNeeded(TrackSizeComputationPhase phase,
const GridTrack& track,
LayoutUnit& growthShare) {
if (phase != ResolveMaxContentMaximums || !track.growthLimitCap())
return;
LayoutUnit distanceToCap =
track.growthLimitCap().value() - track.sizeDuringDistribution();
if (distanceToCap <= 0)
return;
growthShare = std::min(growthShare, distanceToCap);
}
template <TrackSizeComputationPhase phase>
void LayoutGrid::distributeSpaceToTracks(
Vector<GridTrack*>& tracks,
Vector<GridTrack*>* growBeyondGrowthLimitsTracks,
GridSizingData& sizingData,
LayoutUnit& availableLogicalSpace) const {
ASSERT(availableLogicalSpace >= 0);
for (auto* track : tracks)
track->setSizeDuringDistribution(
trackSizeForTrackSizeComputationPhase(phase, *track, ForbidInfinity));
if (availableLogicalSpace > 0) {
std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
size_t tracksSize = tracks.size();
for (size_t i = 0; i < tracksSize; ++i) {
GridTrack& track = *tracks[i];
LayoutUnit availableLogicalSpaceShare =
availableLogicalSpace / (tracksSize - i);
const LayoutUnit& trackBreadth =
trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
LayoutUnit growthShare =
track.infiniteGrowthPotential()
? availableLogicalSpaceShare
: std::min(availableLogicalSpaceShare,
track.growthLimit() - trackBreadth);
clampGrowthShareIfNeeded(phase, track, growthShare);
DCHECK_GE(growthShare, 0) << "We must never shrink any grid track or "
"else we can't guarantee we abide by our "
"min-sizing function.";
track.growSizeDuringDistribution(growthShare);
availableLogicalSpace -= growthShare;
}
}
if (availableLogicalSpace > 0 && growBeyondGrowthLimitsTracks) {
// We need to sort them because there might be tracks with growth limit caps
// (like the ones with fit-content()) which cannot indefinitely grow over
// the limits.
if (phase == ResolveMaxContentMaximums)
std::sort(growBeyondGrowthLimitsTracks->begin(),
growBeyondGrowthLimitsTracks->end(),
sortByGridTrackGrowthPotential);
size_t tracksGrowingAboveMaxBreadthSize =
growBeyondGrowthLimitsTracks->size();
for (size_t i = 0; i < tracksGrowingAboveMaxBreadthSize; ++i) {
GridTrack* track = growBeyondGrowthLimitsTracks->at(i);
LayoutUnit growthShare =
availableLogicalSpace / (tracksGrowingAboveMaxBreadthSize - i);
clampGrowthShareIfNeeded(phase, *track, growthShare);
DCHECK_GE(growthShare, 0) << "We must never shrink any grid track or "
"else we can't guarantee we abide by our "
"min-sizing function.";
track->growSizeDuringDistribution(growthShare);
availableLogicalSpace -= growthShare;
}
}
for (auto* track : tracks)
track->setPlannedSize(
track->plannedSize() == infinity
? track->sizeDuringDistribution()
: std::max(track->plannedSize(), track->sizeDuringDistribution()));
}
#if DCHECK_IS_ON()
bool LayoutGrid::tracksAreWiderThanMinTrackBreadth(
GridTrackSizingDirection direction,
GridSizingData& sizingData) const {
const Vector<GridTrack>& tracks = (direction == ForColumns)
? sizingData.columnTracks
: sizingData.rowTracks;
LayoutUnit maxSize = sizingData.availableSpace().clampNegativeToZero();
for (size_t i = 0; i < tracks.size(); ++i) {
GridTrackSize trackSize = gridTrackSize(direction, i, sizingData);
if (computeUsedBreadthOfMinLength(trackSize, maxSize) >
tracks[i].baseSize())
return false;
}
return true;
}
#endif
size_t LayoutGrid::computeAutoRepeatTracksCount(
GridTrackSizingDirection direction,
SizingOperation sizingOperation) const {
bool isRowAxis = direction == ForColumns;
const auto& autoRepeatTracks = isRowAxis ? styleRef().gridAutoRepeatColumns()
: styleRef().gridAutoRepeatRows();
size_t autoRepeatTrackListLength = autoRepeatTracks.size();
if (!autoRepeatTrackListLength)
return 0;
LayoutUnit availableSize;
if (isRowAxis) {
availableSize = sizingOperation == IntrinsicSizeComputation
? LayoutUnit(-1)
: availableLogicalWidth();
} else {
availableSize = availableLogicalHeightForPercentageComputation();
if (availableSize == -1) {
const Length& maxLength = styleRef().logicalMaxHeight();
if (!maxLength.isMaxSizeNone()) {
availableSize = constrainContentBoxLogicalHeightByMinMax(
availableLogicalHeightUsing(maxLength, ExcludeMarginBorderPadding),
LayoutUnit(-1));
}
}
}
bool needsToFulfillMinimumSize = false;
bool indefiniteMainAndMaxSizes = availableSize == LayoutUnit(-1);
if (indefiniteMainAndMaxSizes) {
const Length& minSize = isRowAxis ? styleRef().logicalMinWidth()
: styleRef().logicalMinHeight();
if (!minSize.isSpecified())
return autoRepeatTrackListLength;
LayoutUnit containingBlockAvailableSize =
isRowAxis ? containingBlockLogicalWidthForContent()
: containingBlockLogicalHeightForContent(
ExcludeMarginBorderPadding);
availableSize = valueForLength(minSize, containingBlockAvailableSize);
needsToFulfillMinimumSize = true;
}
LayoutUnit autoRepeatTracksSize;
for (auto autoTrackSize : autoRepeatTracks) {
DCHECK(autoTrackSize.minTrackBreadth().isLength());
DCHECK(!autoTrackSize.minTrackBreadth().isFlex());
bool hasDefiniteMaxTrackSizingFunction =
autoTrackSize.maxTrackBreadth().isLength() &&
!autoTrackSize.maxTrackBreadth().isContentSized();
auto trackLength = hasDefiniteMaxTrackSizingFunction
? autoTrackSize.maxTrackBreadth().length()
: autoTrackSize.minTrackBreadth().length();
autoRepeatTracksSize += valueForLength(trackLength, availableSize);
}
// For the purpose of finding the number of auto-repeated tracks, the UA must
// floor the track size to a UA-specified value to avoid division by zero. It
// is suggested that this floor be 1px.
autoRepeatTracksSize =
std::max<LayoutUnit>(LayoutUnit(1), autoRepeatTracksSize);
// There will be always at least 1 auto-repeat track, so take it already into
// account when computing the total track size.
LayoutUnit tracksSize = autoRepeatTracksSize;
const Vector<GridTrackSize>& trackSizes =
isRowAxis ? styleRef().gridTemplateColumns()
: styleRef().gridTemplateRows();
for (const auto& track : trackSizes) {
bool hasDefiniteMaxTrackBreadth = track.maxTrackBreadth().isLength() &&
!track.maxTrackBreadth().isContentSized();
DCHECK(hasDefiniteMaxTrackBreadth ||
(track.minTrackBreadth().isLength() &&
!track.minTrackBreadth().isContentSized()));
tracksSize += valueForLength(hasDefiniteMaxTrackBreadth
? track.maxTrackBreadth().length()
: track.minTrackBreadth().length(),
availableSize);
}
// Add gutters as if there where only 1 auto repeat track. Gaps between auto
// repeat tracks will be added later when computing the repetitions.
LayoutUnit gapSize = gridGapForDirection(direction, sizingOperation);
tracksSize += gapSize * trackSizes.size();
LayoutUnit freeSpace = availableSize - tracksSize;
if (freeSpace <= 0)
return autoRepeatTrackListLength;
size_t repetitions =
1 + (freeSpace / (autoRepeatTracksSize + gapSize)).toInt();
// Provided the grid container does not have a definite size or max-size in
// the relevant axis, if the min size is definite then the number of
// repetitions is the largest possible positive integer that fulfills that
// minimum requirement.
if (needsToFulfillMinimumSize)
++repetitions;
return repetitions * autoRepeatTrackListLength;
}
std::unique_ptr<LayoutGrid::OrderedTrackIndexSet>
LayoutGrid::computeEmptyTracksForAutoRepeat(
Grid& grid,
GridTrackSizingDirection direction) const {
bool isRowAxis = direction == ForColumns;
if ((isRowAxis && styleRef().gridAutoRepeatColumnsType() != AutoFit) ||
(!isRowAxis && styleRef().gridAutoRepeatRowsType() != AutoFit))
return nullptr;
std::unique_ptr<OrderedTrackIndexSet> emptyTrackIndexes;
size_t insertionPoint = isRowAxis
? styleRef().gridAutoRepeatColumnsInsertionPoint()
: styleRef().gridAutoRepeatRowsInsertionPoint();
size_t firstAutoRepeatTrack =
insertionPoint + std::abs(grid.smallestTrackStart(direction));
size_t lastAutoRepeatTrack =
firstAutoRepeatTrack + grid.autoRepeatTracks(direction);
if (!grid.hasGridItems()) {
emptyTrackIndexes = WTF::wrapUnique(new OrderedTrackIndexSet);
for (size_t trackIndex = firstAutoRepeatTrack;
trackIndex < lastAutoRepeatTrack; ++trackIndex)
emptyTrackIndexes->add(trackIndex);
} else {
for (size_t trackIndex = firstAutoRepeatTrack;
trackIndex < lastAutoRepeatTrack; ++trackIndex) {
GridIterator iterator(grid, direction, trackIndex);
if (!iterator.nextGridItem()) {
if (!emptyTrackIndexes)
emptyTrackIndexes = WTF::wrapUnique(new OrderedTrackIndexSet);
emptyTrackIndexes->add(trackIndex);
}
}
}
return emptyTrackIndexes;
}
size_t LayoutGrid::clampAutoRepeatTracks(GridTrackSizingDirection direction,
size_t autoRepeatTracks) const {
if (!autoRepeatTracks)
return 0;
size_t insertionPoint = direction == ForColumns
? styleRef().gridAutoRepeatColumnsInsertionPoint()
: styleRef().gridAutoRepeatRowsInsertionPoint();
if (insertionPoint == 0)
return std::min<size_t>(autoRepeatTracks, kGridMaxTracks);
if (insertionPoint >= kGridMaxTracks)
return 0;
return std::min(autoRepeatTracks,
static_cast<size_t>(kGridMaxTracks) - insertionPoint);
}
void LayoutGrid::placeItemsOnGrid(LayoutGrid::Grid& grid,
SizingOperation sizingOperation) const {
size_t autoRepeatRows =
computeAutoRepeatTracksCount(ForRows, sizingOperation);
size_t autoRepeatColumns =
computeAutoRepeatTracksCount(ForColumns, sizingOperation);
autoRepeatRows = clampAutoRepeatTracks(ForRows, autoRepeatRows);
autoRepeatColumns = clampAutoRepeatTracks(ForColumns, autoRepeatColumns);
if (autoRepeatRows != grid.autoRepeatTracks(ForRows) ||
autoRepeatColumns != grid.autoRepeatTracks(ForColumns)) {
grid.setNeedsItemsPlacement(true);
grid.setAutoRepeatTracks(autoRepeatRows, autoRepeatColumns);
}
if (!grid.needsItemsPlacement())
return;
DCHECK(!grid.hasGridItems());
populateExplicitGridAndOrderIterator(grid);
Vector<LayoutBox*> autoMajorAxisAutoGridItems;
Vector<LayoutBox*> specifiedMajorAxisAutoGridItems;
#if DCHECK_IS_ON()
DCHECK(!grid.hasAnyGridItemPaintOrder());
#endif
DCHECK(!grid.hasAnyOrthogonalGridItem());
bool hasAnyOrthogonalGridItem = false;
size_t childIndex = 0;
for (LayoutBox* child = grid.orderIterator().first(); child;
child = grid.orderIterator().next()) {
if (child->isOutOfFlowPositioned())
continue;
hasAnyOrthogonalGridItem =
hasAnyOrthogonalGridItem || isOrthogonalChild(*child);
grid.setGridItemPaintOrder(*child, childIndex++);
GridArea area = grid.gridItemArea(*child);
if (!area.rows.isIndefinite())
area.rows.translate(abs(grid.smallestTrackStart(ForRows)));
if (!area.columns.isIndefinite())
area.columns.translate(abs(grid.smallestTrackStart(ForColumns)));
if (area.rows.isIndefinite() || area.columns.isIndefinite()) {
grid.setGridItemArea(*child, area);
GridSpan majorAxisPositions =
(autoPlacementMajorAxisDirection() == ForColumns) ? area.columns
: area.rows;
if (majorAxisPositions.isIndefinite())
autoMajorAxisAutoGridItems.push_back(child);
else
specifiedMajorAxisAutoGridItems.push_back(child);
continue;
}
grid.insert(*child, area);
}
grid.setHasAnyOrthogonalGridItem(hasAnyOrthogonalGridItem);
#if DCHECK_IS_ON()
if (grid.hasGridItems()) {
DCHECK_GE(grid.numTracks(ForRows),
GridPositionsResolver::explicitGridRowCount(
*style(), grid.autoRepeatTracks(ForRows)));
DCHECK_GE(grid.numTracks(ForColumns),
GridPositionsResolver::explicitGridColumnCount(
*style(), grid.autoRepeatTracks(ForColumns)));
}
#endif
placeSpecifiedMajorAxisItemsOnGrid(grid, specifiedMajorAxisAutoGridItems);
placeAutoMajorAxisItemsOnGrid(grid, autoMajorAxisAutoGridItems);
// Compute collapsable tracks for auto-fit.
grid.setAutoRepeatEmptyColumns(
computeEmptyTracksForAutoRepeat(grid, ForColumns));
grid.setAutoRepeatEmptyRows(computeEmptyTracksForAutoRepeat(grid, ForRows));
grid.setNeedsItemsPlacement(false);
#if DCHECK_IS_ON()
for (LayoutBox* child = grid.orderIterator().first(); child;
child = grid.orderIterator().next()) {
if (child->isOutOfFlowPositioned())
continue;
GridArea area = grid.gridItemArea(*child);
ASSERT(area.rows.isTranslatedDefinite() &&
area.columns.isTranslatedDefinite());
}
#endif
}
void LayoutGrid::populateExplicitGridAndOrderIterator(Grid& grid) const {
OrderIteratorPopulator populator(grid.orderIterator());
int smallestRowStart = 0;
int smallestColumnStart = 0;
size_t autoRepeatRows = grid.autoRepeatTracks(ForRows);
size_t autoRepeatColumns = grid.autoRepeatTracks(ForColumns);
size_t maximumRowIndex =
GridPositionsResolver::explicitGridRowCount(*style(), autoRepeatRows);
size_t maximumColumnIndex = GridPositionsResolver::explicitGridColumnCount(
*style(), autoRepeatColumns);
for (LayoutBox* child = firstInFlowChildBox(); child;
child = child->nextInFlowSiblingBox()) {
populator.collectChild(child);
// This function bypasses the cache (gridItemArea()) as it is used to
// build it.
GridSpan rowPositions =
GridPositionsResolver::resolveGridPositionsFromStyle(
*style(), *child, ForRows, autoRepeatRows);
GridSpan columnPositions =
GridPositionsResolver::resolveGridPositionsFromStyle(
*style(), *child, ForColumns, autoRepeatColumns);
grid.setGridItemArea(*child, GridArea(rowPositions, columnPositions));
// |positions| is 0 if we need to run the auto-placement algorithm.
if (!rowPositions.isIndefinite()) {
smallestRowStart =
std::min(smallestRowStart, rowPositions.untranslatedStartLine());
maximumRowIndex =
std::max<int>(maximumRowIndex, rowPositions.untranslatedEndLine());
} else {
// Grow the grid for items with a definite row span, getting the largest
// such span.
size_t spanSize = GridPositionsResolver::spanSizeForAutoPlacedItem(
*style(), *child, ForRows);
maximumRowIndex = std::max(maximumRowIndex, spanSize);
}
if (!columnPositions.isIndefinite()) {
smallestColumnStart = std::min(smallestColumnStart,
columnPositions.untranslatedStartLine());
maximumColumnIndex = std::max<int>(maximumColumnIndex,
columnPositions.untranslatedEndLine());
} else {
// Grow the grid for items with a definite column span, getting the
// largest such span.
size_t spanSize = GridPositionsResolver::spanSizeForAutoPlacedItem(
*style(), *child, ForColumns);
maximumColumnIndex = std::max(maximumColumnIndex, spanSize);
}
}
grid.setSmallestTracksStart(smallestRowStart, smallestColumnStart);
grid.ensureGridSize(maximumRowIndex + abs(smallestRowStart),
maximumColumnIndex + abs(smallestColumnStart));
}
std::unique_ptr<GridArea>
LayoutGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(
const Grid& grid,
const LayoutBox& gridItem,
GridTrackSizingDirection specifiedDirection,
const GridSpan& specifiedPositions) const {
GridTrackSizingDirection crossDirection =
specifiedDirection == ForColumns ? ForRows : ForColumns;
const size_t endOfCrossDirection = grid.numTracks(crossDirection);
size_t crossDirectionSpanSize =
GridPositionsResolver::spanSizeForAutoPlacedItem(*style(), gridItem,
crossDirection);
GridSpan crossDirectionPositions = GridSpan::translatedDefiniteGridSpan(
endOfCrossDirection, endOfCrossDirection + crossDirectionSpanSize);
return WTF::wrapUnique(
new GridArea(specifiedDirection == ForColumns ? crossDirectionPositions
: specifiedPositions,
specifiedDirection == ForColumns ? specifiedPositions
: crossDirectionPositions));
}
void LayoutGrid::placeSpecifiedMajorAxisItemsOnGrid(
Grid& grid,
const Vector<LayoutBox*>& autoGridItems) const {
bool isForColumns = autoPlacementMajorAxisDirection() == ForColumns;
bool isGridAutoFlowDense = style()->isGridAutoFlowAlgorithmDense();
// Mapping between the major axis tracks (rows or columns) and the last
// auto-placed item's position inserted on that track. This is needed to
// implement "sparse" packing for items locked to a given track.
// See http://dev.w3.org/csswg/css-grid/#auto-placement-algo
HashMap<unsigned, unsigned, DefaultHash<unsigned>::Hash,
WTF::UnsignedWithZeroKeyHashTraits<unsigned>>
minorAxisCursors;
for (const auto& autoGridItem : autoGridItems) {
GridSpan majorAxisPositions =
grid.gridItemSpan(*autoGridItem, autoPlacementMajorAxisDirection());
ASSERT(majorAxisPositions.isTranslatedDefinite());
DCHECK(!grid.gridItemSpan(*autoGridItem, autoPlacementMinorAxisDirection())
.isTranslatedDefinite());
size_t minorAxisSpanSize = GridPositionsResolver::spanSizeForAutoPlacedItem(
*style(), *autoGridItem, autoPlacementMinorAxisDirection());
unsigned majorAxisInitialPosition = majorAxisPositions.startLine();
GridIterator iterator(
grid, autoPlacementMajorAxisDirection(), majorAxisPositions.startLine(),
isGridAutoFlowDense ? 0
: minorAxisCursors.get(majorAxisInitialPosition));
std::unique_ptr<GridArea> emptyGridArea = iterator.nextEmptyGridArea(
majorAxisPositions.integerSpan(), minorAxisSpanSize);
if (!emptyGridArea) {
emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(
grid, *autoGridItem, autoPlacementMajorAxisDirection(),
majorAxisPositions);
}
grid.insert(*autoGridItem, *emptyGridArea);
if (!isGridAutoFlowDense)
minorAxisCursors.set(majorAxisInitialPosition,
isForColumns ? emptyGridArea->rows.startLine()
: emptyGridArea->columns.startLine());
}
}
void LayoutGrid::placeAutoMajorAxisItemsOnGrid(
Grid& grid,
const Vector<LayoutBox*>& autoGridItems) const {
std::pair<size_t, size_t> autoPlacementCursor = std::make_pair(0, 0);
bool isGridAutoFlowDense = style()->isGridAutoFlowAlgorithmDense();
for (const auto& autoGridItem : autoGridItems) {
placeAutoMajorAxisItemOnGrid(grid, *autoGridItem, autoPlacementCursor);
// If grid-auto-flow is dense, reset auto-placement cursor.
if (isGridAutoFlowDense) {
autoPlacementCursor.first = 0;
autoPlacementCursor.second = 0;
}
}
}
void LayoutGrid::placeAutoMajorAxisItemOnGrid(
Grid& grid,
LayoutBox& gridItem,
std::pair<size_t, size_t>& autoPlacementCursor) const {
GridSpan minorAxisPositions =
grid.gridItemSpan(gridItem, autoPlacementMinorAxisDirection());
DCHECK(!grid.gridItemSpan(gridItem, autoPlacementMajorAxisDirection())
.isTranslatedDefinite());
size_t majorAxisSpanSize = GridPositionsResolver::spanSizeForAutoPlacedItem(
*style(), gridItem, autoPlacementMajorAxisDirection());
const size_t endOfMajorAxis =
grid.numTracks(autoPlacementMajorAxisDirection());
size_t majorAxisAutoPlacementCursor =
autoPlacementMajorAxisDirection() == ForColumns
? autoPlacementCursor.second
: autoPlacementCursor.first;
size_t minorAxisAutoPlacementCursor =
autoPlacementMajorAxisDirection() == ForColumns
? autoPlacementCursor.first
: autoPlacementCursor.second;
std::unique_ptr<GridArea> emptyGridArea;
if (minorAxisPositions.isTranslatedDefinite()) {
// Move to the next track in major axis if initial position in minor axis is
// before auto-placement cursor.
if (minorAxisPositions.startLine() < minorAxisAutoPlacementCursor)
majorAxisAutoPlacementCursor++;
if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
GridIterator iterator(grid, autoPlacementMinorAxisDirection(),
minorAxisPositions.startLine(),
majorAxisAutoPlacementCursor);
emptyGridArea = iterator.nextEmptyGridArea(
minorAxisPositions.integerSpan(), majorAxisSpanSize);
}
if (!emptyGridArea) {
emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(
grid, gridItem, autoPlacementMinorAxisDirection(),
minorAxisPositions);
}
} else {
size_t minorAxisSpanSize = GridPositionsResolver::spanSizeForAutoPlacedItem(
*style(), gridItem, autoPlacementMinorAxisDirection());
for (size_t majorAxisIndex = majorAxisAutoPlacementCursor;
majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
GridIterator iterator(grid, autoPlacementMajorAxisDirection(),
majorAxisIndex, minorAxisAutoPlacementCursor);
emptyGridArea =
iterator.nextEmptyGridArea(majorAxisSpanSize, minorAxisSpanSize);
if (emptyGridArea) {
// Check that it fits in the minor axis direction, as we shouldn't grow
// in that direction here (it was already managed in
// populateExplicitGridAndOrderIterator()).
size_t minorAxisFinalPositionIndex =
autoPlacementMinorAxisDirection() == ForColumns
? emptyGridArea->columns.endLine()
: emptyGridArea->rows.endLine();
const size_t endOfMinorAxis =
grid.numTracks(autoPlacementMinorAxisDirection());
if (minorAxisFinalPositionIndex <= endOfMinorAxis)
break;
// Discard empty grid area as it does not fit in the minor axis
// direction. We don't need to create a new empty grid area yet as we
// might find a valid one in the next iteration.
emptyGridArea = nullptr;
}
// As we're moving to the next track in the major axis we should reset the
// auto-placement cursor in the minor axis.
minorAxisAutoPlacementCursor = 0;
}
if (!emptyGridArea)
emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(
grid, gridItem, autoPlacementMinorAxisDirection(),
GridSpan::translatedDefiniteGridSpan(0, minorAxisSpanSize));
}
grid.insert(gridItem, *emptyGridArea);
// Move auto-placement cursor to the new position.
autoPlacementCursor.first = emptyGridArea->rows.startLine();
autoPlacementCursor.second = emptyGridArea->columns.startLine();
}
GridTrackSizingDirection LayoutGrid::autoPlacementMajorAxisDirection() const {
return style()->isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
}
GridTrackSizingDirection LayoutGrid::autoPlacementMinorAxisDirection() const {
return style()->isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
}
void LayoutGrid::dirtyGrid() {
if (m_grid.needsItemsPlacement())
return;
m_grid.setNeedsItemsPlacement(true);
m_gridItemsOverflowingGridArea.resize(0);
}
Vector<LayoutUnit> LayoutGrid::trackSizesForComputedStyle(
GridTrackSizingDirection direction) const {
bool isRowAxis = direction == ForColumns;
auto& positions = isRowAxis ? m_columnPositions : m_rowPositions;
size_t numPositions = positions.size();
LayoutUnit offsetBetweenTracks =
isRowAxis ? m_offsetBetweenColumns : m_offsetBetweenRows;
Vector<LayoutUnit> tracks;
if (numPositions < 2)
return tracks;
DCHECK(!m_grid.needsItemsPlacement());
bool hasCollapsedTracks = m_grid.hasAutoRepeatEmptyTracks(direction);
LayoutUnit gap = !hasCollapsedTracks
? gridGapForDirection(direction, TrackSizing)
: LayoutUnit();
tracks.reserveCapacity(numPositions - 1);
for (size_t i = 0; i < numPositions - 2; ++i)
tracks.push_back(positions[i + 1] - positions[i] - offsetBetweenTracks -
gap);
tracks.push_back(positions[numPositions - 1] - positions[numPositions - 2]);
if (!hasCollapsedTracks)
return tracks;
size_t remainingEmptyTracks = m_grid.autoRepeatEmptyTracks(direction)->size();
size_t lastLine = tracks.size();
gap = gridGapForDirection(direction, TrackSizing);
for (size_t i = 1; i < lastLine; ++i) {
if (m_grid.isEmptyAutoRepeatTrack(direction, i - 1)) {
--remainingEmptyTracks;
} else {
// Remove the gap between consecutive non empty tracks. Remove it also
// just once for an arbitrary number of empty tracks between two non empty
// ones.
bool allRemainingTracksAreEmpty = remainingEmptyTracks == (lastLine - i);
if (!allRemainingTracksAreEmpty ||
!m_grid.isEmptyAutoRepeatTrack(direction, i))
tracks[i - 1] -= gap;
}
}
return tracks;
}
static const StyleContentAlignmentData& contentAlignmentNormalBehavior() {
static const StyleContentAlignmentData normalBehavior = {
ContentPositionNormal, ContentDistributionStretch};
return normalBehavior;
}
void LayoutGrid::applyStretchAlignmentToTracksIfNeeded(
GridTrackSizingDirection direction,
GridSizingData& sizingData) {
LayoutUnit& availableSpace = sizingData.freeSpace(direction);
if (availableSpace <= 0 ||
(direction == ForColumns &&
styleRef().resolvedJustifyContentDistribution(
contentAlignmentNormalBehavior()) != ContentDistributionStretch) ||
(direction == ForRows &&
styleRef().resolvedAlignContentDistribution(
contentAlignmentNormalBehavior()) != ContentDistributionStretch))
return;
// Spec defines auto-sized tracks as the ones with an 'auto' max-sizing
// function.
Vector<GridTrack>& tracks = (direction == ForColumns)
? sizingData.columnTracks
: sizingData.rowTracks;
Vector<unsigned> autoSizedTracksIndex;
for (unsigned i = 0; i < tracks.size(); ++i) {
const GridTrackSize& trackSize = gridTrackSize(direction, i, sizingData);
if (trackSize.hasAutoMaxTrackBreadth())
autoSizedTracksIndex.push_back(i);
}
unsigned numberOfAutoSizedTracks = autoSizedTracksIndex.size();
if (numberOfAutoSizedTracks < 1)
return;
LayoutUnit sizeToIncrease = availableSpace / numberOfAutoSizedTracks;
for (const auto& trackIndex : autoSizedTracksIndex) {
GridTrack* track = tracks.data() + trackIndex;
LayoutUnit baseSize = track->baseSize() + sizeToIncrease;
track->setBaseSize(baseSize);
}
availableSpace = LayoutUnit();
}
void LayoutGrid::layoutGridItems(GridSizingData& sizingData) {
DCHECK_EQ(sizingData.sizingOperation, TrackSizing);
populateGridPositionsForDirection(sizingData, ForColumns);
populateGridPositionsForDirection(sizingData, ForRows);
m_gridItemsOverflowingGridArea.resize(0);
for (LayoutBox* child = firstChildBox(); child;
child = child->nextSiblingBox()) {
if (child->isOutOfFlowPositioned()) {
prepareChildForPositionedLayout(*child);
continue;
}
// Because the grid area cannot be styled, we don't need to adjust
// the grid breadth to account for 'box-sizing'.
LayoutUnit oldOverrideContainingBlockContentLogicalWidth =
child->hasOverrideContainingBlockLogicalWidth()
? child->overrideContainingBlockContentLogicalWidth()
: LayoutUnit();
LayoutUnit oldOverrideContainingBlockContentLogicalHeight =
child->hasOverrideContainingBlockLogicalHeight()
? child->overrideContainingBlockContentLogicalHeight()
: LayoutUnit();
LayoutUnit overrideContainingBlockContentLogicalWidth =
gridAreaBreadthForChildIncludingAlignmentOffsets(*child, ForColumns,
sizingData);
LayoutUnit overrideContainingBlockContentLogicalHeight =
gridAreaBreadthForChildIncludingAlignmentOffsets(*child, ForRows,
sizingData);
if (oldOverrideContainingBlockContentLogicalWidth !=
overrideContainingBlockContentLogicalWidth ||
(oldOverrideContainingBlockContentLogicalHeight !=
overrideContainingBlockContentLogicalHeight &&
child->hasRelativeLogicalHeight()))
child->setNeedsLayout(LayoutInvalidationReason::GridChanged);
child->setOverrideContainingBlockContentLogicalWidth(
overrideContainingBlockContentLogicalWidth);
child->setOverrideContainingBlockContentLogicalHeight(
overrideContainingBlockContentLogicalHeight);
// Stretching logic might force a child layout, so we need to run it before
// the layoutIfNeeded call to avoid unnecessary relayouts. This might imply
// that child margins, needed to correctly determine the available space
// before stretching, are not set yet.
applyStretchAlignmentToChildIfNeeded(*child);
child->layoutIfNeeded();
// We need pending layouts to be done in order to compute auto-margins
// properly.
updateAutoMarginsInColumnAxisIfNeeded(*child);
updateAutoMarginsInRowAxisIfNeeded(*child);
const GridArea& area = sizingData.grid().gridItemArea(*child);
#if DCHECK_IS_ON()
ASSERT(area.columns.startLine() < sizingData.columnTracks.size());
ASSERT(area.rows.startLine() < sizingData.rowTracks.size());
#endif
child->setLogicalLocation(findChildLogicalPosition(*child, sizingData));
// Keep track of children overflowing their grid area as we might need to
// paint them even if the grid-area is not visible. Using physical
// dimensions for simplicity, so we can forget about orthogonalty.
LayoutUnit childGridAreaHeight =
isHorizontalWritingMode() ? overrideContainingBlockContentLogicalHeight
: overrideContainingBlockContentLogicalWidth;
LayoutUnit childGridAreaWidth =
isHorizontalWritingMode() ? overrideContainingBlockContentLogicalWidth
: overrideContainingBlockContentLogicalHeight;
LayoutRect gridAreaRect(
gridAreaLogicalPosition(area),
LayoutSize(childGridAreaWidth, childGridAreaHeight));
if (!gridAreaRect.contains(child->frameRect()))
m_gridItemsOverflowingGridArea.push_back(child);
}
}
void LayoutGrid::prepareChildForPositionedLayout(LayoutBox& child) {
ASSERT(child.isOutOfFlowPositioned());
child.containingBlock()->insertPositionedObject(&child);
PaintLayer* childLayer = child.layer();
childLayer->setStaticInlinePosition(borderAndPaddingStart());
childLayer->setStaticBlockPosition(borderAndPaddingBefore());
}
void LayoutGrid::layoutPositionedObjects(bool relayoutChildren,
PositionedLayoutBehavior info) {
TrackedLayoutBoxListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
for (auto* child : *positionedDescendants) {
if (isOrthogonalChild(*child)) {
// FIXME: Properly support orthogonal writing mode.
layoutPositionedObject(child, relayoutChildren, info);
continue;
}
LayoutUnit columnOffset = LayoutUnit();
LayoutUnit columnBreadth = LayoutUnit();
offsetAndBreadthForPositionedChild(*child, ForColumns, columnOffset,
columnBreadth);
LayoutUnit rowOffset = LayoutUnit();
LayoutUnit rowBreadth = LayoutUnit();
offsetAndBreadthForPositionedChild(*child, ForRows, rowOffset, rowBreadth);
child->setOverrideContainingBlockContentLogicalWidth(columnBreadth);
child->setOverrideContainingBlockContentLogicalHeight(rowBreadth);
child->setExtraInlineOffset(columnOffset);
child->setExtraBlockOffset(rowOffset);
if (child->parent() == this) {
PaintLayer* childLayer = child->layer();
childLayer->setStaticInlinePosition(borderStart() + columnOffset);
childLayer->setStaticBlockPosition(borderBefore() + rowOffset);
}
layoutPositionedObject(child, relayoutChildren, info);
}
}
void LayoutGrid::offsetAndBreadthForPositionedChild(
const LayoutBox& child,
GridTrackSizingDirection direction,
LayoutUnit& offset,
LayoutUnit& breadth) {
ASSERT(!isOrthogonalChild(child));
bool isForColumns = direction == ForColumns;
GridSpan positions = GridPositionsResolver::resolveGridPositionsFromStyle(
*style(), child, direction, autoRepeatCountForDirection(direction));
if (positions.isIndefinite()) {
offset = LayoutUnit();
breadth = isForColumns ? clientLogicalWidth() : clientLogicalHeight();
return;
}
// For positioned items we cannot use GridSpan::translate(). Because we could
// end up with negative values, as the positioned items do not create implicit
// tracks per spec.
int smallestStart = abs(m_grid.smallestTrackStart(direction));
int startLine = positions.untranslatedStartLine() + smallestStart;
int endLine = positions.untranslatedEndLine() + smallestStart;
GridPosition startPosition = isForColumns ? child.style()->gridColumnStart()
: child.style()->gridRowStart();
GridPosition endPosition = isForColumns ? child.style()->gridColumnEnd()
: child.style()->gridRowEnd();
int lastLine = numTracks(direction, m_grid);
bool startIsAuto =
startPosition.isAuto() ||
(startPosition.isNamedGridArea() &&
!NamedLineCollection::isValidNamedLineOrArea(
startPosition.namedGridLine(), styleRef(),
GridPositionsResolver::initialPositionSide(direction))) ||
(startLine < 0) || (startLine > lastLine);
bool endIsAuto = endPosition.isAuto() ||
(endPosition.isNamedGridArea() &&
!NamedLineCollection::isValidNamedLineOrArea(
endPosition.namedGridLine(), styleRef(),
GridPositionsResolver::finalPositionSide(direction))) ||
(endLine < 0) || (endLine > lastLine);
LayoutUnit start;
if (!startIsAuto) {
if (isForColumns) {
if (styleRef().isLeftToRightDirection())
start = m_columnPositions[startLine] - borderLogicalLeft();
else
start = logicalWidth() -
translateRTLCoordinate(m_columnPositions[startLine]) -
borderLogicalRight();
} else {
start = m_rowPositions[startLine] - borderBefore();
}
}
LayoutUnit end = isForColumns ? clientLogicalWidth() : clientLogicalHeight();
if (!endIsAuto) {
if (isForColumns) {
if (styleRef().isLeftToRightDirection())
end = m_columnPositions[endLine] - borderLogicalLeft();
else
end = logicalWidth() -
translateRTLCoordinate(m_columnPositions[endLine]) -
borderLogicalRight();
} else {
end = m_rowPositions[endLine] - borderBefore();
}
// These vectors store line positions including gaps, but we shouldn't
// consider them for the edges of the grid.
if (endLine > 0 && endLine < lastLine) {
DCHECK(!m_grid.needsItemsPlacement());
end -= guttersSize(m_grid, direction, endLine - 1, 2, TrackSizing);
end -= isForColumns ? m_offsetBetweenColumns : m_offsetBetweenRows;
}
}
breadth = std::max(end - start, LayoutUnit());
offset = start;
if (isForColumns && !styleRef().isLeftToRightDirection() &&
!child.styleRef().hasStaticInlinePosition(
child.isHorizontalWritingMode())) {
// If the child doesn't have a static inline position (i.e. "left" and/or
// "right" aren't "auto", we need to calculate the offset from the left
// (even if we're in RTL).
if (endIsAuto) {
offset = LayoutUnit();
} else {
offset = translateRTLCoordinate(m_columnPositions[endLine]) -
borderLogicalLeft();
if (endLine > 0 && endLine < lastLine) {
DCHECK(!m_grid.needsItemsPlacement());
offset += guttersSize(m_grid, direction, endLine - 1, 2, TrackSizing);
offset += isForColumns ? m_offsetBetweenColumns : m_offsetBetweenRows;
}
}
}
}
LayoutUnit LayoutGrid::assumedRowsSizeForOrthogonalChild(
const LayoutBox& child,
const GridSizingData& sizingData) const {
DCHECK(isOrthogonalChild(child));
const Grid& grid = sizingData.grid();
const GridSpan& span = grid.gridItemSpan(child, ForRows);
LayoutUnit gridAreaSize;
bool gridAreaIsIndefinite = false;
LayoutUnit containingBlockAvailableSize =
containingBlockLogicalHeightForContent(ExcludeMarginBorderPadding);
for (auto trackPosition : span) {
GridLength maxTrackSize =
gridTrackSize(ForRows, trackPosition, sizingData).maxTrackBreadth();
if (maxTrackSize.isContentSized() || maxTrackSize.isFlex())
gridAreaIsIndefinite = true;
else
gridAreaSize +=
valueForLength(maxTrackSize.length(), containingBlockAvailableSize);
}
gridAreaSize += guttersSize(grid, ForRows, span.startLine(),
span.integerSpan(), sizingData.sizingOperation);
return gridAreaIsIndefinite
? std::max(child.maxPreferredLogicalWidth(), gridAreaSize)
: gridAreaSize;
}
LayoutUnit LayoutGrid::gridAreaBreadthForChild(
const LayoutBox& child,
GridTrackSizingDirection direction,
const GridSizingData& sizingData) const {
// To determine the column track's size based on an orthogonal grid item we
// need it's logical height, which may depend on the row track's size. It's
// possible that the row tracks sizing logic has not been performed yet, so we
// will need to do an estimation.
if (direction == ForRows &&
sizingData.sizingState == GridSizingData::ColumnSizingFirstIteration)
return assumedRowsSizeForOrthogonalChild(child, sizingData);
const Vector<GridTrack>& tracks =
direction == ForColumns ? sizingData.columnTracks : sizingData.rowTracks;
const GridSpan& span = sizingData.grid().gridItemSpan(child, direction);
LayoutUnit gridAreaBreadth;
for (const auto& trackPosition : span)
gridAreaBreadth += tracks[trackPosition].baseSize();
gridAreaBreadth +=
guttersSize(sizingData.grid(), direction, span.startLine(),
span.integerSpan(), sizingData.sizingOperation);
return gridAreaBreadth;
}
LayoutUnit LayoutGrid::gridAreaBreadthForChildIncludingAlignmentOffsets(
const LayoutBox& child,
GridTrackSizingDirection direction,
const GridSizingData& sizingData) const {
// We need the cached value when available because Content Distribution
// alignment properties may have some influence in the final grid area
// breadth.
const Vector<GridTrack>& tracks = (direction == ForColumns)
? sizingData.columnTracks
: sizingData.rowTracks;
const GridSpan& span = sizingData.grid().gridItemSpan(child, direction);
const Vector<LayoutUnit>& linePositions =
(direction == ForColumns) ? m_columnPositions : m_rowPositions;
LayoutUnit initialTrackPosition = linePositions[span.startLine()];
LayoutUnit finalTrackPosition = linePositions[span.endLine() - 1];
// Track Positions vector stores the 'start' grid line of each track, so we
// have to add last track's baseSize.
return finalTrackPosition - initialTrackPosition +
tracks[span.endLine() - 1].baseSize();
}
void LayoutGrid::populateGridPositionsForDirection(
GridSizingData& sizingData,
GridTrackSizingDirection direction) {
// Since we add alignment offsets and track gutters, grid lines are not always
// adjacent. Hence we will have to assume from now on that we just store
// positions of the initial grid lines of each track, except the last one,
// which is the only one considered as a final grid line of a track.
// The grid container's frame elements (border, padding and <content-position>
// offset) are sensible to the inline-axis flow direction. However, column
// lines positions are 'direction' unaware. This simplification allows us to
// use the same indexes to identify the columns independently on the
// inline-axis direction.
bool isRowAxis = direction == ForColumns;
auto& tracks = isRowAxis ? sizingData.columnTracks : sizingData.rowTracks;
size_t numberOfTracks = tracks.size();
size_t numberOfLines = numberOfTracks + 1;
size_t lastLine = numberOfLines - 1;
ContentAlignmentData offset = computeContentPositionAndDistributionOffset(
direction, sizingData.freeSpace(direction), numberOfTracks);
auto& positions = isRowAxis ? m_columnPositions : m_rowPositions;
positions.resize(numberOfLines);
auto borderAndPadding =
isRowAxis ? borderAndPaddingLogicalLeft() : borderAndPaddingBefore();
positions[0] = borderAndPadding + offset.positionOffset;
const Grid& grid = sizingData.grid();
if (numberOfLines > 1) {
// If we have collapsed tracks we just ignore gaps here and add them later
// as we might not compute the gap between two consecutive tracks without
// examining the surrounding ones.
bool hasCollapsedTracks = grid.hasAutoRepeatEmptyTracks(direction);
LayoutUnit gap =
!hasCollapsedTracks
? gridGapForDirection(direction, sizingData.sizingOperation)
: LayoutUnit();
size_t nextToLastLine = numberOfLines - 2;
for (size_t i = 0; i < nextToLastLine; ++i)
positions[i + 1] =
positions[i] + offset.distributionOffset + tracks[i].baseSize() + gap;
positions[lastLine] =
positions[nextToLastLine] + tracks[nextToLastLine].baseSize();
// Adjust collapsed gaps. Collapsed tracks cause the surrounding gutters to
// collapse (they coincide exactly) except on the edges of the grid where
// they become 0.
if (hasCollapsedTracks) {
gap = gridGapForDirection(direction, sizingData.sizingOperation);
size_t remainingEmptyTracks =
grid.autoRepeatEmptyTracks(direction)->size();
LayoutUnit gapAccumulator;
for (size_t i = 1; i < lastLine; ++i) {
if (grid.isEmptyAutoRepeatTrack(direction, i - 1)) {
--remainingEmptyTracks;
} else {
// Add gap between consecutive non empty tracks. Add it also just once
// for an arbitrary number of empty tracks between two non empty ones.
bool allRemainingTracksAreEmpty =
remainingEmptyTracks == (lastLine - i);
if (!allRemainingTracksAreEmpty ||
!grid.isEmptyAutoRepeatTrack(direction, i))
gapAccumulator += gap;
}
positions[i] += gapAccumulator;
}
positions[lastLine] += gapAccumulator;
}
}
auto& offsetBetweenTracks =
isRowAxis ? m_offsetBetweenColumns : m_offsetBetweenRows;
offsetBetweenTracks = offset.distributionOffset;
}
static LayoutUnit computeOverflowAlignmentOffset(OverflowAlignment overflow,
LayoutUnit trackSize,
LayoutUnit childSize) {
LayoutUnit offset = trackSize - childSize;
switch (overflow) {
case OverflowAlignmentSafe:
// If overflow is 'safe', we have to make sure we don't overflow the
// 'start' edge (potentially cause some data loss as the overflow is
// unreachable).
return offset.clampNegativeToZero();
case OverflowAlignmentUnsafe:
case OverflowAlignmentDefault:
// If we overflow our alignment container and overflow is 'true'
// (default), we ignore the overflow and just return the value regardless
// (which may cause data loss as we overflow the 'start' edge).
return offset;
}
ASSERT_NOT_REACHED();
return LayoutUnit();
}
// FIXME: This logic is shared by LayoutFlexibleBox, so it should be moved to
// LayoutBox.
LayoutUnit LayoutGrid::marginLogicalHeightForChild(
const LayoutBox& child) const {
return isHorizontalWritingMode() ? child.marginHeight() : child.marginWidth();
}
LayoutUnit LayoutGrid::computeMarginLogicalSizeForChild(
MarginDirection forDirection,
const LayoutBox& child) const {
if (!child.styleRef().hasMargin())
return LayoutUnit();
bool isRowAxis = forDirection == InlineDirection;
LayoutUnit marginStart;
LayoutUnit marginEnd;
LayoutUnit logicalSize =
isRowAxis ? child.logicalWidth() : child.logicalHeight();
Length marginStartLength = isRowAxis ? child.styleRef().marginStart()
: child.styleRef().marginBefore();
Length marginEndLength =
isRowAxis ? child.styleRef().marginEnd() : child.styleRef().marginAfter();
child.computeMarginsForDirection(
forDirection, this, child.containingBlockLogicalWidthForContent(),
logicalSize, marginStart, marginEnd, marginStartLength, marginEndLength);
return marginStart + marginEnd;
}
LayoutUnit LayoutGrid::availableAlignmentSpaceForChildBeforeStretching(
LayoutUnit gridAreaBreadthForChild,
const LayoutBox& child) const {
// Because we want to avoid multiple layouts, stretching logic might be
// performed before children are laid out, so we can't use the child cached
// values. Hence, we need to compute margins in order to determine the
// available height before stretching.
return gridAreaBreadthForChild -
(child.needsLayout()
? computeMarginLogicalSizeForChild(BlockDirection, child)
: marginLogicalHeightForChild(child));
}
StyleSelfAlignmentData LayoutGrid::alignSelfForChild(
const LayoutBox& child) const {
if (!child.isAnonymous())
return child.styleRef().resolvedAlignSelf(selfAlignmentNormalBehavior());
// All the 'auto' values has been solved by the StyleAdjuster, but it's
// possible that some grid items generate Anonymous boxes, which need to be
// solved during layout.
return child.styleRef().resolvedAlignSelf(selfAlignmentNormalBehavior(),
style());
}
StyleSelfAlignmentData LayoutGrid::justifySelfForChild(
const LayoutBox& child) const {
if (!child.isAnonymous())
return child.styleRef().resolvedJustifySelf(ItemPositionStretch);
// All the 'auto' values has been solved by the StyleAdjuster, but it's
// possible that some grid items generate Anonymous boxes, which need to be
// solved during layout.
return child.styleRef().resolvedJustifySelf(selfAlignmentNormalBehavior(),
style());
}
// FIXME: This logic is shared by LayoutFlexibleBox, so it should be moved to
// LayoutBox.
void LayoutGrid::applyStretchAlignmentToChildIfNeeded(LayoutBox& child) {
// We clear height override values because we will decide now whether it's
// allowed or not, evaluating the conditions which might have changed since
// the old values were set.
child.clearOverrideLogicalContentHeight();
GridTrackSizingDirection childBlockDirection =
flowAwareDirectionForChild(child, ForRows);
bool blockFlowIsColumnAxis = childBlockDirection == ForRows;
bool allowedToStretchChildBlockSize =
blockFlowIsColumnAxis ? allowedToStretchChildAlongColumnAxis(child)
: allowedToStretchChildAlongRowAxis(child);
if (allowedToStretchChildBlockSize) {
LayoutUnit stretchedLogicalHeight =
availableAlignmentSpaceForChildBeforeStretching(
overrideContainingBlockContentSizeForChild(child,
childBlockDirection),
child);
LayoutUnit desiredLogicalHeight = child.constrainLogicalHeightByMinMax(
stretchedLogicalHeight, LayoutUnit(-1));
child.setOverrideLogicalContentHeight(
desiredLogicalHeight - child.borderAndPaddingLogicalHeight());
if (desiredLogicalHeight != child.logicalHeight()) {
// TODO (lajava): Can avoid laying out here in some cases. See
// https://webkit.org/b/87905.
child.setLogicalHeight(LayoutUnit());
child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
}
}
}
// TODO(lajava): This logic is shared by LayoutFlexibleBox, so it should be
// moved to LayoutBox.
bool LayoutGrid::hasAutoMarginsInColumnAxis(const LayoutBox& child) const {
if (isHorizontalWritingMode())
return child.styleRef().marginTop().isAuto() ||
child.styleRef().marginBottom().isAuto();
return child.styleRef().marginLeft().isAuto() ||
child.styleRef().marginRight().isAuto();
}
// TODO(lajava): This logic is shared by LayoutFlexibleBox, so it should be
// moved to LayoutBox.
bool LayoutGrid::hasAutoMarginsInRowAxis(const LayoutBox& child) const {
if (isHorizontalWritingMode())
return child.styleRef().marginLeft().isAuto() ||
child.styleRef().marginRight().isAuto();
return child.styleRef().marginTop().isAuto() ||
child.styleRef().marginBottom().isAuto();
}
// TODO(lajava): This logic is shared by LayoutFlexibleBox, so it should be
// moved to LayoutBox.
DISABLE_CFI_PERF
void LayoutGrid::updateAutoMarginsInRowAxisIfNeeded(LayoutBox& child) {
ASSERT(!child.isOutOfFlowPositioned());
LayoutUnit availableAlignmentSpace =
child.overrideContainingBlockContentLogicalWidth() -
child.logicalWidth() - child.marginLogicalWidth();
if (availableAlignmentSpace <= 0)
return;
Length marginStart = child.style()->marginStartUsing(style());
Length marginEnd = child.style()->marginEndUsing(style());
if (marginStart.isAuto() && marginEnd.isAuto()) {
child.setMarginStart(availableAlignmentSpace / 2, style());
child.setMarginEnd(availableAlignmentSpace / 2, style());
} else if (marginStart.isAuto()) {
child.setMarginStart(availableAlignmentSpace, style());
} else if (marginEnd.isAuto()) {
child.setMarginEnd(availableAlignmentSpace, style());
}
}
// TODO(lajava): This logic is shared by LayoutFlexibleBox, so it should be
// moved to LayoutBox.
DISABLE_CFI_PERF
void LayoutGrid::updateAutoMarginsInColumnAxisIfNeeded(LayoutBox& child) {
ASSERT(!child.isOutOfFlowPositioned());
LayoutUnit availableAlignmentSpace =
child.overrideContainingBlockContentLogicalHeight() -
child.logicalHeight() - child.marginLogicalHeight();
if (availableAlignmentSpace <= 0)
return;
Length marginBefore = child.style()->marginBeforeUsing(style());
Length marginAfter = child.style()->marginAfterUsing(style());
if (marginBefore.isAuto() && marginAfter.isAuto()) {
child.setMarginBefore(availableAlignmentSpace / 2, style());
child.setMarginAfter(availableAlignmentSpace / 2, style());
} else if (marginBefore.isAuto()) {
child.setMarginBefore(availableAlignmentSpace, style());
} else if (marginAfter.isAuto()) {
child.setMarginAfter(availableAlignmentSpace, style());
}
}
// TODO(lajava): This logic is shared by LayoutFlexibleBox, so it might be
// refactored somehow.
static int synthesizedBaselineFromContentBox(const LayoutBox& box,
LineDirectionMode direction) {
if (direction == HorizontalLine) {
return (box.size().height() - box.borderBottom() - box.paddingBottom() -
box.horizontalScrollbarHeight())
.toInt();
}
return (box.size().width() - box.borderLeft() - box.paddingLeft() -
box.verticalScrollbarWidth())
.toInt();
}
static int synthesizedBaselineFromBorderBox(const LayoutBox& box,
LineDirectionMode direction) {
return (direction == HorizontalLine ? box.size().height()
: box.size().width())
.toInt();
}
// TODO(lajava): This logic is shared by LayoutFlexibleBox, so it might be
// refactored somehow.
int LayoutGrid::baselinePosition(FontBaseline,
bool,
LineDirectionMode direction,
LinePositionMode mode) const {
DCHECK_EQ(mode, PositionOnContainingLine);
int baseline = firstLineBoxBaseline();
// We take content-box's bottom if no valid baseline.
if (baseline == -1)
baseline = synthesizedBaselineFromContentBox(*this, direction);
return baseline + beforeMarginInLineDirection(direction);
}
bool LayoutGrid::isInlineBaselineAlignedChild(const LayoutBox* child) const {
return alignSelfForChild(*child).position() == ItemPositionBaseline &&
!isOrthogonalChild(*child) && !hasAutoMarginsInColumnAxis(*child);
}
int LayoutGrid::firstLineBoxBaseline() const {
if (isWritingModeRoot() || !m_grid.hasGridItems())
return -1;
const LayoutBox* baselineChild = nullptr;
const LayoutBox* firstChild = nullptr;
bool isBaselineAligned = false;
// Finding the first grid item in grid order.
for (size_t column = 0;
!isBaselineAligned && column < m_grid.numTracks(ForColumns); column++) {
for (size_t index = 0; index < m_grid.cell(0, column).size(); index++) {
const LayoutBox* child = m_grid.cell(0, column)[index];
DCHECK(!child->isOutOfFlowPositioned());
// If an item participates in baseline alignmen, we select such item.
if (isInlineBaselineAlignedChild(child)) {
// TODO (lajava): self-baseline and content-baseline alignment
// still not implemented.
baselineChild = child;
isBaselineAligned = true;
break;
}
if (!baselineChild) {
// Use dom order for items in the same cell.
if (!firstChild || (m_grid.gridItemPaintOrder(*child) <
m_grid.gridItemPaintOrder(*firstChild)))
firstChild = child;
}
}
if (!baselineChild && firstChild)
baselineChild = firstChild;
}
if (!baselineChild)
return -1;
int baseline = isOrthogonalChild(*baselineChild)
? -1
: baselineChild->firstLineBoxBaseline();
// We take border-box's bottom if no valid baseline.
if (baseline == -1) {
// TODO (lajava): We should pass |direction| into
// firstLineBoxBaseline and stop bailing out if we're a writing
// mode root. This would also fix some cases where the grid is
// orthogonal to its container.
LineDirectionMode direction =
isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
return (synthesizedBaselineFromBorderBox(*baselineChild, direction) +
baselineChild->logicalTop())
.toInt();
}
return (baseline + baselineChild->logicalTop()).toInt();
}
int LayoutGrid::inlineBlockBaseline(LineDirectionMode direction) const {
int baseline = firstLineBoxBaseline();
if (baseline != -1)
return baseline;
int marginHeight =
(direction == HorizontalLine ? marginTop() : marginRight()).toInt();
return synthesizedBaselineFromContentBox(*this, direction) + marginHeight;
}
GridAxisPosition LayoutGrid::columnAxisPositionForChild(
const LayoutBox& child) const {
bool hasSameWritingMode =
child.styleRef().getWritingMode() == styleRef().getWritingMode();
bool childIsLTR = child.styleRef().isLeftToRightDirection();
switch (alignSelfForChild(child).position()) {
case ItemPositionSelfStart:
// TODO (lajava): Should we implement this logic in a generic utility
// function?
// Aligns the alignment subject to be flush with the edge of the alignment
// container corresponding to the alignment subject's 'start' side in the
// column axis.
if (isOrthogonalChild(child)) {
// If orthogonal writing-modes, self-start will be based on the child's
// inline-axis direction (inline-start), because it's the one parallel
// to the column axis.
if (styleRef().isFlippedBlocksWritingMode())
return childIsLTR ? GridAxisEnd : GridAxisStart;
return childIsLTR ? GridAxisStart : GridAxisEnd;
}
// self-start is based on the child's block-flow direction. That's why we
// need to check against the grid container's block-flow direction.
return hasSameWritingMode ? GridAxisStart : GridAxisEnd;
case ItemPositionSelfEnd:
// TODO (lajava): Should we implement this logic in a generic utility
// function?
// Aligns the alignment subject to be flush with the edge of the alignment
// container corresponding to the alignment subject's 'end' side in the
// column axis.
if (isOrthogonalChild(child)) {
// If orthogonal writing-modes, self-end will be based on the child's
// inline-axis direction, (inline-end) because it's the one parallel to
// the column axis.
if (styleRef().isFlippedBlocksWritingMode())
return childIsLTR ? GridAxisStart : GridAxisEnd;
return childIsLTR ? GridAxisEnd : GridAxisStart;
}
// self-end is based on the child's block-flow direction. That's why we
// need to check against the grid container's block-flow direction.
return hasSameWritingMode ? GridAxisEnd : GridAxisStart;
case ItemPositionLeft:
// Aligns the alignment subject to be flush with the alignment container's
// 'line-left' edge. The alignment axis (column axis) is always orthogonal
// to the inline axis, hence this value behaves as 'start'.
return GridAxisStart;
case ItemPositionRight:
// Aligns the alignment subject to be flush with the alignment container's
// 'line-right' edge. The alignment axis (column axis) is always
// orthogonal to the inline axis, hence this value behaves as 'start'.
return GridAxisStart;
case ItemPositionCenter:
return GridAxisCenter;
// Only used in flex layout, otherwise equivalent to 'start'.
case ItemPositionFlexStart:
// Aligns the alignment subject to be flush with the alignment container's
// 'start' edge (block-start) in the column axis.
case ItemPositionStart:
return GridAxisStart;
// Only used in flex layout, otherwise equivalent to 'end'.
case ItemPositionFlexEnd:
// Aligns the alignment subject to be flush with the alignment container's
// 'end' edge (block-end) in the column axis.
case ItemPositionEnd:
return GridAxisEnd;
case ItemPositionStretch:
return GridAxisStart;
case ItemPositionBaseline:
case ItemPositionLastBaseline:
// FIXME: These two require implementing Baseline Alignment. For now, we
// always 'start' align the child. crbug.com/234191
return GridAxisStart;
case ItemPositionAuto:
case ItemPositionNormal:
break;
}
ASSERT_NOT_REACHED();
return GridAxisStart;
}
GridAxisPosition LayoutGrid::rowAxisPositionForChild(
const LayoutBox& child) const {
bool hasSameDirection =
child.styleRef().direction() == styleRef().direction();
bool gridIsLTR = styleRef().isLeftToRightDirection();
switch (justifySelfForChild(child).position()) {
case ItemPositionSelfStart:
// TODO (lajava): Should we implement this logic in a generic utility
// function?
// Aligns the alignment subject to be flush with the edge of the alignment
// container corresponding to the alignment subject's 'start' side in the
// row axis.
if (isOrthogonalChild(child)) {
// If orthogonal writing-modes, self-start will be based on the child's
// block-axis direction, because it's the one parallel to the row axis.
if (child.styleRef().isFlippedBlocksWritingMode())
return gridIsLTR ? GridAxisEnd : GridAxisStart;
return gridIsLTR ? GridAxisStart : GridAxisEnd;
}
// self-start is based on the child's inline-flow direction. That's why we
// need to check against the grid container's direction.
return hasSameDirection ? GridAxisStart : GridAxisEnd;
case ItemPositionSelfEnd:
// TODO (lajava): Should we implement this logic in a generic utility
// function?
// Aligns the alignment subject to be flush with the edge of the alignment
// container corresponding to the alignment subject's 'end' side in the
// row axis.
if (isOrthogonalChild(child)) {
// If orthogonal writing-modes, self-end will be based on the child's
// block-axis direction, because it's the one parallel to the row axis.
if (child.styleRef().isFlippedBlocksWritingMode())
return gridIsLTR ? GridAxisStart : GridAxisEnd;
return gridIsLTR ? GridAxisEnd : GridAxisStart;
}
// self-end is based on the child's inline-flow direction. That's why we
// need to check against the grid container's direction.
return hasSameDirection ? GridAxisEnd : GridAxisStart;
case ItemPositionLeft:
// Aligns the alignment subject to be flush with the alignment container's
// 'line-left' edge. We want the physical 'left' side, so we have to take
// account, container's inline-flow direction.
return gridIsLTR ? GridAxisStart : GridAxisEnd;
case ItemPositionRight:
// Aligns the alignment subject to be flush with the alignment container's
// 'line-right' edge. We want the physical 'right' side, so we have to
// take account, container's inline-flow direction.
return gridIsLTR ? GridAxisEnd : GridAxisStart;
case ItemPositionCenter:
return GridAxisCenter;
// Only used in flex layout, otherwise equivalent to 'start'.
case ItemPositionFlexStart:
// Aligns the alignment subject to be flush with the alignment container's
// 'start' edge (inline-start) in the row axis.
case ItemPositionStart:
return GridAxisStart;
// Only used in flex layout, otherwise equivalent to 'end'.
case ItemPositionFlexEnd:
// Aligns the alignment subject to be flush with the alignment container's
// 'end' edge (inline-end) in the row axis.
case ItemPositionEnd:
return GridAxisEnd;
case ItemPositionStretch:
return GridAxisStart;
case ItemPositionBaseline:
case ItemPositionLastBaseline:
// FIXME: These two require implementing Baseline Alignment. For now, we
// always 'start' align the child. crbug.com/234191
return GridAxisStart;
case ItemPositionAuto:
case ItemPositionNormal:
break;
}
ASSERT_NOT_REACHED();
return GridAxisStart;
}
LayoutUnit LayoutGrid::columnAxisOffsetForChild(
const LayoutBox& child,
GridSizingData& sizingData) const {
const GridSpan& rowsSpan = sizingData.grid().gridItemSpan(child, ForRows);
size_t childStartLine = rowsSpan.startLine();
LayoutUnit startOfRow = m_rowPositions[childStartLine];
LayoutUnit startPosition = startOfRow + marginBeforeForChild(child);
if (hasAutoMarginsInColumnAxis(child))
return startPosition;
GridAxisPosition axisPosition = columnAxisPositionForChild(child);
switch (axisPosition) {
case GridAxisStart:
return startPosition;
case GridAxisEnd:
case GridAxisCenter: {
size_t childEndLine = rowsSpan.endLine();
LayoutUnit endOfRow = m_rowPositions[childEndLine];
// m_rowPositions include distribution offset (because of content
// alignment) and gutters so we need to subtract them to get the actual
// end position for a given row (this does not have to be done for the
// last track as there are no more m_columnPositions after it).
LayoutUnit trackGap =
gridGapForDirection(ForRows, sizingData.sizingOperation);
if (childEndLine < m_rowPositions.size() - 1) {
endOfRow -= trackGap;
endOfRow -= m_offsetBetweenRows;
}
LayoutUnit columnAxisChildSize =
isOrthogonalChild(child)
? child.logicalWidth() + child.marginLogicalWidth()
: child.logicalHeight() + child.marginLogicalHeight();
OverflowAlignment overflow = alignSelfForChild(child).overflow();
LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(
overflow, endOfRow - startOfRow, columnAxisChildSize);
return startPosition + (axisPosition == GridAxisEnd
? offsetFromStartPosition
: offsetFromStartPosition / 2);
}
}
ASSERT_NOT_REACHED();
return LayoutUnit();
}
LayoutUnit LayoutGrid::rowAxisOffsetForChild(const LayoutBox& child,
GridSizingData& sizingData) const {
const GridSpan& columnsSpan =
sizingData.grid().gridItemSpan(child, ForColumns);
size_t childStartLine = columnsSpan.startLine();
LayoutUnit startOfColumn = m_columnPositions[childStartLine];
LayoutUnit startPosition = startOfColumn + marginStartForChild(child);
if (hasAutoMarginsInRowAxis(child))
return startPosition;
GridAxisPosition axisPosition = rowAxisPositionForChild(child);
switch (axisPosition) {
case GridAxisStart:
return startPosition;
case GridAxisEnd:
case GridAxisCenter: {
size_t childEndLine = columnsSpan.endLine();
LayoutUnit endOfColumn = m_columnPositions[childEndLine];
// m_columnPositions include distribution offset (because of content
// alignment) and gutters so we need to subtract them to get the actual
// end position for a given column (this does not have to be done for the
// last track as there are no more m_columnPositions after it).
LayoutUnit trackGap =
gridGapForDirection(ForColumns, sizingData.sizingOperation);
if (childEndLine < m_columnPositions.size() - 1) {
endOfColumn -= trackGap;
endOfColumn -= m_offsetBetweenColumns;
}
LayoutUnit rowAxisChildSize =
isOrthogonalChild(child)
? child.logicalHeight() + child.marginLogicalHeight()
: child.logicalWidth() + child.marginLogicalWidth();
OverflowAlignment overflow = justifySelfForChild(child).overflow();
LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(
overflow, endOfColumn - startOfColumn, rowAxisChildSize);
return startPosition + (axisPosition == GridAxisEnd
? offsetFromStartPosition
: offsetFromStartPosition / 2);
}
}
ASSERT_NOT_REACHED();
return LayoutUnit();
}
ContentPosition static resolveContentDistributionFallback(
ContentDistributionType distribution) {
switch (distribution) {
case ContentDistributionSpaceBetween:
return ContentPositionStart;
case ContentDistributionSpaceAround:
return ContentPositionCenter;
case ContentDistributionSpaceEvenly:
return ContentPositionCenter;
case ContentDistributionStretch:
return ContentPositionStart;
case ContentDistributionDefault:
return ContentPositionNormal;
}
ASSERT_NOT_REACHED();
return ContentPositionNormal;
}
static ContentAlignmentData contentDistributionOffset(
const LayoutUnit& availableFreeSpace,
ContentPosition& fallbackPosition,
ContentDistributionType distribution,
unsigned numberOfGridTracks) {
if (distribution != ContentDistributionDefault &&
fallbackPosition == ContentPositionNormal)
fallbackPosition = resolveContentDistributionFallback(distribution);
if (availableFreeSpace <= 0)
return {};
LayoutUnit distributionOffset;
switch (distribution) {
case ContentDistributionSpaceBetween:
if (numberOfGridTracks < 2)
return {};
return {LayoutUnit(), availableFreeSpace / (numberOfGridTracks - 1)};
case ContentDistributionSpaceAround:
if (numberOfGridTracks < 1)
return {};
distributionOffset = availableFreeSpace / numberOfGridTracks;
return {distributionOffset / 2, distributionOffset};
case ContentDistributionSpaceEvenly:
distributionOffset = availableFreeSpace / (numberOfGridTracks + 1);
return {distributionOffset, distributionOffset};
case ContentDistributionStretch:
case ContentDistributionDefault:
return {};
}
ASSERT_NOT_REACHED();
return {};
}
ContentAlignmentData LayoutGrid::computeContentPositionAndDistributionOffset(
GridTrackSizingDirection direction,
const LayoutUnit& availableFreeSpace,
unsigned numberOfGridTracks) const {
bool isRowAxis = direction == ForColumns;
ContentPosition position = isRowAxis
? styleRef().resolvedJustifyContentPosition(
contentAlignmentNormalBehavior())
: styleRef().resolvedAlignContentPosition(
contentAlignmentNormalBehavior());
ContentDistributionType distribution =
isRowAxis
? styleRef().resolvedJustifyContentDistribution(
contentAlignmentNormalBehavior())
: styleRef().resolvedAlignContentDistribution(
contentAlignmentNormalBehavior());
// If <content-distribution> value can't be applied, 'position' will become
// the associated <content-position> fallback value.
ContentAlignmentData contentAlignment = contentDistributionOffset(
availableFreeSpace, position, distribution, numberOfGridTracks);
if (contentAlignment.isValid())
return contentAlignment;
OverflowAlignment overflow =
isRowAxis ? styleRef().justifyContentOverflowAlignment()
: styleRef().alignContentOverflowAlignment();
// TODO (lajava): Default value for overflow isn't exaclty as 'unsafe'.
// https://drafts.csswg.org/css-align/#overflow-values
if (availableFreeSpace == 0 ||
(availableFreeSpace < 0 && overflow == OverflowAlignmentSafe))
return {LayoutUnit(), LayoutUnit()};
switch (position) {
case ContentPositionLeft:
// The align-content's axis is always orthogonal to the inline-axis.
return {LayoutUnit(), LayoutUnit()};
case ContentPositionRight:
if (isRowAxis)
return {availableFreeSpace, LayoutUnit()};
// The align-content's axis is always orthogonal to the inline-axis.
return {LayoutUnit(), LayoutUnit()};
case ContentPositionCenter:
return {availableFreeSpace / 2, LayoutUnit()};
// Only used in flex layout, for other layout, it's equivalent to 'End'.
case ContentPositionFlexEnd:
case ContentPositionEnd:
if (isRowAxis)
return {styleRef().isLeftToRightDirection() ? availableFreeSpace
: LayoutUnit(),
LayoutUnit()};
return {availableFreeSpace, LayoutUnit()};
// Only used in flex layout, for other layout, it's equivalent to 'Start'.
case ContentPositionFlexStart:
case ContentPositionStart:
if (isRowAxis)
return {styleRef().isLeftToRightDirection() ? LayoutUnit()
: availableFreeSpace,
LayoutUnit()};
return {LayoutUnit(), LayoutUnit()};
case ContentPositionBaseline:
case ContentPositionLastBaseline:
// FIXME: These two require implementing Baseline Alignment. For now, we
// always 'start' align the child. crbug.com/234191
if (isRowAxis)
return {styleRef().isLeftToRightDirection() ? LayoutUnit()
: availableFreeSpace,
LayoutUnit()};
return {LayoutUnit(), LayoutUnit()};
case ContentPositionNormal:
break;
}
ASSERT_NOT_REACHED();
return {LayoutUnit(), LayoutUnit()};
}
LayoutUnit LayoutGrid::translateRTLCoordinate(LayoutUnit coordinate) const {
ASSERT(!styleRef().isLeftToRightDirection());
LayoutUnit alignmentOffset = m_columnPositions[0];
LayoutUnit rightGridEdgePosition =
m_columnPositions[m_columnPositions.size() - 1];
return rightGridEdgePosition + alignmentOffset - coordinate;
}
LayoutPoint LayoutGrid::findChildLogicalPosition(
const LayoutBox& child,
GridSizingData& sizingData) const {
LayoutUnit columnAxisOffset = columnAxisOffsetForChild(child, sizingData);
LayoutUnit rowAxisOffset = rowAxisOffsetForChild(child, sizingData);
// We stored m_columnPosition's data ignoring the direction, hence we might
// need now to translate positions from RTL to LTR, as it's more convenient
// for painting.
if (!style()->isLeftToRightDirection())
rowAxisOffset = translateRTLCoordinate(rowAxisOffset) -
(isOrthogonalChild(child) ? child.logicalHeight()
: child.logicalWidth());
// "In the positioning phase [...] calculations are performed according to the
// writing mode of the containing block of the box establishing the orthogonal
// flow." However, the resulting LayoutPoint will be used in
// 'setLogicalPosition' in order to set the child's logical position, which
// will only take into account the child's writing-mode.
LayoutPoint childLocation(rowAxisOffset, columnAxisOffset);
return isOrthogonalChild(child) ? childLocation.transposedPoint()
: childLocation;
}
LayoutPoint LayoutGrid::gridAreaLogicalPosition(const GridArea& area) const {
LayoutUnit columnAxisOffset = m_rowPositions[area.rows.startLine()];
LayoutUnit rowAxisOffset = m_columnPositions[area.columns.startLine()];
// See comment in findChildLogicalPosition() about why we need sometimes to
// translate from RTL to LTR the rowAxisOffset coordinate.
return LayoutPoint(style()->isLeftToRightDirection()
? rowAxisOffset
: translateRTLCoordinate(rowAxisOffset),
columnAxisOffset);
}
void LayoutGrid::paintChildren(const PaintInfo& paintInfo,
const LayoutPoint& paintOffset) const {
DCHECK(!m_grid.needsItemsPlacement());
if (m_grid.hasGridItems())
GridPainter(*this).paintChildren(paintInfo, paintOffset);
}
bool LayoutGrid::cachedHasDefiniteLogicalHeight() const {
SECURITY_DCHECK(m_hasDefiniteLogicalHeight);
return m_hasDefiniteLogicalHeight.value();
}
size_t LayoutGrid::numTracks(GridTrackSizingDirection direction,
const Grid& grid) const {
// Due to limitations in our internal representation, we cannot know the
// number of columns from m_grid *if* there is no row (because m_grid would be
// empty). That's why in that case we need to get it from the style. Note that
// we know for sure that there are't any implicit tracks, because not having
// rows implies that there are no "normal" children (out-of-flow children are
// not stored in m_grid).
DCHECK(!grid.needsItemsPlacement());
if (direction == ForRows)
return grid.numTracks(ForRows);
return grid.numTracks(ForRows)
? grid.numTracks(ForColumns)
: GridPositionsResolver::explicitGridColumnCount(
styleRef(), grid.autoRepeatTracks(ForColumns));
}
} // namespace blink
|