1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
* (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
* Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/rendering/RenderBox.h"
#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/editing/htmlediting.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/PinchViewport.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLFrameElementBase.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/page/AutoscrollController.h"
#include "core/page/EventHandler.h"
#include "core/page/Page.h"
#include "core/paint/BackgroundImageGeometry.h"
#include "core/paint/BoxPainter.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderDeprecatedFlexibleBox.h"
#include "core/rendering/RenderFlexibleBox.h"
#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderGrid.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderListBox.h"
#include "core/rendering/RenderListMarker.h"
#include "core/rendering/RenderMultiColumnSpannerPlaceholder.h"
#include "core/rendering/RenderTableCell.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/compositing/RenderLayerCompositor.h"
#include "core/rendering/style/ShadowList.h"
#include "platform/LengthFunctions.h"
#include "platform/geometry/FloatQuad.h"
#include "platform/geometry/FloatRoundedRect.h"
#include "platform/geometry/TransformState.h"
#include <algorithm>
#include <math.h>
namespace blink {
using namespace HTMLNames;
// Used by flexible boxes when flexing this element and by table cells.
typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
// Used by grid elements to properly size their grid items.
// FIXME: Move these into RenderBoxRareData.
static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = 0;
static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0;
static OverrideSizeMap* gExtraInlineOffsetMap = 0;
static OverrideSizeMap* gExtraBlockOffsetMap = 0;
// Size of border belt for autoscroll. When mouse pointer in border belt,
// autoscroll is started.
static const int autoscrollBeltSize = 20;
static const unsigned backgroundObscurationTestMaxDepth = 4;
static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
{
ASSERT(bodyElementRenderer->isBody());
// The <body> only paints its background if the root element has defined a background independent of the body,
// or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
RenderObject* documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
return documentElementRenderer
&& !documentElementRenderer->hasBackground()
&& (documentElementRenderer == bodyElementRenderer->parent());
}
RenderBox::RenderBox(ContainerNode* node)
: RenderBoxModelObject(node)
, m_intrinsicContentLogicalHeight(-1)
, m_minPreferredLogicalWidth(-1)
, m_maxPreferredLogicalWidth(-1)
{
setIsBox();
}
void RenderBox::willBeRemovedFromTree()
{
if (m_rareData && m_rareData->m_spannerPlaceholder) {
m_rareData->m_spannerPlaceholder->spannerWillBeRemoved();
m_rareData->m_spannerPlaceholder = 0;
}
RenderBoxModelObject::willBeRemovedFromTree();
}
void RenderBox::willBeDestroyed()
{
clearOverrideSize();
clearContainingBlockOverrideSize();
clearExtraInlineAndBlockOffests();
RenderBlock::removePercentHeightDescendantIfNeeded(this);
ShapeOutsideInfo::removeInfo(*this);
RenderBoxModelObject::willBeDestroyed();
}
void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
{
ASSERT(isFloatingOrOutOfFlowPositioned());
if (documentBeingDestroyed())
return;
if (isFloating()) {
RenderBlockFlow* parentBlockFlow = 0;
for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
if (curr->isRenderBlockFlow()) {
RenderBlockFlow* currBlockFlow = toRenderBlockFlow(curr);
if (!parentBlockFlow || currBlockFlow->containsFloat(this))
parentBlockFlow = currBlockFlow;
}
}
if (parentBlockFlow) {
parentBlockFlow->markSiblingsWithFloatsForLayout(this);
parentBlockFlow->markAllDescendantsWithFloatsForLayout(this, false);
}
}
if (isOutOfFlowPositioned())
RenderBlock::removePositionedObject(this);
}
void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
{
RenderStyle* oldStyle = style();
if (oldStyle) {
// The background of the root element or the body element could propagate up to
// the canvas. Just dirty the entire canvas when our style changes substantially.
if ((diff.needsPaintInvalidation() || diff.needsLayout()) && node()
&& (isHTMLHtmlElement(*node()) || isHTMLBodyElement(*node()))) {
view()->setShouldDoFullPaintInvalidation();
if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
view()->compositor()->setNeedsUpdateFixedBackground();
}
// When a layout hint happens and an object's position style changes, we have to do a layout
// to dirty the render tree using the old position value now.
if (diff.needsFullLayout() && parent() && oldStyle->position() != newStyle.position()) {
markContainingBlocksForLayout();
if (oldStyle->position() == StaticPosition)
setShouldDoFullPaintInvalidation();
else if (newStyle.hasOutOfFlowPosition())
parent()->setChildNeedsLayout();
if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
removeFloatingOrPositionedChildFromBlockLists();
}
// FIXME: This branch runs when !oldStyle, which means that layout was never called
// so what's the point in invalidating the whole view that we never painted?
} else if (isBody()) {
view()->setShouldDoFullPaintInvalidation();
}
RenderBoxModelObject::styleWillChange(diff, newStyle);
}
void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
// Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
// (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
// writing mode value before style change here.
bool oldHorizontalWritingMode = isHorizontalWritingMode();
RenderBoxModelObject::styleDidChange(diff, oldStyle);
RenderStyle* newStyle = style();
if (needsLayout() && oldStyle)
RenderBlock::removePercentHeightDescendantIfNeeded(this);
if (RenderBlock::hasPercentHeightContainerMap() && slowFirstChild()
&& oldHorizontalWritingMode != isHorizontalWritingMode())
RenderBlock::clearPercentHeightDescendantsFrom(this);
// If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
// new zoomed coordinate space.
if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) {
if (int left = layer()->scrollableArea()->scrollXOffset()) {
left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
layer()->scrollableArea()->scrollToXOffset(left);
}
if (int top = layer()->scrollableArea()->scrollYOffset()) {
top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
layer()->scrollableArea()->scrollToYOffset(top);
}
}
// Our opaqueness might have changed without triggering layout.
if (diff.needsPaintInvalidation()) {
RenderObject* parentToInvalidate = parent();
for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
parentToInvalidate->invalidateBackgroundObscurationStatus();
parentToInvalidate = parentToInvalidate->parent();
}
}
if (isDocumentElement() || isBody()) {
document().view()->recalculateScrollbarOverlayStyle();
document().view()->recalculateCustomScrollbarStyle();
}
updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle);
updateGridPositionAfterStyleChange(oldStyle);
}
void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
{
const ShapeValue* shapeOutside = style.shapeOutside();
const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : RenderStyle::initialShapeOutside();
Length shapeMargin = style.shapeMargin();
Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
float shapeImageThreshold = style.shapeImageThreshold();
float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
// FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
return;
if (!shapeOutside)
ShapeOutsideInfo::removeInfo(*this);
else
ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
if (shapeOutside || shapeOutside != oldShapeOutside)
markShapeOutsideDependentsForLayout();
}
void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle* oldStyle)
{
if (!oldStyle || !parent() || !parent()->isRenderGrid())
return;
if (oldStyle->gridColumnStart() == style()->gridColumnStart()
&& oldStyle->gridColumnEnd() == style()->gridColumnEnd()
&& oldStyle->gridRowStart() == style()->gridRowStart()
&& oldStyle->gridRowEnd() == style()->gridRowEnd()
&& oldStyle->order() == style()->order()
&& oldStyle->hasOutOfFlowPosition() == style()->hasOutOfFlowPosition())
return;
// It should be possible to not dirty the grid in some cases (like moving an explicitly placed grid item).
// For now, it's more simple to just always recompute the grid.
toRenderGrid(parent())->dirtyGrid();
}
void RenderBox::updateFromStyle()
{
RenderBoxModelObject::updateFromStyle();
RenderStyle* styleToUse = style();
bool isRootObject = isDocumentElement();
bool isViewObject = isRenderView();
bool rootLayerScrolls = document().settings() && document().settings()->rootLayerScrolls();
// The root and the RenderView always paint their backgrounds/borders.
if (isRootObject || isViewObject)
setHasBoxDecorationBackground(true);
setFloating(!isOutOfFlowPositioned() && styleToUse->isFloating());
bool boxHasOverflowClip = false;
if (!styleToUse->isOverflowVisible() && isRenderBlock() && (rootLayerScrolls || !isViewObject)) {
// If overflow has been propagated to the viewport, it has no effect here.
if (node() != document().viewportDefiningElement())
boxHasOverflowClip = true;
}
if (boxHasOverflowClip != hasOverflowClip()) {
// FIXME: This shouldn't be required if we tracked the visual overflow
// generated by positioned children or self painting layers. crbug.com/345403
for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling())
child->setMayNeedPaintInvalidation(true);
}
setHasOverflowClip(boxHasOverflowClip);
setHasTransformRelatedProperty(styleToUse->hasTransformRelatedProperty());
setHasReflection(styleToUse->boxReflect());
}
void RenderBox::layout()
{
ASSERT(needsLayout());
RenderObject* child = slowFirstChild();
if (!child) {
clearNeedsLayout();
return;
}
LayoutState state(*this, locationOffset());
while (child) {
child->layoutIfNeeded();
ASSERT(!child->needsLayout());
child = child->nextSibling();
}
invalidateBackgroundObscurationStatus();
clearNeedsLayout();
}
// More IE extensions. clientWidth and clientHeight represent the interior of an object
// excluding border and scrollbar.
LayoutUnit RenderBox::clientWidth() const
{
return m_frameRect.width() - borderLeft() - borderRight() - verticalScrollbarWidth();
}
LayoutUnit RenderBox::clientHeight() const
{
return m_frameRect.height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
}
int RenderBox::pixelSnappedClientWidth() const
{
return snapSizeToPixel(clientWidth(), location().x() + clientLeft());
}
int RenderBox::pixelSnappedClientHeight() const
{
return snapSizeToPixel(clientHeight(), location().y() + clientTop());
}
int RenderBox::pixelSnappedOffsetWidth() const
{
return snapSizeToPixel(offsetWidth(), location().x() + clientLeft());
}
int RenderBox::pixelSnappedOffsetHeight() const
{
return snapSizeToPixel(offsetHeight(), location().y() + clientTop());
}
LayoutUnit RenderBox::scrollWidth() const
{
if (hasOverflowClip())
return layer()->scrollableArea()->scrollWidth();
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
if (style()->isLeftToRightDirection())
return std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft());
return clientWidth() - std::min(LayoutUnit(), layoutOverflowRect().x() - borderLeft());
}
LayoutUnit RenderBox::scrollHeight() const
{
if (hasOverflowClip())
return layer()->scrollableArea()->scrollHeight();
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
return std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop());
}
LayoutUnit RenderBox::scrollLeft() const
{
return hasOverflowClip() ? layer()->scrollableArea()->scrollXOffset() : 0;
}
LayoutUnit RenderBox::scrollTop() const
{
return hasOverflowClip() ? layer()->scrollableArea()->scrollYOffset() : 0;
}
int RenderBox::pixelSnappedScrollWidth() const
{
return snapSizeToPixel(scrollWidth(), location().x() + clientLeft());
}
int RenderBox::pixelSnappedScrollHeight() const
{
if (hasOverflowClip())
return layer()->scrollableArea()->scrollHeight();
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
return snapSizeToPixel(scrollHeight(), location().y() + clientTop());
}
void RenderBox::setScrollLeft(LayoutUnit newLeft)
{
// This doesn't hit in any tests, but since the equivalent code in setScrollTop
// does, presumably this code does as well.
DisableCompositingQueryAsserts disabler;
if (hasOverflowClip())
layer()->scrollableArea()->scrollToXOffset(newLeft, ScrollOffsetClamped, ScrollBehaviorAuto);
}
void RenderBox::setScrollTop(LayoutUnit newTop)
{
// Hits in compositing/overflow/do-not-assert-on-invisible-composited-layers.html
DisableCompositingQueryAsserts disabler;
if (hasOverflowClip())
layer()->scrollableArea()->scrollToYOffset(newTop, ScrollOffsetClamped, ScrollBehaviorAuto);
}
void RenderBox::scrollToOffset(const DoubleSize& offset, ScrollBehavior scrollBehavior)
{
// This doesn't hit in any tests, but since the equivalent code in setScrollTop
// does, presumably this code does as well.
DisableCompositingQueryAsserts disabler;
if (hasOverflowClip())
layer()->scrollableArea()->scrollToOffset(offset, ScrollOffsetClamped, scrollBehavior);
}
static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
{
// If scrollbars aren't explicitly forbidden, permit scrolling.
if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
return true;
// If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
if (frameView->wasScrolledByUser())
return false;
// Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
// like navigation to an anchor.
Page* page = frameView->frame().page();
if (!page)
return false;
return !page->autoscrollController().autoscrollInProgress();
}
void RenderBox::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
{
// Presumably the same issue as in setScrollTop. See crbug.com/343132.
DisableCompositingQueryAsserts disabler;
RenderBox* parentBox = 0;
LayoutRect newRect = rect;
bool restrictedByLineClamp = false;
if (parent()) {
parentBox = parent()->enclosingBox();
restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
}
if (hasOverflowClip() && !restrictedByLineClamp) {
// Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
// This will prevent us from revealing text hidden by the slider in Safari RSS.
newRect = layer()->scrollableArea()->exposeRect(rect, alignX, alignY);
} else if (!parentBox && canBeProgramaticallyScrolled()) {
if (FrameView* frameView = this->frameView()) {
HTMLFrameOwnerElement* ownerElement = document().ownerElement();
if (ownerElement && ownerElement->renderer()) {
HTMLFrameElementBase* frameElementBase = isHTMLFrameElementBase(*ownerElement) ? toHTMLFrameElementBase(ownerElement) : 0;
if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
LayoutRect viewRect = frameView->visibleContentRect();
LayoutRect exposeRect = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
double xOffset = exposeRect.x();
double yOffset = exposeRect.y();
// Adjust offsets if they're outside of the allowable range.
xOffset = std::max(0.0, std::min<double>(frameView->contentsWidth(), xOffset));
yOffset = std::max(0.0, std::min<double>(frameView->contentsHeight(), yOffset));
frameView->setScrollPosition(DoublePoint(xOffset, yOffset));
if (frameView->safeToPropagateScrollToParent()) {
parentBox = ownerElement->renderer()->enclosingBox();
// FIXME: This doesn't correctly convert the rect to
// absolute coordinates in the parent.
newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
} else {
parentBox = 0;
}
}
} else {
if (frame()->settings()->pinchVirtualViewportEnabled()) {
PinchViewport& pinchViewport = frame()->page()->frameHost().pinchViewport();
// We want to move the rect into the viewport that excludes the scrollbars so we intersect
// the pinch viewport with the scrollbar-excluded frameView content rect.
LayoutRect viewRect = intersection(
LayoutRect(pinchViewport.visibleRectInDocument()), frameView->visibleContentRect());
LayoutRect r = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
// pinchViewport.scrollIntoView will attempt to center the given rect within the viewport
// so to prevent it from adjusting r's coordinates the rect must match the viewport's size
// i.e. add the subtracted scrollbars from above back in.
// FIXME: This is hacky and required because getRectToExpose doesn't naturally account
// for the two viewports. crbug.com/449340.
r.setSize(LayoutSize(pinchViewport.visibleRectInDocument().size()));
pinchViewport.scrollIntoView(r);
} else {
LayoutRect viewRect = frameView->visibleContentRect();
LayoutRect r = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
frameView->setScrollPosition(DoublePoint(r.location()));
}
}
}
}
if (frame()->page()->autoscrollController().autoscrollInProgress())
parentBox = enclosingScrollableBox();
if (parentBox)
parentBox->scrollRectToVisible(newRect, alignX, alignY);
}
void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
{
rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
}
void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
{
quads.append(localToAbsoluteQuad(FloatRect(0, 0, m_frameRect.width().toFloat(), m_frameRect.height().toFloat()), 0 /* mode */, wasFixed));
}
void RenderBox::updateLayerTransformAfterLayout()
{
// Transform-origin depends on box size, so we need to update the layer transform after layout.
if (hasLayer())
layer()->updateTransformationMatrix();
}
LayoutUnit RenderBox::constrainLogicalWidthByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb) const
{
RenderStyle* styleToUse = style();
if (!styleToUse->logicalMaxWidth().isMaxSizeNone())
logicalWidth = std::min(logicalWidth, computeLogicalWidthUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb));
return std::max(logicalWidth, computeLogicalWidthUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb));
}
LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
{
RenderStyle* styleToUse = style();
if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
LayoutUnit maxH = computeLogicalHeightUsing(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
if (maxH != -1)
logicalHeight = std::min(logicalHeight, maxH);
}
return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse->logicalMinHeight(), intrinsicContentHeight));
}
LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
{
RenderStyle* styleToUse = style();
if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
LayoutUnit maxH = computeContentLogicalHeight(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
if (maxH != -1)
logicalHeight = std::min(logicalHeight, maxH);
}
return std::max(logicalHeight, computeContentLogicalHeight(styleToUse->logicalMinHeight(), intrinsicContentHeight));
}
IntRect RenderBox::absoluteContentBox() const
{
// This is wrong with transforms and flipped writing modes.
IntRect rect = pixelSnappedIntRect(contentBoxRect());
FloatPoint absPos = localToAbsolute();
rect.move(absPos.x(), absPos.y());
return rect;
}
IntSize RenderBox::absoluteContentBoxOffset() const
{
IntPoint offset = roundedIntPoint(contentBoxOffset());
FloatPoint absPos = localToAbsolute();
offset.move(absPos.x(), absPos.y());
return toIntSize(offset);
}
FloatQuad RenderBox::absoluteContentQuad() const
{
LayoutRect rect = contentBoxRect();
return localToAbsoluteQuad(FloatRect(rect));
}
void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset) const
{
if (!size().isEmpty())
rects.append(LayoutRect(additionalOffset, size()));
}
bool RenderBox::canResize() const
{
// We need a special case for <iframe> because they never have
// hasOverflowClip(). However, they do "implicitly" clip their contents, so
// we want to allow resizing them also.
return (hasOverflowClip() || isRenderIFrame()) && style()->resize() != RESIZE_NONE;
}
void RenderBox::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
{
LayoutPoint adjustedLayerOffset = layerOffset + locationOffset();
RenderBoxModelObject::addLayerHitTestRects(layerRects, currentLayer, adjustedLayerOffset, containerRect);
}
void RenderBox::computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint& layerOffset) const
{
if (!size().isEmpty())
rects.append(LayoutRect(layerOffset, size()));
}
int RenderBox::reflectionOffset() const
{
if (!style()->boxReflect())
return 0;
if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
return valueForLength(style()->boxReflect()->offset(), borderBoxRect().width());
return valueForLength(style()->boxReflect()->offset(), borderBoxRect().height());
}
LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
{
if (!style()->boxReflect())
return LayoutRect();
LayoutRect box = borderBoxRect();
LayoutRect result = r;
switch (style()->boxReflect()->direction()) {
case ReflectionBelow:
result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
break;
case ReflectionAbove:
result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
break;
case ReflectionLeft:
result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
break;
case ReflectionRight:
result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
break;
}
return result;
}
int RenderBox::verticalScrollbarWidth() const
{
if (!hasOverflowClip() || style()->overflowY() == OOVERLAY)
return 0;
return layer()->scrollableArea()->verticalScrollbarWidth();
}
int RenderBox::horizontalScrollbarHeight() const
{
if (!hasOverflowClip() || style()->overflowX() == OOVERLAY)
return 0;
return layer()->scrollableArea()->horizontalScrollbarHeight();
}
int RenderBox::intrinsicScrollbarLogicalWidth() const
{
if (!hasOverflowClip())
return 0;
if (isHorizontalWritingMode() && style()->overflowY() == OSCROLL) {
ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasVerticalScrollbar());
return verticalScrollbarWidth();
}
if (!isHorizontalWritingMode() && style()->overflowX() == OSCROLL) {
ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasHorizontalScrollbar());
return horizontalScrollbarHeight();
}
return 0;
}
bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float delta)
{
// Presumably the same issue as in setScrollTop. See crbug.com/343132.
DisableCompositingQueryAsserts disabler;
// Logical scroll is a higher level concept, all directions by here must be physical
ASSERT(!isLogical(direction));
if (!layer() || !layer()->scrollableArea())
return false;
return layer()->scrollableArea()->scroll(direction, granularity, delta);
}
bool RenderBox::canBeScrolledAndHasScrollableArea() const
{
return canBeProgramaticallyScrolled() && (pixelSnappedScrollHeight() != pixelSnappedClientHeight() || pixelSnappedScrollWidth() != pixelSnappedClientWidth());
}
bool RenderBox::canBeProgramaticallyScrolled() const
{
Node* node = this->node();
if (node && node->isDocumentNode())
return true;
if (!hasOverflowClip())
return false;
bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
if (scrollsOverflow() && hasScrollableOverflow)
return true;
return node && node->hasEditableStyle();
}
bool RenderBox::usesCompositedScrolling() const
{
return hasOverflowClip() && hasLayer() && layer()->scrollableArea()->usesCompositedScrolling();
}
void RenderBox::autoscroll(const IntPoint& position)
{
LocalFrame* frame = this->frame();
if (!frame)
return;
FrameView* frameView = frame->view();
if (!frameView)
return;
IntPoint currentDocumentPosition = frameView->windowToContents(position);
scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
}
// There are two kinds of renderer that can autoscroll.
bool RenderBox::canAutoscroll() const
{
if (node() && node()->isDocumentNode())
return view()->frameView()->isScrollable();
// Check for a box that can be scrolled in its own right.
return canBeScrolledAndHasScrollableArea();
}
// If specified point is in border belt, returned offset denotes direction of
// scrolling.
IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
{
if (!frame())
return IntSize();
FrameView* frameView = frame()->view();
if (!frameView)
return IntSize();
IntRect box(absoluteBoundingBoxRect());
box.move(view()->frameView()->scrollOffset());
IntRect windowBox = view()->frameView()->contentsToWindow(box);
IntPoint windowAutoscrollPoint = windowPoint;
if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
windowAutoscrollPoint.move(autoscrollBeltSize, 0);
if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
windowAutoscrollPoint.move(0, -autoscrollBeltSize);
else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
windowAutoscrollPoint.move(0, autoscrollBeltSize);
return windowAutoscrollPoint - windowPoint;
}
RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
{
while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document().ownerElement())
renderer = renderer->document().ownerElement()->renderer();
else
renderer = renderer->parent();
}
return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
}
static inline int adjustedScrollDelta(int beginningDelta)
{
// This implemention matches Firefox's.
// http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
const int speedReducer = 12;
int adjustedDelta = beginningDelta / speedReducer;
if (adjustedDelta > 1)
adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
else if (adjustedDelta < -1)
adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
return adjustedDelta;
}
static inline IntSize adjustedScrollDelta(const IntSize& delta)
{
return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
}
void RenderBox::panScroll(const IntPoint& sourcePoint)
{
LocalFrame* frame = this->frame();
if (!frame)
return;
IntPoint lastKnownMousePosition = frame->eventHandler().lastKnownMousePosition();
// We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
static IntPoint previousMousePosition;
if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
lastKnownMousePosition = previousMousePosition;
else
previousMousePosition = lastKnownMousePosition;
IntSize delta = lastKnownMousePosition - sourcePoint;
if (abs(delta.width()) <= FrameView::noPanScrollRadius) // at the center we let the space for the icon
delta.setWidth(0);
if (abs(delta.height()) <= FrameView::noPanScrollRadius)
delta.setHeight(0);
scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
}
void RenderBox::scrollByRecursively(const DoubleSize& delta, ScrollOffsetClamping clamp)
{
if (delta.isZero())
return;
bool restrictedByLineClamp = false;
if (parent())
restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
if (hasOverflowClip() && !restrictedByLineClamp) {
DoubleSize newScrollOffset = layer()->scrollableArea()->adjustedScrollOffset() + delta;
layer()->scrollableArea()->scrollToOffset(newScrollOffset, clamp);
// If this layer can't do the scroll we ask the next layer up that can scroll to try
DoubleSize remainingScrollOffset = newScrollOffset - layer()->scrollableArea()->adjustedScrollOffset();
if (!remainingScrollOffset.isZero() && parent()) {
if (RenderBox* scrollableBox = enclosingScrollableBox())
scrollableBox->scrollByRecursively(remainingScrollOffset, clamp);
LocalFrame* frame = this->frame();
if (frame && frame->page())
frame->page()->autoscrollController().updateAutoscrollRenderer();
}
} else if (view()->frameView()) {
// If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
// have an overflow clip. Which means that it is a document node that can be scrolled.
// FIXME: Pass in DoubleSize. crbug.com/414283.
view()->frameView()->scrollBy(flooredIntSize(delta));
// FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement?
// https://bugs.webkit.org/show_bug.cgi?id=28237
}
}
bool RenderBox::needsPreferredWidthsRecalculation() const
{
return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent();
}
IntSize RenderBox::scrolledContentOffset() const
{
ASSERT(hasOverflowClip());
ASSERT(hasLayer());
// FIXME: Return DoubleSize here. crbug.com/414283.
return flooredIntSize(layer()->scrollableArea()->scrollOffset());
}
void RenderBox::applyCachedClipAndScrollOffsetForPaintInvalidation(LayoutRect& paintRect) const
{
ASSERT(hasLayer());
ASSERT(hasOverflowClip());
flipForWritingMode(paintRect);
paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
// Do not clip scroll layer contents because the compositor expects the whole layer
// to be always invalidated in-time.
if (usesCompositedScrolling()) {
flipForWritingMode(paintRect);
return;
}
// size() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
// layer's size instead. Even if the layer's size is wrong, the layer itself will issue paint invalidations
// anyway if its size does change.
LayoutRect clipRect(LayoutPoint(), LayoutSize(layer()->size()));
paintRect = intersection(paintRect, clipRect);
flipForWritingMode(paintRect);
}
void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
}
LayoutUnit RenderBox::minPreferredLogicalWidth() const
{
if (preferredLogicalWidthsDirty()) {
#if ENABLE(ASSERT)
SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
#endif
const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
}
return m_minPreferredLogicalWidth;
}
LayoutUnit RenderBox::maxPreferredLogicalWidth() const
{
if (preferredLogicalWidthsDirty()) {
#if ENABLE(ASSERT)
SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
#endif
const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
}
return m_maxPreferredLogicalWidth;
}
bool RenderBox::hasOverrideHeight() const
{
return m_rareData && m_rareData->m_overrideLogicalContentHeight != -1;
}
bool RenderBox::hasOverrideWidth() const
{
return m_rareData && m_rareData->m_overrideLogicalContentWidth != -1;
}
void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
{
ASSERT(height >= 0);
ensureRareData().m_overrideLogicalContentHeight = height;
}
void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
{
ASSERT(width >= 0);
ensureRareData().m_overrideLogicalContentWidth = width;
}
void RenderBox::clearOverrideLogicalContentHeight()
{
if (m_rareData)
m_rareData->m_overrideLogicalContentHeight = -1;
}
void RenderBox::clearOverrideLogicalContentWidth()
{
if (m_rareData)
m_rareData->m_overrideLogicalContentWidth = -1;
}
void RenderBox::clearOverrideSize()
{
clearOverrideLogicalContentHeight();
clearOverrideLogicalContentWidth();
}
LayoutUnit RenderBox::overrideLogicalContentWidth() const
{
ASSERT(hasOverrideWidth());
return m_rareData->m_overrideLogicalContentWidth;
}
LayoutUnit RenderBox::overrideLogicalContentHeight() const
{
ASSERT(hasOverrideHeight());
return m_rareData->m_overrideLogicalContentHeight;
}
LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
{
ASSERT(hasOverrideContainingBlockLogicalWidth());
return gOverrideContainingBlockLogicalWidthMap->get(this);
}
LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
{
ASSERT(hasOverrideContainingBlockLogicalHeight());
return gOverrideContainingBlockLogicalHeightMap->get(this);
}
bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
{
return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
}
bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
{
return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
}
void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
{
if (!gOverrideContainingBlockLogicalWidthMap)
gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
}
void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
{
if (!gOverrideContainingBlockLogicalHeightMap)
gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
}
void RenderBox::clearContainingBlockOverrideSize()
{
if (gOverrideContainingBlockLogicalWidthMap)
gOverrideContainingBlockLogicalWidthMap->remove(this);
clearOverrideContainingBlockContentLogicalHeight();
}
void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
{
if (gOverrideContainingBlockLogicalHeightMap)
gOverrideContainingBlockLogicalHeightMap->remove(this);
}
LayoutUnit RenderBox::extraInlineOffset() const
{
return gExtraInlineOffsetMap ? gExtraInlineOffsetMap->get(this) : LayoutUnit();
}
LayoutUnit RenderBox::extraBlockOffset() const
{
return gExtraBlockOffsetMap ? gExtraBlockOffsetMap->get(this) : LayoutUnit();
}
void RenderBox::setExtraInlineOffset(LayoutUnit inlineOffest)
{
if (!gExtraInlineOffsetMap)
gExtraInlineOffsetMap = new OverrideSizeMap;
gExtraInlineOffsetMap->set(this, inlineOffest);
}
void RenderBox::setExtraBlockOffset(LayoutUnit blockOffest)
{
if (!gExtraBlockOffsetMap)
gExtraBlockOffsetMap = new OverrideSizeMap;
gExtraBlockOffsetMap->set(this, blockOffest);
}
void RenderBox::clearExtraInlineAndBlockOffests()
{
if (gExtraInlineOffsetMap)
gExtraInlineOffsetMap->remove(this);
if (gExtraBlockOffsetMap)
gExtraBlockOffsetMap->remove(this);
}
LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
{
LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
if (style()->boxSizing() == CONTENT_BOX)
return width + bordersPlusPadding;
return std::max(width, bordersPlusPadding);
}
LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
{
LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
if (style()->boxSizing() == CONTENT_BOX)
return height + bordersPlusPadding;
return std::max(height, bordersPlusPadding);
}
LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
{
if (style()->boxSizing() == BORDER_BOX)
width -= borderAndPaddingLogicalWidth();
return std::max(LayoutUnit(), width);
}
LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
{
if (style()->boxSizing() == BORDER_BOX)
height -= borderAndPaddingLogicalHeight();
return std::max(LayoutUnit(), height);
}
// Hit Testing
bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
{
LayoutPoint adjustedLocation = accumulatedOffset + location();
// Check kids first.
for (RenderObject* child = slowLastChild(); child; child = child->previousSibling()) {
if ((!child->hasLayer() || !toRenderLayerModelObject(child)->layer()->isSelfPaintingLayer()) && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
return true;
}
}
// Check our bounds next. For this purpose always assume that we can only be hit in the
// foreground phase (which is true for replaced elements like images).
LayoutRect boundsRect = borderBoxRect();
boundsRect.moveBy(adjustedLocation);
if (visibleToHitTestRequest(request) && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
return true;
}
return false;
}
void RenderBox::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
BoxPainter(*this).paint(paintInfo, paintOffset);
}
void RenderBox::paintBoxDecorationBackground(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
BoxPainter(*this).paintBoxDecorationBackground(paintInfo, paintOffset);
}
bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent)
{
ASSERT(hasBackground());
LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect());
Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
if (backgroundColor.alpha()) {
paintedExtent = backgroundRect;
return true;
}
if (!style()->backgroundLayers().image() || style()->backgroundLayers().next()) {
paintedExtent = backgroundRect;
return true;
}
BackgroundImageGeometry geometry;
BoxPainter::calculateBackgroundImageGeometry(*this, 0, style()->backgroundLayers(), backgroundRect, geometry);
if (geometry.hasNonLocalGeometry())
return false;
paintedExtent = geometry.destRect();
return true;
}
bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
{
if (isBody() && skipBodyBackground(this))
return false;
Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
if (backgroundColor.hasAlpha())
return false;
// If the element has appearance, it might be painted by theme.
// We cannot be sure if theme paints the background opaque.
// In this case it is safe to not assume opaqueness.
// FIXME: May be ask theme if it paints opaque.
if (style()->hasAppearance())
return false;
// FIXME: Check the opaqueness of background images.
// FIXME: Use rounded rect if border radius is present.
if (style()->hasBorderRadius())
return false;
// FIXME: The background color clip is defined by the last layer.
if (style()->backgroundLayers().next())
return false;
LayoutRect backgroundRect;
switch (style()->backgroundClip()) {
case BorderFillBox:
backgroundRect = borderBoxRect();
break;
case PaddingFillBox:
backgroundRect = paddingBoxRect();
break;
case ContentFillBox:
backgroundRect = contentBoxRect();
break;
default:
break;
}
return backgroundRect.contains(localRect);
}
static bool isCandidateForOpaquenessTest(RenderBox* childBox)
{
RenderStyle* childStyle = childBox->style();
if (childStyle->position() != StaticPosition && childBox->containingBlock() != childBox->parent())
return false;
if (childStyle->visibility() != VISIBLE || childStyle->shapeOutside())
return false;
if (childBox->size().isZero())
return false;
if (RenderLayer* childLayer = childBox->layer()) {
// FIXME: perhaps this could be less conservative?
if (childLayer->compositingState() != NotComposited)
return false;
// FIXME: Deal with z-index.
if (!childStyle->hasAutoZIndex())
return false;
if (childLayer->hasTransformRelatedProperty() || childLayer->isTransparent() || childLayer->hasFilter())
return false;
if (childBox->hasOverflowClip() && childStyle->hasBorderRadius())
return false;
}
return true;
}
bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
{
if (!maxDepthToTest)
return false;
for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
if (!child->isBox())
continue;
RenderBox* childBox = toRenderBox(child);
if (!isCandidateForOpaquenessTest(childBox))
continue;
LayoutPoint childLocation = childBox->location();
if (childBox->isRelPositioned())
childLocation.move(childBox->relativePositionOffset());
LayoutRect childLocalRect = localRect;
childLocalRect.moveBy(-childLocation);
if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
// If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
if (childBox->style()->position() == StaticPosition)
return false;
continue;
}
if (childLocalRect.maxY() > childBox->size().height() || childLocalRect.maxX() > childBox->size().width())
continue;
if (childBox->backgroundIsKnownToBeOpaqueInRect(childLocalRect))
return true;
if (childBox->foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
return true;
}
return false;
}
bool RenderBox::computeBackgroundIsKnownToBeObscured()
{
// Test to see if the children trivially obscure the background.
// FIXME: This test can be much more comprehensive.
if (!hasBackground())
return false;
// Table and root background painting is special.
if (isTable() || isDocumentElement())
return false;
// FIXME: box-shadow is painted while background painting.
if (style()->boxShadow())
return false;
LayoutRect backgroundRect;
if (!getBackgroundPaintedExtent(backgroundRect))
return false;
return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
}
bool RenderBox::backgroundHasOpaqueTopLayer() const
{
const FillLayer& fillLayer = style()->backgroundLayers();
if (fillLayer.clip() != BorderFillBox)
return false;
// Clipped with local scrolling
if (hasOverflowClip() && fillLayer.attachment() == LocalBackgroundAttachment)
return false;
if (fillLayer.hasOpaqueImage(this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(*this, style()->effectiveZoom()))
return true;
// If there is only one layer and no image, check whether the background color is opaque
if (!fillLayer.next() && !fillLayer.hasImage()) {
Color bgColor = resolveColor(CSSPropertyBackgroundColor);
if (bgColor.alpha() == 255)
return true;
}
return false;
}
void RenderBox::paintMask(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
BoxPainter(*this).paintMask(paintInfo, paintOffset);
}
void RenderBox::paintClippingMask(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
BoxPainter(*this).paintClippingMask(paintInfo, paintOffset);
}
void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
{
if (!parent())
return;
AllowPaintInvalidationScope scoper(frameView());
if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
(style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
setShouldDoFullPaintInvalidation();
return;
}
ShapeValue* shapeOutsideValue = style()->shapeOutside();
if (!frameView()->isInPerformLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
ShapeOutsideInfo& info = ShapeOutsideInfo::ensureInfo(*this);
if (!info.isComputingShape()) {
info.markShapeAsDirty();
markShapeOutsideDependentsForLayout();
}
}
if (!paintInvalidationLayerRectsForImage(image, style()->backgroundLayers(), true))
paintInvalidationLayerRectsForImage(image, style()->maskLayers(), false);
}
bool RenderBox::paintInvalidationLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground)
{
Vector<RenderObject*> layerRenderers;
// A background of the body or document must extend to the total visible size of the document. This means the union of the
// view and document bounds, since it can be the case that the view is larger than the document and vice-versa.
// http://dev.w3.org/csswg/css-backgrounds/#the-background
if (drawingBackground && (isDocumentElement() || (isBody() && !document().documentElement()->renderer()->hasBackground()))) {
layerRenderers.append(document().documentElement()->renderer());
layerRenderers.append(view());
if (view()->frameView())
view()->frameView()->setNeedsFullPaintInvalidation();
} else {
layerRenderers.append(this);
}
for (const FillLayer* curLayer = &layers; curLayer; curLayer = curLayer->next()) {
if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(*this, style()->effectiveZoom())) {
for (RenderObject* layerRenderer : layerRenderers)
layerRenderer->setShouldDoFullPaintInvalidation();
return true;
}
}
return false;
}
PaintInvalidationReason RenderBox::invalidatePaintIfNeeded(const PaintInvalidationState& paintInvalidationState, const RenderLayerModelObject& newPaintInvalidationContainer)
{
PaintInvalidationReason reason = RenderBoxModelObject::invalidatePaintIfNeeded(paintInvalidationState, newPaintInvalidationContainer);
// If we are set to do a full paint invalidation that means the RenderView will be
// issue paint invalidations. We can then skip issuing of paint invalidations for the child
// renderers as they'll be covered by the RenderView.
if (!view()->doingFullPaintInvalidation() && !isFullPaintInvalidationReason(reason)) {
invalidatePaintForOverflowIfNeeded();
// Issue paint invalidations for any scrollbars if there is a scrollable area for this renderer.
if (ScrollableArea* area = scrollableArea()) {
if (area->hasVerticalBarDamage())
invalidatePaintRectangle(area->verticalBarDamage());
if (area->hasHorizontalBarDamage())
invalidatePaintRectangle(area->horizontalBarDamage());
}
}
// This is for the next invalidatePaintIfNeeded so must be at the end.
savePreviousBorderBoxSizeIfNeeded();
return reason;
}
void RenderBox::clearPaintInvalidationState(const PaintInvalidationState& paintInvalidationState)
{
RenderBoxModelObject::clearPaintInvalidationState(paintInvalidationState);
if (ScrollableArea* area = scrollableArea())
area->resetScrollbarDamage();
}
#if ENABLE(ASSERT)
bool RenderBox::paintInvalidationStateIsDirty() const
{
if (ScrollableArea* area = scrollableArea()) {
if (area->hasVerticalBarDamage() || area->hasHorizontalBarDamage())
return true;
}
return RenderBoxModelObject::paintInvalidationStateIsDirty();
}
#endif
LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy relevancy)
{
// FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
// here.
LayoutRect clipRect = borderBoxRect();
clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
if (!hasOverflowClip())
return clipRect;
// Subtract out scrollbars if we have them.
if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
clipRect.move(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), 0);
clipRect.contract(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), layer()->scrollableArea()->horizontalScrollbarHeight(relevancy));
return clipRect;
}
LayoutRect RenderBox::clipRect(const LayoutPoint& location)
{
LayoutRect borderBoxRect = this->borderBoxRect();
LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
if (!style()->clipLeft().isAuto()) {
LayoutUnit c = valueForLength(style()->clipLeft(), borderBoxRect.width());
clipRect.move(c, 0);
clipRect.contract(c, 0);
}
if (!style()->clipRight().isAuto())
clipRect.contract(size().width() - valueForLength(style()->clipRight(), size().width()), 0);
if (!style()->clipTop().isAuto()) {
LayoutUnit c = valueForLength(style()->clipTop(), borderBoxRect.height());
clipRect.move(0, c);
clipRect.contract(0, c);
}
if (!style()->clipBottom().isAuto())
clipRect.contract(0, size().height() - valueForLength(style()->clipBottom(), size().height()));
return clipRect;
}
static LayoutUnit portionOfMarginNotConsumedByFloat(LayoutUnit childMargin, LayoutUnit contentSide, LayoutUnit offset)
{
if (childMargin <= 0)
return LayoutUnit();
LayoutUnit contentSideWithMargin = contentSide + childMargin;
if (offset > contentSideWithMargin)
return childMargin;
return offset - contentSide;
}
LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb) const
{
LayoutUnit logicalTopPosition = logicalTop();
LayoutUnit startOffsetForContent = cb->startOffsetForContent();
LayoutUnit endOffsetForContent = cb->endOffsetForContent();
LayoutUnit startOffsetForLine = cb->startOffsetForLine(logicalTopPosition, false);
LayoutUnit endOffsetForLine = cb->endOffsetForLine(logicalTopPosition, false);
// If there aren't any floats constraining us then allow the margins to shrink/expand the width as much as they want.
if (startOffsetForContent == startOffsetForLine && endOffsetForContent == endOffsetForLine)
return cb->availableLogicalWidthForLine(logicalTopPosition, false) - childMarginStart - childMarginEnd;
LayoutUnit width = cb->availableLogicalWidthForLine(logicalTopPosition, false) - std::max(LayoutUnit(), childMarginStart) - std::max(LayoutUnit(), childMarginEnd);
// We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
// then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
// offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
// doesn't fit, we can use the line offset, but we need to grow it by the margin to reflect the fact that the margin was
// "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
width += portionOfMarginNotConsumedByFloat(childMarginStart, startOffsetForContent, startOffsetForLine);
width += portionOfMarginNotConsumedByFloat(childMarginEnd, endOffsetForContent, endOffsetForLine);
return width;
}
LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
{
if (hasOverrideContainingBlockLogicalWidth())
return overrideContainingBlockContentLogicalWidth();
RenderBlock* cb = containingBlock();
return cb->availableLogicalWidth();
}
LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
{
if (hasOverrideContainingBlockLogicalHeight())
return overrideContainingBlockContentLogicalHeight();
RenderBlock* cb = containingBlock();
return cb->availableLogicalHeight(heightType);
}
LayoutUnit RenderBox::containingBlockAvailableLineWidth() const
{
RenderBlock* cb = containingBlock();
if (cb->isRenderBlockFlow())
return toRenderBlockFlow(cb)->availableLogicalWidthForLine(logicalTop(), false, availableLogicalHeight(IncludeMarginBorderPadding));
return LayoutUnit();
}
LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
{
if (hasOverrideContainingBlockLogicalHeight())
return overrideContainingBlockContentLogicalHeight();
RenderBlock* cb = containingBlock();
if (cb->hasOverrideHeight())
return cb->overrideLogicalContentHeight();
RenderStyle* containingBlockStyle = cb->style();
Length logicalHeightLength = containingBlockStyle->logicalHeight();
// FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
if (!logicalHeightLength.isFixed()) {
LayoutUnit fillFallbackExtent = containingBlockStyle->isHorizontalWritingMode()
? view()->frameView()->unscaledVisibleContentSize().height()
: view()->frameView()->unscaledVisibleContentSize().width();
LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
return std::min(fillAvailableExtent, fillFallbackExtent);
}
// Use the content box logical height as specified by the style.
return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
}
void RenderBox::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
{
if (paintInvalidationContainer == this)
return;
if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer)) {
LayoutSize offset = paintInvalidationState->paintOffset() + locationOffset();
if (style()->hasInFlowPosition() && layer())
offset += layer()->offsetForInFlowPosition();
transformState.move(offset);
return;
}
bool containerSkipped;
RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
if (!o)
return;
bool isFixedPos = style()->position() == FixedPosition;
bool hasTransform = hasLayer() && layer()->transform();
// If this box has a transform, it acts as a fixed position container for fixed descendants,
// and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
if (hasTransform && !isFixedPos)
mode &= ~IsFixed;
else if (isFixedPos)
mode |= IsFixed;
if (wasFixed)
*wasFixed = mode & IsFixed;
LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
bool preserve3D = mode & UseTransforms && (o->style()->preserves3D() || style()->preserves3D());
if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
TransformationMatrix t;
getTransformFromContainer(o, containerOffset, t);
transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
} else
transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
if (containerSkipped) {
// There can't be a transform between paintInvalidationContainer and o, because transforms create containers, so it should be safe
// to just subtract the delta between the paintInvalidationContainer and o.
LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
return;
}
mode &= ~ApplyContainerFlip;
o->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed);
}
void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
{
bool isFixedPos = style()->position() == FixedPosition;
bool hasTransform = hasLayer() && layer()->transform();
if (hasTransform && !isFixedPos) {
// If this box has a transform, it acts as a fixed position container for fixed descendants,
// and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
mode &= ~IsFixed;
} else if (isFixedPos)
mode |= IsFixed;
RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
}
LayoutSize RenderBox::offsetFromContainer(const RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
{
ASSERT(o == container());
LayoutSize offset;
if (isRelPositioned())
offset += offsetForInFlowPosition();
if (!isInline() || isReplaced()) {
if (!style()->hasOutOfFlowPosition() && o->hasColumns()) {
const RenderBlock* block = toRenderBlock(o);
LayoutRect columnRect(frameRect());
block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
offset += toSize(columnRect.location());
LayoutPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
offset = toLayoutSize(block->flipForWritingModeIncludingColumns(toLayoutPoint(offset)));
offset += o->columnOffset(columnPoint);
offset = block->flipForWritingMode(offset);
if (offsetDependsOnPoint)
*offsetDependsOnPoint = true;
} else {
offset += topLeftLocationOffset();
if (o->isRenderFlowThread()) {
// So far the point has been in flow thread coordinates (i.e. as if everything in
// the fragmentation context lived in one tall single column). Convert it to a
// visual point now.
LayoutPoint pointInContainer = point + offset;
offset += o->columnOffset(pointInContainer);
if (offsetDependsOnPoint)
*offsetDependsOnPoint = true;
}
}
}
if (o->hasOverflowClip())
offset -= toRenderBox(o)->scrolledContentOffset();
if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
offset += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
return offset;
}
InlineBox* RenderBox::createInlineBox()
{
return new InlineBox(*this);
}
void RenderBox::dirtyLineBoxes(bool fullLayout)
{
if (inlineBoxWrapper()) {
if (fullLayout) {
inlineBoxWrapper()->destroy();
ASSERT(m_rareData);
m_rareData->m_inlineBoxWrapper = 0;
} else {
inlineBoxWrapper()->dirtyLineBoxes();
}
}
}
void RenderBox::positionLineBox(InlineBox* box)
{
if (isOutOfFlowPositioned()) {
// Cache the x position only if we were an INLINE type originally.
bool wasInline = style()->isOriginalDisplayInlineType();
if (wasInline) {
// The value is cached in the xPos of the box. We only need this value if
// our object was inline originally, since otherwise it would have ended up underneath
// the inlines.
RootInlineBox& root = box->root();
root.block().setStaticInlinePositionForChild(*this, LayoutUnit::fromFloatRound(box->logicalLeft()));
if (style()->hasStaticInlinePosition(box->isHorizontal()))
setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
} else {
// Our object was a block originally, so we make our normal flow position be
// just below the line box (as though all the inlines that came before us got
// wrapped in an anonymous block, which is what would have happened had we been
// in flow). This value was cached in the y() of the box.
layer()->setStaticBlockPosition(box->logicalTop());
if (style()->hasStaticBlockPosition(box->isHorizontal()))
setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
}
if (container()->isRenderInline())
moveWithEdgeOfInlineContainerIfNecessary(box->isHorizontal());
// Nuke the box.
box->remove(DontMarkLineBoxes);
box->destroy();
} else if (isReplaced()) {
setLocation(roundedLayoutPoint(box->topLeft()));
setInlineBoxWrapper(box);
}
}
void RenderBox::moveWithEdgeOfInlineContainerIfNecessary(bool isHorizontal)
{
ASSERT(isOutOfFlowPositioned() && container()->isRenderInline() && container()->isRelPositioned());
// If this object is inside a relative positioned inline and its inline position is an explicit offset from the edge of its container
// then it will need to move if its inline container has changed width. We do not track if the width has changed
// but if we are here then we are laying out lines inside it, so it probably has - mark our object for layout so that it can
// move to the new offset created by the new width.
if (!normalChildNeedsLayout() && !style()->hasStaticInlinePosition(isHorizontal))
setChildNeedsLayout(MarkOnlyThis);
}
void RenderBox::deleteLineBoxWrapper()
{
if (inlineBoxWrapper()) {
if (!documentBeingDestroyed())
inlineBoxWrapper()->remove();
inlineBoxWrapper()->destroy();
ASSERT(m_rareData);
m_rareData->m_inlineBoxWrapper = 0;
}
}
void RenderBox::setSpannerPlaceholder(RenderMultiColumnSpannerPlaceholder& placeholder)
{
RELEASE_ASSERT(!m_rareData || !m_rareData->m_spannerPlaceholder); // not expected to change directly from one spanner to another.
ensureRareData().m_spannerPlaceholder = &placeholder;
}
void RenderBox::clearSpannerPlaceholder()
{
if (!m_rareData)
return;
m_rareData->m_spannerPlaceholder = 0;
}
LayoutRect RenderBox::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
{
if (style()->visibility() != VISIBLE) {
RenderLayer* layer = enclosingLayer();
layer->updateDescendantDependentFlags();
if (layer->subtreeIsInvisible())
return LayoutRect();
}
LayoutRect r = visualOverflowRect();
mapRectToPaintInvalidationBacking(paintInvalidationContainer, r, paintInvalidationState);
return r;
}
void RenderBox::mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect& rect, const PaintInvalidationState* paintInvalidationState) const
{
// The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
// Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
// offset corner for the enclosing container). This allows for a fully RL or BT document to issue paint invalidations
// properly even during layout, since the rect remains flipped all the way until the end.
//
// RenderView::computeRectForPaintInvalidation then converts the rect to physical coordinates. We also convert to
// physical when we hit a paintInvalidationContainer boundary. Therefore the final rect returned is always in the
// physical coordinate space of the paintInvalidationContainer.
RenderStyle* styleToUse = style();
EPosition position = styleToUse->position();
// We need to inflate the paint invalidation rect before we use paintInvalidationState,
// else we would forget to inflate it for the current renderer. FIXME: If these were
// included into the visual overflow for repaint, we wouldn't have this issue.
inflatePaintInvalidationRectForReflectionAndFilter(rect);
if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer) && position != FixedPosition) {
if (layer() && layer()->transform())
rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
// We can't trust the bits on RenderObject, because this might be called while re-resolving style.
if (styleToUse->hasInFlowPosition() && layer())
rect.move(layer()->offsetForInFlowPosition());
rect.moveBy(location());
rect.move(paintInvalidationState->paintOffset());
if (paintInvalidationState->isClipped())
rect.intersect(paintInvalidationState->clipRect());
return;
}
if (paintInvalidationContainer == this) {
if (paintInvalidationContainer->style()->isFlippedBlocksWritingMode())
flipForWritingMode(rect);
return;
}
bool containerSkipped;
RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
if (!o)
return;
if (isWritingModeRoot())
flipForWritingMode(rect);
LayoutPoint topLeft = rect.location();
topLeft.move(locationOffset());
// We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
// in the parent's coordinate space that encloses us.
if (hasLayer() && layer()->transform()) {
rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
topLeft = rect.location();
topLeft.move(locationOffset());
}
if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline()) {
topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
} else if (styleToUse->hasInFlowPosition() && layer()) {
// Apply the relative position offset when invalidating a rectangle. The layer
// is translated, but the render box isn't, so we need to do this to get the
// right dirty rect. Since this is called from RenderObject::setStyle, the relative position
// flag on the RenderObject has been cleared, so use the one on the style().
topLeft += layer()->offsetForInFlowPosition();
}
if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isRenderBlockFlow()) {
LayoutRect paintInvalidationRect(topLeft, rect.size());
toRenderBlock(o)->adjustRectForColumns(paintInvalidationRect);
topLeft = paintInvalidationRect.location();
rect = paintInvalidationRect;
}
// FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
// its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
rect.setLocation(topLeft);
if (o->hasOverflowClip()) {
RenderBox* containerBox = toRenderBox(o);
containerBox->applyCachedClipAndScrollOffsetForPaintInvalidation(rect);
if (rect.isEmpty())
return;
}
if (containerSkipped) {
// If the paintInvalidationContainer is below o, then we need to map the rect into paintInvalidationContainer's coordinates.
LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
rect.move(-containerOffset);
// If the paintInvalidationContainer is fixed, then the rect is already in its coordinates so doesn't need viewport-adjusting.
if (paintInvalidationContainer->style()->position() != FixedPosition && o->isRenderView())
toRenderView(o)->adjustViewportConstrainedOffset(rect, RenderView::viewportConstrainedPosition(position));
return;
}
if (o->isRenderView())
toRenderView(o)->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, RenderView::viewportConstrainedPosition(position), paintInvalidationState);
else
o->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
}
void RenderBox::inflatePaintInvalidationRectForReflectionAndFilter(LayoutRect& paintInvalidationRect) const
{
if (hasReflection())
paintInvalidationRect.unite(reflectedRect(paintInvalidationRect));
if (style()->hasFilter())
paintInvalidationRect.expand(style()->filterOutsets());
}
void RenderBox::invalidatePaintForOverhangingFloats(bool)
{
}
void RenderBox::updateLogicalWidth()
{
LogicalExtentComputedValues computedValues;
computeLogicalWidth(computedValues);
setLogicalWidth(computedValues.m_extent);
setLogicalLeft(computedValues.m_position);
setMarginStart(computedValues.m_margins.m_start);
setMarginEnd(computedValues.m_margins.m_end);
}
static float getMaxWidthListMarker(const RenderBox* renderer)
{
#if ENABLE(ASSERT)
ASSERT(renderer);
Node* parentNode = renderer->generatingNode();
ASSERT(parentNode);
ASSERT(isHTMLOListElement(parentNode) || isHTMLUListElement(parentNode));
ASSERT(renderer->style()->textAutosizingMultiplier() != 1);
#endif
float maxWidth = 0;
for (RenderObject* child = renderer->slowFirstChild(); child; child = child->nextSibling()) {
if (!child->isListItem())
continue;
RenderBox* listItem = toRenderBox(child);
for (RenderObject* itemChild = listItem->slowFirstChild(); itemChild; itemChild = itemChild->nextSibling()) {
if (!itemChild->isListMarker())
continue;
RenderBox* itemMarker = toRenderBox(itemChild);
// Make sure to compute the autosized width.
if (itemMarker->needsLayout())
itemMarker->layout();
maxWidth = std::max<float>(maxWidth, toRenderListMarker(itemMarker)->logicalWidth().toFloat());
break;
}
}
return maxWidth;
}
void RenderBox::computeLogicalWidth(LogicalExtentComputedValues& computedValues) const
{
computedValues.m_extent = logicalWidth();
computedValues.m_position = logicalLeft();
computedValues.m_margins.m_start = marginStart();
computedValues.m_margins.m_end = marginEnd();
if (isOutOfFlowPositioned()) {
computePositionedLogicalWidth(computedValues);
return;
}
// If layout is limited to a subtree, the subtree root's logical width does not change.
if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
return;
// The parent box is flexing us, so it has increased or decreased our
// width. Use the width from the style context.
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
if (hasOverrideWidth() && parent()->isFlexibleBoxIncludingDeprecated()) {
computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
return;
}
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
RenderStyle* styleToUse = style();
Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse->logicalWidth();
RenderBlock* cb = containingBlock();
LayoutUnit containerLogicalWidth = std::max(LayoutUnit(), containingBlockLogicalWidthForContent());
bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
if (isInline() && !isInlineBlockOrInlineTable()) {
// just calculate margins
computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
if (treatAsReplaced)
computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
return;
}
// Width calculations
if (treatAsReplaced)
computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
else {
LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
if (hasPerpendicularContainingBlock)
containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
LayoutUnit preferredWidth = computeLogicalWidthUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb);
computedValues.m_extent = constrainLogicalWidthByMinMax(preferredWidth, containerWidthInInlineDirection, cb);
}
// Margin calculations.
computeMarginsForDirection(InlineDirection, cb, containerLogicalWidth, computedValues.m_extent, computedValues.m_margins.m_start,
computedValues.m_margins.m_end, style()->marginStart(), style()->marginEnd());
if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
&& !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated() && !cb->isRenderGrid()) {
LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this);
bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
if (hasInvertedDirection)
computedValues.m_margins.m_start = newMargin;
else
computedValues.m_margins.m_end = newMargin;
}
if (styleToUse->textAutosizingMultiplier() != 1 && styleToUse->marginStart().type() == Fixed) {
Node* parentNode = generatingNode();
if (parentNode && (isHTMLOListElement(*parentNode) || isHTMLUListElement(*parentNode))) {
// Make sure the markers in a list are properly positioned (i.e. not chopped off) when autosized.
const float adjustedMargin = (1 - 1.0 / styleToUse->textAutosizingMultiplier()) * getMaxWidthListMarker(this);
bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
if (hasInvertedDirection)
computedValues.m_margins.m_end += adjustedMargin;
else
computedValues.m_margins.m_start += adjustedMargin;
}
}
}
LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
{
LayoutUnit marginStart = 0;
LayoutUnit marginEnd = 0;
return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
}
LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
{
marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth);
marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth);
return availableLogicalWidth - marginStart - marginEnd;
}
LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(const Length& logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
{
if (logicalWidthLength.type() == FillAvailable)
return fillAvailableMeasure(availableLogicalWidth);
LayoutUnit minLogicalWidth = 0;
LayoutUnit maxLogicalWidth = 0;
computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
if (logicalWidthLength.type() == MinContent)
return minLogicalWidth + borderAndPadding;
if (logicalWidthLength.type() == MaxContent)
return maxLogicalWidth + borderAndPadding;
if (logicalWidthLength.type() == FitContent) {
minLogicalWidth += borderAndPadding;
maxLogicalWidth += borderAndPadding;
return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
}
ASSERT_NOT_REACHED();
return 0;
}
LayoutUnit RenderBox::computeLogicalWidthUsing(SizeType widthType, const Length& logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* cb) const
{
if (!logicalWidth.isIntrinsicOrAuto()) {
// FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
}
if (logicalWidth.isIntrinsic())
return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
LayoutUnit marginStart = 0;
LayoutUnit marginEnd = 0;
LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
if (shrinkToAvoidFloats() && cb->isRenderBlockFlow() && toRenderBlockFlow(cb)->containsFloats())
logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb)));
if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(logicalWidth))
return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
return logicalWidthResult;
}
static bool columnFlexItemHasStretchAlignment(const RenderObject* flexitem)
{
RenderObject* parent = flexitem->parent();
// auto margins mean we don't stretch. Note that this function will only be used for
// widths, so we don't have to check marginBefore/marginAfter.
ASSERT(parent->style()->isColumnFlexDirection());
if (flexitem->style()->marginStart().isAuto() || flexitem->style()->marginEnd().isAuto())
return false;
return flexitem->style()->alignSelf() == ItemPositionStretch || (flexitem->style()->alignSelf() == ItemPositionAuto && parent->style()->alignItems() == ItemPositionStretch);
}
static bool isStretchingColumnFlexItem(const RenderObject* flexitem)
{
RenderObject* parent = flexitem->parent();
if (parent->isDeprecatedFlexibleBox() && parent->style()->boxOrient() == VERTICAL && parent->style()->boxAlign() == BSTRETCH)
return true;
// We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
if (parent->isFlexibleBox() && parent->style()->flexWrap() == FlexNoWrap && parent->style()->isColumnFlexDirection() && columnFlexItemHasStretchAlignment(flexitem))
return true;
return false;
}
bool RenderBox::sizesLogicalWidthToFitContent(const Length& logicalWidth) const
{
if (isFloating() || isInlineBlockOrInlineTable())
return true;
if (logicalWidth.type() == Intrinsic)
return true;
// Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
// In the case of columns that have a stretch alignment, we go ahead and layout at the
// stretched size to avoid an extra layout when applying alignment.
if (parent()->isFlexibleBox()) {
// For multiline columns, we need to apply align-content first, so we can't stretch now.
if (!parent()->style()->isColumnFlexDirection() || parent()->style()->flexWrap() != FlexNoWrap)
return true;
if (!columnFlexItemHasStretchAlignment(this))
return true;
}
// Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
// that don't stretch their kids lay out their children at their intrinsic widths.
// FIXME: Think about writing-mode here.
// https://bugs.webkit.org/show_bug.cgi?id=46473
if (parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
return true;
// Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
// stretching column flexbox.
// FIXME: Think about writing-mode here.
// https://bugs.webkit.org/show_bug.cgi?id=46473
if (logicalWidth.isAuto() && !isStretchingColumnFlexItem(this) && autoWidthShouldFitContent())
return true;
if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
return true;
return false;
}
bool RenderBox::autoWidthShouldFitContent() const
{
return node() && (isHTMLInputElement(*node()) || isHTMLSelectElement(*node()) || isHTMLButtonElement(*node())
|| isHTMLTextAreaElement(*node()) || (isHTMLLegendElement(*node()) && !style()->hasOutOfFlowPosition()));
}
void RenderBox::computeMarginsForDirection(MarginDirection flowDirection, const RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd, Length marginStartLength, Length marginEndLength) const
{
if (flowDirection == BlockDirection || isFloating() || isInline()) {
if (isTableCell() && flowDirection == BlockDirection) {
// FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
// we may just do it with an extra anonymous block inside the cell.
marginStart = 0;
marginEnd = 0;
return;
}
// Margins are calculated with respect to the logical width of
// the containing block (8.3)
// Inline blocks/tables and floats don't have their margins increased.
marginStart = minimumValueForLength(marginStartLength, containerWidth);
marginEnd = minimumValueForLength(marginEndLength, containerWidth);
return;
}
if (containingBlock->isFlexibleBox()) {
// We need to let flexbox handle the margin adjustment - otherwise, flexbox
// will think we're wider than we actually are and calculate line sizes wrong.
// See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
if (marginStartLength.isAuto())
marginStartLength.setValue(0);
if (marginEndLength.isAuto())
marginEndLength.setValue(0);
}
LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
LayoutUnit availableWidth = containerWidth;
if (avoidsFloats() && containingBlock->isRenderBlockFlow() && toRenderBlockFlow(containingBlock)->containsFloats()) {
availableWidth = containingBlockAvailableLineWidth();
if (shrinkToAvoidFloats() && availableWidth < containerWidth) {
marginStart = std::max(LayoutUnit(), marginStartWidth);
marginEnd = std::max(LayoutUnit(), marginEndWidth);
}
}
// CSS 2.1 (10.3.3): "If 'width' is not 'auto' and 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width'
// (plus any of 'margin-left' or 'margin-right' that are not 'auto') is larger than the width of the containing block, then any 'auto'
// values for 'margin-left' or 'margin-right' are, for the following rules, treated as zero.
LayoutUnit marginBoxWidth = childWidth + (!style()->width().isAuto() ? marginStartWidth + marginEndWidth : LayoutUnit());
if (marginBoxWidth < availableWidth) {
// CSS 2.1: "If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element
// with respect to the edges of the containing block."
const RenderStyle* containingBlockStyle = containingBlock->style();
if ((marginStartLength.isAuto() && marginEndLength.isAuto())
|| (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlockStyle->textAlign() == WEBKIT_CENTER)) {
// Other browsers center the margin box for align=center elements so we match them here.
LayoutUnit centeredMarginBoxStart = std::max(LayoutUnit(), (availableWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
marginStart = centeredMarginBoxStart + marginStartWidth;
marginEnd = availableWidth - childWidth - marginStart + marginEndWidth;
return;
}
// Adjust margins for the align attribute
if ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
|| (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT)) {
if (containingBlockStyle->isLeftToRightDirection() != style()->isLeftToRightDirection()) {
if (!marginStartLength.isAuto())
marginEndLength = Length(Auto);
} else {
if (!marginEndLength.isAuto())
marginStartLength = Length(Auto);
}
}
// CSS 2.1: "If there is exactly one value specified as 'auto', its used value follows from the equality."
if (marginEndLength.isAuto()) {
marginStart = marginStartWidth;
marginEnd = availableWidth - childWidth - marginStart;
return;
}
if (marginStartLength.isAuto()) {
marginEnd = marginEndWidth;
marginStart = availableWidth - childWidth - marginEnd;
return;
}
}
// Either no auto margins, or our margin box width is >= the container width, auto margins will just turn into 0.
marginStart = marginStartWidth;
marginEnd = marginEndWidth;
}
void RenderBox::updateLogicalHeight()
{
m_intrinsicContentLogicalHeight = contentLogicalHeight();
LogicalExtentComputedValues computedValues;
computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
setLogicalHeight(computedValues.m_extent);
setLogicalTop(computedValues.m_position);
setMarginBefore(computedValues.m_margins.m_before);
setMarginAfter(computedValues.m_margins.m_after);
}
void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
{
computedValues.m_extent = logicalHeight;
computedValues.m_position = logicalTop;
// Cell height is managed by the table and inline non-replaced elements do not support a height property.
if (isTableCell() || (isInline() && !isReplaced()))
return;
Length h;
if (isOutOfFlowPositioned())
computePositionedLogicalHeight(computedValues);
else {
RenderBlock* cb = containingBlock();
// If we are perpendicular to our containing block then we need to resolve our block-start and block-end margins so that if they
// are 'auto' we are centred or aligned within the inline flow containing block: this is done by computing the margins as though they are inline.
// Note that as this is the 'sizing phase' we are using our own writing mode rather than the containing block's. We use the containing block's
// writing mode when figuring out the block-direction margins for positioning in |computeAndSetBlockDirectionMargins| (i.e. margin collapsing etc.).
// See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
MarginDirection flowDirection = isHorizontalWritingMode() != cb->isHorizontalWritingMode() ? InlineDirection : BlockDirection;
// For tables, calculate margins only.
if (isTable()) {
computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
return;
}
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
bool stretching = parent()->style()->boxAlign() == BSTRETCH;
bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
bool checkMinMaxHeight = false;
// The parent box is flexing us, so it has increased or decreased our height. We have to
// grab our cached flexible height.
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
if (hasOverrideHeight() && (parent()->isFlexibleBoxIncludingDeprecated() || parent()->isRenderGrid()))
h = Length(overrideLogicalContentHeight(), Fixed);
else if (treatAsReplaced)
h = Length(computeReplacedLogicalHeight(), Fixed);
else {
h = style()->logicalHeight();
checkMinMaxHeight = true;
}
// Block children of horizontal flexible boxes fill the height of the box.
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
if (h.isAuto() && inHorizontalBox && toRenderDeprecatedFlexibleBox(parent())->isStretchingChildren()) {
h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
checkMinMaxHeight = false;
}
LayoutUnit heightResult;
if (checkMinMaxHeight) {
heightResult = computeLogicalHeightUsing(style()->logicalHeight(), computedValues.m_extent - borderAndPaddingLogicalHeight());
if (heightResult == -1)
heightResult = computedValues.m_extent;
heightResult = constrainLogicalHeightByMinMax(heightResult, computedValues.m_extent - borderAndPaddingLogicalHeight());
} else {
// The only times we don't check min/max height are when a fixed length has
// been given as an override. Just use that. The value has already been adjusted
// for box-sizing.
ASSERT(h.isFixed());
heightResult = h.value() + borderAndPaddingLogicalHeight();
}
computedValues.m_extent = heightResult;
computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
}
// WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
// <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
// is specified. When we're printing, we also need this quirk if the body or root has a percentage
// height since we don't set a height in RenderView when we're printing. So without this quirk, the
// height has nothing to be a percentage of, and it ends up being 0. That is bad.
bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
&& (isDocumentElement() || (isBody() && document().documentElement()->renderer()->style()->logicalHeight().isPercent())) && !isInline();
if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
LayoutUnit visibleHeight = view()->viewLogicalHeightForPercentages();
if (isDocumentElement())
computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
else {
LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
}
}
}
LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
{
LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
if (logicalHeight != -1)
logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
return logicalHeight;
}
LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height, LayoutUnit intrinsicContentHeight) const
{
LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
if (heightIncludingScrollbar == -1)
return -1;
return std::max(LayoutUnit(), adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
}
LayoutUnit RenderBox::computeIntrinsicLogicalContentHeightUsing(const Length& logicalHeightLength, LayoutUnit intrinsicContentHeight, LayoutUnit borderAndPadding) const
{
// FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
// If that happens, this code will have to change.
if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
if (isReplaced())
return intrinsicSize().height();
if (m_intrinsicContentLogicalHeight != -1)
return m_intrinsicContentLogicalHeight;
return intrinsicContentHeight;
}
if (logicalHeightLength.isFillAvailable())
return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
ASSERT_NOT_REACHED();
return 0;
}
LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
{
// FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
// If that happens, this code will have to change.
if (height.isIntrinsic()) {
if (intrinsicContentHeight == -1)
return -1; // Intrinsic height isn't available.
return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
}
if (height.isFixed())
return height.value();
if (height.isPercent())
return computePercentageLogicalHeight(height);
return -1;
}
bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const
{
// Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
// and percent heights of children should be resolved against the multicol or paged container.
if (containingBlock->isRenderFlowThread())
return true;
// For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
// For standards mode, we treat the percentage as auto if it has an auto-height containing block.
if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
return false;
return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style()->logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
}
LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
{
LayoutUnit availableHeight = -1;
bool skippedAutoHeightContainingBlock = false;
RenderBlock* cb = containingBlock();
const RenderBox* containingBlockChild = this;
LayoutUnit rootMarginBorderPaddingHeight = 0;
while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb)) {
if (cb->isBody() || cb->isDocumentElement())
rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
skippedAutoHeightContainingBlock = true;
containingBlockChild = cb;
cb = cb->containingBlock();
}
cb->addPercentHeightDescendant(const_cast<RenderBox*>(this));
RenderStyle* cbstyle = cb->style();
// A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
// explicitly specified that can be used for any percentage computations.
bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle->logicalHeight().isAuto() || (!cbstyle->logicalTop().isAuto() && !cbstyle->logicalBottom().isAuto()));
bool includeBorderPadding = isTable();
if (isHorizontalWritingMode() != cb->isHorizontalWritingMode())
availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
else if (hasOverrideContainingBlockLogicalHeight())
availableHeight = overrideContainingBlockContentLogicalHeight();
else if (cb->isTableCell()) {
if (!skippedAutoHeightContainingBlock) {
// Table cells violate what the CSS spec says to do with heights. Basically we
// don't care if the cell specified a height or not. We just always make ourselves
// be a percentage of the cell's current content height.
if (!cb->hasOverrideHeight()) {
// Normally we would let the cell size intrinsically, but scrolling overflow has to be
// treated differently, since WinIE lets scrolled overflow regions shrink as needed.
// While we can't get all cases right, we can at least detect when the cell has a specified
// height or when the table has a specified height. In these cases we want to initially have
// no size and allow the flexing of the table or the cell to its specified height to cause us
// to grow to fill the space. This could end up being wrong in some cases, but it is
// preferable to the alternative (sizing intrinsically and making the row end up too big).
RenderTableCell* cell = toRenderTableCell(cb);
if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
return LayoutUnit();
return -1;
}
availableHeight = cb->overrideLogicalContentHeight();
includeBorderPadding = true;
}
} else if (cbstyle->logicalHeight().isFixed()) {
LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle->logicalHeight().value());
availableHeight = std::max(LayoutUnit(), cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), -1));
} else if (cbstyle->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
// We need to recur and compute the percentage height for our containing block.
LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle->logicalHeight());
if (heightWithScrollbar != -1) {
LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
// We need to adjust for min/max height because this method does not
// handle the min/max of the current block, its caller does. So the
// return value from the recursive call will not have been adjusted
// yet.
LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
availableHeight = std::max(LayoutUnit(), contentBoxHeight);
}
} else if (isOutOfFlowPositionedWithSpecifiedHeight) {
// Don't allow this to affect the block' size() member variable, since this
// can get called while the block is still laying out its kids.
LogicalExtentComputedValues computedValues;
cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
} else if (cb->isRenderView())
availableHeight = view()->viewLogicalHeightForPercentages();
if (availableHeight == -1)
return availableHeight;
availableHeight -= rootMarginBorderPaddingHeight;
if (isTable() && isOutOfFlowPositioned())
availableHeight += cb->paddingLogicalHeight();
LayoutUnit result = valueForLength(height, availableHeight);
if (includeBorderPadding) {
// FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
// It is necessary to use the border-box to match WinIE's broken
// box model. This is essential for sizing inside
// table cells using percentage heights.
result -= borderAndPaddingLogicalHeight();
return std::max(LayoutUnit(), result);
}
return result;
}
LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
{
return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), shouldComputePreferred);
}
LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
{
LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMinWidth().isPercent()) || style()->logicalMinWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMaxWidth().isPercent()) || style()->logicalMaxWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
}
LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(const Length& logicalWidth) const
{
switch (logicalWidth.type()) {
case Fixed:
return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
case MinContent:
case MaxContent: {
// MinContent/MaxContent don't need the availableLogicalWidth argument.
LayoutUnit availableLogicalWidth = 0;
return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
}
case FitContent:
case FillAvailable:
case Percent:
case Calculated: {
// FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's writing-mode is perpendicular to the
// containing block's writing-mode.
// https://bugs.webkit.org/show_bug.cgi?id=46496
const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
Length containerLogicalWidth = containingBlock()->style()->logicalWidth();
// FIXME: Handle cases when containing block width is calculated or viewport percent.
// https://bugs.webkit.org/show_bug.cgi?id=91071
if (logicalWidth.isIntrinsic())
return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
return LayoutUnit();
}
case Intrinsic:
case MinIntrinsic:
case Auto:
case MaxSizeNone:
return intrinsicLogicalWidth();
case ExtendToZoom:
case DeviceWidth:
case DeviceHeight:
break;
}
ASSERT_NOT_REACHED();
return 0;
}
LayoutUnit RenderBox::computeReplacedLogicalHeight() const
{
return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
}
bool RenderBox::logicalHeightComputesAsNone(SizeType sizeType) const
{
ASSERT(sizeType == MinSize || sizeType == MaxSize);
Length logicalHeight = sizeType == MinSize ? style()->logicalMinHeight() : style()->logicalMaxHeight();
Length initialLogicalHeight = sizeType == MinSize ? RenderStyle::initialMinSize() : RenderStyle::initialMaxSize();
if (logicalHeight == initialLogicalHeight)
return true;
if (RenderBlock* cb = containingBlockForAutoHeightDetection(logicalHeight))
return cb->hasAutoHeightOrContainingBlockWithAutoHeight();
return false;
}
LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
{
// If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned,
// the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').
LayoutUnit minLogicalHeight;
if (!logicalHeightComputesAsNone(MinSize))
minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
LayoutUnit maxLogicalHeight = logicalHeight;
if (!logicalHeightComputesAsNone(MaxSize))
maxLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
}
LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(const Length& logicalHeight) const
{
switch (logicalHeight.type()) {
case Fixed:
return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
case Percent:
case Calculated:
{
RenderObject* cb = isOutOfFlowPositioned() ? container() : containingBlock();
while (cb->isAnonymous())
cb = cb->containingBlock();
if (cb->isRenderBlock())
toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
if (cb->isOutOfFlowPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
RenderBlock* block = toRenderBlock(cb);
LogicalExtentComputedValues computedValues;
block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
LayoutUnit newHeight = block->adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
}
// FIXME: availableLogicalHeight() is wrong if the replaced element's writing-mode is perpendicular to the
// containing block's writing-mode.
// https://bugs.webkit.org/show_bug.cgi?id=46496
LayoutUnit availableHeight;
if (isOutOfFlowPositioned())
availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
else {
availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
// It is necessary to use the border-box to match WinIE's broken
// box model. This is essential for sizing inside
// table cells using percentage heights.
// FIXME: This needs to be made writing-mode-aware. If the cell and image are perpendicular writing-modes, this isn't right.
// https://bugs.webkit.org/show_bug.cgi?id=46997
while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
if (cb->isTableCell()) {
// Don't let table cells squeeze percent-height replaced elements
// <http://bugs.webkit.org/show_bug.cgi?id=15359>
availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
}
toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
cb = cb->containingBlock();
}
}
return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
}
case MinContent:
case MaxContent:
case FitContent:
case FillAvailable:
return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingHeight()));
default:
return intrinsicLogicalHeight();
}
}
LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
{
// http://www.w3.org/TR/CSS2/visudet.html#propdef-height - We are interested in the content height.
return constrainContentBoxLogicalHeightByMinMax(availableLogicalHeightUsing(style()->logicalHeight(), heightType), -1);
}
LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
{
if (isRenderView())
return isHorizontalWritingMode() ? toRenderView(this)->frameView()->unscaledVisibleContentSize().height() : toRenderView(this)->frameView()->unscaledVisibleContentSize().width();
// We need to stop here, since we don't want to increase the height of the table
// artificially. We're going to rely on this cell getting expanded to some new
// height, and then when we lay out again we'll use the calculation below.
if (isTableCell() && (h.isAuto() || h.isPercent())) {
if (hasOverrideHeight())
return overrideLogicalContentHeight();
return logicalHeight() - borderAndPaddingLogicalHeight();
}
if (h.isPercent() && isOutOfFlowPositioned()) {
// FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
}
LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h, -1);
if (heightIncludingScrollbar != -1)
return std::max(LayoutUnit(), adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
// FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
// https://bugs.webkit.org/show_bug.cgi?id=46500
if (isRenderBlock() && isOutOfFlowPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
LogicalExtentComputedValues computedValues;
block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
}
// FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
if (heightType == ExcludeMarginBorderPadding) {
// FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
}
return availableHeight;
}
void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
{
LayoutUnit marginBefore;
LayoutUnit marginAfter;
computeMarginsForDirection(BlockDirection, containingBlock, containingBlockLogicalWidthForContent(), logicalHeight(), marginBefore, marginAfter,
style()->marginBeforeUsing(containingBlock->style()),
style()->marginAfterUsing(containingBlock->style()));
// Note that in this 'positioning phase' of the layout we are using the containing block's writing mode rather than our own when calculating margins.
// See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
containingBlock->setMarginBeforeForChild(*this, marginBefore);
containingBlock->setMarginAfterForChild(*this, marginAfter);
}
LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
{
if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
return containingBlockLogicalHeightForPositioned(containingBlock, false);
// Use viewport as container for top-level fixed-position elements.
if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
const RenderView* view = toRenderView(containingBlock);
if (FrameView* frameView = view->frameView()) {
LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
return containingBlock->isHorizontalWritingMode() ? viewportRect.width() : viewportRect.height();
}
}
if (hasOverrideContainingBlockLogicalWidth())
return overrideContainingBlockContentLogicalWidth();
if (containingBlock->isBox())
return toRenderBox(containingBlock)->clientLogicalWidth();
ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
const RenderInline* flow = toRenderInline(containingBlock);
InlineFlowBox* first = flow->firstLineBox();
InlineFlowBox* last = flow->lastLineBox();
// If the containing block is empty, return a width of 0.
if (!first || !last)
return LayoutUnit();
LayoutUnit fromLeft;
LayoutUnit fromRight;
if (containingBlock->style()->isLeftToRightDirection()) {
fromLeft = first->logicalLeft() + first->borderLogicalLeft();
fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
} else {
fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
fromLeft = last->logicalLeft() + last->borderLogicalLeft();
}
return std::max(LayoutUnit(), fromRight - fromLeft);
}
LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
{
if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
return containingBlockLogicalWidthForPositioned(containingBlock, false);
// Use viewport as container for top-level fixed-position elements.
if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
const RenderView* view = toRenderView(containingBlock);
if (FrameView* frameView = view->frameView()) {
LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
return containingBlock->isHorizontalWritingMode() ? viewportRect.height() : viewportRect.width();
}
}
if (hasOverrideContainingBlockLogicalHeight())
return overrideContainingBlockContentLogicalHeight();
if (containingBlock->isBox()) {
const RenderBlock* cb = containingBlock->isRenderBlock() ?
toRenderBlock(containingBlock) : containingBlock->containingBlock();
return cb->clientLogicalHeight();
}
ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
const RenderInline* flow = toRenderInline(containingBlock);
InlineFlowBox* first = flow->firstLineBox();
InlineFlowBox* last = flow->lastLineBox();
// If the containing block is empty, return a height of 0.
if (!first || !last)
return LayoutUnit();
LayoutUnit heightResult;
LayoutRect boundingBox = flow->linesBoundingBox();
if (containingBlock->isHorizontalWritingMode())
heightResult = boundingBox.height();
else
heightResult = boundingBox.width();
heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
return heightResult;
}
static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
{
if (!logicalLeft.isAuto() || !logicalRight.isAuto())
return;
// FIXME: The static distance computation has not been patched for mixed writing modes yet.
if (child->parent()->style()->direction() == LTR) {
LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
if (curr->isBox()) {
staticPosition += toRenderBox(curr)->logicalLeft();
if (toRenderBox(curr)->isRelPositioned())
staticPosition += toRenderBox(curr)->relativePositionOffset().width();
} else if (curr->isInline()) {
if (curr->isRelPositioned()) {
if (!curr->style()->logicalLeft().isAuto())
staticPosition += valueForLength(curr->style()->logicalLeft(), curr->containingBlock()->availableWidth());
else
staticPosition -= valueForLength(curr->style()->logicalRight(), curr->containingBlock()->availableWidth());
}
}
}
logicalLeft.setValue(Fixed, staticPosition);
} else {
RenderBox* enclosingBox = child->parent()->enclosingBox();
LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
for (RenderObject* curr = child->parent(); curr; curr = curr->container()) {
if (curr->isBox()) {
if (curr != containerBlock) {
staticPosition -= toRenderBox(curr)->logicalLeft();
if (toRenderBox(curr)->isRelPositioned())
staticPosition -= toRenderBox(curr)->relativePositionOffset().width();
}
if (curr == enclosingBox)
staticPosition -= enclosingBox->logicalWidth();
} else if (curr->isInline()) {
if (curr->isRelPositioned()) {
if (!curr->style()->logicalLeft().isAuto())
staticPosition -= valueForLength(curr->style()->logicalLeft(), curr->containingBlock()->availableWidth());
else
staticPosition += valueForLength(curr->style()->logicalRight(), curr->containingBlock()->availableWidth());
}
}
if (curr == containerBlock)
break;
}
logicalRight.setValue(Fixed, staticPosition);
}
}
void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues) const
{
if (isReplaced()) {
computePositionedLogicalWidthReplaced(computedValues);
return;
}
// QUESTIONS
// FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
// the type 'static' in determining whether to calculate the static distance?
// NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
// FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
// than or less than the computed width(). Be careful of box-sizing and
// percentage issues.
// The following is based off of the W3C Working Draft from April 11, 2006 of
// CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
// <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
// (block-style-comments in this function and in computePositionedLogicalWidthUsing()
// correspond to text from the spec)
// We don't use containingBlock(), since we may be positioned by an enclosing
// relative positioned inline.
const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
// Use the container block's direction except when calculating the static distance
// This conforms with the reference results for abspos-replaced-width-margin-000.htm
// of the CSS 2.1 test suite
TextDirection containerDirection = containerBlock->style()->direction();
bool isHorizontal = isHorizontalWritingMode();
const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
Length logicalLeftLength = style()->logicalLeft();
Length logicalRightLength = style()->logicalRight();
/*---------------------------------------------------------------------------*\
* For the purposes of this section and the next, the term "static position"
* (of an element) refers, roughly, to the position an element would have had
* in the normal flow. More precisely:
*
* * The static position for 'left' is the distance from the left edge of the
* containing block to the left margin edge of a hypothetical box that would
* have been the first box of the element if its 'position' property had
* been 'static' and 'float' had been 'none'. The value is negative if the
* hypothetical box is to the left of the containing block.
* * The static position for 'right' is the distance from the right edge of the
* containing block to the right margin edge of the same hypothetical box as
* above. The value is positive if the hypothetical box is to the left of the
* containing block's edge.
*
* But rather than actually calculating the dimensions of that hypothetical box,
* user agents are free to make a guess at its probable position.
*
* For the purposes of calculating the static position, the containing block of
* fixed positioned elements is the initial containing block instead of the
* viewport, and all scrollable boxes should be assumed to be scrolled to their
* origin.
\*---------------------------------------------------------------------------*/
// see FIXME 1
// Calculate the static distance if needed.
computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth);
// Calculate constraint equation values for 'width' case.
computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
containerLogicalWidth, bordersPlusPadding,
logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
computedValues);
// Calculate constraint equation values for 'max-width' case.
if (!style()->logicalMaxWidth().isMaxSizeNone()) {
LogicalExtentComputedValues maxValues;
computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
containerLogicalWidth, bordersPlusPadding,
logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
maxValues);
if (computedValues.m_extent > maxValues.m_extent) {
computedValues.m_extent = maxValues.m_extent;
computedValues.m_position = maxValues.m_position;
computedValues.m_margins.m_start = maxValues.m_margins.m_start;
computedValues.m_margins.m_end = maxValues.m_margins.m_end;
}
}
// Calculate constraint equation values for 'min-width' case.
if (!style()->logicalMinWidth().isZero() || style()->logicalMinWidth().isIntrinsic()) {
LogicalExtentComputedValues minValues;
computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
containerLogicalWidth, bordersPlusPadding,
logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
minValues);
if (computedValues.m_extent < minValues.m_extent) {
computedValues.m_extent = minValues.m_extent;
computedValues.m_position = minValues.m_position;
computedValues.m_margins.m_start = minValues.m_margins.m_start;
computedValues.m_margins.m_end = minValues.m_margins.m_end;
}
}
if (!style()->hasStaticInlinePosition(isHorizontal))
computedValues.m_position += extraInlineOffset();
computedValues.m_extent += bordersPlusPadding;
}
static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
{
// Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
// along this axis, then we need to flip the coordinate. This can only happen if the containing block is both a flipped mode and perpendicular to us.
if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
} else {
logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
}
}
LayoutUnit RenderBox::shrinkToFitLogicalWidth(LayoutUnit availableLogicalWidth, LayoutUnit bordersPlusPadding) const
{
LayoutUnit preferredLogicalWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
LayoutUnit preferredMinLogicalWidth = minPreferredLogicalWidth() - bordersPlusPadding;
return std::min(std::max(preferredMinLogicalWidth, availableLogicalWidth), preferredLogicalWidth);
}
void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
const Length& logicalLeft, const Length& logicalRight, const Length& marginLogicalLeft,
const Length& marginLogicalRight, LogicalExtentComputedValues& computedValues) const
{
if (logicalWidth.isIntrinsic())
logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
// 'left' and 'right' cannot both be 'auto' because one would of been
// converted to the static position already
ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
// minimumValueForLength will convert 'auto' to 0 so that it doesn't impact the available space computation below.
LayoutUnit logicalLeftValue = minimumValueForLength(logicalLeft, containerLogicalWidth);
LayoutUnit logicalRightValue = minimumValueForLength(logicalRight, containerLogicalWidth);
const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
bool logicalLeftIsAuto = logicalLeft.isAuto();
bool logicalRightIsAuto = logicalRight.isAuto();
LayoutUnit& marginLogicalLeftValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
LayoutUnit& marginLogicalRightValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
/*-----------------------------------------------------------------------*\
* If none of the three is 'auto': If both 'margin-left' and 'margin-
* right' are 'auto', solve the equation under the extra constraint that
* the two margins get equal values, unless this would make them negative,
* in which case when direction of the containing block is 'ltr' ('rtl'),
* set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
* ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
* solve the equation for that value. If the values are over-constrained,
* ignore the value for 'left' (in case the 'direction' property of the
* containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
* and solve for that value.
\*-----------------------------------------------------------------------*/
// NOTE: It is not necessary to solve for 'right' in the over constrained
// case because the value is not used for any further calculations.
computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + logicalRightValue + bordersPlusPadding);
// Margins are now the only unknown
if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
// Both margins auto, solve for equality
if (availableSpace >= 0) {
marginLogicalLeftValue = availableSpace / 2; // split the difference
marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
} else {
// Use the containing block's direction rather than the parent block's
// per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
if (containerDirection == LTR) {
marginLogicalLeftValue = 0;
marginLogicalRightValue = availableSpace; // will be negative
} else {
marginLogicalLeftValue = availableSpace; // will be negative
marginLogicalRightValue = 0;
}
}
} else if (marginLogicalLeft.isAuto()) {
// Solve for left margin
marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
} else if (marginLogicalRight.isAuto()) {
// Solve for right margin
marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
} else {
// Over-constrained, solve for left if direction is RTL
marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
// Use the containing block's direction rather than the parent block's
// per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
if (containerDirection == RTL)
logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
}
} else {
/*--------------------------------------------------------------------*\
* Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
* to 0, and pick the one of the following six rules that applies.
*
* 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
* width is shrink-to-fit. Then solve for 'left'
*
* OMIT RULE 2 AS IT SHOULD NEVER BE HIT
* ------------------------------------------------------------------
* 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
* the 'direction' property of the containing block is 'ltr' set
* 'left' to the static position, otherwise set 'right' to the
* static position. Then solve for 'left' (if 'direction is 'rtl')
* or 'right' (if 'direction' is 'ltr').
* ------------------------------------------------------------------
*
* 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
* width is shrink-to-fit . Then solve for 'right'
* 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
* for 'left'
* 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
* for 'width'
* 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
* for 'right'
*
* Calculation of the shrink-to-fit width is similar to calculating the
* width of a table cell using the automatic table layout algorithm.
* Roughly: calculate the preferred width by formatting the content
* without breaking lines other than where explicit line breaks occur,
* and also calculate the preferred minimum width, e.g., by trying all
* possible line breaks. CSS 2.1 does not define the exact algorithm.
* Thirdly, calculate the available width: this is found by solving
* for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
* to 0.
*
* Then the shrink-to-fit width is:
* min(max(preferred minimum width, available width), preferred width).
\*--------------------------------------------------------------------*/
// NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
// because the value is not used for any further calculations.
// Calculate margins, 'auto' margins are ignored.
marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + logicalLeftValue + logicalRightValue + bordersPlusPadding);
// FIXME: Is there a faster way to find the correct case?
// Use rule/case that applies.
if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
// RULE 1: (use shrink-to-fit for width, and solve of left)
computedValues.m_extent = shrinkToFitLogicalWidth(availableSpace, bordersPlusPadding);
logicalLeftValue = availableSpace - computedValues.m_extent;
} else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
// RULE 3: (use shrink-to-fit for width, and no need solve of right)
computedValues.m_extent = shrinkToFitLogicalWidth(availableSpace, bordersPlusPadding);
} else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
// RULE 4: (solve for left)
computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
logicalLeftValue = availableSpace - computedValues.m_extent;
} else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
// RULE 5: (solve for width)
if (autoWidthShouldFitContent())
computedValues.m_extent = shrinkToFitLogicalWidth(availableSpace, bordersPlusPadding);
else
computedValues.m_extent = std::max(LayoutUnit(), availableSpace);
} else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
// RULE 6: (no need solve for right)
computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
}
}
// Use computed values to calculate the horizontal position.
// FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
// positioned, inline because right now, it is using the logical left position
// of the first line box when really it should use the last line box. When
// this is fixed elsewhere, this block should be removed.
if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
const RenderInline* flow = toRenderInline(containerBlock);
InlineFlowBox* firstLine = flow->firstLineBox();
InlineFlowBox* lastLine = flow->lastLineBox();
if (firstLine && lastLine && firstLine != lastLine) {
computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
return;
}
}
if (containerBlock->isBox() && toRenderBox(containerBlock)->scrollsOverflowY() && containerBlock->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
logicalLeftValue = logicalLeftValue + toRenderBox(containerBlock)->verticalScrollbarWidth();
}
computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
}
static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
{
if (!logicalTop.isAuto() || !logicalBottom.isAuto())
return;
// FIXME: The static distance computation has not been patched for mixed writing modes.
LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
if (curr->isBox() && !curr->isTableRow())
staticLogicalTop += toRenderBox(curr)->logicalTop();
}
logicalTop.setValue(Fixed, staticLogicalTop);
}
void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
{
if (isReplaced()) {
computePositionedLogicalHeightReplaced(computedValues);
return;
}
// The following is based off of the W3C Working Draft from April 11, 2006 of
// CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
// <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
// (block-style-comments in this function and in computePositionedLogicalHeightUsing()
// correspond to text from the spec)
// We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
RenderStyle* styleToUse = style();
const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
const Length marginBefore = styleToUse->marginBefore();
const Length marginAfter = styleToUse->marginAfter();
Length logicalTopLength = styleToUse->logicalTop();
Length logicalBottomLength = styleToUse->logicalBottom();
/*---------------------------------------------------------------------------*\
* For the purposes of this section and the next, the term "static position"
* (of an element) refers, roughly, to the position an element would have had
* in the normal flow. More precisely, the static position for 'top' is the
* distance from the top edge of the containing block to the top margin edge
* of a hypothetical box that would have been the first box of the element if
* its 'position' property had been 'static' and 'float' had been 'none'. The
* value is negative if the hypothetical box is above the containing block.
*
* But rather than actually calculating the dimensions of that hypothetical
* box, user agents are free to make a guess at its probable position.
*
* For the purposes of calculating the static position, the containing block
* of fixed positioned elements is the initial containing block instead of
* the viewport.
\*---------------------------------------------------------------------------*/
// see FIXME 1
// Calculate the static distance if needed.
computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
// Calculate constraint equation values for 'height' case.
LayoutUnit logicalHeight = computedValues.m_extent;
computePositionedLogicalHeightUsing(styleToUse->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
computedValues);
// Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
// see FIXME 2
// Calculate constraint equation values for 'max-height' case.
if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
LogicalExtentComputedValues maxValues;
computePositionedLogicalHeightUsing(styleToUse->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
maxValues);
if (computedValues.m_extent > maxValues.m_extent) {
computedValues.m_extent = maxValues.m_extent;
computedValues.m_position = maxValues.m_position;
computedValues.m_margins.m_before = maxValues.m_margins.m_before;
computedValues.m_margins.m_after = maxValues.m_margins.m_after;
}
}
// Calculate constraint equation values for 'min-height' case.
if (!styleToUse->logicalMinHeight().isZero() || styleToUse->logicalMinHeight().isIntrinsic()) {
LogicalExtentComputedValues minValues;
computePositionedLogicalHeightUsing(styleToUse->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
minValues);
if (computedValues.m_extent < minValues.m_extent) {
computedValues.m_extent = minValues.m_extent;
computedValues.m_position = minValues.m_position;
computedValues.m_margins.m_before = minValues.m_margins.m_before;
computedValues.m_margins.m_after = minValues.m_margins.m_after;
}
}
if (!style()->hasStaticBlockPosition(isHorizontalWritingMode()))
computedValues.m_position += extraBlockOffset();
// Set final height value.
computedValues.m_extent += bordersPlusPadding;
}
static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
{
// Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
// along this axis, then we need to flip the coordinate. This can only happen if the containing block is both a flipped mode and perpendicular to us.
if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
|| (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
// Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
if (child->isHorizontalWritingMode())
logicalTopPos += containerBlock->borderBottom();
else
logicalTopPos += containerBlock->borderRight();
} else {
if (child->isHorizontalWritingMode())
logicalTopPos += containerBlock->borderTop();
else
logicalTopPos += containerBlock->borderLeft();
}
}
void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
const Length& logicalTop, const Length& logicalBottom, const Length& marginBefore,
const Length& marginAfter, LogicalExtentComputedValues& computedValues) const
{
// 'top' and 'bottom' cannot both be 'auto' because 'top would of been
// converted to the static position in computePositionedLogicalHeight()
ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
LayoutUnit logicalHeightValue;
LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
LayoutUnit logicalTopValue = 0;
bool logicalHeightIsAuto = logicalHeightLength.isAuto();
bool logicalTopIsAuto = logicalTop.isAuto();
bool logicalBottomIsAuto = logicalBottom.isAuto();
LayoutUnit resolvedLogicalHeight;
// Height is never unsolved for tables.
if (isTable()) {
resolvedLogicalHeight = contentLogicalHeight;
logicalHeightIsAuto = false;
} else {
if (logicalHeightLength.isIntrinsic())
resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding);
else
resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
}
if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
/*-----------------------------------------------------------------------*\
* If none of the three are 'auto': If both 'margin-top' and 'margin-
* bottom' are 'auto', solve the equation under the extra constraint that
* the two margins get equal values. If one of 'margin-top' or 'margin-
* bottom' is 'auto', solve the equation for that value. If the values
* are over-constrained, ignore the value for 'bottom' and solve for that
* value.
\*-----------------------------------------------------------------------*/
// NOTE: It is not necessary to solve for 'bottom' in the over constrained
// case because the value is not used for any further calculations.
logicalHeightValue = resolvedLogicalHeight;
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
// Margins are now the only unknown
if (marginBefore.isAuto() && marginAfter.isAuto()) {
// Both margins auto, solve for equality
// NOTE: This may result in negative values.
computedValues.m_margins.m_before = availableSpace / 2; // split the difference
computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
} else if (marginBefore.isAuto()) {
// Solve for top margin
computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
} else if (marginAfter.isAuto()) {
// Solve for bottom margin
computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
} else {
// Over-constrained, (no need solve for bottom)
computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
}
} else {
/*--------------------------------------------------------------------*\
* Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
* to 0, and pick the one of the following six rules that applies.
*
* 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
* the height is based on the content, and solve for 'top'.
*
* OMIT RULE 2 AS IT SHOULD NEVER BE HIT
* ------------------------------------------------------------------
* 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
* set 'top' to the static position, and solve for 'bottom'.
* ------------------------------------------------------------------
*
* 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
* the height is based on the content, and solve for 'bottom'.
* 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
* solve for 'top'.
* 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
* solve for 'height'.
* 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
* solve for 'bottom'.
\*--------------------------------------------------------------------*/
// NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
// because the value is not used for any further calculations.
// Calculate margins, 'auto' margins are ignored.
computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth);
computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth);
const LayoutUnit availableSpace = containerLogicalHeight - (computedValues.m_margins.m_before + computedValues.m_margins.m_after + bordersPlusPadding);
// Use rule/case that applies.
if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
// RULE 1: (height is content based, solve of top)
logicalHeightValue = contentLogicalHeight;
logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
} else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
// RULE 3: (height is content based, no need solve of bottom)
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
logicalHeightValue = contentLogicalHeight;
} else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
// RULE 4: (solve of top)
logicalHeightValue = resolvedLogicalHeight;
logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
} else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
// RULE 5: (solve of height)
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
logicalHeightValue = std::max(LayoutUnit(), availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight)));
} else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
// RULE 6: (no need solve of bottom)
logicalHeightValue = resolvedLogicalHeight;
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
}
}
computedValues.m_extent = logicalHeightValue;
// Use computed values to calculate the vertical position.
computedValues.m_position = logicalTopValue + computedValues.m_margins.m_before;
computeLogicalTopPositionedOffset(computedValues.m_position, this, logicalHeightValue, containerBlock, containerLogicalHeight);
}
void RenderBox::computePositionedLogicalWidthReplaced(LogicalExtentComputedValues& computedValues) const
{
// The following is based off of the W3C Working Draft from April 11, 2006 of
// CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
// <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
// (block-style-comments in this function correspond to text from the spec and
// the numbers correspond to numbers in spec)
// We don't use containingBlock(), since we may be positioned by an enclosing
// relative positioned inline.
const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
// To match WinIE, in quirks mode use the parent's 'direction' property
// instead of the the container block's.
TextDirection containerDirection = containerBlock->style()->direction();
// Variables to solve.
bool isHorizontal = isHorizontalWritingMode();
Length logicalLeft = style()->logicalLeft();
Length logicalRight = style()->logicalRight();
Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
LayoutUnit& marginLogicalLeftAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
LayoutUnit& marginLogicalRightAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
/*-----------------------------------------------------------------------*\
* 1. The used value of 'width' is determined as for inline replaced
* elements.
\*-----------------------------------------------------------------------*/
// NOTE: This value of width is final in that the min/max width calculations
// are dealt with in computeReplacedWidth(). This means that the steps to produce
// correct max/min in the non-replaced version, are not necessary.
computedValues.m_extent = computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth();
const LayoutUnit availableSpace = containerLogicalWidth - computedValues.m_extent;
/*-----------------------------------------------------------------------*\
* 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
* of the containing block is 'ltr', set 'left' to the static position;
* else if 'direction' is 'rtl', set 'right' to the static position.
\*-----------------------------------------------------------------------*/
// see FIXME 1
computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth);
/*-----------------------------------------------------------------------*\
* 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
* or 'margin-right' with '0'.
\*-----------------------------------------------------------------------*/
if (logicalLeft.isAuto() || logicalRight.isAuto()) {
if (marginLogicalLeft.isAuto())
marginLogicalLeft.setValue(Fixed, 0);
if (marginLogicalRight.isAuto())
marginLogicalRight.setValue(Fixed, 0);
}
/*-----------------------------------------------------------------------*\
* 4. If at this point both 'margin-left' and 'margin-right' are still
* 'auto', solve the equation under the extra constraint that the two
* margins must get equal values, unless this would make them negative,
* in which case when the direction of the containing block is 'ltr'
* ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
* 'margin-right' ('margin-left').
\*-----------------------------------------------------------------------*/
LayoutUnit logicalLeftValue = 0;
LayoutUnit logicalRightValue = 0;
if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
// 'left' and 'right' cannot be 'auto' due to step 3
ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
if (difference > 0) {
marginLogicalLeftAlias = difference / 2; // split the difference
marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
} else {
// Use the containing block's direction rather than the parent block's
// per CSS 2.1 reference test abspos-replaced-width-margin-000.
if (containerDirection == LTR) {
marginLogicalLeftAlias = 0;
marginLogicalRightAlias = difference; // will be negative
} else {
marginLogicalLeftAlias = difference; // will be negative
marginLogicalRightAlias = 0;
}
}
/*-----------------------------------------------------------------------*\
* 5. If at this point there is an 'auto' left, solve the equation for
* that value.
\*-----------------------------------------------------------------------*/
} else if (logicalLeft.isAuto()) {
marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
// Solve for 'left'
logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
} else if (logicalRight.isAuto()) {
marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
// Solve for 'right'
logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
} else if (marginLogicalLeft.isAuto()) {
marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
// Solve for 'margin-left'
marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
} else if (marginLogicalRight.isAuto()) {
marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
// Solve for 'margin-right'
marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
} else {
// Nothing is 'auto', just calculate the values.
marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
// If the containing block is right-to-left, then push the left position as far to the right as possible
if (containerDirection == RTL) {
int totalLogicalWidth = computedValues.m_extent + logicalLeftValue + logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias;
logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
}
}
/*-----------------------------------------------------------------------*\
* 6. If at this point the values are over-constrained, ignore the value
* for either 'left' (in case the 'direction' property of the
* containing block is 'rtl') or 'right' (in case 'direction' is
* 'ltr') and solve for that value.
\*-----------------------------------------------------------------------*/
// NOTE: Constraints imposed by the width of the containing block and its content have already been accounted for above.
// FIXME: Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space, so that
// can make the result here rather complicated to compute.
// Use computed values to calculate the horizontal position.
// FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
// positioned, inline containing block because right now, it is using the logical left position
// of the first line box when really it should use the last line box. When
// this is fixed elsewhere, this block should be removed.
if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
const RenderInline* flow = toRenderInline(containerBlock);
InlineFlowBox* firstLine = flow->firstLineBox();
InlineFlowBox* lastLine = flow->lastLineBox();
if (firstLine && lastLine && firstLine != lastLine) {
computedValues.m_position = logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
return;
}
}
LayoutUnit logicalLeftPos = logicalLeftValue + marginLogicalLeftAlias;
computeLogicalLeftPositionedOffset(logicalLeftPos, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
computedValues.m_position = logicalLeftPos;
}
void RenderBox::computePositionedLogicalHeightReplaced(LogicalExtentComputedValues& computedValues) const
{
// The following is based off of the W3C Working Draft from April 11, 2006 of
// CSS 2.1: Section 10.6.5 "Absolutely positioned, replaced elements"
// <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-height>
// (block-style-comments in this function correspond to text from the spec and
// the numbers correspond to numbers in spec)
// We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
// Variables to solve.
Length marginBefore = style()->marginBefore();
Length marginAfter = style()->marginAfter();
LayoutUnit& marginBeforeAlias = computedValues.m_margins.m_before;
LayoutUnit& marginAfterAlias = computedValues.m_margins.m_after;
Length logicalTop = style()->logicalTop();
Length logicalBottom = style()->logicalBottom();
/*-----------------------------------------------------------------------*\
* 1. The used value of 'height' is determined as for inline replaced
* elements.
\*-----------------------------------------------------------------------*/
// NOTE: This value of height is final in that the min/max height calculations
// are dealt with in computeReplacedHeight(). This means that the steps to produce
// correct max/min in the non-replaced version, are not necessary.
computedValues.m_extent = computeReplacedLogicalHeight() + borderAndPaddingLogicalHeight();
const LayoutUnit availableSpace = containerLogicalHeight - computedValues.m_extent;
/*-----------------------------------------------------------------------*\
* 2. If both 'top' and 'bottom' have the value 'auto', replace 'top'
* with the element's static position.
\*-----------------------------------------------------------------------*/
// see FIXME 1
computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
/*-----------------------------------------------------------------------*\
* 3. If 'bottom' is 'auto', replace any 'auto' on 'margin-top' or
* 'margin-bottom' with '0'.
\*-----------------------------------------------------------------------*/
// FIXME: The spec. says that this step should only be taken when bottom is
// auto, but if only top is auto, this makes step 4 impossible.
if (logicalTop.isAuto() || logicalBottom.isAuto()) {
if (marginBefore.isAuto())
marginBefore.setValue(Fixed, 0);
if (marginAfter.isAuto())
marginAfter.setValue(Fixed, 0);
}
/*-----------------------------------------------------------------------*\
* 4. If at this point both 'margin-top' and 'margin-bottom' are still
* 'auto', solve the equation under the extra constraint that the two
* margins must get equal values.
\*-----------------------------------------------------------------------*/
LayoutUnit logicalTopValue = 0;
LayoutUnit logicalBottomValue = 0;
if (marginBefore.isAuto() && marginAfter.isAuto()) {
// 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
LayoutUnit difference = availableSpace - (logicalTopValue + logicalBottomValue);
// NOTE: This may result in negative values.
marginBeforeAlias = difference / 2; // split the difference
marginAfterAlias = difference - marginBeforeAlias; // account for odd valued differences
/*-----------------------------------------------------------------------*\
* 5. If at this point there is only one 'auto' left, solve the equation
* for that value.
\*-----------------------------------------------------------------------*/
} else if (logicalTop.isAuto()) {
marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
// Solve for 'top'
logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
} else if (logicalBottom.isAuto()) {
marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
// Solve for 'bottom'
// NOTE: It is not necessary to solve for 'bottom' because we don't ever
// use the value.
} else if (marginBefore.isAuto()) {
marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
// Solve for 'margin-top'
marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
} else if (marginAfter.isAuto()) {
marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
// Solve for 'margin-bottom'
marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
} else {
// Nothing is 'auto', just calculate the values.
marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
// NOTE: It is not necessary to solve for 'bottom' because we don't ever
// use the value.
}
/*-----------------------------------------------------------------------*\
* 6. If at this point the values are over-constrained, ignore the value
* for 'bottom' and solve for that value.
\*-----------------------------------------------------------------------*/
// NOTE: It is not necessary to do this step because we don't end up using
// the value of 'bottom' regardless of whether the values are over-constrained
// or not.
// Use computed values to calculate the vertical position.
LayoutUnit logicalTopPos = logicalTopValue + marginBeforeAlias;
computeLogicalTopPositionedOffset(logicalTopPos, this, computedValues.m_extent, containerBlock, containerLogicalHeight);
computedValues.m_position = logicalTopPos;
}
LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
{
// VisiblePositions at offsets inside containers either a) refer to the positions before/after
// those containers (tables and select elements) or b) refer to the position inside an empty block.
// They never refer to children.
// FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.
LayoutRect rect(location(), LayoutSize(caretWidth, size().height()));
bool ltr = box ? box->isLeftToRightDirection() : style()->isLeftToRightDirection();
if ((!caretOffset) ^ ltr)
rect.move(LayoutSize(size().width() - caretWidth, 0));
if (box) {
RootInlineBox& rootBox = box->root();
LayoutUnit top = rootBox.lineTop();
rect.setY(top);
rect.setHeight(rootBox.lineBottom() - top);
}
// If height of box is smaller than font height, use the latter one,
// otherwise the caret might become invisible.
//
// Also, if the box is not a replaced element, always use the font height.
// This prevents the "big caret" bug described in:
// <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
//
// FIXME: ignoring :first-line, missing good reason to take care of
LayoutUnit fontHeight = style()->fontMetrics().height();
if (fontHeight > rect.height() || (!isReplaced() && !isTable()))
rect.setHeight(fontHeight);
if (extraWidthToEndOfLine)
*extraWidthToEndOfLine = location().x() + size().width() - rect.maxX();
// Move to local coords
rect.moveBy(-location());
// FIXME: Border/padding should be added for all elements but this workaround
// is needed because we use offsets inside an "atomic" element to represent
// positions before and after the element in deprecated editing offsets.
if (node() && !(editingIgnoresContent(node()) || isRenderedTableElement(node()))) {
rect.setX(rect.x() + borderLeft() + paddingLeft());
rect.setY(rect.y() + paddingTop() + borderTop());
}
if (!isHorizontalWritingMode())
return rect.transposedRect();
return rect;
}
PositionWithAffinity RenderBox::positionForPoint(const LayoutPoint& point)
{
// no children...return this render object's element, if there is one, and offset 0
RenderObject* firstChild = slowFirstChild();
if (!firstChild)
return createPositionWithAffinity(nonPseudoNode() ? firstPositionInOrBeforeNode(nonPseudoNode()) : Position());
if (isTable() && nonPseudoNode()) {
LayoutUnit right = size().width() - verticalScrollbarWidth();
LayoutUnit bottom = size().height() - horizontalScrollbarHeight();
if (point.x() < 0 || point.x() > right || point.y() < 0 || point.y() > bottom) {
if (point.x() <= right / 2)
return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
return createPositionWithAffinity(lastPositionInOrAfterNode(nonPseudoNode()));
}
}
// Pass off to the closest child.
LayoutUnit minDist = LayoutUnit::max();
RenderBox* closestRenderer = 0;
LayoutPoint adjustedPoint = point;
if (isTableRow())
adjustedPoint.moveBy(location());
for (RenderObject* renderObject = firstChild; renderObject; renderObject = renderObject->nextSibling()) {
if ((!renderObject->slowFirstChild() && !renderObject->isInline() && !renderObject->isRenderBlockFlow() )
|| renderObject->style()->visibility() != VISIBLE)
continue;
if (!renderObject->isBox())
continue;
RenderBox* renderer = toRenderBox(renderObject);
LayoutUnit top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? LayoutUnit() : renderer->location().y());
LayoutUnit bottom = top + renderer->contentHeight();
LayoutUnit left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? LayoutUnit() : renderer->location().x());
LayoutUnit right = left + renderer->contentWidth();
if (point.x() <= right && point.x() >= left && point.y() <= top && point.y() >= bottom) {
if (renderer->isTableRow())
return renderer->positionForPoint(point + adjustedPoint - renderer->locationOffset());
return renderer->positionForPoint(point - renderer->locationOffset());
}
// Find the distance from (x, y) to the box. Split the space around the box into 8 pieces
// and use a different compare depending on which piece (x, y) is in.
LayoutPoint cmp;
if (point.x() > right) {
if (point.y() < top)
cmp = LayoutPoint(right, top);
else if (point.y() > bottom)
cmp = LayoutPoint(right, bottom);
else
cmp = LayoutPoint(right, point.y());
} else if (point.x() < left) {
if (point.y() < top)
cmp = LayoutPoint(left, top);
else if (point.y() > bottom)
cmp = LayoutPoint(left, bottom);
else
cmp = LayoutPoint(left, point.y());
} else {
if (point.y() < top)
cmp = LayoutPoint(point.x(), top);
else
cmp = LayoutPoint(point.x(), bottom);
}
LayoutSize difference = cmp - point;
LayoutUnit dist = difference.width() * difference.width() + difference.height() * difference.height();
if (dist < minDist) {
closestRenderer = renderer;
minDist = dist;
}
}
if (closestRenderer)
return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset());
return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
}
bool RenderBox::shrinkToAvoidFloats() const
{
// Floating objects don't shrink. Objects that don't avoid floats don't shrink.
if (isInline() || !avoidsFloats() || isFloating())
return false;
// Only auto width objects can possibly shrink to avoid floats.
return style()->width().isAuto();
}
static bool isReplacedElement(Node* node)
{
// Checkboxes and radioboxes are not isReplaced() nor do they have their own renderer in which to override avoidFloats().
return node && node->isElementNode() && (toElement(node)->isFormControlElement() || isHTMLImageElement(toElement(node)));
}
bool RenderBox::avoidsFloats() const
{
return isReplaced() || isReplacedElement(node()) || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isFlexItemIncludingDeprecated();
}
bool RenderBox::hasNonCompositedScrollbars() const
{
if (RenderLayer* layer = this->layer()) {
if (RenderLayerScrollableArea* scrollableArea = layer->scrollableArea()) {
if (scrollableArea->hasHorizontalScrollbar() && !scrollableArea->layerForHorizontalScrollbar())
return true;
if (scrollableArea->hasVerticalScrollbar() && !scrollableArea->layerForVerticalScrollbar())
return true;
}
}
return false;
}
PaintInvalidationReason RenderBox::paintInvalidationReason(const RenderLayerModelObject& paintInvalidationContainer,
const LayoutRect& oldBounds, const LayoutPoint& oldLocation, const LayoutRect& newBounds, const LayoutPoint& newLocation) const
{
PaintInvalidationReason invalidationReason = RenderBoxModelObject::paintInvalidationReason(paintInvalidationContainer, oldBounds, oldLocation, newBounds, newLocation);
if (isFullPaintInvalidationReason(invalidationReason))
return invalidationReason;
// If the transform is not identity or translation, incremental invalidation is not applicable
// because the difference between oldBounds and newBounds doesn't cover all area needing invalidation.
// FIXME: Should also consider ancestor transforms since paintInvalidationContainer. crbug.com/426111.
if (invalidationReason == PaintInvalidationIncremental
&& paintInvalidationContainer != this
&& hasLayer() && layer()->transform() && !layer()->transform()->isIdentityOrTranslation())
return PaintInvalidationBoundsChange;
if (!style()->hasBackground() && !style()->hasBoxDecorations()) {
// We could let incremental invalidation cover non-composited scrollbars, but just
// do a full invalidation because incremental invalidation will go away with slimming paint.
if (invalidationReason == PaintInvalidationIncremental && hasNonCompositedScrollbars())
return PaintInvalidationBorderBoxChange;
return invalidationReason;
}
LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
LayoutSize newBorderBoxSize = size();
if (oldBorderBoxSize == newBorderBoxSize)
return invalidationReason;
// See another hasNonCompositedScrollbars() callsite above.
if (hasNonCompositedScrollbars())
return PaintInvalidationBorderBoxChange;
if (style()->hasVisualOverflowingEffect() || style()->hasAppearance() || style()->hasFilter() || style()->resize() != RESIZE_NONE)
return PaintInvalidationBorderBoxChange;
if (style()->hasBorderRadius()) {
// If a border-radius exists and width/height is smaller than radius width/height,
// we need to fully invalidate to cover the changed radius.
FloatRoundedRect oldRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), oldBorderBoxSize));
FloatRoundedRect newRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), newBorderBoxSize));
if (oldRoundedRect.radii() != newRoundedRect.radii())
return PaintInvalidationBorderBoxChange;
}
if (oldBorderBoxSize.width() != newBorderBoxSize.width() && mustInvalidateBackgroundOrBorderPaintOnWidthChange())
return PaintInvalidationBorderBoxChange;
if (oldBorderBoxSize.height() != newBorderBoxSize.height() && mustInvalidateBackgroundOrBorderPaintOnHeightChange())
return PaintInvalidationBorderBoxChange;
return PaintInvalidationIncremental;
}
void RenderBox::incrementallyInvalidatePaint(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& oldBounds, const LayoutRect& newBounds, const LayoutPoint& positionFromPaintInvalidationBacking)
{
RenderObject::incrementallyInvalidatePaint(paintInvalidationContainer, oldBounds, newBounds, positionFromPaintInvalidationBacking);
bool hasBoxDecorations = style()->hasBoxDecorations();
if (!style()->hasBackground() && !hasBoxDecorations)
return;
LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
LayoutSize newBorderBoxSize = size();
// If border box size didn't change, RenderObject's incrementallyInvalidatePaint() is good.
if (oldBorderBoxSize == newBorderBoxSize)
return;
// If size of the paint invalidation rect equals to size of border box, RenderObject::incrementallyInvalidatePaint()
// is good for boxes having background without box decorations.
ASSERT(oldBounds.location() == newBounds.location()); // Otherwise we won't do incremental invalidation.
if (!hasBoxDecorations
&& positionFromPaintInvalidationBacking == newBounds.location()
&& oldBorderBoxSize == oldBounds.size()
&& newBorderBoxSize == newBounds.size())
return;
// Invalidate the right delta part and the right border of the old or new box which has smaller width.
LayoutUnit deltaWidth = absoluteValue(oldBorderBoxSize.width() - newBorderBoxSize.width());
if (deltaWidth) {
LayoutUnit smallerWidth = std::min(oldBorderBoxSize.width(), newBorderBoxSize.width());
LayoutUnit borderTopRightRadiusWidth = valueForLength(style()->borderTopRightRadius().width(), smallerWidth);
LayoutUnit borderBottomRightRadiusWidth = valueForLength(style()->borderBottomRightRadius().width(), smallerWidth);
LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight(), std::max(borderTopRightRadiusWidth, borderBottomRightRadiusWidth));
LayoutRect rightDeltaRect(positionFromPaintInvalidationBacking.x() + smallerWidth - borderWidth,
positionFromPaintInvalidationBacking.y(),
deltaWidth + borderWidth,
std::max(oldBorderBoxSize.height(), newBorderBoxSize.height()));
invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, rightDeltaRect, oldBounds, newBounds);
}
// Invalidate the bottom delta part and the bottom border of the old or new box which has smaller height.
LayoutUnit deltaHeight = absoluteValue(oldBorderBoxSize.height() - newBorderBoxSize.height());
if (deltaHeight) {
LayoutUnit smallerHeight = std::min(oldBorderBoxSize.height(), newBorderBoxSize.height());
LayoutUnit borderBottomLeftRadiusHeight = valueForLength(style()->borderBottomLeftRadius().height(), smallerHeight);
LayoutUnit borderBottomRightRadiusHeight = valueForLength(style()->borderBottomRightRadius().height(), smallerHeight);
LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom(), std::max(borderBottomLeftRadiusHeight, borderBottomRightRadiusHeight));
LayoutRect bottomDeltaRect(positionFromPaintInvalidationBacking.x(),
positionFromPaintInvalidationBacking.y() + smallerHeight - borderHeight,
std::max(oldBorderBoxSize.width(), newBorderBoxSize.width()),
deltaHeight + borderHeight);
invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, bottomDeltaRect, oldBounds, newBounds);
}
}
void RenderBox::invalidatePaintRectClippedByOldAndNewBounds(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& rect, const LayoutRect& oldBounds, const LayoutRect& newBounds)
{
if (rect.isEmpty())
return;
LayoutRect rectClippedByOldBounds = intersection(rect, oldBounds);
LayoutRect rectClippedByNewBounds = intersection(rect, newBounds);
// Invalidate only once if the clipped rects equal.
if (rectClippedByOldBounds == rectClippedByNewBounds) {
invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, PaintInvalidationIncremental);
return;
}
// Invalidate the bigger one if one contains another. Otherwise invalidate both.
if (!rectClippedByNewBounds.contains(rectClippedByOldBounds))
invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, PaintInvalidationIncremental);
if (!rectClippedByOldBounds.contains(rectClippedByNewBounds))
invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByNewBounds, PaintInvalidationIncremental);
}
void RenderBox::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutScope)
{
ASSERT(!needsLayout());
// If fragmentation height has changed, we need to lay out. No need to enter the renderer if it
// is childless, though.
if (view()->layoutState()->pageLogicalHeightChanged() && slowFirstChild())
layoutScope.setChildNeedsLayout(this);
}
void RenderBox::addVisualEffectOverflow()
{
if (!style()->hasVisualOverflowingEffect())
return;
// Add in the final overflow with shadows, outsets and outline combined.
LayoutRect visualEffectOverflow = borderBoxRect();
visualEffectOverflow.expand(computeVisualEffectOverflowOutsets());
addVisualOverflow(visualEffectOverflow);
}
LayoutRectOutsets RenderBox::computeVisualEffectOverflowOutsets() const
{
ASSERT(style()->hasVisualOverflowingEffect());
LayoutUnit top;
LayoutUnit right;
LayoutUnit bottom;
LayoutUnit left;
if (const ShadowList* boxShadow = style()->boxShadow()) {
// FIXME: Use LayoutUnit edge outsets, and then simplify this.
FloatRectOutsets outsets = boxShadow->rectOutsetsIncludingOriginal();
top = outsets.top();
right = outsets.right();
bottom = outsets.bottom();
left = outsets.left();
}
if (style()->hasBorderImageOutsets()) {
LayoutRectOutsets borderOutsets = style()->borderImageOutsets();
top = std::max(top, borderOutsets.top());
right = std::max(right, borderOutsets.right());
bottom = std::max(bottom, borderOutsets.bottom());
left = std::max(left, borderOutsets.left());
}
if (style()->hasOutline()) {
if (style()->outlineStyleIsAuto()) {
// The result focus ring rects are in coordinates of this object's border box.
Vector<LayoutRect> focusRingRects;
addFocusRingRects(focusRingRects, LayoutPoint());
LayoutRect rect = unionRect(focusRingRects);
int outlineSize = GraphicsContext::focusRingOutsetExtent(style()->outlineOffset(), style()->outlineWidth());
top = std::max(top, -rect.y() + outlineSize);
right = std::max(right, rect.maxX() - size().width() + outlineSize);
bottom = std::max(bottom, rect.maxY() - size().height() + outlineSize);
left = std::max(left, -rect.x() + outlineSize);
} else {
LayoutUnit outlineSize = style()->outlineSize();
top = std::max(top, outlineSize);
right = std::max(right, outlineSize);
bottom = std::max(bottom, outlineSize);
left = std::max(left, outlineSize);
}
}
return LayoutRectOutsets(top, right, bottom, left);
}
void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta)
{
// Never allow flow threads to propagate overflow up to a parent.
if (child->isRenderFlowThread())
return;
// Only propagate layout overflow from the child if the child isn't clipping its overflow. If it is, then
// its overflow is internal to it, and we don't care about it. layoutOverflowRectForPropagation takes care of this
// and just propagates the border box rect instead.
LayoutRect childLayoutOverflowRect = child->layoutOverflowRectForPropagation(style());
childLayoutOverflowRect.move(delta);
addLayoutOverflow(childLayoutOverflowRect);
// Add in visual overflow from the child. Even if the child clips its overflow, it may still
// have visual overflow of its own set from box shadows or reflections. It is unnecessary to propagate this
// overflow if we are clipping our own overflow.
if (child->hasSelfPaintingLayer())
return;
LayoutRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
childVisualOverflowRect.move(delta);
addContentsVisualOverflow(childVisualOverflowRect);
}
void RenderBox::addLayoutOverflow(const LayoutRect& rect)
{
LayoutRect clientBox = noOverflowRect();
if (clientBox.contains(rect) || rect.isEmpty())
return;
// For overflow clip objects, we don't want to propagate overflow into unreachable areas.
LayoutRect overflowRect(rect);
if (hasOverflowClip() || isRenderView()) {
// Overflow is in the block's coordinate space and thus is flipped for horizontal-bt and vertical-rl
// writing modes. At this stage that is actually a simplification, since we can treat horizontal-tb/bt as the same
// and vertical-lr/rl as the same.
bool hasTopOverflow = !style()->isLeftToRightDirection() && !isHorizontalWritingMode();
bool hasLeftOverflow = !style()->isLeftToRightDirection() && isHorizontalWritingMode();
if (isFlexibleBox() && style()->isReverseFlexDirection()) {
RenderFlexibleBox* flexibleBox = toRenderFlexibleBox(this);
if (flexibleBox->isHorizontalFlow())
hasLeftOverflow = true;
else
hasTopOverflow = true;
}
if (!hasTopOverflow)
overflowRect.shiftYEdgeTo(std::max(overflowRect.y(), clientBox.y()));
else
overflowRect.shiftMaxYEdgeTo(std::min(overflowRect.maxY(), clientBox.maxY()));
if (!hasLeftOverflow)
overflowRect.shiftXEdgeTo(std::max(overflowRect.x(), clientBox.x()));
else
overflowRect.shiftMaxXEdgeTo(std::min(overflowRect.maxX(), clientBox.maxX()));
// Now re-test with the adjusted rectangle and see if it has become unreachable or fully
// contained.
if (clientBox.contains(overflowRect) || overflowRect.isEmpty())
return;
}
if (!m_overflow)
m_overflow = adoptPtr(new RenderOverflow(clientBox, borderBoxRect()));
m_overflow->addLayoutOverflow(overflowRect);
}
void RenderBox::addVisualOverflow(const LayoutRect& rect)
{
LayoutRect borderBox = borderBoxRect();
if (borderBox.contains(rect) || rect.isEmpty())
return;
if (!m_overflow)
m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBox));
m_overflow->addVisualOverflow(rect);
}
void RenderBox::addContentsVisualOverflow(const LayoutRect& rect)
{
if (!hasOverflowClip()) {
addVisualOverflow(rect);
return;
}
if (!m_overflow)
m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBoxRect()));
m_overflow->addContentsVisualOverflow(rect);
}
void RenderBox::clearLayoutOverflow()
{
if (!m_overflow)
return;
if (!hasVisualOverflow() && contentsVisualOverflowRect().isEmpty()) {
clearAllOverflows();
return;
}
m_overflow->setLayoutOverflow(noOverflowRect());
}
inline static bool percentageLogicalHeightIsResolvable(const RenderBox* box)
{
return RenderBox::percentageLogicalHeightIsResolvableFromBlock(box->containingBlock(), box->isOutOfFlowPositioned());
}
bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock* containingBlock, bool isOutOfFlowPositioned)
{
// In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
// block that may have a specified height and then use it. In strict mode, this violates the
// specification, which states that percentage heights just revert to auto if the containing
// block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
// only at explicit containers.
const RenderBlock* cb = containingBlock;
bool inQuirksMode = cb->document().inQuirksMode();
while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style()->logicalHeight().isAuto()) {
if (!inQuirksMode && !cb->isAnonymousBlock())
break;
cb = cb->containingBlock();
}
// A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
// explicitly specified that can be used for any percentage computations.
// FIXME: We can't just check top/bottom here.
// https://bugs.webkit.org/show_bug.cgi?id=46500
bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
// Table cells violate what the CSS spec says to do with heights. Basically we
// don't care if the cell specified a height or not. We just always make ourselves
// be a percentage of the cell's current content height.
if (cb->isTableCell())
return true;
// Otherwise we only use our percentage height if our containing block had a specified
// height.
if (cb->style()->logicalHeight().isFixed())
return true;
if (cb->style()->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight)
return percentageLogicalHeightIsResolvableFromBlock(cb->containingBlock(), cb->isOutOfFlowPositioned());
if (cb->isRenderView() || inQuirksMode || isOutOfFlowPositionedWithSpecifiedHeight)
return true;
if (cb->isDocumentElement() && isOutOfFlowPositioned) {
// Match the positioned objects behavior, which is that positioned objects will fill their viewport
// always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
return true;
}
return false;
}
bool RenderBox::hasUnsplittableScrollingOverflow() const
{
// We will paginate as long as we don't scroll overflow in the pagination direction.
bool isHorizontal = isHorizontalWritingMode();
if ((isHorizontal && !scrollsOverflowY()) || (!isHorizontal && !scrollsOverflowX()))
return false;
// We do have overflow. We'll still be willing to paginate as long as the block
// has auto logical height, auto or undefined max-logical-height and a zero or auto min-logical-height.
// Note this is just a heuristic, and it's still possible to have overflow under these
// conditions, but it should work out to be good enough for common cases. Paginating overflow
// with scrollbars present is not the end of the world and is what we used to do in the old model anyway.
return !style()->logicalHeight().isIntrinsicOrAuto()
|| (!style()->logicalMaxHeight().isIntrinsicOrAuto() && !style()->logicalMaxHeight().isMaxSizeNone() && (!style()->logicalMaxHeight().isPercent() || percentageLogicalHeightIsResolvable(this)))
|| (!style()->logicalMinHeight().isIntrinsicOrAuto() && style()->logicalMinHeight().isPositive() && (!style()->logicalMinHeight().isPercent() || percentageLogicalHeightIsResolvable(this)));
}
bool RenderBox::isUnsplittableForPagination() const
{
return isReplaced() || hasUnsplittableScrollingOverflow() || (parent() && isWritingModeRoot());
}
LayoutUnit RenderBox::lineHeight(bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
{
if (isReplaced())
return direction == HorizontalLine ? marginHeight() + size().height() : marginWidth() + size().width();
return LayoutUnit();
}
int RenderBox::baselinePosition(FontBaseline baselineType, bool /*firstLine*/, LineDirectionMode direction, LinePositionMode linePositionMode) const
{
ASSERT(linePositionMode == PositionOnContainingLine);
if (isReplaced()) {
int result = direction == HorizontalLine ? marginHeight() + size().height() : marginWidth() + size().width();
if (baselineType == AlphabeticBaseline)
return result;
return result - result / 2;
}
return 0;
}
RenderLayer* RenderBox::enclosingFloatPaintingLayer() const
{
const RenderObject* curr = this;
while (curr) {
RenderLayer* layer = curr->hasLayer() && curr->isBox() ? toRenderBox(curr)->layer() : 0;
if (layer && layer->isSelfPaintingLayer())
return layer;
curr = curr->parent();
}
return 0;
}
LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* parentStyle) const
{
LayoutRect rect = visualOverflowRectForPropagation(parentStyle);
if (!parentStyle->isHorizontalWritingMode())
return rect.transposedRect();
return rect;
}
LayoutRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) const
{
// If the writing modes of the child and parent match, then we don't have to
// do anything fancy. Just return the result.
LayoutRect rect = visualOverflowRect();
if (parentStyle->writingMode() == style()->writingMode())
return rect;
// We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
// in a particular axis, then we have to flip the rect along that axis.
if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
rect.setX(size().width() - rect.maxX());
else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
rect.setY(size().height() - rect.maxY());
return rect;
}
LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* parentStyle) const
{
LayoutRect rect = layoutOverflowRectForPropagation(parentStyle);
if (!parentStyle->isHorizontalWritingMode())
return rect.transposedRect();
return rect;
}
LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) const
{
// Only propagate interior layout overflow if we don't clip it.
LayoutRect rect = borderBoxRect();
// We want to include the margin, but only when it adds height. Quirky margins don't contribute height
// nor do the margins of self-collapsing blocks.
if (!style()->hasMarginAfterQuirk() && !isSelfCollapsingBlock())
rect.expand(isHorizontalWritingMode() ? LayoutSize(LayoutUnit(), marginAfter()) : LayoutSize(marginAfter(), LayoutUnit()));
if (!hasOverflowClip())
rect.unite(layoutOverflowRect());
bool hasTransform = hasLayer() && layer()->transform();
if (isRelPositioned() || hasTransform) {
// If we are relatively positioned or if we have a transform, then we have to convert
// this rectangle into physical coordinates, apply relative positioning and transforms
// to it, and then convert it back.
flipForWritingMode(rect);
if (hasTransform)
rect = layer()->currentTransform().mapRect(rect);
if (isRelPositioned())
rect.move(offsetForInFlowPosition());
// Now we need to flip back.
flipForWritingMode(rect);
}
// If the writing modes of the child and parent match, then we don't have to
// do anything fancy. Just return the result.
if (parentStyle->writingMode() == style()->writingMode())
return rect;
// We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
// in a particular axis, then we have to flip the rect along that axis.
if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
rect.setX(size().width() - rect.maxX());
else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
rect.setY(size().height() - rect.maxY());
return rect;
}
LayoutRect RenderBox::noOverflowRect() const
{
// Because of the special coordinate system used for overflow rectangles and many other
// rectangles (not quite logical, not quite physical), we need to flip the block progression
// coordinate in vertical-rl and horizontal-bt writing modes. In other words, the rectangle
// returned is physical, except for the block direction progression coordinate (y in horizontal
// writing modes, x in vertical writing modes), which is always "logical top". Apart from the
// flipping, this method does the same as clientBoxRect().
const int scrollBarWidth = verticalScrollbarWidth();
const int scrollBarHeight = horizontalScrollbarHeight();
LayoutUnit left = borderLeft() + (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? scrollBarWidth : 0);
LayoutUnit top = borderTop();
LayoutUnit right = borderRight();
LayoutUnit bottom = borderBottom();
LayoutRect rect(left, top, size().width() - left - right, size().height() - top - bottom);
flipForWritingMode(rect);
// Subtract space occupied by scrollbars. Order is important here: first flip, then subtract
// scrollbars. This may seem backwards and weird, since one would think that a horizontal
// scrollbar at the physical bottom in horizontal-bt ought to be at the logical top (physical
// bottom), between the logical top (physical bottom) border and the logical top (physical
// bottom) padding. But this is how the rest of the code expects us to behave. This is highly
// related to https://bugs.webkit.org/show_bug.cgi?id=76129
// FIXME: when the above mentioned bug is fixed, it should hopefully be possible to call
// clientBoxRect() or paddingBoxRect() in this method, rather than fiddling with the edges on
// our own.
if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
rect.contract(0, scrollBarHeight);
else
rect.contract(scrollBarWidth, scrollBarHeight);
return rect;
}
LayoutUnit RenderBox::offsetLeft() const
{
return adjustedPositionRelativeToOffsetParent(topLeftLocation()).x();
}
LayoutUnit RenderBox::offsetTop() const
{
return adjustedPositionRelativeToOffsetParent(topLeftLocation()).y();
}
LayoutPoint RenderBox::flipForWritingModeForChild(const RenderBox* child, const LayoutPoint& point) const
{
if (!style()->isFlippedBlocksWritingMode())
return point;
// The child is going to add in its x() and y(), so we have to make sure it ends up in
// the right place.
if (isHorizontalWritingMode())
return LayoutPoint(point.x(), point.y() + size().height() - child->size().height() - (2 * child->location().y()));
return LayoutPoint(point.x() + size().width() - child->size().width() - (2 * child->location().x()), point.y());
}
LayoutPoint RenderBox::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
{
if (!hasColumns() || !style()->isFlippedBlocksWritingMode())
return flipForWritingMode(point);
return toRenderBlock(this)->flipForWritingModeIncludingColumns(point);
}
LayoutPoint RenderBox::topLeftLocation() const
{
RenderBlock* containerBlock = containingBlock();
if (!containerBlock || containerBlock == this)
return location();
return containerBlock->flipForWritingModeForChild(this, location());
}
bool RenderBox::hasRelativeLogicalHeight() const
{
return style()->logicalHeight().isPercent()
|| style()->logicalMinHeight().isPercent()
|| style()->logicalMaxHeight().isPercent();
}
static void markBoxForRelayoutAfterSplit(RenderBox* box)
{
// FIXME: The table code should handle that automatically. If not,
// we should fix it and remove the table part checks.
if (box->isTable()) {
// Because we may have added some sections with already computed column structures, we need to
// sync the table structure with them now. This avoids crashes when adding new cells to the table.
toRenderTable(box)->forceSectionsRecalc();
} else if (box->isTableSection())
toRenderTableSection(box)->setNeedsCellRecalc();
box->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
}
RenderObject* RenderBox::splitAnonymousBoxesAroundChild(RenderObject* beforeChild)
{
bool didSplitParentAnonymousBoxes = false;
while (beforeChild->parent() != this) {
RenderBox* boxToSplit = toRenderBox(beforeChild->parent());
if (boxToSplit->slowFirstChild() != beforeChild && boxToSplit->isAnonymous()) {
didSplitParentAnonymousBoxes = true;
// We have to split the parent box into two boxes and move children
// from |beforeChild| to end into the new post box.
RenderBox* postBox = boxToSplit->createAnonymousBoxWithSameTypeAs(this);
postBox->setChildrenInline(boxToSplit->childrenInline());
RenderBox* parentBox = toRenderBox(boxToSplit->parent());
// We need to invalidate the |parentBox| before inserting the new node
// so that the table paint invalidation logic knows the structure is dirty.
// See for example RenderTableCell:clippedOverflowRectForPaintInvalidation.
markBoxForRelayoutAfterSplit(parentBox);
parentBox->virtualChildren()->insertChildNode(parentBox, postBox, boxToSplit->nextSibling());
boxToSplit->moveChildrenTo(postBox, beforeChild, 0, true);
markBoxForRelayoutAfterSplit(boxToSplit);
markBoxForRelayoutAfterSplit(postBox);
beforeChild = postBox;
} else
beforeChild = boxToSplit;
}
if (didSplitParentAnonymousBoxes)
markBoxForRelayoutAfterSplit(this);
ASSERT(beforeChild->parent() == this);
return beforeChild;
}
LayoutUnit RenderBox::offsetFromLogicalTopOfFirstPage() const
{
LayoutState* layoutState = view()->layoutState();
if (layoutState && !layoutState->isPaginated())
return LayoutUnit();
if (!layoutState && !flowThreadContainingBlock())
return LayoutUnit();
RenderBlock* containerBlock = containingBlock();
return containerBlock->offsetFromLogicalTopOfFirstPage() + logicalTop();
}
void RenderBox::savePreviousBorderBoxSizeIfNeeded()
{
// If m_rareData is already created, always save.
if (!m_rareData) {
LayoutSize paintInvalidationSize = previousPaintInvalidationRect().size();
// Don't save old border box size if the paint rect is empty because we'll
// full invalidate once the paint rect becomes non-empty.
if (paintInvalidationSize.isEmpty())
return;
// Don't save old border box size if we can use size of the old paint rect
// as the old border box size in the next invalidation.
if (paintInvalidationSize == size())
return;
// We need the old border box size only when the box has background or box decorations.
if (!style()->hasBackground() && !style()->hasBoxDecorations())
return;
}
ensureRareData().m_previousBorderBoxSize = size();
}
LayoutSize RenderBox::computePreviousBorderBoxSize(const LayoutSize& previousBoundsSize) const
{
// PreviousBorderBoxSize is only valid when there is background or box decorations.
ASSERT(style()->hasBackground() || style()->hasBoxDecorations());
if (m_rareData && m_rareData->m_previousBorderBoxSize.width() != -1)
return m_rareData->m_previousBorderBoxSize;
// We didn't save the old border box size because it was the same as the size of oldBounds.
return previousBoundsSize;
}
void RenderBox::logicalExtentAfterUpdatingLogicalWidth(const LayoutUnit& newLogicalTop, RenderBox::LogicalExtentComputedValues& computedValues)
{
// FIXME: None of this is right for perpendicular writing-mode children.
LayoutUnit oldLogicalWidth = logicalWidth();
LayoutUnit oldLogicalLeft = logicalLeft();
LayoutUnit oldMarginLeft = marginLeft();
LayoutUnit oldMarginRight = marginRight();
LayoutUnit oldLogicalTop = logicalTop();
setLogicalTop(newLogicalTop);
updateLogicalWidth();
computedValues.m_extent = logicalWidth();
computedValues.m_position = logicalLeft();
computedValues.m_margins.m_start = marginStart();
computedValues.m_margins.m_end = marginEnd();
setLogicalTop(oldLogicalTop);
setLogicalWidth(oldLogicalWidth);
setLogicalLeft(oldLogicalLeft);
setMarginLeft(oldMarginLeft);
setMarginRight(oldMarginRight);
}
} // namespace blink
|