summaryrefslogtreecommitdiff
path: root/render/layout.c
blob: 60ad8baa9b4234d1e2a190a208223a4ed12b94b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
/*
 * Copyright 2005 Richard Wilson <info@tinct.net>
 * Copyright 2006 James Bursa <bursa@users.sourceforge.net>
 * Copyright 2008 Michael Drake <tlsa@netsurf-browser.org>
 * Copyright 2003 Phil Mellor <monkeyson@users.sourceforge.net>
 *
 * This file is part of NetSurf, http://www.netsurf-browser.org/
 *
 * NetSurf is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * NetSurf 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/** \file
 * HTML layout (implementation).
 *
 * Layout is carried out in two stages:
 *
 * 1. + calculation of minimum / maximum box widths, and
 *    + determination of whether block level boxes will have >zero height
 *
 * 2. + layout (position and dimensions)
 *
 * In most cases the functions for the two stages are a corresponding pair
 * layout_minmax_X() and layout_X().
 */

#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "css/css.h"
#include "css/utils.h"
#include "content/content_protected.h"
#include "desktop/gui.h"
#include "desktop/options.h"
#include "desktop/scrollbar.h"
#include "render/box.h"
#include "render/font.h"
#include "render/form.h"
#include "render/html_internal.h"
#include "render/layout.h"
#include "render/table.h"
#include "utils/log.h"
#include "utils/talloc.h"
#include "utils/utils.h"


/* Define to enable layout debugging */
#undef LAYOUT_DEBUG

#define AUTO INT_MIN

/* Fixed point value percentage of an integer, to an integer */
#define FPCT_OF_INT_TOINT(a, b) FIXTOINT(FMUL(FDIV(a, F_100), INTTOFIX(b)))


static bool layout_block_context(struct box *block, int viewport_height,
		html_content *content);
static void layout_minmax_block(struct box *block,
		const struct font_functions *font_func);
static struct box* layout_next_margin_block(struct box *box, struct box *block,
		int viewport_height, int *max_pos_margin, int *max_neg_margin);
static bool layout_block_object(struct box *block);
static void layout_get_object_dimensions(struct box *box,
		int *width, int *height,
		bool update_width, bool update_height);
static void layout_block_find_dimensions(int available_width,
		int viewport_height, int lm, int rm,
		struct box *box);
static bool layout_apply_minmax_height(struct box *box, struct box *container);
static void layout_block_add_scrollbar(struct box *box, int which);
static int layout_solve_width(struct box *box, int available_width, int width,
		int lm, int rm, int max_width, int min_width);
static void layout_float_find_dimensions(int available_width,
		const css_computed_style *style, struct box *box);
static void layout_find_dimensions(int available_width, int viewport_height,
		struct box *box, const css_computed_style *style,
		int *width, int *height, int *max_width, int *min_width,
		int margin[4], int padding[4], struct box_border border[4]);
static void layout_tweak_form_dimensions(struct box *box, bool percentage,
		int available_width, bool setwidth, int *dimension);
static int layout_clear(struct box *fl, enum css_clear_e clear);
static void find_sides(struct box *fl, int y0, int y1,
		int *x0, int *x1, struct box **left, struct box **right);
static void layout_minmax_inline_container(struct box *inline_container,
		bool *has_height, const struct font_functions *font_func);
static int line_height(const css_computed_style *style);
static bool layout_line(struct box *first, int *width, int *y,
		int cx, int cy, struct box *cont, bool indent,
		bool has_text_children,
		html_content *content, struct box **next_box);
static struct box *layout_minmax_line(struct box *first, int *min, int *max,
		bool first_line, bool *line_has_height,
		const struct font_functions *font_func);
static int layout_text_indent(const css_computed_style *style, int width);
static bool layout_float(struct box *b, int width, html_content *content);
static void place_float_below(struct box *c, int width, int cx, int y,
		struct box *cont);
static bool layout_table(struct box *box, int available_width,
		html_content *content);
static void layout_move_children(struct box *box, int x, int y);
static void calculate_mbp_width(const css_computed_style *style,
		unsigned int side, bool margin, bool border, bool padding,
		int *fixed, float *frac);
static void layout_lists(struct box *box,
		const struct font_functions *font_func);
static void layout_position_relative(struct box *root, struct box *fp,
		int fx, int fy);
static void layout_compute_relative_offset(struct box *box, int *x, int *y);
static bool layout_position_absolute(struct box *box,
		struct box *containing_block,
		int cx, int cy,
		html_content *content);
static bool layout_absolute(struct box *box, struct box *containing_block,
		int cx, int cy,
		html_content *content);
static void layout_compute_offsets(struct box *box,
		struct box *containing_block,
		int *top, int *right, int *bottom, int *left);


/**
 * Calculate positions of boxes in a document.
 *
 * \param  doc	     content of type CONTENT_HTML
 * \param  width     available width
 * \param  height    available height
 * \return  true on success, false on memory exhaustion
 */

bool layout_document(html_content *content, int width, int height)
{
	bool ret;
	struct box *doc = content->layout;
	const struct font_functions *font_func = content->font_func;

	layout_minmax_block(doc, font_func);

	layout_block_find_dimensions(width, height, 0, 0, doc);
	doc->x = doc->margin[LEFT] + doc->border[LEFT].width;
	doc->y = doc->margin[TOP] + doc->border[TOP].width;
	width -= doc->margin[LEFT] + doc->border[LEFT].width +
			doc->padding[LEFT] + doc->padding[RIGHT] +
			doc->border[RIGHT].width + doc->margin[RIGHT];
	if (width < 0)
		width = 0;
	doc->width = width;

	ret = layout_block_context(doc, height, content);

	/* make <html> and <body> fill available height */
	if (doc->y + doc->padding[TOP] + doc->height + doc->padding[BOTTOM] +
			doc->border[BOTTOM].width + doc->margin[BOTTOM] <
			height) {
		doc->height = height - (doc->y + doc->padding[TOP] +
				doc->padding[BOTTOM] +
				doc->border[BOTTOM].width +
				doc->margin[BOTTOM]);
		if (doc->children)
			doc->children->height = doc->height -
					(doc->children->margin[TOP] +
					 doc->children->border[TOP].width +
					 doc->children->padding[TOP] +
					 doc->children->padding[BOTTOM] +
					 doc->children->border[BOTTOM].width +
					 doc->children->margin[BOTTOM]);
	}

	layout_lists(doc, font_func);
	layout_position_absolute(doc, doc, 0, 0, content);
	layout_position_relative(doc, doc, 0, 0);

	layout_calculate_descendant_bboxes(doc);

	return ret;
}


/**
 * Layout a block formatting context.
 *
 * \param  block	    BLOCK, INLINE_BLOCK, or TABLE_CELL to layout
 * \param  viewport_height  Height of viewport in pixels or -ve if unknown
 * \param  content	    Memory pool for any new boxes
 * \return  true on success, false on memory exhaustion
 *
 * This function carries out layout of a block and its children, as described
 * in CSS 2.1 9.4.1.
 */

bool layout_block_context(struct box *block, int viewport_height,
		html_content *content)
{
	struct box *box;
	int cx, cy;  /**< current coordinates */
	int max_pos_margin = 0;
	int max_neg_margin = 0;
	int y = 0;
	int lm, rm;
	struct box *margin_collapse = NULL;
	bool in_margin = false;
	css_fixed gadget_size;
	css_unit gadget_unit; /* Checkbox / radio buttons */

	assert(block->type == BOX_BLOCK ||
			block->type == BOX_INLINE_BLOCK ||
			block->type == BOX_TABLE_CELL);
	assert(block->width != UNKNOWN_WIDTH);
	assert(block->width != AUTO);

#ifdef riscos
	/* Why the ifdef? You don't really want to know. If you do, read on.
	 *
	 * So, the only way into this function is through the rest of the
	 * layout code. The only external entry points into the layout code
	 * are layout_document and layout_inline_container. The latter is only
	 * ever called when editing text in form textareas, so we can ignore it
	 * for the purposes of this discussion.
	 *
	 * layout_document is only ever called from html_reformat, which itself
	 * is only ever called from content_reformat. content_reformat locks
	 * the content structure while reformatting is taking place.
	 *
	 * If we call gui_multitask here, then any pending UI events will get
	 * processed. This includes window expose/redraw events. Upon receipt
	 * of these events, the UI code will call content_redraw for the
	 * window's content. content_redraw will return immediately if the
	 * content is currently locked (which it will be if we're still doing
	 * layout).
	 *
	 * On RISC OS, this isn't a problem as the UI code's window redraw
	 * handler explicitly checks for locked contents and does nothing
	 * in that case. This effectively means that the window contents
	 * aren't updated, so whatever's already in the window will remain
	 * on-screen. On GTK, however, redraw is not direct-to-screen, but
	 * to a pixmap which is then blitted to screen. If we perform no
	 * redraw, then the pixmap will be flat white. When this is
	 * subsequently blitted, the user gets greeted with an unsightly
	 * flicker to white (and then back to the document when the content
	 * is redrawn when unlocked).
	 *
	 * In the long term, this upcall into the GUI event dispatch code needs
	 * to disappear. It needs to remain for the timebeing, however, as
	 * document reflow can be fairly time consuming and we need to remain
	 * responsive to user input.
	 */
	gui_multitask();
#endif

	block->float_children = NULL;
	block->clear_level = 0;

	/* special case if the block contains an object */
	if (block->object) {
		if (!layout_block_object(block))
			return false;
		layout_get_object_dimensions(block, &block->width,
				&block->height, false, true);
		return true;
	} else if (block->flags & REPLACE_DIM) {
		return true;
	}

	/* special case if the block contains an radio button or checkbox */
	if (block->gadget && (block->gadget->type == GADGET_RADIO ||
			block->gadget->type == GADGET_CHECKBOX)) {
		/* form checkbox or radio button
		 * if width or height is AUTO, set it to 1em */
		gadget_unit = CSS_UNIT_EM;
		gadget_size = INTTOFIX(1);
		if (block->height == AUTO)
			block->height = FIXTOINT(nscss_len2px(gadget_size,
					gadget_unit, block->style));
	}

	box = block->children;
	/* set current coordinates to top-left of the block */
	cx = 0;
	y = cy = block->padding[TOP];
	if (box)
		box->y = block->padding[TOP];

	/* Step through the descendants of the block in depth-first order, but
	 * not into the children of boxes which aren't blocks. For example, if
	 * the tree passed to this function looks like this (box->type shown):
	 *
	 *  block -> BOX_BLOCK
	 *             BOX_BLOCK * (1)
	 *               BOX_INLINE_CONTAINER * (2)
	 *                 BOX_INLINE
	 *                 BOX_TEXT
	 *                 ...
	 *             BOX_BLOCK * (3)
	 *               BOX_TABLE * (4)
	 *                 BOX_TABLE_ROW
	 *                   BOX_TABLE_CELL
	 *                     ...
	 *                   BOX_TABLE_CELL
	 *                     ...
	 *               BOX_BLOCK * (5)
	 *                 BOX_INLINE_CONTAINER * (6)
	 *                   BOX_TEXT
	 *                   ...
	 * then the while loop will visit each box marked with *, setting box
	 * to each in the order shown. */
	while (box) {
		assert(box->type == BOX_BLOCK || box->type == BOX_TABLE ||
				box->type == BOX_INLINE_CONTAINER);

		/* Tables are laid out before being positioned, because the
		 * position depends on the width which is calculated in
		 * table layout. Blocks and inline containers are positioned
		 * before being laid out, because width is not dependent on
		 * content, and the position is required during layout for
		 * correct handling of floats.
		 */

		if (box->style &&
				(css_computed_position(box->style) ==
					CSS_POSITION_ABSOLUTE ||
				 css_computed_position(box->style) ==
					CSS_POSITION_FIXED)) {
			box->x = box->parent->padding[LEFT];
			/* absolute positioned; this element will establish
			 * its own block context when it gets laid out later,
			 * so no need to look at its children now. */
			goto advance_to_next_box;
		}

		/* If we don't know which box the current margin collapses
		 * through to, find out.  Update the pos/neg margin values. */
		if (margin_collapse == NULL) {
			margin_collapse = layout_next_margin_block(box, block,
					viewport_height,
					&max_pos_margin, &max_neg_margin);
			/* We have a margin that has not yet been applied. */
			in_margin = true;
		}

		/* Clearance. */
		y = 0;
		if (box->style && css_computed_clear(box->style) !=
				CSS_CLEAR_NONE)
			y = layout_clear(block->float_children,
					css_computed_clear(box->style));

		/* Blocks establishing a block formatting context get minimum
		 * left and right margins to avoid any floats. */
		lm = rm = 0;

		if (box->type == BOX_BLOCK || box->object) {
			if (!box->object && !(box->flags & REPLACE_DIM) &&
					box->style &&
					css_computed_overflow(box->style) !=
					CSS_OVERFLOW_VISIBLE) {
				/* box establishes new block formatting context
				 * so available width may be diminished due to
				 * floats. */
				int x0, x1, top;
				struct box *left, *right;
				top = cy + max_pos_margin - max_neg_margin;
				top = (top > y) ? top : y;
				x0 = cx;
				x1 = cx + box->parent->width -
						box->parent->padding[LEFT] -
						box->parent->padding[RIGHT];
				find_sides(block->float_children, top, top,
						&x0, &x1, &left, &right);
				/* calculate min required left & right margins
				 * needed to avoid floats */
				lm = x0 - cx;
				rm = cx + box->parent->width -
						box->parent->padding[LEFT] -
						box->parent->padding[RIGHT] -
						x1;
			}
			layout_block_find_dimensions(box->parent->width,
					viewport_height, lm, rm, box);
			if (box->type == BOX_BLOCK) {
				layout_block_add_scrollbar(box, RIGHT);
				layout_block_add_scrollbar(box, BOTTOM);
			}
		} else if (box->type == BOX_TABLE) {
			if (box->style != NULL) {
				enum css_width_e wtype;
				css_fixed width = 0;
				css_unit unit = CSS_UNIT_PX;

				wtype = css_computed_width(box->style, &width,
						&unit);

				if (wtype == CSS_WIDTH_AUTO) {
					/* max available width may be
					 * diminished due to floats. */
					int x0, x1, top;
					struct box *left, *right;
					top = cy + max_pos_margin -
							max_neg_margin;
					top = (top > y) ? top : y;
					x0 = cx;
					x1 = cx + box->parent->width -
						box->parent->padding[LEFT] -
						box->parent->padding[RIGHT];
					find_sides(block->float_children,
						top, top, &x0, &x1,
						&left, &right);
					/* calculate min required left & right
					 * margins needed to avoid floats */
					lm = x0 - cx;
					rm = cx + box->parent->width -
						box->parent->padding[LEFT] -
						box->parent->padding[RIGHT] -
						x1;
				}
			}
			if (!layout_table(box, box->parent->width - lm - rm,
					content))
				return false;
			layout_solve_width(box, box->parent->width, box->width,
					lm, rm, -1, -1);
		}

		/* Position box: horizontal. */
		box->x = box->parent->padding[LEFT] + box->margin[LEFT] +
				box->border[LEFT].width;
		cx += box->x;

		/* Position box: vertical. */
		if (box->border[TOP].width) {
			box->y += box->border[TOP].width;
			cy += box->border[TOP].width;
		}

		/* Vertical margin */
		if (((box->type == BOX_BLOCK &&
				(box->flags & HAS_HEIGHT)) ||
				box->type == BOX_TABLE ||
				(box->type == BOX_INLINE_CONTAINER &&
				box != box->parent->children) ||
				margin_collapse == box) &&
				in_margin == true) {
			/* Margin goes above this box. */
			cy += max_pos_margin - max_neg_margin;
			box->y += max_pos_margin - max_neg_margin;

			/* Current margin has been applied. */
			in_margin = false;
			max_pos_margin = max_neg_margin = 0;
		}

		/* Handle clearance */
		if (box->type != BOX_INLINE_CONTAINER &&
				(y > 0) && (cy < y)) {
			/* box clears something*/
			box->y += y - cy;
			cy = y;
		}

		/* Unless the box has an overflow style of visible, the box
		 * establishes a new block context. */
		if (box->type == BOX_BLOCK && box->style &&
				css_computed_overflow(box->style) !=
				CSS_OVERFLOW_VISIBLE) {

			layout_block_context(box, viewport_height, content);

			cy += box->padding[TOP];

			if (box->height == AUTO) {
				box->height = 0;
				layout_block_add_scrollbar(box, BOTTOM);
			}

			cx -= box->x;
			cy += box->height + box->padding[BOTTOM] +
					box->border[BOTTOM].width;
			y = box->y + box->padding[TOP] + box->height +
					box->padding[BOTTOM] +
					box->border[BOTTOM].width;

			/* Skip children, because they are done in the new
			 * block context */
			goto advance_to_next_box;
		}

#ifdef LAYOUT_DEBUG
		LOG(("box %p, cx %i, cy %i", box, cx, cy));
#endif

		/* Layout (except tables). */
		if (box->object) {
			if (!layout_block_object(box))
				return false;
		} else if (box->type == BOX_INLINE_CONTAINER) {
			box->width = box->parent->width;
			if (!layout_inline_container(box, box->width, block,
					cx, cy, content))
				return false;
		} else if (box->type == BOX_TABLE) {
			/* Move down to avoid floats if necessary. */
			int x0, x1;
			struct box *left, *right;
			y = cy;
			while (1) {
				enum css_width_e wtype;
				css_fixed width = 0;
				css_unit unit = CSS_UNIT_PX;

				wtype = css_computed_width(box->style,
						&width, &unit);

				x0 = cx;
				x1 = cx + box->parent->width;
				find_sides(block->float_children, y,
						y + box->height,
						&x0, &x1, &left, &right);
				if (wtype == CSS_WIDTH_AUTO)
					break;
				if (box->width <= x1 - x0)
					break;
				if (!left && !right)
					break;
				else if (!left)
					y = right->y + right->height + 1;
				else if (!right)
					y = left->y + left->height + 1;
				else if (left->y + left->height <
						right->y + right->height)
					y = left->y + left->height + 1;
				else
					y = right->y + right->height + 1;
			}
			box->x += x0 - cx;
			cx = x0;
			box->y += y - cy;
			cy = y;
		}

		/* Advance to next box. */
		if (box->type == BOX_BLOCK && !box->object && box->children) {
			/* Down into children. */

			if (box == margin_collapse) {
				/* Current margin collapsed though to this box.
				 * Unset margin_collapse. */
				margin_collapse = NULL;
			}

			y = box->padding[TOP];
			box = box->children;
			box->y = y;
			cy += y;
			continue;
		} else if (box->type == BOX_BLOCK || box->object)
			cy += box->padding[TOP];

		if (box->type == BOX_BLOCK && box->height == AUTO) {
			box->height = 0;
			layout_block_add_scrollbar(box, BOTTOM);
		}

		cy += box->height + box->padding[BOTTOM] +
				box->border[BOTTOM].width;
		cx -= box->x;
		y = box->y + box->padding[TOP] + box->height +
				box->padding[BOTTOM] +
				box->border[BOTTOM].width;

	advance_to_next_box:
		if (!box->next) {
			/* No more siblings:
			 * up to first ancestor with a sibling. */

			do {
				if (box == margin_collapse) {
					/* Current margin collapsed though to
					 * this box.  Unset margin_collapse. */
					margin_collapse = NULL;
				}

				/* Apply bottom margin */
				if (max_pos_margin < box->margin[BOTTOM])
					max_pos_margin = box->margin[BOTTOM];
				else if (max_neg_margin < -box->margin[BOTTOM])
					max_neg_margin = -box->margin[BOTTOM];

				box = box->parent;
				if (box == block)
					break;

				/* Margin is invalidated if this is a box
				 * margins can't collapse through. */
				if (box->type == BOX_BLOCK &&
						box->flags & MAKE_HEIGHT) {
					margin_collapse = NULL;
					in_margin = false;
					max_pos_margin = max_neg_margin = 0;
				}

				if (box->height == AUTO) {
					box->height = y - box->padding[TOP];

					if (box->type == BOX_BLOCK)
						layout_block_add_scrollbar(box,
								BOTTOM);
				} else
					cy += box->height -
							(y - box->padding[TOP]);

				/* Apply any min-height and max-height to
				 * boxes in normal flow */
				if (box->style &&
					css_computed_position(box->style) !=
						CSS_POSITION_ABSOLUTE &&
						layout_apply_minmax_height(box,
								NULL)) {
					/* Height altered */
					/* Set current cy */
					cy += box->height -
							(y - box->padding[TOP]);
				}

				cy += box->padding[BOTTOM] +
						box->border[BOTTOM].width;
				cx -= box->x;
				y = box->y + box->padding[TOP] + box->height +
						box->padding[BOTTOM] +
						box->border[BOTTOM].width;

			} while (box->next == NULL);
			if (box == block)
				break;
		}

		/* To next sibling. */

		if (box == margin_collapse) {
			/* Current margin collapsed though to this box.
			 * Unset margin_collapse. */
			margin_collapse = NULL;
		}

		if (max_pos_margin < box->margin[BOTTOM])
			max_pos_margin = box->margin[BOTTOM];
		else if (max_neg_margin < -box->margin[BOTTOM])
			max_neg_margin = -box->margin[BOTTOM];

		box = box->next;
		box->y = y;
	}

	/* Account for bottom margin of last contained block */
	cy += max_pos_margin - max_neg_margin;

	/* Increase height to contain any floats inside (CSS 2.1 10.6.7). */
	for (box = block->float_children; box; box = box->next_float) {
		y = box->y + box->height + box->padding[BOTTOM] +
				box->border[BOTTOM].width + box->margin[BOTTOM];
		if (cy < y)
			cy = y;
	}

	if (block->height == AUTO) {
		block->height = cy - block->padding[TOP];
		if (block->type == BOX_BLOCK)
			layout_block_add_scrollbar(block, BOTTOM);
	}

	if (block->style && css_computed_position(block->style) !=
			CSS_POSITION_ABSOLUTE) {
		/* Block is in normal flow */
		layout_apply_minmax_height(block, NULL);
	}

	return true;
}


/**
 * Calculate minimum and maximum width of a block.
 *
 * \param  block  box of type BLOCK, INLINE_BLOCK, or TABLE_CELL
 * \post  block->min_width and block->max_width filled in,
 *        0 <= block->min_width <= block->max_width
 */

void layout_minmax_block(struct box *block,
		const struct font_functions *font_func)
{
	struct box *child;
	int min = 0, max = 0;
	int extra_fixed = 0;
	float extra_frac = 0;
	enum css_width_e wtype = CSS_WIDTH_AUTO;
	css_fixed width = 0;
	css_unit wunit = CSS_UNIT_PX;
	enum css_height_e htype = CSS_HEIGHT_AUTO;
	css_fixed height = 0;
	css_unit hunit = CSS_UNIT_PX;
	bool child_has_height = false;

	assert(block->type == BOX_BLOCK ||
			block->type == BOX_INLINE_BLOCK ||
			block->type == BOX_TABLE_CELL);

	/* check if the widths have already been calculated */
	if (block->max_width != UNKNOWN_MAX_WIDTH)
		return;

	if (block->style != NULL) {
		wtype = css_computed_width(block->style, &width, &wunit);
		htype = css_computed_height(block->style, &height, &hunit);
	}

	/* set whether the minimum width is of any interest for this box */
	if (((block->parent && (block->parent->type == BOX_FLOAT_LEFT ||
			block->parent->type == BOX_FLOAT_RIGHT)) ||
			block->type == BOX_INLINE_BLOCK) &&
			wtype != CSS_WIDTH_SET) {
		/* box shrinks to fit; need minimum width */
		block->flags |= NEED_MIN;
	} else if (block->type == BOX_TABLE_CELL) {		
		/* box shrinks to fit; need minimum width */
		block->flags |= NEED_MIN;
	} else if (block->parent && (block->parent->flags & NEED_MIN) &&
			wtype != CSS_WIDTH_SET) {	
		/* box inside shrink-to-fit context; need minimum width */
		block->flags |= NEED_MIN;
	}

	if (block->gadget && (block->gadget->type == GADGET_TEXTBOX ||
			block->gadget->type == GADGET_PASSWORD ||
			block->gadget->type == GADGET_FILE ||
			block->gadget->type == GADGET_TEXTAREA) &&
			block->style && wtype == CSS_WIDTH_AUTO) {
		css_fixed size = INTTOFIX(10);
		css_unit unit = CSS_UNIT_EM;

		min = max = FIXTOINT(nscss_len2px(size, unit, block->style));

		block->flags |= HAS_HEIGHT;
	}

	if (block->gadget && (block->gadget->type == GADGET_RADIO ||
			block->gadget->type == GADGET_CHECKBOX) &&
			block->style && wtype == CSS_WIDTH_AUTO) {
		css_fixed size = INTTOFIX(1);
		css_unit unit = CSS_UNIT_EM;

		/* form checkbox or radio button
		 * if width is AUTO, set it to 1em */
		min = max = FIXTOINT(nscss_len2px(size, unit, block->style));

		block->flags |= HAS_HEIGHT;
	}

	if (block->object) {
		if (content_get_type(block->object) == CONTENT_HTML) {
			layout_minmax_block(html_get_box_tree(block->object),
					font_func);
			min = html_get_box_tree(block->object)->min_width;
			max = html_get_box_tree(block->object)->max_width;
		} else {
			min = max = content_get_width(block->object);
		}

		block->flags |= HAS_HEIGHT;
	} else {
		/* recurse through children */
		for (child = block->children; child; child = child->next) {
			switch (child->type) {
			case BOX_BLOCK:
				layout_minmax_block(child, font_func);
				if (child->flags & HAS_HEIGHT)
					child_has_height = true;
				break;
			case BOX_INLINE_CONTAINER:
				if (block->flags & NEED_MIN)
					child->flags |= NEED_MIN;

				layout_minmax_inline_container(child,
						&child_has_height, font_func);
				if (child_has_height &&
						child ==
						child->parent->children) {
					block->flags |= MAKE_HEIGHT;
				}
				break;
			case BOX_TABLE:
				layout_minmax_table(child, font_func);
				/* todo: fix for zero height tables */
				child_has_height = true;
				child->flags |= MAKE_HEIGHT;
				break;
			default:
				assert(0);
			}
			assert(child->max_width != UNKNOWN_MAX_WIDTH);

			if (child->style &&
					(css_computed_position(child->style) ==
							CSS_POSITION_ABSOLUTE ||
					css_computed_position(child->style) ==
							CSS_POSITION_FIXED)) {
				/* This child is positioned out of normal flow,
				 * so it will have no affect on width */
				continue;
			}

			if (min < child->min_width)
				min = child->min_width;
			if (max < child->max_width)
				max = child->max_width;

			if (child_has_height)
				block->flags |= HAS_HEIGHT;
		}
	}

	if (max < min) {
		box_dump(stderr, block, 0);
		assert(0);
	}

	/* fixed width takes priority */
	if (block->type != BOX_TABLE_CELL && wtype == CSS_WIDTH_SET &&
			wunit != CSS_UNIT_PCT) {
		min = max = FIXTOINT(nscss_len2px(width, wunit, block->style));
	}

	if (htype == CSS_HEIGHT_SET && hunit != CSS_UNIT_PCT &&
			height > INTTOFIX(0)) {
		block->flags |= MAKE_HEIGHT;
		block->flags |= HAS_HEIGHT;
	}

	/* add margins, border, padding to min, max widths */
	/* Note: we don't know available width here so percentage margin
	 * and paddings are wrong. */
	if (block->gadget && wtype == CSS_WIDTH_SET &&
			(block->gadget->type == GADGET_SUBMIT ||
			block->gadget->type == GADGET_RESET ||
			block->gadget->type == GADGET_BUTTON)) {
		/* some gadgets with specified width already include border and
		 * padding, so just get margin */
		calculate_mbp_width(block->style, LEFT, true, false, false,
				&extra_fixed, &extra_frac);
		calculate_mbp_width(block->style, RIGHT, true, false, false,
				&extra_fixed, &extra_frac);
	} else {
		calculate_mbp_width(block->style, LEFT, true, true, true,
				&extra_fixed, &extra_frac);
		calculate_mbp_width(block->style, RIGHT, true, true, true,
				&extra_fixed, &extra_frac);
	}
	if (extra_fixed < 0)
		extra_fixed = 0;
	if (extra_frac < 0)
		extra_frac = 0;
	if (1.0 <= extra_frac)
		extra_frac = 0.9;
	if (block->style != NULL &&
			(css_computed_float(block->style) == CSS_FLOAT_LEFT ||
			css_computed_float(block->style) == CSS_FLOAT_RIGHT)) {
		/* floated boxs */
		block->min_width = min + extra_fixed;
		block->max_width = max + extra_fixed;
	} else {
		/* not floated */
		block->min_width = (min + extra_fixed) / (1.0 - extra_frac);
		block->max_width = (max + extra_fixed) / (1.0 - extra_frac);
	}

	assert(0 <= block->min_width && block->min_width <= block->max_width);
}


/**
 * Find next block that current margin collapses to.
 *
 * \param  box    box to start tree-order search from (top margin is included)
 * \param  block  box responsible for current block fromatting context
 * \param  viewport_height  height of viewport in px
 * \param  max_pos_margin  updated to to maximum positive margin encountered
 * \param  max_neg_margin  updated to to maximum negative margin encountered
 * \return  next box that current margin collapses to, or NULL if none.
 */

struct box* layout_next_margin_block(struct box *box, struct box *block,
		int viewport_height, int *max_pos_margin, int *max_neg_margin)
{
	assert(block != NULL);

	while (box != NULL) {

		if (box->type == BOX_INLINE_CONTAINER || (box->style &&
				(css_computed_position(box->style) !=
					CSS_POSITION_ABSOLUTE &&
				 css_computed_position(box->style) !=
					CSS_POSITION_FIXED))) {
			/* Not positioned */

			/* Get margins */
			if (box->style) {
				layout_find_dimensions(box->parent->width,
						viewport_height, box,
						box->style,
						NULL, NULL, NULL, NULL,
						box->margin, box->padding,
						box->border);

				/* Apply top margin */
				if (*max_pos_margin < box->margin[TOP])
					*max_pos_margin = box->margin[TOP];
				else if (*max_neg_margin < -box->margin[TOP])
					*max_neg_margin = -box->margin[TOP];
			}

			/* Check whether box is the box current margin collapses
			 * to */
			if (box->flags & MAKE_HEIGHT ||
					box->border[TOP].width ||
					box->padding[TOP] ||
					(box->style &&
					css_computed_overflow(box->style) !=
					CSS_OVERFLOW_VISIBLE) ||
					(box->type == BOX_INLINE_CONTAINER &&
					box != box->parent->children)) {
				/* Collapse to this box; return it */
				return box;
			}
		}


		/* Find next box */
		if (box->type == BOX_BLOCK && !box->object && box->children &&
				box->style &&
				css_computed_overflow(box->style) ==
				CSS_OVERFLOW_VISIBLE) {
			/* Down into children. */
			box = box->children;
		} else {
			if (!box->next) {
				/* No more siblings:
				 * Go up to first ancestor with a sibling. */
				do {
					/* Apply bottom margin */
					if (*max_pos_margin <
							box->margin[BOTTOM])
						*max_pos_margin =
							box->margin[BOTTOM];
					else if (*max_neg_margin <
							-box->margin[BOTTOM])
						*max_neg_margin =
							-box->margin[BOTTOM];

					box = box->parent;
				} while (box != block && !box->next);

				if (box == block) {
					/* Margins don't collapse with stuff
					 * outside the block formatting context
					 */
					return block;
				}
			}

			/* Apply bottom margin */
			if (*max_pos_margin < box->margin[BOTTOM])
				*max_pos_margin = box->margin[BOTTOM];
			else if (*max_neg_margin < -box->margin[BOTTOM])
				*max_neg_margin = -box->margin[BOTTOM];

			/* To next sibling. */
			box = box->next;

			/* Get margins */
			if (box->style) {
				layout_find_dimensions(box->parent->width,
						viewport_height, box,
						box->style,
						NULL, NULL, NULL, NULL,
						box->margin, box->padding,
						box->border);
			}
		}
	}

	return NULL;
}


/**
 * Layout a block which contains an object.
 *
 * \param  block  box of type BLOCK, INLINE_BLOCK, TABLE, or TABLE_CELL
 * \return  true on success, false on memory exhaustion
 */

bool layout_block_object(struct box *block)
{
	assert(block);
	assert(block->type == BOX_BLOCK ||
			block->type == BOX_INLINE_BLOCK ||
			block->type == BOX_TABLE ||
			block->type == BOX_TABLE_CELL);
	assert(block->object);

#ifdef LAYOUT_DEBUG
	LOG(("block %p, object %s, width %i", block,
			content_get_url(block->object), block->width));
#endif

	if (content_get_type(block->object) == CONTENT_HTML) {
		content_reformat(block->object, block->width, 1);
	} else {
		/* Non-HTML objects */
		/* this case handled already in
		 * layout_block_find_dimensions() */
	}

	return true;
}


/**
 * Compute the size of replaced boxes with auto dimensions, according to
 * content.
 *
 * \param  box     Box with object
 * \param  width   Width value in px or AUTO.  If AUTO, updated to value in px.
 * \param  height  Height value in px or AUTO. If AUTO, updated to value in px.
 * \param  uppate_width   Whether to update the width.
 * \param  update_height  Whether to update the height.
 *
 * See CSS 2.1 sections 10.3 and 10.6.
 */

void layout_get_object_dimensions(struct box *box, int *width, int *height,
		bool update_width, bool update_height)
{
	assert(box->object != NULL);
	assert(width != NULL && height != NULL);

	if (*width == AUTO && *height == AUTO) {
		/* No given dimensions; use intrinsic dimensions */
		if (update_width)
			*width = content_get_width(box->object);
		if (update_height)
			*height = content_get_height(box->object);

	} else if (update_width && *width == AUTO) {
		/* Have given height; width is calculated from the given height
		 * and ratio of intrinsic dimensions */
		int intrinsic_width = content_get_width(box->object);
		int intrinsic_height = content_get_height(box->object);

		if (intrinsic_height != 0)
			*width = (*height * intrinsic_width) /
					intrinsic_height;
		else
			*width = intrinsic_width;

	} else if (update_height && *height == AUTO) {
		/* Have given width; height is calculated from the given width
		 * and ratio of intrinsic dimensions */
		int intrinsic_width = content_get_width(box->object);
		int intrinsic_height = content_get_height(box->object);

		if (intrinsic_width != 0)
			*height = (*width * intrinsic_height) /
					intrinsic_width;
		else
			*height = intrinsic_height;
	}
}


/**
 * Compute dimensions of box, margins, paddings, and borders for a block-level
 * element.
 *
 * \param  available_width  Max width available in pixels
 * \param  viewport_height  Height of viewport in pixels or -ve if unknown
 * \param  lm		    min left margin required to avoid floats in px.
 *				zero if not applicable
 * \param  rm		    min right margin required to avoid floats in px.
 *				zero if not applicable
 * \param  box		    box to find dimensions of. updated with new width,
 *			    height, margins, borders and paddings
 *
 * See CSS 2.1 10.3.3, 10.3.4, 10.6.2, and 10.6.3.
 */

void layout_block_find_dimensions(int available_width, int viewport_height,
		int lm, int rm, struct box *box)
{
	int width, max_width, min_width;
	int height;
	int *margin = box->margin;
	int *padding = box->padding;
	struct box_border *border = box->border;
	const css_computed_style *style = box->style;

	layout_find_dimensions(available_width, viewport_height, box, style,
			&width, &height, &max_width, &min_width,
			margin, padding, border);

	if (box->object && !(box->flags & REPLACE_DIM) &&
			content_get_type(box->object) != CONTENT_HTML) {
		/* block-level replaced element, see 10.3.4 and 10.6.2 */
		layout_get_object_dimensions(box, &width, &height,
				true, true);
	}

	box->width = layout_solve_width(box, available_width, width, lm, rm,
			max_width, min_width);
	box->height = height;

	if (margin[TOP] == AUTO)
		margin[TOP] = 0;
	if (margin[BOTTOM] == AUTO)
		margin[BOTTOM] = 0;
}

/**
 * Manimpulate box height according to CSS min-height and max-height properties
 *
 * \param  box		block to modify with any min-height or max-height
 * \param  container	containing block for absolutely positioned elements, or
 *			NULL for non absolutely positioned elements.
 * \return		whether the height has been changed
 */

bool layout_apply_minmax_height(struct box *box, struct box *container)
{
	int h;
	struct box *containing_block = NULL;
	bool updated = false;

	/* Find containing block for percentage heights */
	if (box->style != NULL && css_computed_position(box->style) ==
			CSS_POSITION_ABSOLUTE) {
		/* Box is absolutely positioned */
		assert(container);
		containing_block = container;
	} else if (box->float_container && box->style != NULL &&
			(css_computed_float(box->style) == CSS_FLOAT_LEFT ||
			 css_computed_float(box->style) == CSS_FLOAT_RIGHT)) {
		/* Box is a float */
		assert(box->parent && box->parent->parent &&
				box->parent->parent->parent);
		containing_block = box->parent->parent->parent;
	} else if (box->parent && box->parent->type != BOX_INLINE_CONTAINER) {
		/* Box is a block level element */
		containing_block = box->parent;
	} else if (box->parent && box->parent->type == BOX_INLINE_CONTAINER) {
		/* Box is an inline block */
		assert(box->parent->parent);
		containing_block = box->parent->parent;
	}

	if (box->style) {
		enum css_height_e htype = CSS_HEIGHT_AUTO;
		css_fixed value = 0;
		css_unit unit = CSS_UNIT_PX;

		if (containing_block) {
			htype = css_computed_height(containing_block->style,
					&value, &unit);
		}

		/* max-height */
		if (css_computed_max_height(box->style, &value, &unit) ==
				CSS_MAX_HEIGHT_SET) {
			if (unit == CSS_UNIT_PCT) {
				if (containing_block &&
					containing_block->height != AUTO &&
					(css_computed_position(box->style) ==
							CSS_POSITION_ABSOLUTE ||
						htype == CSS_HEIGHT_SET)) {
					/* Box is absolutely positioned or its
					 * containing block has a valid
					 * specified height. (CSS 2.1
					 * Section 10.5) */
					h = FPCT_OF_INT_TOINT(value,
						containing_block->height);
					if (h < box->height) {
						box->height = h;
						updated = true;
					}
				}
			} else {
				h = FIXTOINT(nscss_len2px(value, unit,
						box->style));
				if (h < box->height) {
					box->height = h;
					updated = true;
				}
			}
		}

		/* min-height */
		if (css_computed_min_height(box->style, &value, &unit) ==
				CSS_MIN_HEIGHT_SET) {
			if (unit == CSS_UNIT_PCT) {
				if (containing_block &&
					containing_block->height != AUTO &&
					(css_computed_position(box->style) ==
							CSS_POSITION_ABSOLUTE ||
						htype == CSS_HEIGHT_SET)) {
					/* Box is absolutely positioned or its
					 * containing block has a valid
					 * specified height. (CSS 2.1
					 * Section 10.5) */
					h = FPCT_OF_INT_TOINT(value,
						containing_block->height);
					if (h > box->height) {
						box->height = h;
						updated = true;
					}
				}
			} else {
				h = FIXTOINT(nscss_len2px(value, unit,
						box->style));
				if (h > box->height) {
					box->height = h;
					updated = true;
				}
			}
		}
	}
	return updated;
}

/**
 * Manipulate a block's [RB]padding/height/width to accommodate scrollbars
 *
 * \param  box	  Box to apply scrollbar space too. Must be BOX_BLOCK.
 * \param  which  Which scrollbar to make space for. Must be RIGHT or BOTTOM.
 */

void layout_block_add_scrollbar(struct box *box, int which)
{
	enum css_overflow_e overflow;

	assert(box->type == BOX_BLOCK && (which == RIGHT || which == BOTTOM));

	if (box->style == NULL)
		return;

	overflow = css_computed_overflow(box->style);

	if (overflow == CSS_OVERFLOW_SCROLL || overflow == CSS_OVERFLOW_AUTO ||
			(box->object && content_get_type(box->object) ==
					CONTENT_HTML)) {
		/* make space for scrollbars, unless height/width are AUTO */
		if (which == BOTTOM && box->height != AUTO &&
				(overflow == CSS_OVERFLOW_SCROLL ||
				box_hscrollbar_present(box))) {
			box->padding[BOTTOM] += SCROLLBAR_WIDTH;
		}
		if (which == RIGHT && box->width != AUTO &&
				(overflow == CSS_OVERFLOW_SCROLL ||
				box_vscrollbar_present(box))) {
			box->width -= SCROLLBAR_WIDTH;
			box->padding[RIGHT] += SCROLLBAR_WIDTH;
		}
	}
}

/**
 * Solve the width constraint as given in CSS 2.1 section 10.3.3.
 *
 * \param  box              Box to solve constraint for
 * \param  available_width  Max width available in pixels
 * \param  width	    Current box width
 * \param  lm		    Min left margin required to avoid floats in px.
 *				zero if not applicable
 * \param  rm		    Min right margin required to avoid floats in px.
 *				zero if not applicable
 * \param  max_width	    Box max-width ( -ve means no max-width to apply)
 * \param  min_width	    Box min-width ( <=0 means no min-width to apply)
 * \return		    New box width
 *
 * \post \a box's left/right margins will be updated.
 */

int layout_solve_width(struct box *box, int available_width, int width,
		int lm, int rm, int max_width, int min_width)
{
	bool auto_width = false;

	/* Increase specified left/right margins */
	if (box->margin[LEFT] != AUTO && box->margin[LEFT] < lm &&
			box->margin[LEFT] >= 0)
		box->margin[LEFT] = lm;
	if (box->margin[RIGHT] != AUTO && box->margin[RIGHT] < rm &&
			box->margin[RIGHT] >= 0)
		box->margin[RIGHT] = rm;

	/* Find width */
	if (width == AUTO) {
		/* any other 'auto' become 0 or the minimum required values */
		if (box->margin[LEFT] == AUTO)
			box->margin[LEFT] = lm;
		if (box->margin[RIGHT] == AUTO)
			box->margin[RIGHT] = rm;

		width = available_width -
				(box->margin[LEFT] + box->border[LEFT].width +
				box->padding[LEFT] + box->padding[RIGHT] +
				box->border[RIGHT].width + box->margin[RIGHT]);
		width = width < 0 ? 0 : width;
		auto_width = true;
	}

	if (max_width >= 0 && width > max_width) {
		/* max-width is admissable and width exceeds max-width */
		width = max_width;
		auto_width = false;
	}

	if (min_width > 0 && width < min_width) {
		/* min-width is admissable and width is less than max-width */
		width = min_width;
		auto_width = false;
	}

	/* Width was auto, and unconstrained by min/max width, so we're done */
	if (auto_width)
		return width;

	/* Width was not auto, or was constrained by min/max width
	 * Need to compute left/right margins */

	/* HTML alignment (only applies to over-constrained boxes) */
	if (box->margin[LEFT] != AUTO && box->margin[RIGHT] != AUTO &&
			box->parent != NULL && box->parent->style != NULL) {
		switch (css_computed_text_align(box->parent->style)) {
		case CSS_TEXT_ALIGN_LIBCSS_RIGHT:
			box->margin[LEFT] = AUTO;
			box->margin[RIGHT] = 0;
			break;
		case CSS_TEXT_ALIGN_LIBCSS_CENTER:
			box->margin[LEFT] = box->margin[RIGHT] = AUTO;
			break;
		case CSS_TEXT_ALIGN_LIBCSS_LEFT:
			box->margin[LEFT] = 0;
			box->margin[RIGHT] = AUTO;
			break;
		default:
			/* Leave it alone; no HTML alignment */
			break;
		}
	}

	if (box->margin[LEFT] == AUTO && box->margin[RIGHT] == AUTO) {
		/* make the margins equal, centering the element */
		box->margin[LEFT] = box->margin[RIGHT] =
				(available_width - lm - rm -
				(box->border[LEFT].width + box->padding[LEFT] +
				width + box->padding[RIGHT] +
				box->border[RIGHT].width)) / 2;

		if (box->margin[LEFT] < 0) {
			box->margin[RIGHT] += box->margin[LEFT];
			box->margin[LEFT] = 0;
		}

		box->margin[LEFT] += lm;

	} else if (box->margin[LEFT] == AUTO) {
		box->margin[LEFT] = available_width - lm -
				(box->border[LEFT].width + box->padding[LEFT] +
				width + box->padding[RIGHT] +
				box->border[RIGHT].width + box->margin[RIGHT]);
		box->margin[LEFT] = box->margin[LEFT] < lm
				? lm : box->margin[LEFT];
	} else {
		/* margin-right auto or "over-constrained" */
		box->margin[RIGHT] = available_width - rm -
				(box->margin[LEFT] + box->border[LEFT].width +
				 box->padding[LEFT] + width +
				 box->padding[RIGHT] +
				 box->border[RIGHT].width);
	}

	return width;
}


/**
 * Compute dimensions of box, margins, paddings, and borders for a floating
 * element using shrink-to-fit. Also used for inline-blocks.
 *
 * \param  available_width  Max width available in pixels
 * \param  style	    Box's style
 * \param  box		    Box for which to find dimensions
 *				Box margins, borders, paddings, width and
 *				height are updated.
 */

void layout_float_find_dimensions(int available_width,
		const css_computed_style *style, struct box *box)
{
	int width, height, max_width, min_width;
	int *margin = box->margin;
	int *padding = box->padding;
	struct box_border *border = box->border;
	int scrollbar_width =
			(css_computed_overflow(style) == CSS_OVERFLOW_SCROLL ||
			 css_computed_overflow(style) == CSS_OVERFLOW_AUTO) ?
			SCROLLBAR_WIDTH : 0;

	layout_find_dimensions(available_width, -1, box, style, &width, &height,
			&max_width, &min_width, margin, padding, border);

	if (margin[LEFT] == AUTO)
		margin[LEFT] = 0;
	if (margin[RIGHT] == AUTO)
		margin[RIGHT] = 0;

	padding[RIGHT] += scrollbar_width;
	padding[BOTTOM] += scrollbar_width;

	if (box->object && !(box->flags & REPLACE_DIM) &&
			content_get_type(box->object) != CONTENT_HTML) {
		/* Floating replaced element, with intrinsic width or height.
		 * See 10.3.6 and 10.6.2 */
		layout_get_object_dimensions(box, &width, &height,
				true, true);
	} else if (box->gadget && (box->gadget->type == GADGET_TEXTBOX ||
			box->gadget->type == GADGET_PASSWORD ||
			box->gadget->type == GADGET_FILE ||
			box->gadget->type == GADGET_TEXTAREA)) {
		css_fixed size = 0;
		css_unit unit = CSS_UNIT_EM;

		/* Give sensible dimensions to gadgets, with auto width/height,
		 * that don't shrink to fit contained text. */
		assert(box->style);

		if (box->gadget->type == GADGET_TEXTBOX ||
				box->gadget->type == GADGET_PASSWORD ||
				box->gadget->type == GADGET_FILE) {
			if (width == AUTO) {
				size = INTTOFIX(10);
				width = FIXTOINT(nscss_len2px(size, unit,
						box->style));
			}
			if (box->gadget->type == GADGET_FILE &&
					height == AUTO) {
				size = FLTTOFIX(1.5);
				height = FIXTOINT(nscss_len2px(size, unit,
						box->style));
			}
		}
		if (box->gadget->type == GADGET_TEXTAREA) {
			if (width == AUTO) {
				size = INTTOFIX(10);
				width = FIXTOINT(nscss_len2px(size, unit,
						box->style));
			} else {
				width -= scrollbar_width;
			}
			if (height == AUTO) {
				size = INTTOFIX(4);
				height = FIXTOINT(nscss_len2px(size, unit,
						box->style));
			}
		}
	} else if (width == AUTO) {
		/* CSS 2.1 section 10.3.5 */
		width = min(max(box->min_width, available_width),
				box->max_width);

		/* width includes margin, borders and padding */
		if (width == available_width) {
			width -= box->margin[LEFT] + box->border[LEFT].width +
					box->padding[LEFT] +
					box->padding[RIGHT] +
					box->border[RIGHT].width +
					box->margin[RIGHT];
		} else {
			/* width was obtained from a min_width or max_width
			 * value, so need to use the same method for calculating
			 * mbp as was used in layout_minmax_block() */
			int fixed = 0;
			float frac = 0;
			calculate_mbp_width(box->style, LEFT, true, true, true,
					&fixed, &frac);
			calculate_mbp_width(box->style, RIGHT, true, true, true,
					&fixed, &frac);
			if (fixed < 0)
				fixed = 0;

			width -= fixed;
		}

		if (max_width >= 0 && width > max_width) width = max_width;
		if (min_width >  0 && width < min_width) width = min_width;

	} else {
		if (max_width >= 0 && width > max_width) width = max_width;
		if (min_width >  0 && width < min_width) width = min_width;
		width -= scrollbar_width;
	}

	box->width = width;
	box->height = height;

	if (margin[TOP] == AUTO)
		margin[TOP] = 0;
	if (margin[BOTTOM] == AUTO)
		margin[BOTTOM] = 0;
}


/**
 * Calculate width, height, and thickness of margins, paddings, and borders.
 *
 * \param  available_width  width of containing block
 * \param  viewport_height  height of viewport in pixels or -ve if unknown
 * \param  box		    current box
 * \param  style	    style giving width, height, margins, paddings,
 *                          and borders
 * \param  width            updated to width, may be NULL
 * \param  height           updated to height, may be NULL
 * \param  max_width        updated to max-width, may be NULL
 * \param  min_width        updated to min-width, may be NULL
 * \param  margin[4]	    filled with margins, may be NULL
 * \param  padding[4]	    filled with paddings, may be NULL
 * \param  border[4]	    filled with border widths, may be NULL
 */

void layout_find_dimensions(int available_width, int viewport_height,
		struct box *box, const css_computed_style *style,
		int *width, int *height, int *max_width, int *min_width,
		int margin[4], int padding[4], struct box_border border[4])
{
	struct box *containing_block = NULL;
	unsigned int i;
	bool percentage;

	if (width) {
		enum css_width_e wtype;
		css_fixed value = 0;
		css_unit unit = CSS_UNIT_PX;

		wtype = css_computed_width(style, &value, &unit);

		if (wtype == CSS_WIDTH_SET) {
			if (unit == CSS_UNIT_PCT) {
				*width = (FIXTOFLT(value) * available_width)
						/ 100;
			} else {
				*width = FIXTOINT(nscss_len2px(value, unit,
						style));
			}
		} else {
			*width = AUTO;
		}

		/* specified gadget widths include borders and padding in some
		 * cases */
		if (box->gadget && *width != AUTO) {
			percentage = unit == CSS_UNIT_PCT;

			layout_tweak_form_dimensions(box, percentage,
					available_width, true, width);
		}
	}

	if (height) {
		enum css_height_e htype;
		css_fixed value = 0;
		css_unit unit = CSS_UNIT_PX;

		htype = css_computed_height(style, &value, &unit);

		if (htype == CSS_HEIGHT_SET) {
			if (unit == CSS_UNIT_PCT) {
				enum css_height_e cbhtype;

				if (css_computed_position(box->style) ==
						CSS_POSITION_ABSOLUTE &&
						box->parent) {
					/* Box is absolutely positioned */
					assert(box->float_container);
					containing_block = box->float_container;
				} else if (box->float_container &&
					css_computed_position(box->style) !=
						CSS_POSITION_ABSOLUTE &&
					(css_computed_float(box->style) ==
						CSS_FLOAT_LEFT ||
					 css_computed_float(box->style) ==
						CSS_FLOAT_RIGHT)) {
					/* Box is a float */
					assert(box->parent &&
						box->parent->parent &&
						box->parent->parent->parent);

					containing_block =
						box->parent->parent->parent;
				} else if (box->parent && box->parent->type !=
						BOX_INLINE_CONTAINER) {
					/* Box is a block level element */
					containing_block = box->parent;
				} else if (box->parent && box->parent->type ==
						BOX_INLINE_CONTAINER) {
					/* Box is an inline block */
					assert(box->parent->parent);
					containing_block = box->parent->parent;
				}

				if (containing_block) {
					css_fixed f = 0;
					css_unit u = CSS_UNIT_PX;

					cbhtype = css_computed_height(
							containing_block->style,
							&f, &u);
				}

				if (containing_block &&
					containing_block->height != AUTO &&
					(css_computed_position(box->style) ==
							CSS_POSITION_ABSOLUTE ||
						cbhtype == CSS_HEIGHT_SET)) {
					/* Box is absolutely positioned or its
					 * containing block has a valid
					 * specified height.
					 * (CSS 2.1 Section 10.5) */
					*height = FPCT_OF_INT_TOINT(value,
						containing_block->height);
				} else if ((!box->parent ||
						!box->parent->parent) &&
						viewport_height >= 0) {
					/* If root element or it's child
					 * (HTML or BODY) */
					*height = FPCT_OF_INT_TOINT(value,
							viewport_height);
				} else {
					/* precentage height not permissible
					 * treat height as auto */
					*height = AUTO;
				}
			} else {
				*height = FIXTOINT(nscss_len2px(value, unit,
						style));
			}
		} else {
			*height = AUTO;
		}

		/* specified gadget heights include borders and padding in
		 * some cases */
		if (box->gadget && *height != AUTO) {
			percentage = unit == CSS_UNIT_PCT;

			layout_tweak_form_dimensions(box, percentage,
					available_width, false, height);
		}
	}

	if (max_width) {
		enum css_max_width_e type;
		css_fixed value = 0;
		css_unit unit = CSS_UNIT_PX;

		type = css_computed_max_width(style, &value, &unit);

		if (type == CSS_MAX_WIDTH_SET) {
			if (unit == CSS_UNIT_PCT) {
				*max_width = FPCT_OF_INT_TOINT(value,
						available_width);
			} else {
				*max_width = FIXTOINT(nscss_len2px(value, unit,
						style));
			}
		} else {
			/* Inadmissible */
			*max_width = -1;
		}

		/* specified gadget widths include borders and padding in some
		 * cases */
		if (box->gadget && *max_width != -1) {
			percentage = unit == CSS_UNIT_PCT;

			layout_tweak_form_dimensions(box, percentage,
					available_width, true, max_width);
		}
	}

	if (min_width) {
		enum css_min_width_e type;
		css_fixed value = 0;
		css_unit unit = CSS_UNIT_PX;

		type = css_computed_min_width(style, &value, &unit);

		if (type == CSS_MIN_WIDTH_SET) {
			if (unit == CSS_UNIT_PCT) {
				*min_width = FPCT_OF_INT_TOINT(value,
						available_width);
			} else {
				*min_width = FIXTOINT(nscss_len2px(value, unit,
						style));
			}
		} else {
			/* Inadmissible */
			*min_width = 0;
		}

		/* specified gadget widths include borders and padding in some
		 * cases */
		if (box->gadget && *min_width != 0) {
			percentage = unit == CSS_UNIT_PCT;

			layout_tweak_form_dimensions(box, percentage,
					available_width, true, min_width);
		}
	}

	for (i = 0; i != 4; i++) {
		if (margin) {
			enum css_margin_e type = CSS_MARGIN_AUTO;
			css_fixed value = 0;
			css_unit unit = CSS_UNIT_PX;

			switch (i) {
			case TOP:
				type = css_computed_margin_top(style,
						&value, &unit);
				break;
			case RIGHT:
				type = css_computed_margin_right(style,
						&value, &unit);
				break;
			case BOTTOM:
				type = css_computed_margin_bottom(style,
						&value, &unit);
				break;
			case LEFT:
				type = css_computed_margin_left(style,
						&value, &unit);
				break;
			}

			if (type == CSS_MARGIN_SET) {
				if (unit == CSS_UNIT_PCT) {
					margin[i] = FPCT_OF_INT_TOINT(value,
							available_width);
				} else {
					margin[i] = FIXTOINT(nscss_len2px(value,
							unit, style));
				}
			} else {
				margin[i] = AUTO;
			}
		}

		if (padding) {
			css_fixed value = 0;
			css_unit unit = CSS_UNIT_PX;

			switch (i) {
			case TOP:
				css_computed_padding_top(style, &value, &unit);
				break;
			case RIGHT:
				css_computed_padding_right(style, &value,
						&unit);
				break;
			case BOTTOM:
				css_computed_padding_bottom(style, &value,
						&unit);
				break;
			case LEFT:
				css_computed_padding_left(style, &value, &unit);
				break;
			}

			if (unit == CSS_UNIT_PCT) {
				padding[i] = FPCT_OF_INT_TOINT(value,
						available_width);
			} else {
				padding[i] = FIXTOINT(nscss_len2px(value, unit,
						style));
			}
		}

		/* Table cell borders are populated in table.c */
		if (border && box->type != BOX_TABLE_CELL) {
			enum css_border_style_e bstyle = CSS_BORDER_STYLE_NONE;
			css_color color = 0;
			css_fixed value = 0;
			css_unit unit = CSS_UNIT_PX;

			switch (i) {
			case TOP:
				css_computed_border_top_width(style, &value,
						&unit);
				bstyle = css_computed_border_top_style(style);
				css_computed_border_top_color(style, &color);
				break;
			case RIGHT:
				css_computed_border_right_width(style, &value,
						&unit);
				bstyle = css_computed_border_right_style(style);
				css_computed_border_right_color(style, &color);
				break;
			case BOTTOM:
				css_computed_border_bottom_width(style, &value,
						&unit);
				bstyle = css_computed_border_bottom_style(
						style);
				css_computed_border_bottom_color(style, &color);
				break;
			case LEFT:
				css_computed_border_left_width(style, &value,
						&unit);
				bstyle = css_computed_border_left_style(style);
				css_computed_border_left_color(style, &color);
				break;
			}

			border[i].style = bstyle;
			border[i].c = color;

			if (bstyle == CSS_BORDER_STYLE_HIDDEN ||
					bstyle == CSS_BORDER_STYLE_NONE)
				/* spec unclear: following Mozilla */
				border[i].width = 0;
			else
				border[i].width = FIXTOINT(nscss_len2px(value,
						unit, style));

			/* Special case for border-collapse: make all borders
			 * on table/table-row-group/table-row zero width. */
			if (css_computed_border_collapse(style) ==
					CSS_BORDER_COLLAPSE_COLLAPSE &&
					(box->type == BOX_TABLE ||
					 box->type == BOX_TABLE_ROW_GROUP ||
					 box->type == BOX_TABLE_ROW))
				border[i].width = 0;
		}
	}
}


/**
 * Under some circumstances, specified dimensions for form elements include
 * borders and padding.
 *
 * \param  box		    gadget to adjust dimensions of
 * \param  percentage	    whether the gadget has its dimension specified as a
 *				percentage
 * \param  available_width  width of containing block
 * \param  setwidth	    set true if the dimension to be tweaked is a width,
 *				else set false for a height
 * \param  dimension	    current value for given width/height dimension.
 *				updated to new value after consideration of
 *				gadget properties.
 */

void layout_tweak_form_dimensions(struct box *box, bool percentage,
		int available_width, bool setwidth, int *dimension)
{
	int fixed = 0;
	float frac = 0;

	assert(box && box->gadget);

	/* specified gadget widths include borders and padding in some
	 * cases */
	if (percentage || box->gadget->type == GADGET_SUBMIT ||
			box->gadget->type == GADGET_RESET ||
			box->gadget->type == GADGET_BUTTON) {
		calculate_mbp_width(box->style, setwidth ? LEFT : TOP,
				false, true, true, &fixed, &frac);
		calculate_mbp_width(box->style, setwidth ? RIGHT : BOTTOM,
				false, true, true, &fixed, &frac);
		*dimension -= frac * available_width + fixed;
		*dimension = *dimension > 0 ? *dimension : 0;
	}
}


/**
 * Find y coordinate which clears all floats on left and/or right.
 *
 * \param  fl	  first float in float list
 * \param  clear  type of clear
 * \return  y coordinate relative to ancestor box for floats
 */

int layout_clear(struct box *fl, enum css_clear_e clear)
{
	int y = 0;
	for (; fl; fl = fl->next_float) {
		if ((clear == CSS_CLEAR_LEFT || clear == CSS_CLEAR_BOTH) &&
				fl->type == BOX_FLOAT_LEFT)
			if (y < fl->y + fl->height)
				y = fl->y + fl->height;
		if ((clear == CSS_CLEAR_RIGHT || clear == CSS_CLEAR_BOTH) &&
				fl->type == BOX_FLOAT_RIGHT)
			if (y < fl->y + fl->height)
				y = fl->y + fl->height;
	}
	return y;
}


/**
 * Find left and right edges in a vertical range.
 *
 * \param  fl	  first float in float list
 * \param  y0	  start of y range to search
 * \param  y1	  end of y range to search
 * \param  x0	  start left edge, updated to available left edge
 * \param  x1	  start right edge, updated to available right edge
 * \param  left	  returns float on left if present
 * \param  right  returns float on right if present
 */

void find_sides(struct box *fl, int y0, int y1,
		int *x0, int *x1, struct box **left, struct box **right)
{
	int fy0, fy1, fx0, fx1;

#ifdef LAYOUT_DEBUG
	LOG(("y0 %i, y1 %i, x0 %i, x1 %i", y0, y1, *x0, *x1));
#endif

	*left = *right = 0;
	for (; fl; fl = fl->next_float) {
		fy0 = fl->y;
		fy1 = fl->y + fl->height;
		if (y0 < fy1 && fy0 <= y1) {
			if (fl->type == BOX_FLOAT_LEFT) {
				fx1 = fl->x + fl->width;
				if (*x0 < fx1) {
					*x0 = fx1;
					*left = fl;
				}
			} else if (fl->type == BOX_FLOAT_RIGHT) {
				fx0 = fl->x;
				if (fx0 < *x1) {
					*x1 = fx0;
					*right = fl;
				}
			}
		}
	}

#ifdef LAYOUT_DEBUG
	LOG(("x0 %i, x1 %i, left %p, right %p", *x0, *x1, *left, *right));
#endif
}


/**
 * Layout lines of text or inline boxes with floats.
 *
 * \param  box	  inline container
 * \param  width  horizontal space available
 * \param  cont	  ancestor box which defines horizontal space, for floats
 * \param  cx	  box position relative to cont
 * \param  cy	  box position relative to cont
 * \param  content  memory pool for any new boxes
 * \return  true on success, false on memory exhaustion
 */

bool layout_inline_container(struct box *inline_container, int width,
		struct box *cont, int cx, int cy, html_content *content)
{
	bool first_line = true;
	bool has_text_children;
	struct box *c, *next;
	int y = 0;
	int curwidth,maxwidth = width;

	assert(inline_container->type == BOX_INLINE_CONTAINER);

#ifdef LAYOUT_DEBUG
	LOG(("inline_container %p, width %i, cont %p, cx %i, cy %i",
			inline_container, width, cont, cx, cy));
#endif

	has_text_children = false;
	for (c = inline_container->children; c; c = c->next) {
		bool is_pre = false;

		if (c->style) {
			enum css_white_space_e whitespace;

			whitespace = css_computed_white_space(c->style);

			is_pre = (whitespace == CSS_WHITE_SPACE_PRE ||
				whitespace == CSS_WHITE_SPACE_PRE_LINE ||
				whitespace == CSS_WHITE_SPACE_PRE_WRAP);
		}

		if ((!c->object && !(c->flags & REPLACE_DIM) && c->text &&
				(c->length || is_pre)) ||
				c->type == BOX_BR)
			has_text_children = true;
	}

	/** \todo fix wrapping so that a box with horizontal scrollbar will
	 * shrink back to 'width' if no word is wider than 'width' (Or just set
	 * curwidth = width and have the multiword lines wrap to the min width)
	 */
	for (c = inline_container->children; c; ) {
#ifdef LAYOUT_DEBUG
		LOG(("c %p", c));
#endif
		curwidth = inline_container->width;
		if (!layout_line(c, &curwidth, &y, cx, cy + y, cont, first_line,
				has_text_children, content, &next))
			return false;
		maxwidth = max(maxwidth,curwidth);
		c = next;
		first_line = false;
	}

	inline_container->width = maxwidth;
	inline_container->height = y;

	return true;
}


/**
 * Calculate minimum and maximum width of an inline container.
 *
 * \param  inline_container  box of type INLINE_CONTAINER
 * \post  inline_container->min_width and inline_container->max_width filled in,
 *        0 <= inline_container->min_width <= inline_container->max_width
 */

void layout_minmax_inline_container(struct box *inline_container,
		bool *has_height, const struct font_functions *font_func)
{
	struct box *child;
	int line_min = 0, line_max = 0;
	int min = 0, max = 0;
	bool first_line = true;
	bool line_has_height;

	assert(inline_container->type == BOX_INLINE_CONTAINER);

	/* check if the widths have already been calculated */
	if (inline_container->max_width != UNKNOWN_MAX_WIDTH)
		return;

	*has_height = false;

	for (child = inline_container->children; child; ) {
		child = layout_minmax_line(child, &line_min, &line_max,
				first_line, &line_has_height, font_func);
		if (min < line_min)
			min = line_min;
		if (max < line_max)
			max = line_max;
		first_line = false;
		*has_height |= line_has_height;
        }

	inline_container->min_width = min;
	inline_container->max_width = max;

	assert(0 <= inline_container->min_width &&
			inline_container->min_width <=
			inline_container->max_width);
}


/**
 * Calculate line height from a style.
 */

int line_height(const css_computed_style *style)
{
	enum css_line_height_e lhtype;
	css_fixed lhvalue = 0;
	css_unit lhunit = CSS_UNIT_PX;
	css_fixed line_height;

	assert(style);

	lhtype = css_computed_line_height(style, &lhvalue, &lhunit);
	if (lhtype == CSS_LINE_HEIGHT_NORMAL) {
		/* Normal => use a constant of 1.3 * font-size */
		lhvalue = FLTTOFIX(1.3);
		lhtype = CSS_LINE_HEIGHT_NUMBER;
	}

	if (lhtype == CSS_LINE_HEIGHT_NUMBER ||
			lhunit == CSS_UNIT_PCT) {
		line_height = nscss_len2px(lhvalue, CSS_UNIT_EM, style);

		if (lhtype != CSS_LINE_HEIGHT_NUMBER)
			line_height = FDIV(line_height, F_100);
	} else {
		assert(lhunit != CSS_UNIT_PCT);

		line_height = nscss_len2px(lhvalue, lhunit, style);
	}

	return FIXTOINT(line_height);
}


/**
 * Split a text box.
 *
 * \param  content     memory pool for any new boxes
 * \param  fstyle      style for text in text box
 * \param  split_box   box with text to split
 * \param  new_length  new length for text in split_box, after splitting
 * \param  new_width   new width for text in split_box, after splitting
 * \return  true on success, false on memory exhaustion
 *
 * A new box is created and inserted into the box tree after split_box,
 * containing the text after new_length excluding the initial space character.
 */

static bool layout_text_box_split(html_content *content,
		plot_font_style_t *fstyle, struct box *split_box,
		size_t new_length, int new_width)
{
	int space_width = split_box->space;
	struct box *c2;
	const struct font_functions *font_func = content->font_func;

	if (space_width == 0) {
		/* Currently split_box has no space. */
		/* Get the space width because the split_box will need it */
		/* Don't set it in split_box yet, or it will get cloned. */
		font_func->font_width(fstyle, " ", 1, &space_width);
	} else if (space_width == UNKNOWN_WIDTH) {
		/* Split_box has a space but its width is unknown. */
		/* Get the space width because the split_box will need it */
		/* Set it in split_box, so it gets cloned. */
		font_func->font_width(fstyle, " ", 1, &space_width);
		split_box->space = space_width;
	}

	/* Create clone of split_box, c2 */
	c2 = talloc_memdup(content, split_box, sizeof *c2);
	if (!c2)
		return false;
	c2->flags |= CLONE;

	/* Set remaining text in c2 */
	if (split_box->parent->parent->gadget != NULL) {
		/* Inside a form text input / textarea, special case */
		/* TODO: Move text inputs to core textarea widget and remove
		 *       this */
		c2->text = talloc_strndup(content,
				split_box->text + new_length + 1,
				split_box->length - (new_length + 1));
		if (!c2->text)
			return false;
	} else {
		c2->text += new_length + 1;
	}

	/* Set c2 according to the remaining text */
	c2->width -= new_width + space_width;
	c2->flags &= ~MEASURED; /* width has been estimated */
	c2->length = split_box->length - (new_length + 1);

	/* Update split_box for its reduced text */
	split_box->width = new_width;
	split_box->flags |= MEASURED;
	split_box->length = new_length;
	split_box->space = space_width;

	/* Insert c2 into box list */
	c2->next = split_box->next;
	split_box->next = c2;
	c2->prev = split_box;
	if (c2->next)
		c2->next->prev = c2;
	else
		c2->parent->last = c2;

	return true;
}


/**
 * Position a line of boxes in inline formatting context.
 *
 * \param  first   box at start of line
 * \param  width   available width on input, updated with actual width on output
 *                 (may be incorrect if the line gets split?)
 * \param  y	   coordinate of top of line, updated on exit to bottom
 * \param  cx	   coordinate of left of line relative to cont
 * \param  cy	   coordinate of top of line relative to cont
 * \param  cont	   ancestor box which defines horizontal space, for floats
 * \param  indent  apply any first-line indent
 * \param  has_text_children  at least one TEXT in the inline_container
 * \param  next_box  updated to first box for next line, or 0 at end
 * \param  content  memory pool for any new boxes
 * \return  true on success, false on memory exhaustion
 */

bool layout_line(struct box *first, int *width, int *y,
		int cx, int cy, struct box *cont, bool indent,
		bool has_text_children,
		html_content *content, struct box **next_box)
{
	int height, used_height;
	int x0 = 0;
	int x1 = *width;
	int x, h, x_previous;
	int fy = cy;
	struct box *left;
	struct box *right;
	struct box *b;
	struct box *split_box = 0;
	struct box *d;
	struct box *br_box = 0;
	bool move_y = false;
	bool place_below = false;
	int space_before = 0, space_after = 0;
	unsigned int inline_count = 0;
	unsigned int i;
	const struct font_functions *font_func = content->font_func;
	plot_font_style_t fstyle;

#ifdef LAYOUT_DEBUG
	LOG(("first %p, first->text '%.*s', width %i, y %i, cx %i, cy %i",
			first, (int) first->length, first->text, *width,
			*y, cx, cy));
#endif

	/* find sides at top of line */
	x0 += cx;
	x1 += cx;
	find_sides(cont->float_children, cy, cy, &x0, &x1, &left, &right);
	x0 -= cx;
	x1 -= cx;

	if (indent)
		x0 += layout_text_indent(first->parent->parent->style, *width);

	if (x1 < x0)
		x1 = x0;

	/* get minimum line height from containing block.
	 * this is the line-height if there are text children and also in the
	 * case of an initially empty text input */
	if (has_text_children || first->parent->parent->gadget)
		used_height = height =
				line_height(first->parent->parent->style);
	else
		/* inline containers with no text are usually for layout and
		 * look better with no minimum line-height */
		used_height = height = 0;

	/* pass 1: find height of line assuming sides at top of line: loop
	 * body executed at least once
	 * keep in sync with the loop in layout_minmax_line() */
#ifdef LAYOUT_DEBUG
	LOG(("x0 %i, x1 %i, x1 - x0 %i", x0, x1, x1 - x0));
#endif

	for (x = 0, b = first; x <= x1 - x0 && b != 0; b = b->next) {
		enum css_width_e wtype;
		enum css_height_e htype;
		css_fixed value = 0;
		css_unit unit = CSS_UNIT_PX;

		assert(b->type == BOX_INLINE || b->type == BOX_INLINE_BLOCK ||
				b->type == BOX_FLOAT_LEFT ||
				b->type == BOX_FLOAT_RIGHT ||
				b->type == BOX_BR || b->type == BOX_TEXT ||
				b->type == BOX_INLINE_END);

#ifdef LAYOUT_DEBUG
		LOG(("pass 1: b %p, x %i", b, x));
#endif

		if (b->type == BOX_BR)
			break;

		if (b->type == BOX_FLOAT_LEFT || b->type == BOX_FLOAT_RIGHT)
			continue;
		if (b->type == BOX_INLINE_BLOCK &&
				(css_computed_position(b->style) ==
						CSS_POSITION_ABSOLUTE ||
				 css_computed_position(b->style) ==
						CSS_POSITION_FIXED))
			continue;

		assert(b->style != NULL);
		font_plot_style_from_css(b->style, &fstyle);

		x += space_after;

		if (b->type == BOX_INLINE_BLOCK) {
			if (b->max_width != UNKNOWN_WIDTH)
				if (!layout_float(b, *width, content))
					return false;
			h = b->border[TOP].width + b->padding[TOP] + b->height +
					b->padding[BOTTOM] +
					b->border[BOTTOM].width;
			if (height < h)
				height = h;
			x += b->margin[LEFT] + b->border[LEFT].width +
					b->padding[LEFT] + b->width +
					b->padding[RIGHT] +
					b->border[RIGHT].width +
					b->margin[RIGHT];
			space_after = 0;
			continue;
		}

		if (b->type == BOX_INLINE) {
			/* calculate borders, margins, and padding */
			layout_find_dimensions(*width, -1, b, b->style, 0, 0,
					0, 0, b->margin, b->padding, b->border);
			for (i = 0; i != 4; i++)
				if (b->margin[i] == AUTO)
					b->margin[i] = 0;
			x += b->margin[LEFT] + b->border[LEFT].width +
					b->padding[LEFT];
			if (b->inline_end) {
				b->inline_end->margin[RIGHT] = b->margin[RIGHT];
				b->inline_end->padding[RIGHT] =
						b->padding[RIGHT];
				b->inline_end->border[RIGHT] =
						b->border[RIGHT];
			} else {
				x += b->padding[RIGHT] +
						b->border[RIGHT].width +
						b->margin[RIGHT];
			}
		} else if (b->type == BOX_INLINE_END) {
			b->width = 0;
			if (b->space == UNKNOWN_WIDTH) {
				font_func->font_width(&fstyle, " ", 1,
						&b->space);
				/** \todo handle errors */
			}
			space_after = b->space;

			x += b->padding[RIGHT] + b->border[RIGHT].width +
					b->margin[RIGHT];
			continue;
		}

		if (!b->object && !b->gadget &&
				!(b->flags & REPLACE_DIM)) {
			/* inline non-replaced, 10.3.1 and 10.6.1 */
			b->height = line_height(b->style ? b->style :
					b->parent->parent->style);
			if (height < b->height)
				height = b->height;

			if (!b->text) {
				b->width = 0;
				space_after = 0;
				continue;
			}

			if (b->width == UNKNOWN_WIDTH) {
				/** \todo handle errors */

				/* If it's a select element, we must use the
				 * width of the widest option text */
				if (b->parent->parent->gadget &&
						b->parent->parent->gadget->type
						== GADGET_SELECT) {
					int opt_maxwidth = 0;
					struct form_option *o;

					for (o = b->parent->parent->gadget->
							data.select.items; o;
							o = o->next) {
						int opt_width;
						font_func->font_width(&fstyle,
								o->text,
								strlen(o->text),
								&opt_width);

						if (opt_maxwidth < opt_width)
							opt_maxwidth =opt_width;
					}
					b->width = opt_maxwidth;
					if (option_core_select_menu)
						b->width += SCROLLBAR_WIDTH;
				} else {
					font_func->font_width(&fstyle, b->text,
							b->length, &b->width);
					b->flags |= MEASURED;
				}
			}

			/* If the current text has not been measured (i.e. its
			 * width was estimated after splitting), and it fits on
			 * the line, measure it properly, so next box is placed
			 * correctly. */
			if (b->text && (x + b->width < x1 - x0) &&
					!(b->flags & MEASURED) &&
					b->next) {
				font_func->font_width(&fstyle, b->text,
						b->length, &b->width);
				b->flags |= MEASURED;
			}

			x += b->width;
			if (b->space == UNKNOWN_WIDTH) {
				font_func->font_width(&fstyle, " ", 1,
						&b->space);
				/** \todo handle errors */
			}
			space_after = b->space;
			continue;
		}

		space_after = 0;

		/* inline replaced, 10.3.2 and 10.6.2 */
		assert(b->style);

		/* calculate box width */
		wtype = css_computed_width(b->style, &value, &unit);
		if (wtype == CSS_WIDTH_SET) {
			if (unit == CSS_UNIT_PCT) {
				b->width = FPCT_OF_INT_TOINT(value, *width);
			} else {
				b->width = FIXTOINT(nscss_len2px(value, unit,
						b->style));
			}
		} else {
			b->width = AUTO;
		}

		/* height */
		htype = css_computed_height(b->style, &value, &unit);
		if (htype == CSS_HEIGHT_SET) {
			b->height = FIXTOINT(nscss_len2px(value, unit,
					b->style));
		} else {
			b->height = AUTO;
		}

		if (b->object && !(b->flags & REPLACE_DIM)) {
			layout_get_object_dimensions(b, &b->width, &b->height,
					true, true);
		} else {
			/* form control with no object */
			if (b->width == AUTO)
				b->width = FIXTOINT(nscss_len2px(INTTOFIX(1),
						CSS_UNIT_EM, b->style));
			if (b->height == AUTO)
				b->height = FIXTOINT(nscss_len2px(INTTOFIX(1),
						CSS_UNIT_EM, b->style));
		}

		if (b->object && content_get_type(b->object) == CONTENT_HTML &&
				b->width != 
				content_get_available_width(b->object)) {
			htype = css_computed_height(b->style, &value, &unit);

			content_reformat(b->object, b->width, b->height);

			if (htype == CSS_HEIGHT_AUTO)
				b->height = content_get_height(b->object);
		}

		if (height < b->height)
			height = b->height;

		x += b->width;
	}

	/* find new sides using this height */
	x0 = cx;
	x1 = cx + *width;
	find_sides(cont->float_children, cy, cy + height, &x0, &x1,
			&left, &right);
	x0 -= cx;
	x1 -= cx;

	if (indent)
		x0 += layout_text_indent(first->parent->parent->style, *width);

	if (x1 < x0)
		x1 = x0;

	space_after = space_before = 0;

	/* pass 2: place boxes in line: loop body executed at least once */
#ifdef LAYOUT_DEBUG
	LOG(("x0 %i, x1 %i, x1 - x0 %i", x0, x1, x1 - x0));
#endif

	for (x = x_previous = 0, b = first; x <= x1 - x0 && b; b = b->next) {
#ifdef LAYOUT_DEBUG
		LOG(("pass 2: b %p, x %i", b, x));
#endif

		if (b->type == BOX_INLINE_BLOCK &&
				(css_computed_position(b->style) ==
						CSS_POSITION_ABSOLUTE ||
				 css_computed_position(b->style) ==
						CSS_POSITION_FIXED)) {
			b->x = x + space_after;

		} else if (b->type == BOX_INLINE ||
				b->type == BOX_INLINE_BLOCK ||
				b->type == BOX_TEXT ||
				b->type == BOX_INLINE_END) {
			assert(b->width != UNKNOWN_WIDTH);

			x_previous = x;
			x += space_after;
			b->x = x;

			if ((b->type == BOX_INLINE && !b->inline_end) ||
					b->type == BOX_INLINE_BLOCK) {
				b->x += b->margin[LEFT] + b->border[LEFT].width;
				x = b->x + b->padding[LEFT] + b->width +
						b->padding[RIGHT] +
						b->border[RIGHT].width +
						b->margin[RIGHT];
			} else if (b->type == BOX_INLINE) {
				b->x += b->margin[LEFT] + b->border[LEFT].width;
				x = b->x + b->padding[LEFT] + b->width;
			} else if (b->type == BOX_INLINE_END) {
				b->height = b->inline_end->height;
				x += b->padding[RIGHT] +
						b->border[RIGHT].width +
						b->margin[RIGHT];
			} else {
				x += b->width;
			}

			space_before = space_after;
			if (b->object || b->flags & REPLACE_DIM)
				space_after = 0;
			else if (b->text || b->type == BOX_INLINE_END) {
				if (b->space == UNKNOWN_WIDTH) {
					font_plot_style_from_css(b->style,
							&fstyle);
					/** \todo handle errors */
					font_func->font_width(&fstyle, " ", 1,
							&b->space);
				}
				space_after = b->space;
			} else {
				space_after = 0;
			}
			split_box = b;
			move_y = true;
			inline_count++;
		} else if (b->type == BOX_BR) {
			b->x = x;
			b->width = 0;
			br_box = b;
			b = b->next;
			split_box = 0;
			move_y = true;
			break;

		} else {
			/* float */
#ifdef LAYOUT_DEBUG
			LOG(("float %p", b));
#endif

			d = b->children;
			d->float_children = 0;
			b->float_container = d->float_container = cont;

			if (!layout_float(d, *width, content))
				return false;

#ifdef LAYOUT_DEBUG
			LOG(("%p : %d %d", d, d->margin[TOP],
					d->border[TOP].width));
#endif

			d->x = d->margin[LEFT] + d->border[LEFT].width;
			d->y = d->margin[TOP] + d->border[TOP].width;
			b->width = d->margin[LEFT] + d->border[LEFT].width +
					d->padding[LEFT] + d->width +
					d->padding[RIGHT] +
					d->border[RIGHT].width +
					d->margin[RIGHT];
			b->height = d->margin[TOP] + d->border[TOP].width +
					d->padding[TOP] + d->height +
					d->padding[BOTTOM] +
					d->border[BOTTOM].width +
					d->margin[BOTTOM];

			if (b->width > (x1 - x0) - x)
				place_below = true;
			if (d->style && (css_computed_clear(d->style) ==
						CSS_CLEAR_NONE ||
					(css_computed_clear(d->style) ==
						CSS_CLEAR_LEFT && left == 0) ||
					(css_computed_clear(d->style) ==
						CSS_CLEAR_RIGHT &&
						right == 0) ||
					(css_computed_clear(d->style) ==
						CSS_CLEAR_BOTH &&
						left == 0 && right == 0)) &&
					(!place_below ||
					(left == 0 && right == 0 && x == 0)) &&
					cy >= cont->clear_level) {
				/* + not cleared or,
				 *   cleared and there are no floats to clear
				 * + fits without needing to be placed below or,
				 *   this line is empty with no floats
				 * + current y, cy, is below the clear level
				 *
				 * Float affects current line */
				if (b->type == BOX_FLOAT_LEFT) {
					b->x = cx + x0;
					if (b->width > 0)
						x0 += b->width;
					left = b;
				} else {
					b->x = cx + x1 - b->width;
					if (b->width > 0)
						x1 -= b->width;
					right = b;
				}
				b->y = cy;
			} else {
				/* cleared or doesn't fit on line */
				/* place below into next available space */
				int fcy = (cy > cont->clear_level) ? cy :
						cont->clear_level;
				fy = (fy > fcy) ? fy : fcy;
				fy = (fy == cy) ? fy + height : fy;

				place_float_below(b, *width, cx, fy, cont);
				fy = b->y;
				if (d->style && (
						(css_computed_clear(d->style) ==
						CSS_CLEAR_LEFT && left != 0) ||
						(css_computed_clear(d->style) ==
						CSS_CLEAR_RIGHT &&
						right != 0) ||
						(css_computed_clear(d->style) ==
						CSS_CLEAR_BOTH &&
						(left != 0 || right != 0)))) {
					/* to be cleared below existing
					 * floats */
					if (b->type == BOX_FLOAT_LEFT)
						b->x = cx;
					else
						b->x = cx + *width - b->width;

					fcy = layout_clear(cont->float_children,
						css_computed_clear(d->style));
					if (fcy > cont->clear_level)
						cont->clear_level = fcy;
					if (b->y < fcy)
						b->y = fcy;
				}
				if (b->type == BOX_FLOAT_LEFT)
					left = b;
				else
					right = b;
			}
			if (cont->float_children == b) {
#ifdef LAYOUT_DEBUG
				LOG(("float %p already placed", b));
#endif

				box_dump(stderr, cont, 0);
				assert(0);
			}
			b->next_float = cont->float_children;
			cont->float_children = b;
			split_box = 0;
		}
	}

	if (x1 - x0 < x && split_box) {
		/* the last box went over the end */
		unsigned int i;
		size_t space = 0;
		int w;

		x = x_previous;

		if ((split_box->type == BOX_INLINE ||
				split_box->type == BOX_TEXT) &&
				!split_box->object &&
				!(split_box->flags & REPLACE_DIM) &&
				!split_box->gadget && split_box->text) {
			/* skip leading spaces, otherwise code gets fooled into
			 * thinking it's all one long word */
			for (i = 0; i != split_box->length &&
					split_box->text[i] == ' '; i++)
				;
			/* find end of word */
			for (; i != split_box->length &&
					split_box->text[i] != ' '; i++)
				;
			if (i != split_box->length)
				space = i;
		}

		/* space != 0 implies split_box->text != 0 */

		if (space == 0)
			w = split_box->width;
		else {
			font_plot_style_from_css(split_box->style, &fstyle);
			/** \todo handle errors */
			font_func->font_width(&fstyle, split_box->text,
					space, &w);
		}

#ifdef LAYOUT_DEBUG
		LOG(("splitting: split_box %p \"%.*s\", space %zu, w %i, "
				"left %p, right %p, inline_count %u",
				split_box, (int) split_box->length,
				split_box->text, space, w,
				left, right, inline_count));
#endif

		if ((space == 0 || x1 - x0 <= x + space_before + w) &&
				!left && !right && inline_count == 1) {
			/* first word of box doesn't fit, but no floats and
			 * first box on line so force in */
			if (space == 0) {
				/* only one word in this box or not text */
				b = split_box->next;
			} else {
				/* cut off first word for this line */
				if (!layout_text_box_split(content, &fstyle,
						split_box, space, w))
					return false;
				b = split_box->next;
			}
			x += space_before + w;
#ifdef LAYOUT_DEBUG
			LOG(("forcing"));
#endif
		} else if ((space == 0 || x1 - x0 <= x + space_before + w) &&
				inline_count == 1) {
			/* first word of first box doesn't fit, but a float is
			 * taking some of the width so move below it */
			assert(left || right);
			used_height = 0;
			if (left) {
#ifdef LAYOUT_DEBUG
				LOG(("cy %i, left->y %i, left->height %i",
						cy, left->y, left->height));
#endif
				used_height = left->y + left->height - cy + 1;
#ifdef LAYOUT_DEBUG
				LOG(("used_height %i", used_height));
#endif
			}
			if (right && used_height <
					right->y + right->height - cy + 1)
				used_height = right->y + right->height - cy + 1;
			assert(0 < used_height);
			b = split_box;
#ifdef LAYOUT_DEBUG
			LOG(("moving below float"));
#endif
                } else if (space == 0 || x1 - x0 <= x + space_before + w) {
                	/* first word of box doesn't fit so leave box for next
                	 * line */
			b = split_box;
#ifdef LAYOUT_DEBUG
			LOG(("leaving for next line"));
#endif
		} else {
			/* fit as many words as possible */
			assert(space != 0);
			font_plot_style_from_css(split_box->style, &fstyle);
			/** \todo handle errors */
			font_func->font_split(&fstyle,
					split_box->text, split_box->length,
					x1 - x0 - x - space_before, &space, &w);
#ifdef LAYOUT_DEBUG
			LOG(("'%.*s' %i %zu %i", (int) split_box->length,
					split_box->text, x1 - x0, space, w));
#endif
			if (space == 0)
				space = 1;
			if (space != split_box->length) {
				if (!layout_text_box_split(content, &fstyle,
						split_box, space, w))
					return false;
				b = split_box->next;
			}
			x += space_before + w;
#ifdef LAYOUT_DEBUG
			LOG(("fitting words"));
#endif
		}
		move_y = true;
	}

	/* set positions */
	switch (css_computed_text_align(first->parent->parent->style)) {
	case CSS_TEXT_ALIGN_RIGHT:
	case CSS_TEXT_ALIGN_LIBCSS_RIGHT:
		x0 = x1 - x;
		break;
	case CSS_TEXT_ALIGN_CENTER:
	case CSS_TEXT_ALIGN_LIBCSS_CENTER:
		x0 = (x0 + (x1 - x)) / 2;
		break;
	case CSS_TEXT_ALIGN_LEFT:
	case CSS_TEXT_ALIGN_LIBCSS_LEFT:
	case CSS_TEXT_ALIGN_JUSTIFY:
		/* leave on left */
		break;
	case CSS_TEXT_ALIGN_DEFAULT:
		/* None; consider text direction */
		switch (css_computed_direction(first->parent->parent->style)) {
		case CSS_DIRECTION_LTR:
			/* leave on left */
			break;
		case CSS_DIRECTION_RTL:
			x0 = x1 - x;
			break;
		}
		break;
	}

	for (d = first; d != b; d = d->next) {
		d->flags &= ~NEW_LINE;

		if (d->type == BOX_INLINE_BLOCK &&
				(css_computed_position(d->style) ==
						CSS_POSITION_ABSOLUTE ||
				 css_computed_position(d->style) ==
						CSS_POSITION_FIXED)) {
			/* positioned inline-blocks:
			 * set static position (x,y) only, rest of positioning
			 * is handled later */
			d->x += x0;
			d->y = *y;
			continue;
		} else if ((d->type == BOX_INLINE &&
				((d->object || d->gadget) == false) &&
				!(d->flags & REPLACE_DIM)) ||
				d->type == BOX_BR ||
				d->type == BOX_TEXT ||
				d->type == BOX_INLINE_END) {
			/* regular (non-replaced) inlines */
			d->x += x0;
			d->y = *y - d->padding[TOP];

			if (d->type == BOX_TEXT && d->height > used_height) {
				/* text */
				used_height = d->height;
			}
		} else if ((d->type == BOX_INLINE) ||
				d->type == BOX_INLINE_BLOCK) {
			/* replaced inlines and inline-blocks */
			d->x += x0;
			d->y = *y + d->border[TOP].width + d->margin[TOP];
			h = d->margin[TOP] + d->border[TOP].width +
					d->padding[TOP] + d->height +
					d->padding[BOTTOM] +
					d->border[BOTTOM].width +
					d->margin[BOTTOM];
			if (used_height < h)
				used_height = h;
		}
	}

	first->flags |= NEW_LINE;

	assert(b != first || (move_y && 0 < used_height && (left || right)));

	/* handle vertical-align by adjusting box y values */
	/** \todo  proper vertical alignment handling */
	for (d = first; d != b; d = d->next) {
		if ((d->type == BOX_INLINE && d->inline_end) ||
				d->type == BOX_BR ||
				d->type == BOX_TEXT ||
				d->type == BOX_INLINE_END) {
			css_fixed value = 0;
			css_unit unit = CSS_UNIT_PX;
			switch (css_computed_vertical_align(d->style, &value,
					&unit)) {
			case CSS_VERTICAL_ALIGN_SUPER:
			case CSS_VERTICAL_ALIGN_TOP:
			case CSS_VERTICAL_ALIGN_TEXT_TOP:
				/* already at top */
				break;
			case CSS_VERTICAL_ALIGN_SUB:
			case CSS_VERTICAL_ALIGN_BOTTOM:
			case CSS_VERTICAL_ALIGN_TEXT_BOTTOM:
				d->y += used_height - d->height;
				break;
			default:
			case CSS_VERTICAL_ALIGN_BASELINE:
				d->y += 0.75 * (used_height - d->height);
				break;
			}
		}
	}

	/* handle clearance for br */
	if (br_box && css_computed_clear(br_box->style) != CSS_CLEAR_NONE) {
		int clear_y = layout_clear(cont->float_children,
				css_computed_clear(br_box->style));
		if (used_height < clear_y - cy)
			used_height = clear_y - cy;
	}

	if (move_y)
		*y += used_height;
	*next_box = b;
	*width = x; /* return actual width */
	return true;
}


/**
 * Calculate minimum and maximum width of a line.
 *
 * \param  first       a box in an inline container
 * \param  line_min    updated to minimum width of line starting at first
 * \param  line_max    updated to maximum width of line starting at first
 * \param  first_line  true iff this is the first line in the inline container
 * \param  line_has_height  updated to true or false, depending on line
 * \return  first box in next line, or 0 if no more lines
 * \post  0 <= *line_min <= *line_max
 */

struct box *layout_minmax_line(struct box *first,
		int *line_min, int *line_max, bool first_line,
  		bool *line_has_height, const struct font_functions *font_func)
{
	int min = 0, max = 0, width, height, fixed;
	float frac;
	size_t i, j;
	struct box *b;
	plot_font_style_t fstyle;

	assert(first->parent);
	assert(first->parent->parent);
	assert(first->parent->parent->style);

	*line_has_height = false;

	/* corresponds to the pass 1 loop in layout_line() */
	for (b = first; b; b = b->next) {
		enum css_width_e wtype;
		enum css_height_e htype;
		css_fixed value = 0;
		css_unit unit = CSS_UNIT_PX;

		assert(b->type == BOX_INLINE || b->type == BOX_INLINE_BLOCK ||
				b->type == BOX_FLOAT_LEFT ||
				b->type == BOX_FLOAT_RIGHT ||
				b->type == BOX_BR || b->type == BOX_TEXT ||
				b->type == BOX_INLINE_END);

#ifdef LAYOUT_DEBUG
		LOG(("%p: min %i, max %i", b, min, max));
#endif

		if (b->type == BOX_BR) {
			b = b->next;
			break;
		}

		if (b->type == BOX_FLOAT_LEFT || b->type == BOX_FLOAT_RIGHT) {
			assert(b->children);
			if (b->children->type == BOX_BLOCK)
				layout_minmax_block(b->children, font_func);
			else
				layout_minmax_table(b->children, font_func);
			b->min_width = b->children->min_width;
			b->max_width = b->children->max_width;
			if (min < b->min_width)
				min = b->min_width;
			max += b->max_width;
			continue;
		}

		if (b->type == BOX_INLINE_BLOCK) {
			layout_minmax_block(b, font_func);
			if (min < b->min_width)
				min = b->min_width;
			max += b->max_width;

			if (b->flags & HAS_HEIGHT)
				*line_has_height = true;
			continue;
		}

		assert(b->style);
		font_plot_style_from_css(b->style, &fstyle);

		if (b->type == BOX_INLINE && !b->object &&
				!(b->flags & REPLACE_DIM)) {
			fixed = frac = 0;
			calculate_mbp_width(b->style, LEFT, true, true, true,
					&fixed, &frac);
			if (!b->inline_end)
				calculate_mbp_width(b->style, RIGHT,
						true, true, true,
						&fixed, &frac);
			if (0 < fixed)
				max += fixed;
			*line_has_height = true;
			/* \todo  update min width, consider fractional extra */
		} else if (b->type == BOX_INLINE_END) {
			fixed = frac = 0;
			calculate_mbp_width(b->inline_end->style, RIGHT,
					true, true, true,
					&fixed, &frac);
			if (0 < fixed)
				max += fixed;
			if (b->next && b->space == UNKNOWN_WIDTH) {
				font_func->font_width(&fstyle, " ", 1,
						&b->space);
				max += b->space;
			}
			*line_has_height = true;
			continue;
		}

		if (!b->object && !b->gadget &&
				!(b->flags & REPLACE_DIM)) {
			/* inline non-replaced, 10.3.1 and 10.6.1 */
			if (!b->text)
				continue;

			if (b->width == UNKNOWN_WIDTH) {
				/** \todo handle errors */

				/* If it's a select element, we must use the
				 * width of the widest option text */
				if (b->parent->parent->gadget &&
						b->parent->parent->gadget->type
						== GADGET_SELECT) {
					int opt_maxwidth = 0;
					struct form_option *o;

					for (o = b->parent->parent->gadget->
							data.select.items; o;
							o = o->next) {
						int opt_width;
						font_func->font_width(&fstyle,
								o->text,
								strlen(o->text),
								&opt_width);

						if (opt_maxwidth < opt_width)
							opt_maxwidth =opt_width;
					}

					b->width = opt_maxwidth;
					if (option_core_select_menu)
						b->width += SCROLLBAR_WIDTH;

				} else {
					font_func->font_width(&fstyle, b->text,
						b->length, &b->width);
					b->flags |= MEASURED;
				}
			}
			max += b->width;
			if (b->next && b->space == UNKNOWN_WIDTH) {
				font_func->font_width(&fstyle, " ", 1,
						&b->space);
				max += b->space;
			}

			/* min = widest word */
			if (b->parent->flags & NEED_MIN) {
				/* If we care what the minimum width is,
				 * calculate it.  (It's only needed if we're
				 * shrinking-to-fit.) */
				i = 0;
				do {
					for (j = i; j != b->length &&
							b->text[j] != ' '; j++)
						;
					font_func->font_width(&fstyle,
							b->text + i,
							j - i, &width);
					if (min < width)
						min = width;
					i = j + 1;
				} while (j != b->length);
			}

			*line_has_height = true;

			continue;
		}

		/* inline replaced, 10.3.2 and 10.6.2 */
		assert(b->style);

		/* calculate box width */
		wtype = css_computed_width(b->style, &value, &unit);
		if (wtype == CSS_WIDTH_SET) {
			if (unit == CSS_UNIT_PCT) {
				/*
				b->width = FPCT_OF_INT_TOINT(value, width);
				*/

				width = AUTO;
			} else {
				width = FIXTOINT(nscss_len2px(value, unit,
						b->style));
				if (width < 0)
					width = 0;
			}
		} else {
			width = AUTO;
		}

		/* height */
		htype = css_computed_height(b->style, &value, &unit);
		if (htype == CSS_HEIGHT_SET) {
			height = FIXTOINT(nscss_len2px(value, unit, b->style));
		} else {
			height = AUTO;
		}

		if (b->object || (b->flags & REPLACE_DIM)) {
			if (b->object) {
				layout_get_object_dimensions(b, &width, &height,
						true, false);
			}

			fixed = frac = 0;
			calculate_mbp_width(b->style, LEFT, true, true, true,
					&fixed, &frac);
			calculate_mbp_width(b->style, RIGHT, true, true, true,
					&fixed, &frac);

			if (0 < width + fixed)
				width += fixed;
		} else {
			/* form control with no object */
			if (width == AUTO)
				width = FIXTOINT(nscss_len2px(INTTOFIX(1),
						CSS_UNIT_EM, b->style));
		}

		if (min < width)
			min = width;
		max += width;

		*line_has_height = true;
	}

	if (first_line) {
		/* todo: handle percentage values properly */
		/* todo: handle text-indent interaction with floats */
		int text_indent = layout_text_indent(
				first->parent->parent->style, 100);
		min = (min + text_indent < 0) ? 0 : min + text_indent;
		max = (max + text_indent < 0) ? 0 : max + text_indent;
	}

	*line_min = min;
	*line_max = max;

#ifdef LAYOUT_DEBUG
	LOG(("line_min %i, line_max %i", min, max));
#endif

	assert(b != first);
	assert(0 <= *line_min && *line_min <= *line_max);
	return b;
}


/**
 * Calculate the text-indent length.
 *
 * \param  style  style of block
 * \param  width  width of containing block
 * \return  length of indent
 */

int layout_text_indent(const css_computed_style *style, int width)
{
	css_fixed value = 0;
	css_unit unit = CSS_UNIT_PX;

	css_computed_text_indent(style, &value, &unit);

	if (unit == CSS_UNIT_PCT) {
		return FPCT_OF_INT_TOINT(value, width);
	} else {
		return FIXTOINT(nscss_len2px(value, unit, style));
	}
}


/**
 * Layout the contents of a float or inline block.
 *
 * \param  b	  float or inline block box
 * \param  width  available width
 * \param  content  memory pool for any new boxes
 * \return  true on success, false on memory exhaustion
 */

bool layout_float(struct box *b, int width, html_content *content)
{
	assert(b->type == BOX_TABLE || b->type == BOX_BLOCK ||
			b->type == BOX_INLINE_BLOCK);
	layout_float_find_dimensions(width, b->style, b);
	if (b->type == BOX_TABLE) {
		if (!layout_table(b, width, content))
			return false;
		if (b->margin[LEFT] == AUTO)
			b->margin[LEFT] = 0;
		if (b->margin[RIGHT] == AUTO)
			b->margin[RIGHT] = 0;
		if (b->margin[TOP] == AUTO)
			b->margin[TOP] = 0;
		if (b->margin[BOTTOM] == AUTO)
			b->margin[BOTTOM] = 0;
	} else
		return layout_block_context(b, -1, content);
	return true;
}


/**
 * Position a float in the first available space.
 *
 * \param  c	  float box to position
 * \param  width  available width
 * \param  cx	  x coordinate relative to cont to place float right of
 * \param  y	  y coordinate relative to cont to place float below
 * \param  cont	  ancestor box which defines horizontal space, for floats
 */

void place_float_below(struct box *c, int width, int cx, int y,
		struct box *cont)
{
	int x0, x1, yy = y;
	struct box *left;
	struct box *right;

#ifdef LAYOUT_DEBUG
	LOG(("c %p, width %i, cx %i, y %i, cont %p", c, width, cx, y, cont));
#endif

	do {
		y = yy;
		x0 = cx;
		x1 = cx + width;
		find_sides(cont->float_children, y, y + c->height, &x0, &x1,
				&left, &right);
		if (left != 0 && right != 0) {
			yy = (left->y + left->height <
					right->y + right->height ?
					left->y + left->height :
					right->y + right->height);
		} else if (left == 0 && right != 0) {
			yy = right->y + right->height;
		} else if (left != 0 && right == 0) {
			yy = left->y + left->height;
		}
	} while (!((left == 0 && right == 0) || (c->width <= x1 - x0)));

	if (c->type == BOX_FLOAT_LEFT) {
		c->x = x0;
	} else {
		c->x = x1 - c->width;
	}
	c->y = y;
}


/**
 * Layout a table.
 *
 * \param  table	    table to layout
 * \param  available_width  width of containing block
 * \param  content	   memory pool for any new boxes
 * \return  true on success, false on memory exhaustion
 */

bool layout_table(struct box *table, int available_width,
		html_content *content)
{
	unsigned int columns = table->columns;  /* total columns */
	unsigned int i;
	unsigned int *row_span;
	int *excess_y;
	int table_width, min_width = 0, max_width = 0;
	int required_width = 0;
	int x, remainder = 0, count = 0;
	int table_height = 0;
	int min_height = 0;
	int *xs;  /* array of column x positions */
	int auto_width;
	int spare_width;
	int relative_sum = 0;
	int border_spacing_h = 0, border_spacing_v = 0;
	int spare_height;
	int positioned_columns = 0;
	struct box *containing_block = NULL;
	struct box *c;
	struct box *row;
	struct box *row_group;
	struct box **row_span_cell;
	struct column *col;
	const css_computed_style *style = table->style;
	enum css_width_e wtype;
	enum css_height_e htype;
	css_fixed value = 0;
	css_unit unit = CSS_UNIT_PX;

	assert(table->type == BOX_TABLE);
	assert(style);
	assert(table->children && table->children->children);
	assert(columns);

	/* allocate working buffers */
	col = malloc(columns * sizeof col[0]);
	excess_y = malloc(columns * sizeof excess_y[0]);
	row_span = malloc(columns * sizeof row_span[0]);
	row_span_cell = malloc(columns * sizeof row_span_cell[0]);
	xs = malloc((columns + 1) * sizeof xs[0]);
	if (!col || !xs || !row_span || !excess_y || !row_span_cell) {
		free(col);
		free(excess_y);
		free(row_span);
		free(row_span_cell);
		free(xs);
		return false;
	}

	memcpy(col, table->col, sizeof(col[0]) * columns);

	/* find margins, paddings, and borders for table and cells */
	layout_find_dimensions(available_width, -1, table, style, 0, 0, 0, 0,
			table->margin, table->padding, table->border);
	for (row_group = table->children; row_group;
			row_group = row_group->next) {
		for (row = row_group->children; row; row = row->next) {
			for (c = row->children; c; c = c->next) {
				assert(c->style);
				table_used_border_for_cell(c);
				layout_find_dimensions(available_width, -1,
						c, c->style, 0, 0, 0, 0, 0,
						c->padding, c->border);
				if (css_computed_overflow(c->style) ==
						CSS_OVERFLOW_SCROLL ||
					css_computed_overflow(c->style) ==
						CSS_OVERFLOW_AUTO) {
					c->padding[RIGHT] += SCROLLBAR_WIDTH;
					c->padding[BOTTOM] += SCROLLBAR_WIDTH;
				}
			}
		}
	}

	/* border-spacing is used in the separated borders model */
	if (css_computed_border_collapse(style) ==
			CSS_BORDER_COLLAPSE_SEPARATE) {
		css_fixed h = 0, v = 0;
		css_unit hu = CSS_UNIT_PX, vu = CSS_UNIT_PX;

		css_computed_border_spacing(style, &h, &hu, &v, &vu);

		border_spacing_h = FIXTOINT(nscss_len2px(h, hu, style));
		border_spacing_v = FIXTOINT(nscss_len2px(v, vu, style));
	}

	/* find specified table width, or available width if auto-width */
	wtype = css_computed_width(style, &value, &unit);
	if (wtype == CSS_WIDTH_SET) {
		if (unit == CSS_UNIT_PCT) {
			table_width = FPCT_OF_INT_TOINT(value, available_width);
		} else {
			table_width =
				FIXTOINT(nscss_len2px(value, unit, style));
		}

		/* specified width includes border */
		table_width -= table->border[LEFT].width +
				table->border[RIGHT].width;
		table_width = table_width < 0 ? 0 : table_width;

		auto_width = table_width;
	} else {
		table_width = AUTO;
		auto_width = available_width -
				((table->margin[LEFT] == AUTO ? 0 :
						table->margin[LEFT]) +
				 table->border[LEFT].width +
				 table->padding[LEFT] +
				 table->padding[RIGHT] +
				 table->border[RIGHT].width +
				 (table->margin[RIGHT] == AUTO ? 0 :
						table->margin[RIGHT]));
	}

	/* Find any table height specified within CSS/HTML */
	htype = css_computed_height(style, &value, &unit);
	if (htype == CSS_HEIGHT_SET) {
		if (unit == CSS_UNIT_PCT) {
			/* This is the minimum height for the table
			 * (see 17.5.3) */
			if (css_computed_position(table->style) ==
					CSS_POSITION_ABSOLUTE) {
				/* Table is absolutely positioned */
				assert(table->float_container);
				containing_block = table->float_container;
			} else if (table->float_container &&
					css_computed_position(table->style) !=
						CSS_POSITION_ABSOLUTE &&
					(css_computed_float(table->style) ==
						CSS_FLOAT_LEFT ||
					css_computed_float(table->style) ==
						CSS_FLOAT_RIGHT)) {
				/* Table is a float */
				assert(table->parent && table->parent->parent &&
						table->parent->parent->parent);
				containing_block =
						table->parent->parent->parent;
			} else if (table->parent && table->parent->type !=
					BOX_INLINE_CONTAINER) {
				/* Table is a block level element */
				containing_block = table->parent;
			} else if (table->parent && table->parent->type ==
					BOX_INLINE_CONTAINER) {
				/* Table is an inline block */
				assert(table->parent->parent);
				containing_block = table->parent->parent;
			}

			if (containing_block) {
				css_fixed ignored = 0;

				htype = css_computed_height(
						containing_block->style,
						&ignored, &unit);
			}

			if (containing_block &&
					containing_block->height != AUTO &&
					(css_computed_position(table->style) ==
							CSS_POSITION_ABSOLUTE ||
					htype == CSS_HEIGHT_SET)) {
				/* Table is absolutely positioned or its
				 * containing block has a valid specified
				 * height. (CSS 2.1 Section 10.5) */
				min_height = FPCT_OF_INT_TOINT(value,
						containing_block->height);
			}
		} else {
			/* This is the minimum height for the table
			 * (see 17.5.3) */
			min_height = FIXTOINT(nscss_len2px(value, unit, style));
		}
	}

	/* calculate width required by cells */
	for (i = 0; i != columns; i++) {
#ifdef LAYOUT_DEBUG
		LOG(("table %p, column %u: type %s, width %i, min %i, max %i",
				table, i,
				((const char *[]) {"UNKNOWN", "FIXED", "AUTO",
				"PERCENT", "RELATIVE"})[col[i].type],
				col[i].width, col[i].min, col[i].max));
#endif

		if (col[i].positioned) {
			positioned_columns++;
			continue;
		} else if (col[i].type == COLUMN_WIDTH_FIXED) {
			if (col[i].width < col[i].min)
				col[i].width = col[i].max = col[i].min;
			else
				col[i].min = col[i].max = col[i].width;
			required_width += col[i].width;
		} else if (col[i].type == COLUMN_WIDTH_PERCENT) {
			int width = col[i].width * auto_width / 100;
			required_width += col[i].min < width ? width :
					col[i].min;
		} else
			required_width += col[i].min;

#ifdef LAYOUT_DEBUG
		LOG(("required_width %i", required_width));
#endif
	}
	required_width += (columns + 1 - positioned_columns) *
			border_spacing_h;

#ifdef LAYOUT_DEBUG
	LOG(("width %i, min %i, max %i, auto %i, required %i",
			table_width, table->min_width, table->max_width,
			auto_width, required_width));
#endif

	if (auto_width < required_width) {
		/* table narrower than required width for columns:
		 * treat percentage widths as maximums */
		for (i = 0; i != columns; i++) {
			if (col[i].type == COLUMN_WIDTH_RELATIVE)
				continue;
			if (col[i].type == COLUMN_WIDTH_PERCENT) {
				col[i].max = auto_width * col[i].width / 100;
				if (col[i].max < col[i].min)
					col[i].max = col[i].min;
			}
			min_width += col[i].min;
			max_width += col[i].max;
		}
	} else {
		/* take percentages exactly */
		for (i = 0; i != columns; i++) {
			if (col[i].type == COLUMN_WIDTH_RELATIVE)
				continue;
			if (col[i].type == COLUMN_WIDTH_PERCENT) {
				int width = auto_width * col[i].width / 100;
				if (width < col[i].min)
					width = col[i].min;
				col[i].min = col[i].width = col[i].max = width;
				col[i].type = COLUMN_WIDTH_FIXED;
			}
			min_width += col[i].min;
			max_width += col[i].max;
		}
	}

	/* allocate relative widths */
	spare_width = auto_width;
	for (i = 0; i != columns; i++) {
		if (col[i].type == COLUMN_WIDTH_RELATIVE)
			relative_sum += col[i].width;
		else if (col[i].type == COLUMN_WIDTH_FIXED)
			spare_width -= col[i].width;
		else
			spare_width -= col[i].min;
	}
	spare_width -= (columns + 1) * border_spacing_h;
	if (relative_sum != 0) {
		if (spare_width < 0)
			spare_width = 0;
		for (i = 0; i != columns; i++) {
			if (col[i].type == COLUMN_WIDTH_RELATIVE) {
				col[i].min = ceil(col[i].max =
						(float) spare_width
						* (float) col[i].width
						/ relative_sum);
				min_width += col[i].min;
				max_width += col[i].max;
			}
		}
	}
	min_width += (columns + 1) * border_spacing_h;
	max_width += (columns + 1) * border_spacing_h;

	if (auto_width <= min_width) {
		/* not enough space: minimise column widths */
		for (i = 0; i < columns; i++) {
			col[i].width = col[i].min;
		}
		table_width = min_width;
	} else if (max_width <= auto_width) {
		/* more space than maximum width */
		if (table_width == AUTO) {
			/* for auto-width tables, make columns max width */
			for (i = 0; i < columns; i++) {
				col[i].width = col[i].max;
			}
			table_width = max_width;
		} else {
			/* for fixed-width tables, distribute the extra space
			 * too */
			unsigned int flexible_columns = 0;
			for (i = 0; i != columns; i++)
				if (col[i].type != COLUMN_WIDTH_FIXED)
					flexible_columns++;
			if (flexible_columns == 0) {
				int extra = (table_width - max_width) / columns;
				remainder = (table_width - max_width) -
						(extra * columns);
				for (i = 0; i != columns; i++) {
					col[i].width = col[i].max + extra;
					count -= remainder;
					if (count < 0) {
						col[i].width++;
						count += columns;
					}
				}

			} else {
				int extra = (table_width - max_width) /
						flexible_columns;
				remainder = (table_width - max_width) -
						(extra * flexible_columns);
				for (i = 0; i != columns; i++)
					if (col[i].type != COLUMN_WIDTH_FIXED) {
						col[i].width = col[i].max +
								extra;
						count -= remainder;
						if (count < 0) {
							col[i].width++;
							count += flexible_columns;
						}
					}
			}
		}
	} else {
		/* space between min and max: fill it exactly */
		float scale = (float) (auto_width - min_width) /
				(float) (max_width - min_width);
		/* fprintf(stderr, "filling, scale %f\n", scale); */
		for (i = 0; i < columns; i++) {
			col[i].width = col[i].min + (int) (0.5 +
					(col[i].max - col[i].min) * scale);
		}
		table_width = auto_width;
	}

	xs[0] = x = border_spacing_h;
	for (i = 0; i != columns; i++) {
		if (!col[i].positioned)
			x += col[i].width + border_spacing_h;
		xs[i + 1] = x;
		row_span[i] = 0;
		excess_y[i] = 0;
		row_span_cell[i] = 0;
	}

	/* position cells */
	table_height = border_spacing_v;
	for (row_group = table->children; row_group;
			row_group = row_group->next) {
		int row_group_height = 0;
		for (row = row_group->children; row; row = row->next) {
			int row_height = 0;

			htype = css_computed_height(row->style, &value, &unit);
			if (htype == CSS_HEIGHT_SET && unit != CSS_UNIT_PCT) {
				row_height = FIXTOINT(nscss_len2px(value, unit,
						row->style));
			}
			for (c = row->children; c; c = c->next) {
				assert(c->style);
				c->width = xs[c->start_column + c->columns] -
						xs[c->start_column] -
						border_spacing_h -
						c->border[LEFT].width -
						c->padding[LEFT] -
						c->padding[RIGHT] -
						c->border[RIGHT].width;
				c->float_children = 0;

				c->height = AUTO;
				if (!layout_block_context(c, -1, content)) {
					free(col);
					free(excess_y);
					free(row_span);
					free(row_span_cell);
					free(xs);
					return false;
				}
				/* warning: c->descendant_y0 and
				 * c->descendant_y1 used as temporary storage
				 * until after vertical alignment is complete */
				c->descendant_y0 = c->height;
				c->descendant_y1 = c->padding[BOTTOM];

				htype = css_computed_height(c->style,
						&value, &unit);

				if (htype == CSS_HEIGHT_SET &&
						unit != CSS_UNIT_PCT) {
					/* some sites use height="1" or similar
					 * to attempt to make cells as small as
					 * possible, so treat it as a minimum */
					int h = FIXTOINT(nscss_len2px(value,
							unit, c->style));
					if (c->height < h)
						c->height = h;
				}
				/* specified row height is treated as a minimum
				 */
				if (c->height < row_height)
					c->height = row_height;
				c->x = xs[c->start_column] +
						c->border[LEFT].width;
				c->y = c->border[TOP].width;
				for (i = 0; i != c->columns; i++) {
					row_span[c->start_column + i] = c->rows;
					excess_y[c->start_column + i] =
							c->border[TOP].width +
							c->padding[TOP] +
							c->height +
							c->padding[BOTTOM] +
							c->border[BOTTOM].width;
					row_span_cell[c->start_column + i] = 0;
				}
				row_span_cell[c->start_column] = c;
				c->padding[BOTTOM] = -border_spacing_v -
						c->border[TOP].width -
						c->padding[TOP] -
						c->height -
						c->border[BOTTOM].width;
			}
			for (i = 0; i != columns; i++)
				if (row_span[i] != 0)
					row_span[i]--;
				else
					row_span_cell[i] = 0;
			if (row->next || row_group->next) {
				/* row height is greatest excess of a cell
				 * which ends in this row */
				for (i = 0; i != columns; i++)
					if (row_span[i] == 0 && row_height <
							excess_y[i])
						row_height = excess_y[i];
			} else {
				/* except in the last row */
				for (i = 0; i != columns; i++)
					if (row_height < excess_y[i])
						row_height = excess_y[i];
			}
			for (i = 0; i != columns; i++) {
				if (row_height < excess_y[i])
					excess_y[i] -= row_height;
				else
					excess_y[i] = 0;
				if (row_span_cell[i] != 0)
					row_span_cell[i]->padding[BOTTOM] +=
							row_height +
							border_spacing_v;
			}

			row->x = 0;
			row->y = row_group_height;
			row->width = table_width;
			row->height = row_height;
			row_group_height += row_height + border_spacing_v;
		}
		row_group->x = 0;
		row_group->y = table_height;
		row_group->width = table_width;
		row_group->height = row_group_height;
		table_height += row_group_height;
	}
	/* Table height is either the height of the contents, or specified
	 * height if greater */
	table_height = max(table_height, min_height);
	/** \TODO distribute spare height over the row groups / rows / cells */

	/* perform vertical alignment */
	for (row_group = table->children; row_group;
			row_group = row_group->next) {
		for (row = row_group->children; row; row = row->next) {
			for (c = row->children; c; c = c->next) {
				enum css_vertical_align_e vertical_align;

				/* unextended bottom padding is in
				 * c->descendant_y1, and unextended
				 * cell height is in c->descendant_y0 */
				spare_height = (c->padding[BOTTOM] -
						c->descendant_y1) +
						(c->height - c->descendant_y0);

				vertical_align = css_computed_vertical_align(
						c->style, &value, &unit);

				switch (vertical_align) {
				case CSS_VERTICAL_ALIGN_SUB:
				case CSS_VERTICAL_ALIGN_SUPER:
				case CSS_VERTICAL_ALIGN_TEXT_TOP:
				case CSS_VERTICAL_ALIGN_TEXT_BOTTOM:
				case CSS_VERTICAL_ALIGN_SET:
				case CSS_VERTICAL_ALIGN_BASELINE:
					/* todo: baseline alignment, for now
					 * just use ALIGN_TOP */
				case CSS_VERTICAL_ALIGN_TOP:
					break;
				case CSS_VERTICAL_ALIGN_MIDDLE:
					c->padding[TOP] += spare_height / 2;
					c->padding[BOTTOM] -= spare_height / 2;
					layout_move_children(c, 0,
							spare_height / 2);
					break;
				case CSS_VERTICAL_ALIGN_BOTTOM:
					c->padding[TOP] += spare_height;
					c->padding[BOTTOM] -= spare_height;
					layout_move_children(c, 0,
							spare_height);
					break;
				case CSS_VERTICAL_ALIGN_INHERIT:
					assert(0);
					break;
				}
			}
		}
	}

	/* Top and bottom margins of 'auto' are set to 0.  CSS2.1 10.6.3 */
	if (table->margin[TOP] == AUTO)
		table->margin[TOP] = 0;
	if (table->margin[BOTTOM] == AUTO)
		table->margin[BOTTOM] = 0;

	free(col);
	free(excess_y);
	free(row_span);
	free(row_span_cell);
	free(xs);

	table->width = table_width;
	table->height = table_height;

	return true;
}


/**
 * Calculate minimum and maximum width of a table.
 *
 * \param  table  box of type TABLE
 * \post  table->min_width and table->max_width filled in,
 *        0 <= table->min_width <= table->max_width
 */

void layout_minmax_table(struct box *table,
		const struct font_functions *font_func)
{
	unsigned int i, j;
	int border_spacing_h = 0;
	int table_min = 0, table_max = 0;
	int extra_fixed = 0;
	float extra_frac = 0;
	struct column *col = table->col;
	struct box *row_group, *row, *cell;
	enum css_width_e wtype;
	css_fixed value = 0;
	css_unit unit = CSS_UNIT_PX;

	/* check if the widths have already been calculated */
	if (table->max_width != UNKNOWN_MAX_WIDTH)
		return;

	/* start with 0 except for fixed-width columns */
	for (i = 0; i != table->columns; i++) {
		if (col[i].type == COLUMN_WIDTH_FIXED)
			col[i].min = col[i].max = col[i].width;
		else
			col[i].min = col[i].max = 0;
	}

	/* border-spacing is used in the separated borders model */
	if (css_computed_border_collapse(table->style) ==
			CSS_BORDER_COLLAPSE_SEPARATE) {
		css_fixed h = 0, v = 0;
		css_unit hu = CSS_UNIT_PX, vu = CSS_UNIT_PX;

		css_computed_border_spacing(table->style, &h, &hu, &v, &vu);

		border_spacing_h = FIXTOINT(nscss_len2px(h, hu, table->style));
	}

	/* 1st pass: consider cells with colspan 1 only */
	for (row_group = table->children; row_group; row_group =row_group->next)
	for (row = row_group->children; row; row = row->next)
	for (cell = row->children; cell; cell = cell->next) {
		assert(cell->type == BOX_TABLE_CELL);
		assert(cell->style);
		/** TODO: Handle colspan="0" correctly.
		 *        It's currently converted to 1 in box normaisation */
		assert(cell->columns != 0);

		if (cell->columns != 1)
			continue;

		layout_minmax_block(cell, font_func);
		i = cell->start_column;

		if (col[i].positioned)
			continue;

		/* update column min, max widths using cell widths */
		if (col[i].min < cell->min_width)
			col[i].min = cell->min_width;
		if (col[i].max < cell->max_width)
			col[i].max = cell->max_width;
	}

	/* 2nd pass: cells which span multiple columns */
	for (row_group = table->children; row_group; row_group =row_group->next)
	for (row = row_group->children; row; row = row->next)
	for (cell = row->children; cell; cell = cell->next) {
		unsigned int flexible_columns = 0;
		int min = 0, max = 0, fixed_width = 0, extra;

		if (cell->columns == 1)
			continue;

		layout_minmax_block(cell, font_func);
		i = cell->start_column;

		/* find min width so far of spanned columns, and count
		 * number of non-fixed spanned columns and total fixed width */
		for (j = 0; j != cell->columns; j++) {
			min += col[i + j].min;
			if (col[i + j].type == COLUMN_WIDTH_FIXED)
				fixed_width += col[i + j].width;
			else
				flexible_columns++;
		}
		min += (cell->columns - 1) * border_spacing_h;

		/* distribute extra min to spanned columns */
		if (min < cell->min_width) {
			if (flexible_columns == 0) {
				extra = 1 + (cell->min_width - min) /
						cell->columns;
				for (j = 0; j != cell->columns; j++) {
					col[i + j].min += extra;
					if (col[i + j].max < col[i + j].min)
						col[i + j].max = col[i + j].min;
				}
			} else {
				extra = 1 + (cell->min_width - min) /
						flexible_columns;
				for (j = 0; j != cell->columns; j++) {
					if (col[i + j].type !=
							COLUMN_WIDTH_FIXED) {
						col[i + j].min += extra;
						if (col[i + j].max <
								col[i + j].min)
							col[i + j].max =
								col[i + j].min;
					}
				}
			}
		}

		/* find max width so far of spanned columns */
		for (j = 0; j != cell->columns; j++)
			max += col[i + j].max;
		max += (cell->columns - 1) * border_spacing_h;

		/* distribute extra max to spanned columns */
		if (max < cell->max_width && flexible_columns) {
			extra = 1 + (cell->max_width - max) / flexible_columns;
			for (j = 0; j != cell->columns; j++)
				if (col[i + j].type != COLUMN_WIDTH_FIXED)
					col[i + j].max += extra;
		}
	}

	for (i = 0; i != table->columns; i++) {
		if (col[i].max < col[i].min) {
			box_dump(stderr, table, 0);
			assert(0);
		}
		table_min += col[i].min;
		table_max += col[i].max;
	}

	/* fixed width takes priority, unless it is too narrow */
	wtype = css_computed_width(table->style, &value, &unit);
	if (wtype == CSS_WIDTH_SET && unit != CSS_UNIT_PCT) {
		int width = FIXTOINT(nscss_len2px(value, unit, table->style));
		if (table_min < width)
			table_min = width;
		if (table_max < width)
			table_max = width;
	}

	/* add margins, border, padding to min, max widths */
	calculate_mbp_width(table->style, LEFT, true, true, true,
			&extra_fixed, &extra_frac);
	calculate_mbp_width(table->style, RIGHT, true, true, true,
			&extra_fixed, &extra_frac);
	if (extra_fixed < 0)
		extra_fixed = 0;
	if (extra_frac < 0)
		extra_frac = 0;
	if (1.0 <= extra_frac)
		extra_frac = 0.9;
	table->min_width = (table_min + extra_fixed) / (1.0 - extra_frac);
	table->max_width = (table_max + extra_fixed) / (1.0 - extra_frac);
	table->min_width += (table->columns + 1) * border_spacing_h;
	table->max_width += (table->columns + 1) * border_spacing_h;

	assert(0 <= table->min_width && table->min_width <= table->max_width);
}


/**
 * Moves the children of a box by a specified amount
 *
 * \param  box  top of tree of boxes
 * \param  x	the amount to move children by horizontally
 * \param  y	the amount to move children by vertically
 */

void layout_move_children(struct box *box, int x, int y)
{
	assert(box);

	for (box = box->children; box; box = box->next) {
		box->x += x;
		box->y += y;
	}
}


/**
 * Determine width of margin, borders, and padding on one side of a box.
 *
 * \param  style    style to measure
 * \param  size     side of box to measure
 * \param  margin   whether margin width is required
 * \param  border   whether border width is required
 * \param  padding  whether padding width is required
 * \param  fixed    increased by sum of fixed margin, border, and padding
 * \param  frac     increased by sum of fractional margin and padding
 */

void calculate_mbp_width(const css_computed_style *style, unsigned int side,
		bool margin, bool border, bool padding,
		int *fixed, float *frac)
{
	typedef uint8_t (*len_func)(const css_computed_style *style,
			css_fixed *length, css_unit *unit);

	static len_func margin_funcs[4] = {
		css_computed_margin_top,
		css_computed_margin_right,
		css_computed_margin_bottom,
		css_computed_margin_left
	};
	static len_func padding_funcs[4] = {
		css_computed_padding_top,
		css_computed_padding_right,
		css_computed_padding_bottom,
		css_computed_padding_left
	};
	static struct {
		len_func width;
		uint8_t (*style)(const css_computed_style *style);
	} border_funcs[4] = {
		{ css_computed_border_top_width,
				css_computed_border_top_style },
		{ css_computed_border_right_width,
				css_computed_border_right_style },
		{ css_computed_border_bottom_width,
				css_computed_border_bottom_style },
		{ css_computed_border_left_width,
				css_computed_border_left_style }
	};

	css_fixed value = 0;
	css_unit unit = CSS_UNIT_PX;

	assert(style);

	/* margin */
	if (margin) {
		enum css_margin_e type;

		type = margin_funcs[side](style, &value, &unit);
		if (type == CSS_MARGIN_SET) {
			if (unit == CSS_UNIT_PCT) {
				*frac += FIXTOINT(FDIV(value, F_100));
			} else {
				*fixed += FIXTOINT(nscss_len2px(value, unit,
						style));
			}
		}
	}

	/* border */
	if (border) {
		if (border_funcs[side].style(style) !=
				CSS_BORDER_STYLE_NONE) {
			border_funcs[side].width(style, &value, &unit);

			*fixed += FIXTOINT(nscss_len2px(value, unit, style));
		}
	}

	/* padding */
	if (padding) {
		padding_funcs[side](style, &value, &unit);
		if (unit == CSS_UNIT_PCT) {
			*frac += FIXTOINT(FDIV(value, F_100));
		} else {
			*fixed += FIXTOINT(nscss_len2px(value, unit, style));
		}
	}
}


/**
 * Layout list markers.
 */

void layout_lists(struct box *box,
		const struct font_functions *font_func)
{
	struct box *child;
	struct box *marker;
	plot_font_style_t fstyle;

	for (child = box->children; child; child = child->next) {
		if (child->list_marker) {
			marker = child->list_marker;
			if (marker->object) {
				marker->width = 
					content_get_width(marker->object);
				marker->x = -marker->width;
				marker->height = 
					content_get_height(marker->object);
				marker->y = (line_height(marker->style) -
						marker->height) / 2;
			} else if (marker->text) {
				if (marker->width == UNKNOWN_WIDTH) {
					font_plot_style_from_css(marker->style,
							&fstyle);
					font_func->font_width(&fstyle,
							marker->text,
							marker->length,
							&marker->width);
					marker->flags |= MEASURED;
				}
				marker->x = -marker->width;
				marker->y = 0;
				marker->height = line_height(marker->style);
			} else {
				marker->x = 0;
				marker->y = 0;
				marker->width = 0;
				marker->height = 0;
			}
			/* Gap between marker and content */
			marker->x -= 4;
		}
		layout_lists(child, font_func);
	}
}


/**
 * Adjust positions of relatively positioned boxes.
 *
 * \param  root  box to adjust the position of
 * \param  fp    box which forms the block formatting context for children of
 *		 "root" which are floats
 * \param  fx    x offset due to intervening relatively positioned boxes
 *               between current box, "root", and the block formatting context
 *               box, "fp", for float children of "root"
 * \param  fy    y offset due to intervening relatively positioned boxes
 *               between current box, "root", and the block formatting context
 *               box, "fp", for float children of "root"
 */

void layout_position_relative(struct box *root, struct box *fp, int fx, int fy)
{
	struct box *box; /* for children of "root" */
	struct box *fn;  /* for block formatting context box for children of
			  * "box" */
	struct box *fc;  /* for float children of the block formatting context,
			  * "fp" */
	int x, y;	 /* for the offsets resulting from any relative
			  * positioning on the current block */
	int fnx, fny;    /* for affsets which apply to flat children of "box" */

	/**\todo ensure containing box is large enough after moving boxes */

	assert(root);

	/* Normal children */
	for (box = root->children; box; box = box->next) {

		if (box->type == BOX_TEXT)
			continue;

		/* If relatively positioned, get offsets */
		if (box->style && css_computed_position(box->style) ==
				CSS_POSITION_RELATIVE)
			layout_compute_relative_offset(box, &x, &y);
		else
			x = y = 0;

		/* Adjust float coordinates.
		 * (note float x and y are relative to their block formatting
		 * context box and not their parent) */
		if (box->style && (css_computed_float(box->style) ==
					CSS_FLOAT_LEFT ||
				css_computed_float(box->style) ==
					CSS_FLOAT_RIGHT) &&
				(fx != 0 || fy != 0)) {
			/* box is a float and there is a float offset to
			 * apply */
			for (fc = fp->float_children; fc; fc = fc->next_float) {
				if (box == fc->children) {
					/* Box is floated in the block
					 * formatting context block, fp.
					 * Apply float offsets. */
					box->x += fx;
					box->y += fy;
					fx = fy = 0;
				}
			}
		}

		if (box->float_children) {
			fn = box;
			fnx = fny = 0;
		} else {
			fn = fp;
			fnx = fx + x;
			fny = fy + y;
		}

		/* recurse first */
		layout_position_relative(box, fn, fnx, fny);

		/* Ignore things we're not interested in. */
		if (!box->style || (box->style &&
				css_computed_position(box->style) !=
				CSS_POSITION_RELATIVE))
			continue;

		box->x += x;
		box->y += y;

		/* Handle INLINEs - their "children" are in fact
		 * the sibling boxes between the INLINE and
		 * INLINE_END boxes */
		if (box->type == BOX_INLINE && box->inline_end) {
			struct box *b;
			for (b = box->next; b && b != box->inline_end;
					b = b->next) {
				b->x += x;
				b->y += y;
			}
		}
	}
}


/**
 * Compute a box's relative offset as per CSS 2.1 9.4.3
 *
 * \param  box	Box to compute relative offsets for.
 * \param  x	Receives relative offset in x.
 * \param  y	Receives relative offset in y.
 */

void layout_compute_relative_offset(struct box *box, int *x, int *y)
{
	int left, right, top, bottom;
	struct box *containing_block;

	assert(box && box->parent && box->style &&
			css_computed_position(box->style) ==
			CSS_POSITION_RELATIVE);

	if (box->float_container &&
			(css_computed_float(box->style) == CSS_FLOAT_LEFT ||
			css_computed_float(box->style) == CSS_FLOAT_RIGHT)) {
		containing_block = box->float_container;
	} else {
		containing_block = box->parent;
	}

	layout_compute_offsets(box, containing_block,
			&top, &right, &bottom, &left);

	if (left == AUTO && right == AUTO)
		left = right = 0;
	else if (left == AUTO)
		/* left is auto => computed = -right */
		left = -right;
	else if (right == AUTO)
		/* right is auto => computed = -left */
		right = -left;
	else {
		/* over constrained => examine direction property
		 * of containing block */
		if (containing_block->style &&
				css_computed_direction(
				containing_block->style) ==
				CSS_DIRECTION_RTL) {
			/* right wins */
			left = -right;
		} else {
			/* assume LTR in all other cases */
			right = -left;
		}
	}

	assert(left == -right);

	if (top == AUTO && bottom == AUTO)
		top = bottom = 0;
	else if (top == AUTO)
		top = -bottom;
	else if (bottom == AUTO)
		bottom = -top;
	else
		bottom = -top;

#ifdef LAYOUT_DEBUG
	LOG(("left %i, right %i, top %i, bottom %i", left, right, top, bottom));
#endif

	*x = left;
	*y = top;
}


/**
 * Recursively layout and position absolutely positioned boxes.
 *
 * \param  box               tree of boxes to layout
 * \param  containing_block  current containing block
 * \param  cx                position of box relative to containing_block
 * \param  cy                position of box relative to containing_block
 * \param  content           memory pool for any new boxes
 * \return  true on success, false on memory exhaustion
 */

bool layout_position_absolute(struct box *box,
		struct box *containing_block,
		int cx, int cy,
		html_content *content)
{
	struct box *c;

	for (c = box->children; c; c = c->next) {
		if ((c->type == BOX_BLOCK || c->type == BOX_TABLE ||
				c->type == BOX_INLINE_BLOCK) &&
				(css_computed_position(c->style) ==
						CSS_POSITION_ABSOLUTE ||
				 css_computed_position(c->style) ==
						CSS_POSITION_FIXED)) {
			if (!layout_absolute(c, containing_block,
					cx, cy, content))
				return false;
			if (!layout_position_absolute(c, c, 0, 0, content))
				return false;
		} else if (c->style && css_computed_position(c->style) ==
				CSS_POSITION_RELATIVE) {
			if (!layout_position_absolute(c, c, 0, 0, content))
				return false;
		} else {
			int px, py;
			if (c->style && (css_computed_float(c->style) ==
						CSS_FLOAT_LEFT ||
					css_computed_float(c->style) ==
						CSS_FLOAT_RIGHT)) {
				/* Float x/y coords are relative to nearest
				 * ansestor with float_children, rather than
				 * relative to parent. Need to get x/y relative
				 * to parent */
				struct box *p;
				px = c->x;
				py = c->y;
				for (p = box->parent; p && !p->float_children;
						p = p->parent) {
					px -= p->x;
					py -= p->y;
				}
			} else {
				/* Not a float, so box x/y coords are relative
				 * to parent */
				px = c->x;
				py = c->y;
			}
			if (!layout_position_absolute(c, containing_block,
					cx + px, cy + py, content))
				return false;
		}
	}

	return true;
}


/**
 * Layout and position an absolutely positioned box.
 *
 * \param  box               absolute box to layout and position
 * \param  containing_block  containing block
 * \param  cx                position of box relative to containing_block
 * \param  cy                position of box relative to containing_block
 * \param  content           memory pool for any new boxes
 * \return  true on success, false on memory exhaustion
 */

bool layout_absolute(struct box *box, struct box *containing_block,
		int cx, int cy,
		html_content *content)
{
	int static_left, static_top;  /* static position */
	int top, right, bottom, left;
	int width, height, max_width, min_width;
	int *margin = box->margin;
	int *padding = box->padding;
	struct box_border *border = box->border;
	int available_width = containing_block->width;
	int space;

	assert(box->type == BOX_BLOCK || box->type == BOX_TABLE ||
			box->type == BOX_INLINE_BLOCK);

	/* The static position is where the box would be if it was not
	 * absolutely positioned. The x and y are filled in by
	 * layout_block_context(). */
	static_left = cx + box->x;
	static_top = cy + box->y;

	if (containing_block->type == BOX_BLOCK ||
			containing_block->type == BOX_INLINE_BLOCK ||
			containing_block->type == BOX_TABLE_CELL) {
		/* Block level container => temporarily increase containing
		 * block dimensions to include padding (we restore this
		 * again at the end) */
		containing_block->width += containing_block->padding[LEFT] +
				containing_block->padding[RIGHT];
		containing_block->height += containing_block->padding[TOP] +
				containing_block->padding[BOTTOM];
	} else {
		/** \todo inline containers */
	}

	layout_compute_offsets(box, containing_block,
			&top, &right, &bottom, &left);

	/* Pass containing block into layout_find_dimensions via the float
	 * containing block box member. This is unused for absolutely positioned
	 * boxes because a box can't be floated and absolutely positioned. */
	box->float_container = containing_block;
	layout_find_dimensions(available_width, -1, box, box->style,
			&width, &height, &max_width, &min_width,
			margin, padding, border);
	box->float_container = NULL;

	/* 10.3.7 */
#ifdef LAYOUT_DEBUG
	LOG(("%i + %i + %i + %i + %i + %i + %i + %i + %i = %i",
			left, margin[LEFT], border[LEFT].width,
			padding[LEFT], width, padding[RIGHT],
			border[RIGHT].width, margin[RIGHT], right,
			containing_block->width));
#endif

	if (left == AUTO && width == AUTO && right == AUTO) {
		if (margin[LEFT] == AUTO)
			margin[LEFT] = 0;
		if (margin[RIGHT] == AUTO)
			margin[RIGHT] = 0;
		left = static_left;

		width = min(max(box->min_width, available_width),
			box->max_width);
		width -= box->margin[LEFT] + box->border[LEFT].width +
			box->padding[LEFT] + box->padding[RIGHT] +
			box->border[RIGHT].width + box->margin[RIGHT];

		/* Adjust for {min|max}-width */
		if (max_width >= 0 && width > max_width) width = max_width;
		if (min_width >  0 && width < min_width) width = min_width;

		right = containing_block->width -
			left -
			margin[LEFT] - border[LEFT].width - padding[LEFT] -
			width -
			padding[RIGHT] - border[RIGHT].width - margin[RIGHT];
	} else if (left != AUTO && width != AUTO && right != AUTO) {

		/* Adjust for {min|max}-width */
		if (max_width >= 0 && width > max_width) width = max_width;
		if (min_width >  0 && width < min_width) width = min_width;

		if (margin[LEFT] == AUTO && margin[RIGHT] == AUTO) {
			space = containing_block->width -
					left - border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - right;
			if (space < 0) {
				margin[LEFT] = 0;
				margin[RIGHT] = space;
			} else {
				margin[LEFT] = margin[RIGHT] = space / 2;
			}
		} else if (margin[LEFT] == AUTO) {
			margin[LEFT] = containing_block->width -
					left - border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT] -
					right;
		} else if (margin[RIGHT] == AUTO) {
			margin[RIGHT] = containing_block->width -
					left - margin[LEFT] -
					border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - right;
		} else {
			right = containing_block->width -
					left - margin[LEFT] -
					border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT];
		}
	} else {
		if (margin[LEFT] == AUTO)
			margin[LEFT] = 0;
		if (margin[RIGHT] == AUTO)
			margin[RIGHT] = 0;

		if (left == AUTO && width == AUTO && right != AUTO) {
			available_width -= right;

			width = min(max(box->min_width, available_width),
				box->max_width);
			width -= box->margin[LEFT] + box->border[LEFT].width +
				box->padding[LEFT] + box->padding[RIGHT] +
				box->border[RIGHT].width + box->margin[RIGHT];

			/* Adjust for {min|max}-width */
			if (max_width >= 0 && width > max_width)
				width = max_width;
			if (min_width >  0 && width < min_width)
				width = min_width;

			left = containing_block->width -
					margin[LEFT] - border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT] -
					right;
		} else if (left == AUTO && width != AUTO && right == AUTO) {

			/* Adjust for {min|max}-width */
			if (max_width >= 0 && width > max_width)
				width = max_width;
			if (min_width >  0 && width < min_width)
				width = min_width;

			left = static_left;
			right = containing_block->width -
					left - margin[LEFT] -
					border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT];
		} else if (left != AUTO && width == AUTO && right == AUTO) {
			available_width -= left;

			width = min(max(box->min_width, available_width),
				box->max_width);
			width -= box->margin[LEFT] + box->border[LEFT].width +
				box->padding[LEFT] + box->padding[RIGHT] +
				box->border[RIGHT].width + box->margin[RIGHT];

			/* Adjust for {min|max}-width */
			if (max_width >= 0 && width > max_width)
				width = max_width;
			if (min_width >  0 && width < min_width)
				width = min_width;

			right = containing_block->width -
					left - margin[LEFT] -
					border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT];
		} else if (left == AUTO && width != AUTO && right != AUTO) {

			/* Adjust for {min|max}-width */
			if (max_width >= 0 && width > max_width)
				width = max_width;
			if (min_width >  0 && width < min_width)
				width = min_width;

			left = containing_block->width -
					margin[LEFT] - border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT] -
					right;
		} else if (left != AUTO && width == AUTO && right != AUTO) {
			width = containing_block->width -
					left - margin[LEFT] -
					border[LEFT].width -
					padding[LEFT] - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT] -
					right;

			/* Adjust for {min|max}-width */
			if (max_width >= 0 && width > max_width)
				width = max_width;
			if (min_width >  0 && width < min_width)
				width = min_width;

		} else if (left != AUTO && width != AUTO && right == AUTO) {

			/* Adjust for {min|max}-width */
			if (max_width >= 0 && width > max_width)
				width = max_width;
			if (min_width >  0 && width < min_width)
				width = min_width;

			right = containing_block->width -
					left - margin[LEFT] -
					border[LEFT].width -
					padding[LEFT] - width - padding[RIGHT] -
					border[RIGHT].width - margin[RIGHT];
		}
	}

#ifdef LAYOUT_DEBUG
	LOG(("%i + %i + %i + %i + %i + %i + %i + %i + %i = %i",
			left, margin[LEFT], border[LEFT].width, padding[LEFT],
			width, padding[RIGHT], border[RIGHT].width,
			margin[RIGHT], right,
			containing_block->width));
#endif

	box->x = left + margin[LEFT] + border[LEFT].width - cx;
	if (containing_block->type == BOX_BLOCK ||
			containing_block->type == BOX_INLINE_BLOCK ||
			containing_block->type == BOX_TABLE_CELL) {
		/* Block-level ancestor => reset container's width */
		containing_block->width -= containing_block->padding[LEFT] +
				containing_block->padding[RIGHT];
	} else {
		/** \todo inline ancestors */
	}
	box->width = width;
	box->height = height;

	if (box->type == BOX_BLOCK || box->type == BOX_INLINE_BLOCK ||
			box->object) {
		if (!layout_block_context(box, -1, content))
			return false;
	} else if (box->type == BOX_TABLE) {
		/* \todo  layout_table considers margins etc. again */
		if (!layout_table(box, width, content))
			return false;
		layout_solve_width(box, box->parent->width, box->width, 0, 0,
				-1, -1);
	}

	/* 10.6.4 */
#ifdef LAYOUT_DEBUG
	LOG(("%i + %i + %i + %i + %i + %i + %i + %i + %i = %i",
			top, margin[TOP], border[TOP].width, padding[TOP],
			height, padding[BOTTOM], border[BOTTOM].width,
			margin[BOTTOM], bottom,
			containing_block->height));
#endif

	if (top == AUTO && height == AUTO && bottom == AUTO) {
		top = static_top;
		height = box->height;
		if (margin[TOP] == AUTO)
			margin[TOP] = 0;
		if (margin[BOTTOM] == AUTO)
			margin[BOTTOM] = 0;
		bottom = containing_block->height -
				top - margin[TOP] - border[TOP].width -
				padding[TOP] - height - padding[BOTTOM] -
				border[BOTTOM].width - margin[BOTTOM];
	} else if (top != AUTO && height != AUTO && bottom != AUTO) {
		if (margin[TOP] == AUTO && margin[BOTTOM] == AUTO) {
			space = containing_block->height -
					top - border[TOP].width - padding[TOP] -
					height - padding[BOTTOM] -
					border[BOTTOM].width - bottom;
			margin[TOP] = margin[BOTTOM] = space / 2;
		} else if (margin[TOP] == AUTO) {
			margin[TOP] = containing_block->height -
					top - border[TOP].width - padding[TOP] -
					height - padding[BOTTOM] -
					border[BOTTOM].width - margin[BOTTOM] -
					bottom;
		} else if (margin[BOTTOM] == AUTO) {
			margin[BOTTOM] = containing_block->height -
					top - margin[TOP] - border[TOP].width -
					padding[TOP] - height -
					padding[BOTTOM] - border[BOTTOM].width -
					bottom;
		} else {
			bottom = containing_block->height -
					top - margin[TOP] - border[TOP].width -
					padding[TOP] - height -
					padding[BOTTOM] - border[BOTTOM].width -
					margin[BOTTOM];
		}
	} else {
		if (margin[TOP] == AUTO)
			margin[TOP] = 0;
		if (margin[BOTTOM] == AUTO)
			margin[BOTTOM] = 0;
		if (top == AUTO && height == AUTO && bottom != AUTO) {
			height = box->height;
			top = containing_block->height -
					margin[TOP] - border[TOP].width -
					padding[TOP] - height -
					padding[BOTTOM] - border[BOTTOM].width -
					margin[BOTTOM] - bottom;
		} else if (top == AUTO && height != AUTO && bottom == AUTO) {
			top = static_top;
			bottom = containing_block->height -
					top - margin[TOP] - border[TOP].width -
					padding[TOP] - height -
					padding[BOTTOM] - border[BOTTOM].width -
					margin[BOTTOM];
		} else if (top != AUTO && height == AUTO && bottom == AUTO) {
			height = box->height;
			bottom = containing_block->height -
					top - margin[TOP] - border[TOP].width -
					padding[TOP] - height -
					padding[BOTTOM] - border[BOTTOM].width -
					margin[BOTTOM];
		} else if (top == AUTO && height != AUTO && bottom != AUTO) {
			top = containing_block->height -
					margin[TOP] - border[TOP].width -
					padding[TOP] - height -
					padding[BOTTOM] - border[BOTTOM].width -
					margin[BOTTOM] - bottom;
		} else if (top != AUTO && height == AUTO && bottom != AUTO) {
			height = containing_block->height -
					top - margin[TOP] - border[TOP].width -
					padding[TOP] - padding[BOTTOM] -
					border[BOTTOM].width - margin[BOTTOM] -
					bottom;
		} else if (top != AUTO && height != AUTO && bottom == AUTO) {
			bottom = containing_block->height -
					top - margin[TOP] - border[TOP].width -
					padding[TOP] - height -
					padding[BOTTOM] - border[BOTTOM].width -
					margin[BOTTOM];
		}
	}

#ifdef LAYOUT_DEBUG
	LOG(("%i + %i + %i + %i + %i + %i + %i + %i + %i = %i",
			top, margin[TOP], border[TOP].width, padding[TOP],
			height, padding[BOTTOM], border[BOTTOM].width,
			margin[BOTTOM], bottom,
			containing_block->height));
#endif

	box->y = top + margin[TOP] + border[TOP].width - cy;
	if (containing_block->type == BOX_BLOCK ||
			containing_block->type == BOX_INLINE_BLOCK ||
			containing_block->type == BOX_TABLE_CELL) {
		/* Block-level ancestor => reset container's height */
		containing_block->height -= containing_block->padding[TOP] +
				containing_block->padding[BOTTOM];
	} else {
		/** \todo Inline ancestors */
	}
	box->height = height;
	layout_apply_minmax_height(box, containing_block);

	return true;
}


/**
 * Compute box offsets for a relatively or absolutely positioned box with
 * respect to a box.
 *
 * \param  box               box to compute offsets for
 * \param  containing_block  box to compute percentages with respect to
 * \param  top               updated to top offset, or AUTO
 * \param  right             updated to right offset, or AUTO
 * \param  bottom            updated to bottom offset, or AUTO
 * \param  left              updated to left offset, or AUTO
 *
 * See CSS 2.1 9.3.2. containing_block must have width and height.
 */

void layout_compute_offsets(struct box *box,
		struct box *containing_block,
		int *top, int *right, int *bottom, int *left)
{
	uint32_t type;
	css_fixed value = 0;
	css_unit unit = CSS_UNIT_PX;

	assert(containing_block->width != UNKNOWN_WIDTH &&
			containing_block->width != AUTO &&
			containing_block->height != AUTO);

	/* left */
	type = css_computed_left(box->style, &value, &unit);
	if (type == CSS_LEFT_SET) {
		if (unit == CSS_UNIT_PCT) {
			*left = FPCT_OF_INT_TOINT(value,
					containing_block->width);
		} else {
			*left = FIXTOINT(nscss_len2px(value, unit, box->style));
		}
	} else {
		*left = AUTO;
	}

	/* right */
	type = css_computed_right(box->style, &value, &unit);
	if (type == CSS_RIGHT_SET) {
		if (unit == CSS_UNIT_PCT) {
			*right = FPCT_OF_INT_TOINT(value,
					containing_block->width);
		} else {
			*right = FIXTOINT(nscss_len2px(value, unit,
					box->style));
		}
	} else {
		*right = AUTO;
	}

	/* top */
	type = css_computed_top(box->style, &value, &unit);
	if (type == CSS_TOP_SET) {
		if (unit == CSS_UNIT_PCT) {
			*top = FPCT_OF_INT_TOINT(value,
					containing_block->height);
		} else {
			*top = FIXTOINT(nscss_len2px(value, unit, box->style));
		}
	} else {
		*top = AUTO;
	}

	/* bottom */
	type = css_computed_bottom(box->style, &value, &unit);
	if (type == CSS_BOTTOM_SET) {
		if (unit == CSS_UNIT_PCT) {
			*bottom = FPCT_OF_INT_TOINT(value,
					containing_block->height);
		} else {
			*bottom = FIXTOINT(nscss_len2px(value, unit,
					box->style));
		}
	} else {
		*bottom = AUTO;
	}
}


/**
 * Find a box's bounding box relative to itself, i.e. the box's border edge box
 *
 * \param  box      box find bounding box of
 * \param  desc_x0  updated to left of box's bbox
 * \param  desc_y0  updated to top of box's bbox
 * \param  desc_x1  updated to right of box's bbox
 * \param  desc_y1  updated to bottom of box's bbox
 */

static void layout_get_box_bbox(struct box *box, int *desc_x0, int *desc_y0,
		int *desc_x1, int *desc_y1)
{
	*desc_x0 = -box->border[LEFT].width;
	*desc_y0 = -box->border[TOP].width;
	*desc_x1 = box->padding[LEFT] + box->width + box->padding[RIGHT] +
			box->border[RIGHT].width;
	*desc_y1 = box->padding[TOP] + box->height + box->padding[BOTTOM] +
			box->border[BOTTOM].width;
}


/**
 * Apply changes to box descendant_[xy][01] values due to given child.
 *
 * \param  box    box to update
 * \param  child  a box, which may affect box's descendant bbox
 * \param  off_x  offset to apply to child->x coord to treat as child of box
 * \param  off_y  offset to apply to child->y coord to treat as child of box
 */

static void layout_update_descendant_bbox(struct box *box, struct box *child,
		int off_x, int off_y)
{
	int child_desc_x0, child_desc_y0, child_desc_x1, child_desc_y1;

	/* get coordinates of child relative to box */
	int child_x = child->x - off_x;
	int child_y = child->y - off_y;

	bool html_object = (child->object &&
			content_get_type(child->object) == CONTENT_HTML);

	if (child->style == NULL ||
			(child->style && css_computed_overflow(child->style) ==
			CSS_OVERFLOW_VISIBLE && html_object == false)) {
		/* get child's descendant bbox relative to box */
		child_desc_x0 = child_x + child->descendant_x0;
		child_desc_y0 = child_y + child->descendant_y0;
		child_desc_x1 = child_x + child->descendant_x1;
		child_desc_y1 = child_y + child->descendant_y1;
	} else {
		/* child's descendants don't matter; use child's border edge */
		layout_get_box_bbox(child, &child_desc_x0, &child_desc_y0,
				&child_desc_x1, &child_desc_y1);
		/* get the bbox relative to box */
		child_desc_x0 += child_x;
		child_desc_y0 += child_y;
		child_desc_x1 += child_x;
		child_desc_y1 += child_y;
	}

	/* increase box's descendant bbox to contain descendants */
	if (child_desc_x0 < box->descendant_x0)
		box->descendant_x0 = child_desc_x0;
	if (child_desc_y0 < box->descendant_y0)
		box->descendant_y0 = child_desc_y0;
	if (box->descendant_x1 < child_desc_x1)
		box->descendant_x1 = child_desc_x1;
	if (box->descendant_y1 < child_desc_y1)
		box->descendant_y1 = child_desc_y1;
}


/**
 * Recursively calculate the descendant_[xy][01] values for a laid-out box tree.
 *
 * \param  box  tree of boxes to update
 */

void layout_calculate_descendant_bboxes(struct box *box)
{
	struct box *child;

	assert((box->width != UNKNOWN_WIDTH) && (box->height != AUTO));
	/* assert((box->width >= 0) && (box->height >= 0)); */

	/* Initialise box's descendant box to border edge box */
	layout_get_box_bbox(box, &box->descendant_x0, &box->descendant_y0,
			&box->descendant_x1, &box->descendant_y1);

	/* Extend it to contain HTML contents if box is replaced */
	if (box->object && content_get_type(box->object) == CONTENT_HTML) {
		if (box->descendant_x1 < content_get_width(box->object))
			box->descendant_x1 = content_get_width(box->object);
		if (box->descendant_y1 < content_get_height(box->object))
			box->descendant_y1 = content_get_height(box->object);
	}

	if (box->type == BOX_INLINE || box->type == BOX_TEXT)
		return;

	if (box->type == BOX_INLINE_END) {
		box = box->inline_end;
		for (child = box->next; child;
				child = child->next) {
			if (child->type == BOX_FLOAT_LEFT ||
					child->type == BOX_FLOAT_RIGHT)
				continue;

			layout_update_descendant_bbox(box, child,
					box->x, box->y);

			if (child == box->inline_end)
				break;
		}
		return;
	}

	for (child = box->children; child; child = child->next) {
		if (child->type == BOX_FLOAT_LEFT ||
				child->type == BOX_FLOAT_RIGHT)
			continue;

		layout_calculate_descendant_bboxes(child);

		if (box->style && css_computed_overflow(box->style) ==
				CSS_OVERFLOW_HIDDEN)
			continue;

		layout_update_descendant_bbox(box, child, 0, 0);
	}

	for (child = box->float_children; child; child = child->next_float) {
		assert(child->type == BOX_FLOAT_LEFT ||
				child->type == BOX_FLOAT_RIGHT);

		layout_calculate_descendant_bboxes(child);

		layout_update_descendant_bbox(box, child, 0, 0);
	}

	if (box->list_marker) {
		child = box->list_marker;
		layout_calculate_descendant_bboxes(child);

		layout_update_descendant_bbox(box, child, 0, 0);
	}
}