1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
//! # Page-Aware Layout Engine
//!
//! This is the heart of Forme and the reason it exists.
//!
//! ## The Problem With Every Other Engine
//!
//! Most PDF renderers do this:
//! 1. Lay out all content on an infinitely tall canvas
//! 2. Slice the canvas into pages
//! 3. Try to fix the things that broke at slice points
//!
//! Step 3 is where everything falls apart. Flexbox layouts collapse because
//! the flex algorithm ran on the pre-sliced dimensions. Table rows get split
//! in the wrong places. Headers don't repeat. Content gets "mashed together."
//!
//! ## How Forme Works
//!
//! Forme never creates an infinite canvas. The layout algorithm is:
//!
//! 1. Open a page with known dimensions and remaining space
//! 2. Place each child node. Before placing, ask: "does this fit?"
//! 3. If it fits: place it, reduce remaining space
//! 4. If it doesn't fit and is unbreakable: start a new page, place it there
//! 5. If it doesn't fit and is breakable: place what fits, split the rest
//! to a new page, and RE-RUN flex layout on both fragments
//! 6. For tables: when splitting, clone the header rows onto the new page
//!
//! The key insight in step 5: when a flex container splits across pages,
//! BOTH fragments get their own independent flex layout pass. This is why
//! react-pdf's flex breaks on page wrap — it runs flex once on the whole
//! container and then slices, so the flex calculations are wrong on both
//! halves. We run flex AFTER splitting.
pub mod audit;
pub mod flex;
pub mod grid;
pub mod page_break;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use serde::Serialize;
use crate::font::FontContext;
use crate::model::*;
use crate::style::*;
use crate::text::bidi;
use crate::text::shaping;
use crate::text::{BrokenLine, RunBrokenLine, StyledChar, TextLayout};
/// A bookmark entry collected during layout.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BookmarkEntry {
pub title: String,
pub page_index: usize,
pub y: f64,
}
// ── Serializable layout metadata (for debug overlays / dev tools) ───
/// Complete layout metadata for all pages.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LayoutInfo {
pub pages: Vec<PageInfo>,
}
/// Layout metadata for a single page.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PageInfo {
pub width: f64,
pub height: f64,
pub content_x: f64,
pub content_y: f64,
pub content_width: f64,
pub content_height: f64,
pub elements: Vec<ElementInfo>,
}
/// Serializable snapshot of ResolvedStyle for the inspector panel.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ElementStyleInfo {
// Box model
pub margin: Edges,
pub padding: Edges,
pub border_width: Edges,
#[serde(skip_serializing_if = "Option::is_none")]
pub width: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub height: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_width: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_height: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_width: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_height: Option<f64>,
// Flex
pub flex_direction: FlexDirection,
pub justify_content: JustifyContent,
pub align_items: AlignItems,
#[serde(skip_serializing_if = "Option::is_none")]
pub align_self: Option<AlignItems>,
pub flex_wrap: FlexWrap,
pub align_content: AlignContent,
pub flex_grow: f64,
pub flex_shrink: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub flex_basis: Option<String>,
pub gap: f64,
pub row_gap: f64,
pub column_gap: f64,
// Text
pub font_family: String,
pub font_size: f64,
pub font_weight: u32,
pub font_style: FontStyle,
pub line_height: f64,
pub text_align: TextAlign,
pub letter_spacing: f64,
pub text_decoration: TextDecoration,
pub text_transform: TextTransform,
// Visual
pub color: Color,
pub background_color: Option<Color>,
pub border_color: EdgeValues<Color>,
pub border_style: EdgeValues<crate::style::BorderStyle>,
pub border_radius: CornerValues,
pub opacity: f64,
// Positioning
pub position: Position,
#[serde(skip_serializing_if = "Option::is_none")]
pub top: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub right: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bottom: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub left: Option<f64>,
// Overflow
pub overflow: Overflow,
// Page behavior
pub breakable: bool,
pub break_before: bool,
pub min_widow_lines: u32,
pub min_orphan_lines: u32,
}
fn size_constraint_to_str(sc: &SizeConstraint) -> Option<String> {
match sc {
SizeConstraint::Auto => None,
SizeConstraint::Fixed(v) => Some(format!("{v}")),
}
}
impl ElementStyleInfo {
fn from_resolved(style: &ResolvedStyle) -> Self {
ElementStyleInfo {
margin: style.margin.to_edges(),
padding: style.padding,
border_width: style.border_width,
width: size_constraint_to_str(&style.width),
height: size_constraint_to_str(&style.height),
min_width: if style.min_width > 0.0 {
Some(style.min_width)
} else {
None
},
min_height: if style.min_height > 0.0 {
Some(style.min_height)
} else {
None
},
max_width: if style.max_width.is_finite() {
Some(style.max_width)
} else {
None
},
max_height: if style.max_height.is_finite() {
Some(style.max_height)
} else {
None
},
flex_direction: style.flex_direction,
justify_content: style.justify_content,
align_items: style.align_items,
align_self: style.align_self,
flex_wrap: style.flex_wrap,
align_content: style.align_content,
flex_grow: style.flex_grow,
flex_shrink: style.flex_shrink,
flex_basis: size_constraint_to_str(&style.flex_basis),
gap: style.gap,
row_gap: style.row_gap,
column_gap: style.column_gap,
font_family: style.font_family.clone(),
font_size: style.font_size,
font_weight: style.font_weight,
font_style: style.font_style,
line_height: style.line_height,
text_align: style.text_align,
letter_spacing: style.letter_spacing,
text_decoration: style.text_decoration,
text_transform: style.text_transform,
color: style.color,
background_color: style.background_color,
border_color: style.border_color,
border_style: style.border_style,
border_radius: style.border_radius,
opacity: style.opacity,
position: style.position,
top: style.top,
right: style.right,
bottom: style.bottom,
left: style.left,
overflow: style.overflow,
breakable: style.breakable,
break_before: style.break_before,
min_widow_lines: style.min_widow_lines,
min_orphan_lines: style.min_orphan_lines,
}
}
}
impl Default for ElementStyleInfo {
fn default() -> Self {
ElementStyleInfo {
margin: Edges::default(),
padding: Edges::default(),
border_width: Edges::default(),
width: None,
height: None,
min_width: None,
min_height: None,
max_width: None,
max_height: None,
flex_direction: FlexDirection::default(),
justify_content: JustifyContent::default(),
align_items: AlignItems::default(),
align_self: None,
flex_wrap: FlexWrap::default(),
align_content: AlignContent::default(),
flex_grow: 0.0,
flex_shrink: 1.0,
flex_basis: None,
gap: 0.0,
row_gap: 0.0,
column_gap: 0.0,
font_family: "Helvetica".to_string(),
font_size: 12.0,
font_weight: 400,
font_style: FontStyle::default(),
line_height: 1.4,
text_align: TextAlign::default(),
letter_spacing: 0.0,
text_decoration: TextDecoration::None,
text_transform: TextTransform::None,
color: Color::BLACK,
background_color: None,
border_color: EdgeValues::uniform(Color::BLACK),
border_style: EdgeValues::uniform(crate::style::BorderStyle::Solid),
border_radius: CornerValues::uniform(0.0),
opacity: 1.0,
position: Position::default(),
top: None,
right: None,
bottom: None,
left: None,
overflow: Overflow::default(),
breakable: false,
break_before: false,
min_widow_lines: 2,
min_orphan_lines: 2,
}
}
}
/// Layout metadata for a single positioned element (hierarchical).
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ElementInfo {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
/// DrawCommand-based kind (Rect, Text, Image, etc.) for backward compat.
pub kind: String,
/// Logical node type (View, Text, Image, TableRow, etc.).
pub node_type: String,
/// Resolved style snapshot for the inspector panel.
pub style: ElementStyleInfo,
/// Child elements (preserves hierarchy).
pub children: Vec<ElementInfo>,
/// Source code location for click-to-source.
#[serde(skip_serializing_if = "Option::is_none")]
pub source_location: Option<SourceLocation>,
/// Text content extracted from TextLine draw commands (for component tree).
#[serde(skip_serializing_if = "Option::is_none")]
pub text_content: Option<String>,
/// Optional hyperlink URL.
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<String>,
/// Optional bookmark title.
#[serde(skip_serializing_if = "Option::is_none")]
pub bookmark: Option<String>,
}
impl LayoutInfo {
/// Extract serializable layout metadata from laid-out pages.
pub fn from_pages(pages: &[LayoutPage]) -> Self {
LayoutInfo {
pages: pages
.iter()
.map(|page| {
let (page_w, page_h) = page.config.size.dimensions();
let content_x = page.config.margin.left;
let content_y = page.config.margin.top;
let content_width = page_w - page.config.margin.horizontal();
let content_height = page_h - page.config.margin.vertical();
let elements = Self::build_element_tree(&page.elements);
PageInfo {
width: page_w,
height: page_h,
content_x,
content_y,
content_width,
content_height,
elements,
}
})
.collect(),
}
}
fn build_element_tree(elems: &[LayoutElement]) -> Vec<ElementInfo> {
elems
.iter()
.map(|elem| {
let kind = match &elem.draw {
DrawCommand::None => "None",
DrawCommand::Rect { .. } => "Rect",
DrawCommand::Text { .. } => "Text",
DrawCommand::Image { .. } => "Image",
DrawCommand::ImagePlaceholder => "ImagePlaceholder",
DrawCommand::Svg { .. } => "Svg",
DrawCommand::Barcode { .. } => "Barcode",
DrawCommand::QrCode { .. } => "QrCode",
DrawCommand::Chart { .. } => "Chart",
DrawCommand::Watermark { .. } => "Watermark",
DrawCommand::FormField { .. } => "FormField",
};
let text_content = match &elem.draw {
DrawCommand::Text { lines, .. } => {
let text: String = lines
.iter()
.flat_map(|line| {
line.glyphs.iter().flat_map(|g| {
// Use cluster_text for ligatures (e.g., "fi" → 2 chars)
g.cluster_text.as_deref().unwrap_or("").chars().chain(
if g.cluster_text.is_none() {
Some(g.char_value)
} else {
None
},
)
})
})
.collect();
if text.is_empty() {
None
} else {
Some(text)
}
}
_ => None,
};
let node_type = elem.node_type.clone().unwrap_or_else(|| kind.to_string());
let style = elem
.resolved_style
.as_ref()
.map(ElementStyleInfo::from_resolved)
.unwrap_or_default();
ElementInfo {
x: elem.x,
y: elem.y,
width: elem.width,
height: elem.height,
kind: kind.to_string(),
node_type,
style,
children: Self::build_element_tree(&elem.children),
source_location: elem.source_location.clone(),
text_content,
href: elem.href.clone(),
bookmark: elem.bookmark.clone(),
}
})
.collect()
}
}
/// A fully laid-out page ready for PDF serialization.
#[derive(Debug, Clone)]
pub struct LayoutPage {
pub width: f64,
pub height: f64,
pub elements: Vec<LayoutElement>,
/// Fixed header nodes to inject after layout (internal use).
pub(crate) fixed_header: Vec<(Node, f64)>,
/// Fixed footer nodes to inject after layout (internal use).
pub(crate) fixed_footer: Vec<(Node, f64)>,
/// Watermark nodes to inject after layout (internal use).
pub(crate) watermarks: Vec<Node>,
/// Page config needed for fixed element layout (internal use).
pub(crate) config: PageConfig,
/// The page's NAME (CSS `page` property), for fixed-element scoping.
pub(crate) page_name: Option<String>,
}
/// A positioned element on a page.
#[derive(Debug, Clone)]
pub struct LayoutElement {
/// Absolute position on the page (top-left corner).
pub x: f64,
pub y: f64,
/// Dimensions including padding and border, excluding margin.
pub width: f64,
pub height: f64,
/// The visual properties to draw.
pub draw: DrawCommand,
/// Child elements (positioned relative to page, not parent).
pub children: Vec<LayoutElement>,
/// Logical node type for dev tools (e.g. "View", "Text", "Image").
pub node_type: Option<String>,
/// Resolved style snapshot for inspector panel.
pub resolved_style: Option<ResolvedStyle>,
/// Source code location for click-to-source in the dev inspector.
pub source_location: Option<SourceLocation>,
/// Optional hyperlink URL for link annotations.
pub href: Option<String>,
/// Optional bookmark title for PDF outline entries.
pub bookmark: Option<String>,
/// Optional alt text for images and SVGs (accessibility).
pub alt: Option<String>,
/// Whether this is a table header row (for tagged PDF: TH vs TD).
pub is_header_row: bool,
/// Number of columns this table cell spans (for tagged PDF: /ColSpan).
/// 1 for every non-cell element and for unspanned cells.
pub col_span: u32,
/// Overflow behavior (Visible or Hidden). When Hidden, PDF clips children.
pub overflow: Overflow,
/// Opacity for the entire element including its children (0.0–1.0). The
/// PDF serializer wraps `write_element` in a `q\n/GS{n} gs ... Q` block
/// when this is < 1.0, so descendants render at the cumulative alpha.
/// Default is 1.0 (no extra wrap).
pub opacity: f64,
}
/// Does a fixed node appear on a page, considering the parity/first
/// filter and page-name scoping (`@page <name>` margin boxes)?
fn fixed_applies_on(node: &Node, page_index: usize, page_name: Option<&str>) -> bool {
match &node.kind {
NodeKind::Fixed {
pages,
page_name: only,
exclude_page_names,
..
} => {
pages.applies(page_index)
&& match only {
Some(n) => page_name == Some(n.as_str()),
None => true,
}
&& !exclude_page_names
.iter()
.any(|n| page_name == Some(n.as_str()))
}
_ => true,
}
}
/// Return a human-readable name for a NodeKind variant.
fn node_kind_name(kind: &NodeKind) -> &'static str {
match kind {
NodeKind::View => "View",
NodeKind::Text { .. } => "Text",
NodeKind::Heading { level: 1, .. } => "H1",
NodeKind::Heading { level: 2, .. } => "H2",
NodeKind::Heading { level: 3, .. } => "H3",
NodeKind::Heading { level: 4, .. } => "H4",
NodeKind::Heading { level: 5, .. } => "H5",
// Default clamps levels outside 1..=6 to H6 (matches HTML's
// tolerance: invalid levels still render as the deepest heading
// rather than vanishing).
NodeKind::Heading { .. } => "H6",
NodeKind::List { .. } => "List",
NodeKind::ListItem => "ListItem",
NodeKind::Image { .. } => "Image",
NodeKind::Table { .. } => "Table",
NodeKind::TableRow { .. } => "TableRow",
NodeKind::TableCell { .. } => "TableCell",
NodeKind::Fixed {
position: FixedPosition::Header,
..
} => "FixedHeader",
NodeKind::Fixed {
position: FixedPosition::Footer,
..
} => "FixedFooter",
NodeKind::Page { .. } => "Page",
NodeKind::PageBreak => "PageBreak",
NodeKind::PageName { .. } => "PageName",
NodeKind::Svg { .. } => "Svg",
NodeKind::Canvas { .. } => "Canvas",
NodeKind::Barcode { .. } => "Barcode",
NodeKind::QrCode { .. } => "QrCode",
NodeKind::BarChart { .. } => "BarChart",
NodeKind::LineChart { .. } => "LineChart",
NodeKind::PieChart { .. } => "PieChart",
NodeKind::AreaChart { .. } => "AreaChart",
NodeKind::DotPlot { .. } => "DotPlot",
NodeKind::Watermark { .. } => "Watermark",
NodeKind::TextField { .. } => "TextField",
NodeKind::Checkbox { .. } => "Checkbox",
NodeKind::Dropdown { .. } => "Dropdown",
NodeKind::RadioButton { .. } => "RadioButton",
}
}
/// Build the zero-height marker element that carries a container's `bookmark`
/// into the PDF outline, or `None` if the node has no bookmark.
///
/// Both container paths (`layout_view`'s fits branch and `layout_breakable_view`)
/// go through this so the marker is the *single* carrier of the bookmark on
/// either path. That matters twice over:
///
/// - `layout_breakable_view` can skip building a wrapper entirely (see
/// `needs_wrapper`), so without a marker an unstyled overflowing view would
/// lose its bookmark outright.
/// - `collect_bookmarks` walks every element and every descendant, so leaving
/// the bookmark on *both* the marker and its enclosing wrapper emits the
/// outline entry twice. One carrier, one entry.
///
/// `node_type` must be set explicitly: leaving it `None` makes the LayoutInfo
/// serializer fall back to `kind.to_string()`, which leaks the
/// `DrawCommand::None` variant name into `nodeType` as the string "None" — not
/// a value in the public `ElementNodeType` union.
fn bookmark_marker(node: &Node, x: f64, y: f64) -> Option<LayoutElement> {
node.bookmark.as_ref().map(|title| LayoutElement {
x,
y,
width: 0.0,
height: 0.0,
draw: DrawCommand::None,
children: vec![],
node_type: Some("Bookmark".to_string()),
resolved_style: None,
source_location: None,
href: None,
bookmark: Some(title.clone()),
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
})
}
// ─── List marker helpers ────────────────────────────────────────────
/// Produce the visible marker text for a list item at the given index.
/// For unordered lists, returns the bullet glyph (or empty for `None`).
/// For ordered lists, returns the index in the chosen numbering system
/// followed by a period (e.g. "3.", "iii.", "c.").
fn format_marker(idx: u32, ordered: bool, marker_type: ListMarkerType) -> String {
if !ordered {
// v1: Disc/Circle/Square all render as "•" (U+2022 BULLET),
// which is in standard fonts' WinAnsi range. Proper distinct
// glyphs for circle/square are a follow-up.
return match marker_type {
ListMarkerType::None => String::new(),
_ => "•".to_string(),
};
}
let body = match marker_type {
ListMarkerType::LowerAlpha => to_alpha(idx, false),
ListMarkerType::UpperAlpha => to_alpha(idx, true),
ListMarkerType::LowerRoman => to_roman(idx, false),
ListMarkerType::UpperRoman => to_roman(idx, true),
ListMarkerType::None => return String::new(),
// Decimal + every unordered variant routed here (caller shouldn't
// mix unordered marker_type with ordered=true, but be permissive).
_ => idx.to_string(),
};
format!("{body}.")
}
/// Convert a 1-based index to an alphabetic marker (a, b, ..., z, aa,
/// ab, ...). `upper = true` returns uppercase letters.
fn to_alpha(mut n: u32, upper: bool) -> String {
if n == 0 {
return String::new();
}
let base = if upper { b'A' } else { b'a' };
let mut bytes: Vec<u8> = Vec::new();
while n > 0 {
let rem = ((n - 1) % 26) as u8;
bytes.push(base + rem);
n = (n - 1) / 26;
}
bytes.reverse();
String::from_utf8(bytes).unwrap_or_default()
}
/// Convert a 1-based index to a Roman numeral. `upper = true` returns
/// uppercase. Falls back to the decimal representation for n outside
/// 1..=3999 (Roman numerals lose meaning past that).
fn to_roman(n: u32, upper: bool) -> String {
if n == 0 || n > 3999 {
return n.to_string();
}
const UPPER: &[(&str, u32)] = &[
("M", 1000),
("CM", 900),
("D", 500),
("CD", 400),
("C", 100),
("XC", 90),
("L", 50),
("XL", 40),
("X", 10),
("IX", 9),
("V", 5),
("IV", 4),
("I", 1),
];
const LOWER: &[(&str, u32)] = &[
("m", 1000),
("cm", 900),
("d", 500),
("cd", 400),
("c", 100),
("xc", 90),
("l", 50),
("xl", 40),
("x", 10),
("ix", 9),
("v", 5),
("iv", 4),
("i", 1),
];
let table = if upper { UPPER } else { LOWER };
let mut out = String::new();
let mut remaining = n;
for &(sym, val) in table {
while remaining >= val {
out.push_str(sym);
remaining -= val;
}
}
out
}
/// Reserve a left-side gutter wide enough to fit the widest marker the
/// list will render at its font size, plus a small gap. v1 uses an
/// approximation based on font-size × char-count rather than measuring
/// each marker through the FontContext — works well in practice for the
/// standard latin fonts and avoids threading font measurement through
/// the layout entry-point.
fn compute_marker_gutter_width(
ordered: bool,
marker_type: ListMarkerType,
start: u32,
n_items: u32,
style: &ResolvedStyle,
) -> f64 {
if matches!(marker_type, ListMarkerType::None) {
return 0.0;
}
// Approximate average character advance — close enough for the gutter.
let approx_char_w = style.font_size * 0.6;
let gap = 6.0_f64;
if !ordered {
// Bullet glyph (one char) + gap.
return approx_char_w + gap;
}
// Pick the widest marker the list will ever emit (the last one).
let last_idx = start + n_items.saturating_sub(1);
let widest = match marker_type {
ListMarkerType::Decimal => format_marker(last_idx, true, ListMarkerType::Decimal),
ListMarkerType::LowerAlpha => format_marker(last_idx, true, ListMarkerType::LowerAlpha),
ListMarkerType::UpperAlpha => format_marker(last_idx, true, ListMarkerType::UpperAlpha),
ListMarkerType::LowerRoman => format_marker(last_idx, true, ListMarkerType::LowerRoman),
ListMarkerType::UpperRoman => format_marker(last_idx, true, ListMarkerType::UpperRoman),
_ => format_marker(last_idx, true, ListMarkerType::Decimal),
};
widest.chars().count() as f64 * approx_char_w + gap
}
/// Configuration for an interactive PDF form field.
#[derive(Debug, Clone)]
pub enum FormFieldType {
TextField {
value: Option<String>,
placeholder: Option<String>,
multiline: bool,
password: bool,
read_only: bool,
max_length: Option<u32>,
font_size: f64,
},
Checkbox {
checked: bool,
read_only: bool,
},
Dropdown {
options: Vec<String>,
value: Option<String>,
read_only: bool,
font_size: f64,
},
RadioButton {
value: String,
checked: bool,
read_only: bool,
},
}
/// What to actually draw for this element.
#[derive(Debug, Clone)]
pub enum DrawCommand {
/// Nothing to draw (just a layout container).
None,
/// Draw a rectangle (background, border).
Rect {
background: Option<Color>,
border_width: Edges,
border_color: EdgeValues<Color>,
border_style: EdgeValues<crate::style::BorderStyle>,
border_radius: CornerValues,
opacity: f64,
/// Optional drop shadow rendered before the background. Boxed
/// to keep the `DrawCommand` enum's largest variant size down.
box_shadow: Option<Box<crate::style::BoxShadow>>,
/// Optional gradient paint. When `Some`, takes precedence over
/// `background` (solid color). Boxed for the same enum-size
/// reason as `box_shadow`.
background_gradient: Option<Box<crate::style::Background>>,
},
/// Draw text.
Text {
lines: Vec<TextLine>,
color: Color,
text_decoration: TextDecoration,
opacity: f64,
},
/// Draw an image.
Image {
image_data: crate::image_loader::LoadedImage,
},
/// Draw a grey placeholder rectangle (fallback when image loading fails).
ImagePlaceholder,
/// Draw SVG vector graphics.
Svg {
commands: Vec<crate::svg::SvgCommand>,
/// Display width (the rendered box width in points).
width: f64,
/// Display height (the rendered box height in points).
height: f64,
/// SVG viewBox origin / dimensions. When the user omits viewBox these
/// default to `(0, 0, width, height)` so the scale comes out to 1 and
/// the content stream behaves as if no transform was applied.
viewbox_min_x: f64,
viewbox_min_y: f64,
viewbox_width: f64,
viewbox_height: f64,
/// When true, clip content to [0, 0, width, height] (used by Canvas).
clip: bool,
},
/// Draw a 1D barcode as filled rectangles.
Barcode {
bars: Vec<u8>,
bar_width: f64,
height: f64,
color: Color,
},
/// Draw a QR code as filled rectangles.
QrCode {
modules: Vec<Vec<bool>>,
module_size: f64,
color: Color,
},
/// Draw a chart as a list of drawing primitives.
Chart {
primitives: Vec<crate::chart::ChartPrimitive>,
},
/// Draw a watermark (rotated text with opacity).
Watermark {
lines: Vec<TextLine>,
color: Color,
opacity: f64,
angle_rad: f64,
/// Font family used (for PDF font registration).
font_family: String,
},
/// An interactive PDF form field (AcroForm widget annotation).
FormField {
field_type: FormFieldType,
name: String,
},
}
#[derive(Debug, Clone)]
pub struct TextLine {
pub x: f64,
pub y: f64,
pub glyphs: Vec<PositionedGlyph>,
pub width: f64,
pub height: f64,
/// Extra width added to each space character for justification (PDF `Tw` operator).
pub word_spacing: f64,
}
#[derive(Debug, Clone)]
pub struct PositionedGlyph {
/// Glyph ID. For custom fonts with shaping, this is a real GID from GSUB.
/// For standard fonts, this is `char as u16` (Unicode codepoint).
pub glyph_id: u16,
/// X position relative to line start.
pub x_offset: f64,
/// Y offset from GPOS (e.g., mark positioning). Usually 0.0.
pub y_offset: f64,
/// Actual advance width of this glyph in points (from shaping or font metrics).
pub x_advance: f64,
pub font_size: f64,
/// Shared font family. `Arc<str>` (not `String`) so cloning a glyph — which
/// happens millions of times per large doc via TextLine/subtree clones and
/// measure trial-layouts — is a refcount bump, not a heap allocation. dhat
/// flagged this field's per-glyph `String` clone as the #1 site by count
/// (~29% of all allocations). See benchmarks/harness/dhat-top.mjs.
pub font_family: Arc<str>,
pub font_weight: u32,
pub font_style: FontStyle,
/// The character this glyph represents. For ligatures, the first char of the cluster.
pub char_value: char,
/// Per-glyph color (for text runs with different colors).
pub color: Option<Color>,
/// Per-glyph href (for inline links within runs).
pub href: Option<String>,
/// Per-glyph text decoration (for runs with different decorations).
pub text_decoration: TextDecoration,
/// Letter spacing applied to this glyph.
pub letter_spacing: f64,
/// For ligature glyphs, the full cluster text (e.g., "fi" for an fi ligature).
/// `None` for 1:1 char-to-glyph mappings.
pub cluster_text: Option<String>,
}
/// Shift a layout element and all its nested content (children, text lines)
/// down by `dy` points. Used to reposition footer elements after layout.
fn offset_element_y(el: &mut LayoutElement, dy: f64) {
el.y += dy;
if let DrawCommand::Text { ref mut lines, .. } = el.draw {
for line in lines.iter_mut() {
line.y += dy;
}
}
for child in &mut el.children {
offset_element_y(child, dy);
}
}
/// Shift a layout element and all its nested content horizontally by `dx` points.
fn offset_element_x(el: &mut LayoutElement, dx: f64) {
el.x += dx;
if let DrawCommand::Text { ref mut lines, .. } = el.draw {
for line in lines.iter_mut() {
line.x += dx;
}
}
for child in &mut el.children {
offset_element_x(child, dx);
}
}
/// After flex-grow expands an element's height, redistribute its children
/// vertically according to its justify-content setting. Only meaningful for
/// column containers whose height was just increased by flex-grow.
fn reapply_justify_content(elem: &mut LayoutElement) {
let style = match elem.resolved_style {
Some(ref s) => s,
None => return,
};
if matches!(style.justify_content, JustifyContent::FlexStart) {
return;
}
if elem.children.is_empty() {
return;
}
let padding_top = style.padding.top + style.border_width.top;
let padding_bottom = style.padding.bottom + style.border_width.bottom;
let inner_h = elem.height - padding_top - padding_bottom;
let content_top = elem.y + padding_top;
// Find the span of children content
let last_child = &elem.children[elem.children.len() - 1];
let children_bottom = last_child.y + last_child.height;
let children_span = children_bottom - content_top;
let slack = inner_h - children_span;
if slack < 0.001 {
return;
}
let n = elem.children.len();
let offsets: Vec<f64> = match style.justify_content {
JustifyContent::FlexEnd => vec![slack; n],
JustifyContent::Center => vec![slack / 2.0; n],
JustifyContent::SpaceBetween => {
if n <= 1 {
vec![0.0; n]
} else {
let per_gap = slack / (n - 1) as f64;
(0..n).map(|i| i as f64 * per_gap).collect()
}
}
JustifyContent::SpaceAround => {
let space = slack / n as f64;
(0..n).map(|i| space / 2.0 + i as f64 * space).collect()
}
JustifyContent::SpaceEvenly => {
let space = slack / (n + 1) as f64;
(0..n).map(|i| (i + 1) as f64 * space).collect()
}
JustifyContent::FlexStart => unreachable!(),
};
for (i, child) in elem.children.iter_mut().enumerate() {
let dy = offsets[i];
if dy.abs() > 0.001 {
offset_element_y(child, dy);
}
}
}
/// Apply a text transform to a string.
fn apply_text_transform(text: &str, transform: TextTransform) -> String {
match transform {
TextTransform::None => text.to_string(),
TextTransform::Uppercase => text.to_uppercase(),
TextTransform::Lowercase => text.to_lowercase(),
TextTransform::Capitalize => {
let mut result = String::with_capacity(text.len());
let mut prev_is_whitespace = true;
for ch in text.chars() {
if prev_is_whitespace && ch.is_alphabetic() {
for upper in ch.to_uppercase() {
result.push(upper);
}
} else {
result.push(ch);
}
prev_is_whitespace = ch.is_whitespace();
}
result
}
}
}
/// Sentinel character for `{{pageNumber}}` placeholder.
/// A single char that is atomic (can't be split by line breaking), measured
/// as the width of "00", and recognized by the PDF serializer for replacement.
pub const PAGE_NUMBER_SENTINEL: char = '\x02';
/// Sentinel character for `{{totalPages}}` placeholder.
pub const TOTAL_PAGES_SENTINEL: char = '\x03';
/// Replace page number placeholders with single sentinel characters.
/// The sentinels are measured as the width of "00" by the font system,
/// are atomic (single char, so line breaking can't split them), and are
/// replaced with actual values by the PDF serializer.
fn substitute_page_placeholders(text: &str) -> String {
if text.contains("{{pageNumber}}") || text.contains("{{totalPages}}") {
text.replace("{{pageNumber}}", &PAGE_NUMBER_SENTINEL.to_string())
.replace("{{totalPages}}", &TOTAL_PAGES_SENTINEL.to_string())
} else {
text.to_string()
}
}
/// Apply a text transform to a single character, given whether it's the first
/// letter of a word (for Capitalize).
fn apply_char_transform(ch: char, transform: TextTransform, is_word_start: bool) -> char {
match transform {
TextTransform::None => ch,
TextTransform::Uppercase => ch.to_uppercase().next().unwrap_or(ch),
TextTransform::Lowercase => ch.to_lowercase().next().unwrap_or(ch),
TextTransform::Capitalize => {
if is_word_start && ch.is_alphabetic() {
ch.to_uppercase().next().unwrap_or(ch)
} else {
ch
}
}
}
}
/// The main layout engine.
pub struct LayoutEngine {
text_layout: TextLayout,
image_dim_cache: RefCell<HashMap<String, (u32, u32)>>,
/// THE RENDER-DEFECT CHANNEL.
///
/// The subset warnings answer "what did you ask for that we don't
/// support?" — this channel answers the other question: "what did WE
/// get wrong?" Every message here means the engine produced output it
/// knows is not what the document asked for (a table column below its
/// min-content width, clamped overflowing columns, ...). These are
/// prefixed "render defect:" and surface through the same warnings
/// stream. The template-compat experiment (template-compat/REPORT.md)
/// found every catastrophic silent failure lived in this blind spot —
/// more entries belong here as they're discovered.
warnings: RefCell<Vec<String>>,
/// THE MEASURE/LAYOUT AGREEMENT CHECK (env `FORME_MEASURE_CHECK=1`).
///
/// Four shipped bugs shared one shape: `measure_*` computed a height
/// layout never produced (table column count, table intrinsic width,
/// image phantom height, row-measure percent double-resolution) — two
/// code paths for the same quantity with nothing forcing agreement,
/// each divergence found by a user or a corpus experiment. This check
/// makes the invariant enforced instead of remembered: when an
/// auto-height view's measured children height exceeds what its
/// children actually occupied (no page break involved), a
/// "measure-check:" warning is emitted. Test gates render the fixture
/// corpus with this on and fail on any emission, so the fifth
/// divergence announces itself at development time.
measure_check: bool,
}
/// Tracks where we are on the current page during layout.
#[derive(Debug, Clone)]
struct PageCursor {
config: PageConfig,
/// The config subsequent pages use — differs from `config` only on a
/// first page created from `Document::first_page` (@page :first).
base_config: PageConfig,
/// 0-based index of this page within the document. Kept in sync with
/// the `pages` vec at document level; table cell-overflow pages can
/// briefly skew it, which only matters for First/NotFirst filters and
/// resolves at injection time where the real index is used.
page_index: usize,
content_width: f64,
content_height: f64,
y: f64,
elements: Vec<LayoutElement>,
fixed_header: Vec<(Node, f64)>,
fixed_footer: Vec<(Node, f64)>,
/// Watermark nodes stored for repetition on every page.
watermarks: Vec<Node>,
content_x: f64,
content_y: f64,
/// Extra Y offset applied on continuation pages (e.g. parent view's padding+border)
continuation_top_offset: f64,
/// The nearest positioned-ancestor content box `(x, y, width, height)` —
/// the containing block for `position: absolute` descendants. Defaults to
/// the page content box; updated when layout descends into a `relative`/
/// `absolute` element and restored on the way out.
containing_block: (f64, f64, f64, f64),
/// `@page :left` / `:right` configs, when the document declares them.
/// Flow layout ALWAYS uses `config`'s geometry; the parity config is
/// applied as the finalized page's config plus a constant x translation
/// of flow content (mirrored margins preserve content width by
/// construction, so a translation is exact — never a re-layout). Docs
/// without parity configs keep these `None` and run the exact same
/// instructions as before.
left_config: Option<PageConfig>,
right_config: Option<PageConfig>,
/// The config this page presents as (margin boxes, PDF margins,
/// LayoutInfo). Equals `config` unless a parity config selected.
display_config: Option<PageConfig>,
/// The margin-left flow content was ACTUALLY anchored at. Flowing
/// containers capture the first page's content_x and carry it across
/// page breaks (the bake), so the parity translation must be relative
/// to this anchor, not to the current cursor's nominal config.
flow_anchor_left: f64,
/// The active page NAME (CSS `page` property / `@page <name>`). Set
/// by `PageName` marker nodes; carried across breaks so every page of
/// a named run is named.
page_name: Option<String>,
/// Display for non-parity pages of the active (named) family — the
/// merged `@page <name>` horizontal geometry. `None` at document
/// level (unnamed non-parity pages have no translation).
base_display: Option<PageConfig>,
/// Display when the current page is the DOCUMENT first page
/// (`@page <name>:first`). Document-level `:first` uses the real
/// `new_first` config instead and keeps this `None`.
first_display: Option<PageConfig>,
/// Document-level flow family, kept for restoring after a named run:
/// the base real config and the doc `:left`/`:right` displays.
doc_base: PageConfig,
doc_left: Option<PageConfig>,
doc_right: Option<PageConfig>,
/// Named page families (from `Document::named_pages`).
named_sets: std::collections::HashMap<String, crate::model::NamedPageSet>,
}
impl PageCursor {
fn new(config: &PageConfig) -> Self {
let (page_w, page_h) = config.size.dimensions();
let content_width = page_w - config.margin.horizontal();
let content_height = page_h - config.margin.vertical();
Self {
config: config.clone(),
base_config: config.clone(),
page_index: 0,
content_width,
content_height,
y: 0.0,
elements: Vec::new(),
fixed_header: Vec::new(),
fixed_footer: Vec::new(),
watermarks: Vec::new(),
content_x: config.margin.left,
content_y: config.margin.top,
continuation_top_offset: 0.0,
containing_block: (
config.margin.left,
config.margin.top,
content_width,
content_height,
),
left_config: None,
right_config: None,
display_config: None,
flow_anchor_left: config.margin.left,
page_name: None,
base_display: None,
first_display: None,
doc_base: config.clone(),
doc_left: None,
doc_right: None,
named_sets: std::collections::HashMap::new(),
}
}
/// Select the display config for a 1-based page number from the
/// active family. Precedence per CSS Paged Media specificity:
/// `:first` (document page 1) over parity over the family base. Page
/// 1 is a RIGHT page (left-to-right page progression); document-level
/// `:first` uses a real config (`new_first`) and is handled at cursor
/// creation instead.
fn display_for(&self, page_number: usize) -> Option<PageConfig> {
if page_number == 1 {
if let Some(first) = &self.first_display {
return Some(first.clone());
}
}
let parity = if page_number % 2 == 1 {
self.right_config.clone()
} else {
self.left_config.clone()
};
parity.or_else(|| self.base_display.clone())
}
/// Does this fixed node appear on the current page, considering both
/// the parity/first filter and page-name scoping?
fn fixed_applies(&self, node: &Node) -> bool {
fixed_applies_on(node, self.page_index, self.page_name.as_deref())
}
/// Successor cursor for a page-NAME switch (CSS `page` property). The
/// new name's family supplies the REAL config (a named run starts at
/// a forced break, so vertical margins may genuinely differ) and the
/// display candidates; `None` restores the document-level family.
/// `in_place` renames the current (still empty) page instead of
/// starting the next one.
fn renamed_page(&self, name: Option<String>, in_place: bool) -> Self {
let set = name
.as_deref()
.and_then(|n| self.named_sets.get(n))
.cloned();
let real = set
.as_ref()
.map(|s| s.base.clone())
.unwrap_or_else(|| self.doc_base.clone());
let mut cursor = PageCursor::new(&real);
cursor.page_index = if in_place {
self.page_index
} else {
self.page_index + 1
};
cursor.page_name = name;
cursor.doc_base = self.doc_base.clone();
cursor.doc_left = self.doc_left.clone();
cursor.doc_right = self.doc_right.clone();
cursor.named_sets = self.named_sets.clone();
match &set {
Some(s) => {
cursor.left_config = s.display_left.clone();
cursor.right_config = s.display_right.clone();
cursor.base_display = s.display.clone();
cursor.first_display = s.display_first.clone();
}
None => {
// Unknown or absent name: the document family still
// applies (CSS: `:left`/`:right`/base match named pages
// too when no named rule overrides them).
cursor.left_config = self.doc_left.clone();
cursor.right_config = self.doc_right.clone();
}
}
cursor.display_config = cursor.display_for(cursor.page_index + 1);
cursor.flow_anchor_left = self.flow_anchor_left;
cursor.fixed_header = self.fixed_header.clone();
cursor.fixed_footer = self.fixed_footer.clone();
cursor.watermarks = self.watermarks.clone();
cursor.continuation_top_offset = self.continuation_top_offset;
let header_height: f64 = cursor
.fixed_header
.iter()
.filter(|(n, _)| cursor.fixed_applies(n))
.map(|(_, h)| *h)
.sum();
cursor.y = header_height + cursor.continuation_top_offset;
cursor
}
/// First-page cursor: lays out with `first`'s geometry while
/// subsequent pages fall back to `base` (@page :first).
fn new_first(first: &PageConfig, base: &PageConfig) -> Self {
let mut cursor = PageCursor::new(first);
cursor.base_config = base.clone();
cursor
}
fn remaining_height(&self) -> f64 {
let footer_height: f64 = self
.fixed_footer
.iter()
.filter(|(n, _)| self.fixed_applies(n))
.map(|(_, h)| *h)
.sum();
(self.content_height - self.y - footer_height).max(0.0)
}
fn finalize(&self) -> LayoutPage {
let (page_w, page_h) = self.config.size.dimensions();
// Parity translation: flow content was laid out at the base
// horizontal geometry; a selected :left/:right config shifts it by
// the constant margin-left delta. Only flow elements exist at this
// point — fixed elements, margin boxes, and watermarks are injected
// later from the page's own (parity) config and must NOT translate.
let (elements, config) = match &self.display_config {
Some(display) => {
let dx = display.margin.left - self.flow_anchor_left;
let mut elements = self.elements.clone();
if dx != 0.0 {
fn shift(els: &mut [LayoutElement], dx: f64) {
for el in els {
el.x += dx;
shift(&mut el.children, dx);
}
}
shift(&mut elements, dx);
}
(elements, display.clone())
}
None => (self.elements.clone(), self.config.clone()),
};
LayoutPage {
width: page_w,
height: page_h,
elements,
fixed_header: self.fixed_header.clone(),
fixed_footer: self.fixed_footer.clone(),
watermarks: self.watermarks.clone(),
config,
page_name: self.page_name.clone(),
}
}
fn new_page(&self) -> Self {
// Subsequent pages use the base config — identical to `config`
// except when this cursor was a first page with its own geometry.
let mut cursor = PageCursor::new(&self.base_config);
cursor.page_index = self.page_index + 1;
cursor.page_name = self.page_name.clone();
cursor.left_config = self.left_config.clone();
cursor.right_config = self.right_config.clone();
cursor.base_display = self.base_display.clone();
cursor.first_display = self.first_display.clone();
cursor.doc_base = self.doc_base.clone();
cursor.doc_left = self.doc_left.clone();
cursor.doc_right = self.doc_right.clone();
cursor.named_sets = self.named_sets.clone();
cursor.display_config = cursor.display_for(cursor.page_index + 1);
cursor.flow_anchor_left = self.flow_anchor_left;
cursor.fixed_header = self.fixed_header.clone();
cursor.fixed_footer = self.fixed_footer.clone();
cursor.watermarks = self.watermarks.clone();
cursor.continuation_top_offset = self.continuation_top_offset;
let header_height: f64 = cursor
.fixed_header
.iter()
.filter(|(n, _)| cursor.fixed_applies(n))
.map(|(_, h)| *h)
.sum();
cursor.y = header_height + cursor.continuation_top_offset;
cursor
}
}
impl Default for LayoutEngine {
fn default() -> Self {
Self::new()
}
}
impl LayoutEngine {
pub fn new() -> Self {
Self {
text_layout: TextLayout::new(),
image_dim_cache: RefCell::new(HashMap::new()),
warnings: RefCell::new(Vec::new()),
measure_check: std::env::var("FORME_MEASURE_CHECK").is_ok_and(|v| v == "1"),
}
}
/// Look up cached image dimensions, or load and cache them.
fn get_image_dimensions(&self, src: &str) -> Option<(u32, u32)> {
if let Some(dims) = self.image_dim_cache.borrow().get(src) {
return Some(*dims);
}
if let Ok(dims) = crate::image_loader::load_image_dimensions(src) {
self.image_dim_cache
.borrow_mut()
.insert(src.to_string(), dims);
Some(dims)
} else {
None
}
}
/// Report a render defect (see the `warnings` field doc): the engine
/// knowingly produced output that differs from what was asked.
fn defect(&self, msg: String) {
let mut w = self.warnings.borrow_mut();
// One report per distinct defect per render — a 500-row table
// must not repeat its column story 500 times.
if !w.contains(&msg) {
w.push(msg);
}
}
/// Drain the render-defect warnings collected by the LAST `layout()`
/// call (each call starts fresh — the sentinel re-layout loop runs
/// layout multiple times and only the final pass's defects stand).
pub fn take_warnings(&self) -> Vec<String> {
std::mem::take(&mut *self.warnings.borrow_mut())
}
/// Main entry point: lay out a document into pages.
pub fn layout(&self, document: &Document, font_context: &FontContext) -> Vec<LayoutPage> {
self.warnings.borrow_mut().clear();
let mut pages: Vec<LayoutPage> = Vec::new();
let mut cursor = match &document.first_page {
Some(first) => PageCursor::new_first(first, &document.default_page),
None => PageCursor::new(&document.default_page),
};
// @page :left / :right parity configs. Page 1 is a RIGHT page (CSS
// Paged Media, LTR page progression); :first outranks :right on
// page 1, so the parity display only applies when :first is absent.
// Explicit <Page> nodes carry their own configs and do not
// participate in parity selection.
cursor.left_config = document.left_page.clone();
cursor.right_config = document.right_page.clone();
// The document-level family + named sets, for PageName switches.
cursor.doc_base = document.default_page.clone();
cursor.doc_left = document.left_page.clone();
cursor.doc_right = document.right_page.clone();
cursor.named_sets = document.named_pages.clone();
if document.first_page.is_none() {
cursor.display_config = cursor.display_for(1);
}
// Build a root resolved style from document default_style + lang
let base = document.default_style.clone().unwrap_or_default();
let root_style = Style {
lang: base.lang.clone().or(document.metadata.lang.clone()),
..base
}
.resolve(None, cursor.content_width);
for node in &document.children {
match &node.kind {
NodeKind::Page { config } => {
if !cursor.elements.is_empty() || cursor.y > 0.0 {
pages.push(cursor.finalize());
}
cursor = PageCursor::new(config);
cursor.page_index = pages.len();
// Build a page-level root style that carries document lang
// AND has a fixed height matching the page content area.
// The fixed height ensures flex-grow page-level detection
// works correctly (layout_children uses parent height).
// Resolve the Page node's own style so properties like
// fontFamily set on <Page style={...}> inherit to children.
let mut page_root = node.style.resolve(Some(&root_style), cursor.content_width);
page_root.height = SizeConstraint::Fixed(cursor.content_height);
let cx = cursor.content_x;
let cw = cursor.content_width;
self.layout_children(
&node.children,
&node.style,
&mut cursor,
&mut pages,
cx,
cw,
Some(&page_root),
font_context,
);
}
NodeKind::PageBreak => {
pages.push(cursor.finalize());
cursor = cursor.new_page();
}
_ => {
let cx = cursor.content_x;
let cw = cursor.content_width;
self.layout_node(
node,
&mut cursor,
&mut pages,
cx,
cw,
Some(&root_style),
font_context,
None,
None,
);
}
}
}
// Same rule as the PageName switch: a page is real when something
// RENDERED on it. Bare y-advance (a parent's closing padding after
// a named-page restore, a trailing spacer) is whitespace and must
// not emit a blank final page. An empty document stays empty —
// zero pages is the documented contract (test_empty_document).
if !cursor.elements.is_empty() {
pages.push(cursor.finalize());
}
// Trailing pages with no visible ink are artifacts, not content —
// a named-page restore that nothing follows leaves a page holding
// only an invisible per-fragment structure container (DrawCommand
// ::None, no text, no children with either). Drop them BEFORE
// fixed-element injection so no running furniture makes a blank
// page look deliberate. At least one page always remains.
fn has_visible_ink(els: &[LayoutElement]) -> bool {
els.iter().any(|e| {
let paints = match &e.draw {
DrawCommand::None => false,
// A fragment wrapper clones the view's Rect onto every
// page it spans — with no fill and zero-width borders
// it marks nothing.
DrawCommand::Rect {
background,
border_width,
..
} => {
background.is_some()
|| border_width.top > 0.0
|| border_width.right > 0.0
|| border_width.bottom > 0.0
|| border_width.left > 0.0
}
_ => true,
};
paints || has_visible_ink(&e.children)
})
}
while pages.len() > 1 && !has_visible_ink(&pages.last().unwrap().elements) {
pages.pop();
}
self.inject_fixed_elements(&mut pages, font_context);
pages
}
#[allow(clippy::too_many_arguments)]
fn layout_node(
&self,
node: &Node,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
parent_style: Option<&ResolvedStyle>,
font_context: &FontContext,
cross_axis_height: Option<f64>,
forced_outer_width: Option<f64>,
) {
let mut style = node.style.resolve(parent_style, available_width);
// When a flex row stretches a child, inject the cross-axis height so
// justify-content, flex-grow, and other height-dependent logic works.
if let Some(h) = cross_axis_height {
if matches!(style.height, SizeConstraint::Auto) {
style.height = SizeConstraint::Fixed(h);
}
}
// When a flex parent has already resolved this child's outer width
// (via flex-basis / flex-grow / flex-shrink distribution), override
// style.width so layout_view uses the distributed value instead of
// re-resolving the raw percentage against the constrained width.
if let Some(w) = forced_outer_width {
style.width = SizeConstraint::Fixed(w);
}
// A forced break-before with no in-flow content yet on the page has
// nothing to break from, so it is suppressed — the same rule Chrome's
// print path applies. This covers both the document start and a
// consecutive forced break (which would otherwise emit a blank page).
// Migrated wkhtmltopdf-era templates set page-break-before on every
// section including the first; without this guard the document opens
// with a blank page. Keyed on committed in-flow boxes rather than
// `cursor.y` because the body's own margin (and any running header)
// advances `y` above zero before the first block is ever laid out —
// the content-bearing half of the swallowed-siblings guard above.
if style.break_before && !cursor.elements.is_empty() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
// Remember where this node's elements begin so a `position: relative`
// offset can shift its paint after normal-flow layout (below).
let elem_start = cursor.elements.len();
match &node.kind {
NodeKind::PageBreak => {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
NodeKind::PageName { name } => {
// A page-name switch forces a break between differently
// named boxes (CSS Paged Media). An empty current page is
// renamed in place instead — this is how a named run
// claims page 1 (and why a named rule outranks a bare
// `:first`: the marker replaces the first-page cursor).
if cursor.page_name.as_deref() != name.as_deref() {
// "Content" means RENDERED elements. A y-advance with
// nothing painted (a body margin, an empty spacer) is
// whitespace, and a named run must still claim the
// page — counting bare y produced a blank leading
// page whenever the document opened with a named
// block under a UA body margin.
let has_content = !cursor.elements.is_empty();
if has_content {
pages.push(cursor.finalize());
}
*cursor = cursor.renamed_page(name.clone(), !has_content);
}
}
NodeKind::Fixed {
position, pages, ..
} => {
let height = self.measure_node_height(node, available_width, &style, font_context);
match position {
FixedPosition::Header => {
cursor.fixed_header.push((node.clone(), height));
// Space is only consumed on pages the element
// actually appears on (CSS :first suppression,
// parity, page-name scoping).
let _ = pages;
if cursor.fixed_applies(node) {
cursor.y += height;
}
}
FixedPosition::Footer => {
cursor.fixed_footer.push((node.clone(), height));
}
}
}
NodeKind::Watermark { .. } => {
// Watermarks take zero layout height — just store on cursor for injection
cursor.watermarks.push(node.clone());
}
NodeKind::TextField {
name,
value,
placeholder,
width: field_w,
height: field_h,
multiline,
password,
read_only,
max_length,
font_size,
} => {
self.layout_form_field(
node,
&style,
cursor,
pages,
x,
*field_w,
*field_h,
DrawCommand::FormField {
field_type: FormFieldType::TextField {
value: value.clone(),
placeholder: placeholder.clone(),
multiline: *multiline,
password: *password,
read_only: *read_only,
max_length: *max_length,
font_size: *font_size,
},
name: name.clone(),
},
"TextField",
);
}
NodeKind::Checkbox {
name,
checked,
width: field_w,
height: field_h,
read_only,
} => {
self.layout_form_field(
node,
&style,
cursor,
pages,
x,
*field_w,
*field_h,
DrawCommand::FormField {
field_type: FormFieldType::Checkbox {
checked: *checked,
read_only: *read_only,
},
name: name.clone(),
},
"Checkbox",
);
}
NodeKind::Dropdown {
name,
options,
value,
width: field_w,
height: field_h,
read_only,
font_size,
} => {
self.layout_form_field(
node,
&style,
cursor,
pages,
x,
*field_w,
*field_h,
DrawCommand::FormField {
field_type: FormFieldType::Dropdown {
options: options.clone(),
value: value.clone(),
read_only: *read_only,
font_size: *font_size,
},
name: name.clone(),
},
"Dropdown",
);
}
NodeKind::RadioButton {
name,
value,
checked,
width: field_w,
height: field_h,
read_only,
} => {
self.layout_form_field(
node,
&style,
cursor,
pages,
x,
*field_w,
*field_h,
DrawCommand::FormField {
field_type: FormFieldType::RadioButton {
value: value.clone(),
checked: *checked,
read_only: *read_only,
},
name: name.clone(),
},
"RadioButton",
);
}
NodeKind::Text {
content,
href,
runs,
} => {
self.layout_text(
content,
href.as_deref(),
runs,
&style,
cursor,
pages,
x,
available_width,
font_context,
node.source_location.as_ref(),
node.bookmark.as_deref(),
None,
);
}
NodeKind::Heading {
content,
href,
runs,
..
} => {
// Headings lay out exactly like Text but tag the wrapping
// element as "H1".."H6" via node_type_override so the
// tagged-PDF builder picks up the semantic role. Style
// defaults (size, weight, margins) come from the React layer.
let heading_role = node_kind_name(&node.kind); // "H1".."H6"
self.layout_text(
content,
href.as_deref(),
runs,
&style,
cursor,
pages,
x,
available_width,
font_context,
node.source_location.as_ref(),
node.bookmark.as_deref(),
Some(heading_role),
);
}
NodeKind::List {
ordered,
marker_type,
start,
} => {
self.layout_list(
node,
*ordered,
*marker_type,
*start,
&style,
cursor,
pages,
x,
available_width,
font_context,
);
}
NodeKind::ListItem => {
// A bare ListItem outside of a List is just a container —
// fall back to view-style layout. Real list rendering goes
// through layout_list which spawns each ListItem with the
// proper marker.
self.layout_view(
node,
&style,
cursor,
pages,
x,
available_width,
font_context,
);
}
NodeKind::Image { width, height, .. } => {
self.layout_image(
node,
&style,
cursor,
pages,
x,
available_width,
*width,
*height,
);
}
NodeKind::Table { columns } => {
self.layout_table(
node,
&style,
columns,
cursor,
pages,
x,
available_width,
font_context,
);
}
NodeKind::View | NodeKind::Page { .. } => {
self.layout_view(
node,
&style,
cursor,
pages,
x,
available_width,
font_context,
);
}
NodeKind::TableRow { .. } | NodeKind::TableCell { .. } => {
self.layout_view(
node,
&style,
cursor,
pages,
x,
available_width,
font_context,
);
}
NodeKind::Svg {
width: svg_w,
height: svg_h,
view_box,
content,
} => {
self.layout_svg(
node,
&style,
cursor,
pages,
x,
available_width,
*svg_w,
*svg_h,
view_box.as_deref(),
content,
);
}
NodeKind::Barcode {
data,
format,
width: explicit_width,
height: bar_height,
} => {
self.layout_barcode(
node,
&style,
cursor,
pages,
x,
available_width,
data,
*format,
*explicit_width,
*bar_height,
);
}
NodeKind::QrCode {
data,
size: explicit_size,
} => {
self.layout_qrcode(
node,
&style,
cursor,
pages,
x,
available_width,
data,
*explicit_size,
);
}
NodeKind::Canvas {
width: canvas_w,
height: canvas_h,
operations,
} => {
self.layout_canvas(
node,
&style,
cursor,
pages,
x,
available_width,
*canvas_w,
*canvas_h,
operations,
);
}
NodeKind::BarChart {
data,
width: chart_w,
height: chart_h,
color,
show_labels,
show_values,
show_grid,
title,
} => {
let config = crate::chart::bar::BarChartConfig {
color: color.clone(),
show_labels: *show_labels,
show_values: *show_values,
show_grid: *show_grid,
title: title.clone(),
};
let primitives = crate::chart::bar::build(*chart_w, *chart_h, data, &config);
self.layout_chart(
node, &style, cursor, pages, x, *chart_w, *chart_h, primitives, "BarChart",
);
}
NodeKind::LineChart {
series,
labels,
width: chart_w,
height: chart_h,
show_points,
show_grid,
title,
} => {
let config = crate::chart::line::LineChartConfig {
show_points: *show_points,
show_grid: *show_grid,
title: title.clone(),
};
let primitives =
crate::chart::line::build(*chart_w, *chart_h, series, labels, &config);
self.layout_chart(
node,
&style,
cursor,
pages,
x,
*chart_w,
*chart_h,
primitives,
"LineChart",
);
}
NodeKind::PieChart {
data,
width: chart_w,
height: chart_h,
donut,
show_legend,
title,
} => {
let config = crate::chart::pie::PieChartConfig {
donut: *donut,
show_legend: *show_legend,
title: title.clone(),
};
let primitives = crate::chart::pie::build(*chart_w, *chart_h, data, &config);
self.layout_chart(
node, &style, cursor, pages, x, *chart_w, *chart_h, primitives, "PieChart",
);
}
NodeKind::AreaChart {
series,
labels,
width: chart_w,
height: chart_h,
show_grid,
title,
} => {
let config = crate::chart::area::AreaChartConfig {
show_grid: *show_grid,
title: title.clone(),
};
let primitives =
crate::chart::area::build(*chart_w, *chart_h, series, labels, &config);
self.layout_chart(
node,
&style,
cursor,
pages,
x,
*chart_w,
*chart_h,
primitives,
"AreaChart",
);
}
NodeKind::DotPlot {
groups,
width: chart_w,
height: chart_h,
x_min,
x_max,
y_min,
y_max,
x_label,
y_label,
show_legend,
dot_size,
} => {
let config = crate::chart::dot::DotPlotConfig {
x_min: *x_min,
x_max: *x_max,
y_min: *y_min,
y_max: *y_max,
x_label: x_label.clone(),
y_label: y_label.clone(),
show_legend: *show_legend,
dot_size: *dot_size,
};
let primitives = crate::chart::dot::build(*chart_w, *chart_h, groups, &config);
self.layout_chart(
node, &style, cursor, pages, x, *chart_w, *chart_h, primitives, "DotPlot",
);
}
}
// position: relative — the element kept its normal-flow space (cursor.y
// was advanced as usual above); now paint it and its content offset by
// top/left/right/bottom. `left`/`top` shift positive, `right`/`bottom`
// negative; siblings are unaffected because flow already advanced.
// `position` defaults to Relative, so the presence of offsets is the
// real discriminator — the mapper only sets offsets on a positioned
// element, and Absolute is handled separately in `layout_children`.
if matches!(style.position, Position::Relative)
&& (style.top.is_some()
|| style.left.is_some()
|| style.right.is_some()
|| style.bottom.is_some())
{
let dx = style.left.unwrap_or(0.0) - style.right.unwrap_or(0.0);
let dy = style.top.unwrap_or(0.0) - style.bottom.unwrap_or(0.0);
for el in &mut cursor.elements[elem_start..] {
if dx != 0.0 {
offset_element_x(el, dx);
}
if dy != 0.0 {
offset_element_y(el, dy);
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn layout_view(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
font_context: &FontContext,
) {
let padding = &style.padding;
let margin = &style.margin.to_edges();
let border = &style.border_width;
let outer_width = match style.width {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => available_width - margin.horizontal(),
}
// min wins over max on conflict, per CSS.
.min(style.max_width)
.max(style.min_width);
let inner_width = outer_width - padding.horizontal() - border.horizontal();
let children_height =
self.measure_children_height(&node.children, inner_width, style, font_context);
let total_height = match style.height {
SizeConstraint::Fixed(h) => h,
SizeConstraint::Auto => children_height + padding.vertical() + border.vertical(),
}
.max(style.min_height);
let node_x = x + margin.left;
let fits = total_height <= cursor.remaining_height() - margin.vertical();
if fits || !style.breakable {
if !fits && !style.breakable {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
// Snapshot-and-collect: lay out children first, then wrap in parent
let rect_y = cursor.content_y + cursor.y + margin.top;
let snapshot = cursor.elements.len();
// Pushed after the snapshot so it's drained into the rect's
// children below — same shape the breakable path produces. Sits at
// `rect_y`, exactly where the bookmark used to resolve when it rode
// on `rect_element`, so the outline destination is unchanged.
if let Some(marker) = bookmark_marker(node, node_x, rect_y) {
cursor.elements.push(marker);
}
let saved_y = cursor.y;
cursor.y += margin.top + padding.top + border.top;
let pages_before = pages.len();
let children_x = node_x + padding.left + border.left;
let is_grid =
matches!(style.display, Display::Grid) && style.grid_template_columns.is_some();
if is_grid {
self.layout_grid_children(
&node.children,
style,
cursor,
pages,
children_x,
inner_width,
font_context,
);
} else {
self.layout_children(
&node.children,
&node.style,
cursor,
pages,
children_x,
inner_width,
Some(style),
font_context,
);
}
// Collect child elements that were pushed during layout
let child_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
// Measure/layout agreement check (see the `measure_check` field
// doc). Only the phantom-space direction is flagged — measured
// MORE than the children occupied — and only when the height came
// from measurement (Auto) and no page break muddied the extent
// arithmetic. (Overfill has legitimate causes: absolute children,
// negative margins.)
if self.measure_check
&& matches!(style.height, SizeConstraint::Auto)
&& pages.len() == pages_before
&& !child_elements.is_empty()
{
let content_top = rect_y + padding.top + border.top;
let extent = child_elements
.iter()
.map(|el| el.y + el.height)
.fold(f64::NEG_INFINITY, f64::max)
- content_top;
if extent > 0.0 && children_height - extent > 2.0 {
self.defect(format!(
"measure-check: {} measured children at {children_height:.1}pt but they occupy {extent:.1}pt (phantom {:.1}pt)",
node_kind_name(&node.kind),
children_height - extent,
));
}
}
let rect_element = LayoutElement {
x: node_x,
y: rect_y,
width: outer_width,
height: total_height,
draw: DrawCommand::Rect {
background: style.background_color,
border_width: style.border_width,
border_color: style.border_color,
border_style: style.border_style,
border_radius: style.border_radius,
opacity: 1.0,
box_shadow: style.box_shadow.map(Box::new),
background_gradient: style.background.clone().map(Box::new),
},
children: child_elements,
node_type: Some(node_kind_name(&node.kind).to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
// The marker above owns the bookmark now. Carrying it here too
// would make `collect_bookmarks` emit the outline entry twice.
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
};
cursor.elements.push(rect_element);
cursor.y = saved_y + total_height + margin.vertical();
} else {
self.layout_breakable_view(
node,
style,
cursor,
pages,
node_x,
outer_width,
inner_width,
font_context,
);
}
}
#[allow(clippy::too_many_arguments)]
fn layout_breakable_view(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
node_x: f64,
outer_width: f64,
inner_width: f64,
font_context: &FontContext,
) {
let padding = &style.padding;
let border = &style.border_width;
let margin = &style.margin.to_edges();
// Save state before child layout for page-break detection
let initial_page_count = pages.len();
let snapshot = cursor.elements.len();
let rect_start_y = cursor.content_y + cursor.y + margin.top;
// Emit a zero-height marker element so the bookmark gets into the PDF
// outline. Deliberately placed at `rect_start_y` — the view's outer top
// edge — BEFORE the cursor advances past padding/border, so every
// container path resolves a bookmark to the same coordinate. It used to
// sit at the content top, which is inset by padding + border, so an
// unstyled overflowing view landed lower than an otherwise identical
// styled or non-overflowing one.
if let Some(marker) = bookmark_marker(node, node_x, rect_start_y) {
cursor.elements.push(marker);
}
cursor.y += margin.top + padding.top + border.top;
let prev_continuation_offset = cursor.continuation_top_offset;
cursor.continuation_top_offset = padding.top + border.top;
let children_x = node_x + padding.left + border.left;
let is_grid =
matches!(style.display, Display::Grid) && style.grid_template_columns.is_some();
if is_grid {
self.layout_grid_children(
&node.children,
style,
cursor,
pages,
children_x,
inner_width,
font_context,
);
} else {
self.layout_children(
&node.children,
&node.style,
cursor,
pages,
children_x,
inner_width,
Some(style),
font_context,
);
}
cursor.continuation_top_offset = prev_continuation_offset;
// Check if this view has any visual styling worth wrapping
let has_visual = style.background_color.is_some()
|| style.border_width.top > 0.0
|| style.border_width.right > 0.0
|| style.border_width.bottom > 0.0
|| style.border_width.left > 0.0;
// Also wrap when flex_grow > 0 so the flex-grow code finds a proper wrapper element
let needs_wrapper = has_visual || style.flex_grow > 0.0;
if !needs_wrapper {
// No visual styling and no flex-grow — skip wrapping
cursor.y += padding.bottom + border.bottom + margin.bottom;
return;
}
let draw_cmd = DrawCommand::Rect {
background: style.background_color,
border_width: style.border_width,
border_color: style.border_color,
border_style: style.border_style,
border_radius: style.border_radius,
opacity: 1.0,
box_shadow: style.box_shadow.map(Box::new),
background_gradient: style.background.clone().map(Box::new),
};
if pages.len() == initial_page_count {
// No page breaks: simple wrap (same as non-breakable path)
let child_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
let rect_height =
cursor.content_y + cursor.y + padding.bottom + border.bottom - rect_start_y;
cursor.elements.push(LayoutElement {
x: node_x,
y: rect_start_y,
width: outer_width,
height: rect_height,
draw: draw_cmd,
children: child_elements,
node_type: Some(node_kind_name(&node.kind).to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
// The marker above owns the bookmark. `collect_bookmarks`
// recurses into children, and the marker was drained into
// `child_elements` — carrying it here too emits the outline
// entry twice for one `bookmark` prop.
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
} else {
// Page breaks occurred: wrap elements on each page with clone semantics
// A. First page — wrap elements from snapshot onward
let page = &mut pages[initial_page_count];
let footer_h: f64 = page.fixed_footer.iter().map(|(_, h)| *h).sum();
let page_content_bottom =
page.config.margin.top + (page.height - page.config.margin.vertical()) - footer_h;
let our_elements: Vec<LayoutElement> = page.elements.drain(snapshot..).collect();
if !our_elements.is_empty() {
let rect_height = page_content_bottom - rect_start_y;
page.elements.push(LayoutElement {
x: node_x,
y: rect_start_y,
width: outer_width,
height: rect_height,
draw: draw_cmd.clone(),
children: our_elements,
node_type: Some(node_kind_name(&node.kind).to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
// Marker owns it — see the no-page-break branch above.
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
}
// B. Intermediate pages — wrap ALL elements
for page in &mut pages[initial_page_count + 1..] {
let header_h: f64 = page.fixed_header.iter().map(|(_, h)| *h).sum();
let content_top = page.config.margin.top + header_h;
let footer_h: f64 = page.fixed_footer.iter().map(|(_, h)| *h).sum();
let content_bottom = page.config.margin.top
+ (page.height - page.config.margin.vertical())
- footer_h;
let all_elements: Vec<LayoutElement> = std::mem::take(&mut page.elements);
if !all_elements.is_empty() {
page.elements.push(LayoutElement {
x: node_x,
y: content_top,
width: outer_width,
height: content_bottom - content_top,
draw: draw_cmd.clone(),
children: all_elements,
node_type: Some(node_kind_name(&node.kind).to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: None,
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
}
}
// C. Current page (cursor.elements) — wrap ALL elements
let all_elements: Vec<LayoutElement> = std::mem::take(&mut cursor.elements);
if !all_elements.is_empty() {
let header_h: f64 = cursor.fixed_header.iter().map(|(_, h)| *h).sum();
let content_top = cursor.content_y + header_h;
let rect_height =
cursor.content_y + cursor.y + padding.bottom + border.bottom - content_top;
cursor.elements.push(LayoutElement {
x: node_x,
y: content_top,
width: outer_width,
height: rect_height,
draw: draw_cmd,
children: all_elements,
node_type: Some(node_kind_name(&node.kind).to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: None,
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
}
}
cursor.y += padding.bottom + border.bottom + margin.bottom;
}
#[allow(clippy::too_many_arguments)]
fn layout_children(
&self,
children: &[Node],
_parent_raw_style: &Style,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
content_x: f64,
available_width: f64,
parent_style: Option<&ResolvedStyle>,
font_context: &FontContext,
) {
// Save parent content box position for absolute children
let parent_box_y = cursor.content_y + cursor.y;
let parent_box_x = content_x;
// The page the parent box STARTS on. When flow layout breaks pages,
// absolute children must anchor to (and render on) this FIRST
// fragment per CSS — parent_box_x/y are coordinates on this page.
let entry_page_index = pages.len();
// If this container is *explicitly* positioned it becomes the
// containing block for its absolute descendants. Update the cursor's
// containing block for the duration of this subtree; restore after the
// second pass. (`position` defaults to Relative, so only the explicit
// `positioned` flag counts.)
let parent_positioned = parent_style.map(|s| s.positioned).unwrap_or(false);
let saved_cb = cursor.containing_block;
if parent_positioned {
let cb_height = parent_style
.and_then(|ps| match ps.height {
SizeConstraint::Fixed(h) => {
Some(h - ps.padding.vertical() - ps.border_width.vertical())
}
SizeConstraint::Auto => None,
})
.unwrap_or(saved_cb.3);
cursor.containing_block = (parent_box_x, parent_box_y, available_width, cb_height);
}
// Separate absolute vs flow children
let (flow_children, abs_children): (Vec<&Node>, Vec<&Node>) = children
.iter()
.partition(|child| !matches!(child.style.position, Some(Position::Absolute)));
let direction = parent_style
.map(|s| s.flex_direction)
.unwrap_or(FlexDirection::Column);
let row_gap = parent_style.map(|s| s.row_gap).unwrap_or(0.0);
let column_gap = parent_style.map(|s| s.column_gap).unwrap_or(0.0);
// First pass: flow children
match direction {
FlexDirection::Column | FlexDirection::ColumnReverse => {
let items: Vec<&Node> = if matches!(direction, FlexDirection::ColumnReverse) {
flow_children.into_iter().rev().collect()
} else {
flow_children
};
let justify = parent_style
.map(|s| s.justify_content)
.unwrap_or(JustifyContent::FlexStart);
let align = parent_style
.map(|s| s.align_items)
.unwrap_or(AlignItems::Stretch);
let start_y = cursor.y;
let initial_pages = pages.len();
// Track each child's element range for align-items adjustment
let mut child_ranges: Vec<(usize, usize)> = Vec::new();
for (i, child) in items.iter().enumerate() {
if i > 0 {
cursor.y += row_gap;
}
let child_start = cursor.elements.len();
// Auto margins take priority over align-items for cross-axis positioning.
// For column flex, horizontal auto margins center or push the child.
let child_margin = &child.style.resolve(parent_style, available_width).margin;
let has_auto_h = child_margin.has_auto_horizontal();
// For align-items Center/FlexEnd, measure child width and adjust x.
// Returns (child_x, layout_width): layout_width is what we pass
// to layout_node. For Fixed-width children (incl. percentage),
// we pass available_width so percentages re-resolve correctly.
// For Auto-width children, we pass the intrinsic width so they
// don't stretch to fill the parent.
let (child_x, layout_w) = if has_auto_h {
let child_style = child.style.resolve(parent_style, available_width);
let has_explicit_width =
matches!(child_style.width, SizeConstraint::Fixed(_));
let intrinsic = self
.measure_intrinsic_width(child, &child_style, font_context)
.min(available_width);
let w = match child_style.width {
SizeConstraint::Fixed(fw) => fw,
// Auto width + max-width is the centered-column
// idiom: the block fills, the clamp shrinks it,
// auto margins split what's left. Plain auto
// keeps the engine's shrink-to-fit behavior.
SizeConstraint::Auto if child_style.max_width.is_finite() => {
(available_width - child_margin.horizontal())
.min(child_style.max_width)
}
SizeConstraint::Auto => intrinsic,
}
.min(child_style.max_width)
.max(child_style.min_width);
let lw = if has_explicit_width {
available_width
} else {
w
};
let fixed_h = child_margin.horizontal();
let slack = (available_width - w - fixed_h).max(0.0);
let auto_left = child_margin.left.is_auto();
let auto_right = child_margin.right.is_auto();
let ml = match (auto_left, auto_right) {
(true, true) => slack / 2.0,
(true, false) => slack,
(false, true) => 0.0,
(false, false) => 0.0,
};
(content_x + child_margin.left.resolve() + ml, lw)
} else if !matches!(align, AlignItems::Stretch | AlignItems::FlexStart) {
let child_style = child.style.resolve(parent_style, available_width);
let has_explicit_width =
matches!(child_style.width, SizeConstraint::Fixed(_));
let intrinsic = self
.measure_intrinsic_width(child, &child_style, font_context)
.min(available_width);
let w = match child_style.width {
SizeConstraint::Fixed(fw) => fw,
SizeConstraint::Auto => intrinsic,
};
let lw = if has_explicit_width {
available_width
} else {
w
};
match align {
AlignItems::Center => (content_x + (available_width - w) / 2.0, lw),
AlignItems::FlexEnd => (content_x + available_width - w, lw),
_ => (content_x, available_width),
}
} else {
(content_x, available_width)
};
self.layout_node(
child,
cursor,
pages,
child_x,
layout_w,
parent_style,
font_context,
None,
None,
);
child_ranges.push((child_start, cursor.elements.len()));
}
// flex-grow: distribute extra vertical space proportionally
// Compute container inner height from parent style or page content area
let container_inner_h: Option<f64> = parent_style
.and_then(|ps| match ps.height {
SizeConstraint::Fixed(h) => {
Some(h - ps.padding.vertical() - ps.border_width.vertical())
}
SizeConstraint::Auto => None,
})
.or_else(|| {
// Page-level: use remaining content height from start
if parent_style.is_none() {
Some(cursor.content_height - start_y)
} else {
None
}
});
if let Some(inner_h) = container_inner_h {
if pages.len() == initial_pages {
let child_styles: Vec<ResolvedStyle> = items
.iter()
.map(|child| child.style.resolve(parent_style, available_width))
.collect();
let total_grow: f64 = child_styles.iter().map(|s| s.flex_grow).sum();
if total_grow > 0.0 {
let children_total = cursor.y - start_y;
let slack = (inner_h - children_total).max(0.0);
if slack > 0.0 {
let mut cumulative_shift = 0.0_f64;
for (i, cs) in child_styles.iter().enumerate() {
let (start, end) = child_ranges[i];
if cumulative_shift > 0.001 {
for j in start..end {
offset_element_y(
&mut cursor.elements[j],
cumulative_shift,
);
}
}
if cs.flex_grow > 0.0 {
let extra = slack * (cs.flex_grow / total_grow);
// Expand the container element's height
if start < end {
let elem = &mut cursor.elements[end - 1];
elem.height += extra;
reapply_justify_content(elem);
}
cumulative_shift += extra;
}
}
cursor.y += cumulative_shift;
}
}
}
}
// Auto vertical margin pass: distribute any remaining slack to
// children with marginTop/marginBottom: Auto. Per CSS flex spec,
// this runs AFTER flex-grow and BEFORE justify-content — auto
// margins consume free space first, leaving nothing for
// justify-content. Mirrors the cross-axis handling in
// layout_flex_row (~2256-2267) but applied to the main axis here.
if let Some(inner_h) = container_inner_h {
if pages.len() == initial_pages {
let auto_styles: Vec<ResolvedStyle> = items
.iter()
.map(|child| child.style.resolve(parent_style, available_width))
.collect();
let total_autos: usize = auto_styles
.iter()
.map(|s| {
s.margin.top.is_auto() as usize + s.margin.bottom.is_auto() as usize
})
.sum();
if total_autos > 0 {
let children_total = cursor.y - start_y;
let total_slack = (inner_h - children_total).max(0.0);
if total_slack > 0.0 {
let per_auto = total_slack / total_autos as f64;
let mut cumulative_shift = 0.0_f64;
for (i, cs) in auto_styles.iter().enumerate() {
let (start, end) = child_ranges[i];
let mt_auto = cs.margin.top.is_auto();
let mb_auto = cs.margin.bottom.is_auto();
// mt-auto pushes THIS child down by per_auto;
// any cumulative_shift from earlier children
// (including their mb-auto carryover) applies too.
let this_child_shift =
cumulative_shift + if mt_auto { per_auto } else { 0.0 };
if this_child_shift > 0.001 {
for j in start..end {
offset_element_y(
&mut cursor.elements[j],
this_child_shift,
);
}
}
// mb-auto adds slack between this child and
// any subsequent ones (carried forward).
cumulative_shift =
this_child_shift + if mb_auto { per_auto } else { 0.0 };
}
cursor.y += cumulative_shift;
}
}
}
}
// justify-content: redistribute children vertically when parent has fixed height
let needs_justify =
!matches!(justify, JustifyContent::FlexStart) && pages.len() == initial_pages;
if needs_justify {
// Use container_inner_h if available, otherwise compute from parent style
let justify_inner_h = container_inner_h.or_else(|| {
parent_style.and_then(|ps| match ps.height {
SizeConstraint::Fixed(h) => {
Some(h - ps.padding.vertical() - ps.border_width.vertical())
}
SizeConstraint::Auto => None,
})
});
if let Some(inner_h) = justify_inner_h {
let children_total = cursor.y - start_y;
let slack = inner_h - children_total;
if slack > 0.0 {
let n = child_ranges.len();
let offsets: Vec<f64> = match justify {
JustifyContent::FlexEnd => vec![slack; n],
JustifyContent::Center => vec![slack / 2.0; n],
JustifyContent::SpaceBetween => {
if n <= 1 {
vec![0.0; n]
} else {
let per_gap = slack / (n - 1) as f64;
(0..n).map(|i| i as f64 * per_gap).collect()
}
}
JustifyContent::SpaceAround => {
let space = slack / n as f64;
(0..n).map(|i| space / 2.0 + i as f64 * space).collect()
}
JustifyContent::SpaceEvenly => {
let space = slack / (n + 1) as f64;
(0..n).map(|i| (i + 1) as f64 * space).collect()
}
JustifyContent::FlexStart => vec![0.0; n],
};
for (i, &(start, end)) in child_ranges.iter().enumerate() {
let dy = offsets[i];
if dy.abs() > 0.001 {
for j in start..end {
offset_element_y(&mut cursor.elements[j], dy);
}
}
}
cursor.y += *offsets.last().unwrap_or(&0.0);
}
}
}
}
FlexDirection::Row | FlexDirection::RowReverse => {
let flow_owned: Vec<Node> = flow_children.into_iter().cloned().collect();
self.layout_flex_row(
&flow_owned,
cursor,
pages,
content_x,
available_width,
parent_style,
column_gap,
row_gap,
font_context,
);
}
}
// The containing block for these absolutes: the direct parent when it
// is positioned (preserving the auto-height lazy computation), else the
// nearest positioned ancestor / page carried on the cursor. This is the
// v0-divergence retirement — an absolute inside an *unpositioned* parent
// now escapes to its nearest positioned ancestor, matching browsers.
// Did the parent fragment across pages during flow layout? Its
// absolutes then anchor to the FIRST fragment (CSS): coordinates
// are already first-page coordinates (parent_box_x/y), the auto
// height is the first fragment's extent (down to that page's
// content bottom — the fragment ran to the page end), and the
// elements are emitted onto that page rather than the post-break
// cursor. Emitting into the cursor was the last-fragment bug: the
// badge drawn from first-page coordinates landed on the last page.
let parent_fragmented = parent_positioned && pages.len() > entry_page_index;
let (cb_x, cb_y, cb_w, cb_h) = if parent_positioned {
let ph = parent_style
.and_then(|ps| match ps.height {
SizeConstraint::Fixed(h) => {
Some(h - ps.padding.vertical() - ps.border_width.vertical())
}
SizeConstraint::Auto => None,
})
.unwrap_or_else(|| {
if parent_fragmented {
let first = &pages[entry_page_index];
(first.height - first.config.margin.bottom) - parent_box_y
} else {
cursor.content_y + cursor.y - parent_box_y
}
});
(parent_box_x, parent_box_y, available_width, ph)
} else {
cursor.containing_block
};
// Second pass: absolute children
for abs_child in &abs_children {
let abs_style = abs_child.style.resolve(parent_style, cb_w);
// Measure intrinsic size
let child_width = match abs_style.width {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => {
// If both left and right are set, stretch width
if let (Some(l), Some(r)) = (abs_style.left, abs_style.right) {
(cb_w - l - r).max(0.0)
} else {
self.measure_intrinsic_width(abs_child, &abs_style, font_context)
}
}
};
let child_height = match abs_style.height {
SizeConstraint::Fixed(h) => h,
SizeConstraint::Auto => {
self.measure_node_height(abs_child, child_width, &abs_style, font_context)
}
};
// Position relative to the containing block. Per CSS, the
// offsets position the MARGIN edge: layout_node applies
// margin.top/left inside the slot, so a top/left anchor needs
// no adjustment — but bottom/right anchors must reserve the
// margins, or a margin shoves the border box past the anchor
// (template-compat 15: `bottom:0` + `margin-top:1rem` pushed a
// footer off the page bottom, leaving only ascender tips).
let abs_margin = abs_style.margin.to_edges();
let abs_x = if let Some(l) = abs_style.left {
cb_x + l
} else if let Some(r) = abs_style.right {
cb_x + cb_w - r - child_width - abs_margin.horizontal()
} else {
cb_x
};
let abs_y = if let Some(t) = abs_style.top {
cb_y + t
} else if let Some(b) = abs_style.bottom {
cb_y + cb_h - b - child_height - abs_margin.vertical()
} else {
cb_y
};
// Lay out the absolute child into a temporary cursor
let mut abs_cursor = PageCursor::new(&cursor.config);
abs_cursor.y = 0.0;
abs_cursor.content_x = abs_x;
abs_cursor.content_y = abs_y;
self.layout_node(
abs_child,
&mut abs_cursor,
&mut Vec::new(),
abs_x,
child_width,
parent_style,
font_context,
None,
None,
);
// Add absolute elements to the page the containing block starts
// on: the finalized first fragment when the parent broke across
// pages, else the current cursor (renders on top either way).
if parent_fragmented {
pages[entry_page_index].elements.extend(abs_cursor.elements);
} else {
cursor.elements.extend(abs_cursor.elements);
}
}
// Restore the containing block for the caller's remaining siblings.
cursor.containing_block = saved_cb;
}
#[allow(clippy::too_many_arguments)]
fn layout_flex_row(
&self,
children: &[Node],
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
content_x: f64,
available_width: f64,
parent_style: Option<&ResolvedStyle>,
column_gap: f64,
row_gap: f64,
font_context: &FontContext,
) {
if children.is_empty() {
return;
}
let flex_wrap = parent_style
.map(|s| s.flex_wrap)
.unwrap_or(FlexWrap::NoWrap);
// Phase 1: resolve styles and measure base widths for all items
// flex_basis takes precedence over width for flex items (per CSS spec)
let items: Vec<FlexItem> = children
.iter()
.map(|child| {
let style = child.style.resolve(parent_style, available_width);
let base_width = match style.flex_basis {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => match style.width {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => {
self.measure_intrinsic_width(child, &style, font_context)
}
},
};
let min_content_width = self.measure_min_content_width(child, &style, font_context);
FlexItem {
node: child,
style,
base_width,
min_content_width,
}
})
.collect();
// Phase 2: determine wrap lines
let base_widths: Vec<f64> = items.iter().map(|i| i.base_width).collect();
let lines = match flex_wrap {
FlexWrap::NoWrap => {
vec![flex::WrapLine {
start: 0,
end: items.len(),
}]
}
FlexWrap::Wrap => flex::partition_into_lines(&base_widths, column_gap, available_width),
FlexWrap::WrapReverse => {
let mut l = flex::partition_into_lines(&base_widths, column_gap, available_width);
l.reverse();
l
}
};
if lines.is_empty() {
return;
}
// Phase 3: lay out each line
let justify = parent_style.map(|s| s.justify_content).unwrap_or_default();
// We need mutable final_widths per line, so collect into a vec
let mut final_widths: Vec<f64> = items.iter().map(|i| i.base_width).collect();
let initial_pages_count = pages.len();
let flex_start_y = cursor.y;
let mut line_infos: Vec<(usize, usize, f64)> = Vec::new();
for (line_idx, line) in lines.iter().enumerate() {
let line_items = &items[line.start..line.end];
let line_count = line.end - line.start;
let line_gap = column_gap * (line_count as f64 - 1.0).max(0.0);
let distributable = available_width - line_gap;
// Flex distribution for this line
let total_base: f64 = line_items.iter().map(|i| i.base_width).sum();
let remaining = distributable - total_base;
if remaining > 0.0 {
let total_grow: f64 = line_items.iter().map(|i| i.style.flex_grow).sum();
if total_grow > 0.0 {
for (j, item) in line_items.iter().enumerate() {
final_widths[line.start + j] =
item.base_width + remaining * (item.style.flex_grow / total_grow);
}
}
} else if remaining < 0.0 {
let total_shrink: f64 = line_items
.iter()
.map(|i| i.style.flex_shrink * i.base_width)
.sum();
if total_shrink > 0.0 {
for (j, item) in line_items.iter().enumerate() {
let factor = (item.style.flex_shrink * item.base_width) / total_shrink;
let w = item.base_width + remaining * factor;
let floor = item.style.min_width.max(item.min_content_width);
final_widths[line.start + j] = w.max(floor);
}
}
}
// Measure line height
let mut line_height: f64 = line_items
.iter()
.enumerate()
.map(|(j, item)| {
let fw = final_widths[line.start + j];
self.measure_node_height(item.node, fw, &item.style, font_context)
+ item.style.margin.vertical()
})
.fold(0.0f64, f64::max);
// CSS 9.4.8: a single-line (nowrap) flex container with a
// definite cross size gives its one flex line the CONTAINER'S
// inner cross size, not the tallest item's. Without this,
// align-items: center / flex-end on a fixed-height row were
// no-ops — a 36pt logo box "centered" its 20pt text inside a
// 20pt line (the launch-demo mark). `max` rather than replace:
// when items overspill a too-small container the line keeps
// content size (the spec would shrink and overflow; keeping
// the larger value is the conservative reading for existing
// documents).
if let Some(ps) = parent_style {
if matches!(ps.flex_wrap, FlexWrap::NoWrap) {
if let SizeConstraint::Fixed(h) = ps.height {
let inner = h - ps.padding.vertical() - ps.border_width.vertical();
line_height = line_height.max(inner);
}
}
}
// Page break check for this line. The `cursor.y > 0.0` guard
// matches the other break sites: when the current page is
// already empty, moving to a fresh page can't gain space — a
// line taller than a full page would otherwise emit a blank
// page and then overflow anyway (found by the HTML spike's
// taller-than-page flex item).
if line_height > cursor.remaining_height() && cursor.y > 0.0 {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
// Add row_gap between lines (not before first)
if line_idx > 0 {
cursor.y += row_gap;
}
let row_start_y = cursor.y;
// Justify-content for this line
let actual_total: f64 = (line.start..line.end).map(|i| final_widths[i]).sum();
let slack = available_width - actual_total - line_gap;
let (start_offset, between_extra) = match justify {
JustifyContent::FlexStart => (0.0, 0.0),
JustifyContent::FlexEnd => (slack, 0.0),
JustifyContent::Center => (slack / 2.0, 0.0),
JustifyContent::SpaceBetween => {
if line_count > 1 {
(0.0, slack / (line_count as f64 - 1.0))
} else {
(0.0, 0.0)
}
}
JustifyContent::SpaceAround => {
let s = slack / line_count as f64;
(s / 2.0, s)
}
JustifyContent::SpaceEvenly => {
let s = slack / (line_count as f64 + 1.0);
(s, s)
}
};
let line_elem_start = cursor.elements.len();
let mut x = content_x + start_offset;
// Sequential-split detection, precise form: the genuinely
// sequential outcome is an ITEM's own layout breaking the
// page while siblings share its line — the siblings don't
// continue beside it on the next page, so columns serialize.
// The signature is page growth DURING the item loop. A row
// that merely relocated whole broke in the line-fit check
// ABOVE, before this count is taken, and stays silent (the
// old check fired on any page growth during the row's whole
// layout and closed a correct PR — a warning that cries
// wolf is worse than none).
let line_start_pages = pages.len();
for (j, item) in line_items.iter().enumerate() {
if j > 0 {
x += column_gap + between_extra;
}
let fw = final_widths[line.start + j];
let align = item
.style
.align_self
.unwrap_or(parent_style.map(|s| s.align_items).unwrap_or_default());
let item_height =
self.measure_node_height(item.node, fw, &item.style, font_context);
// Auto margins on cross axis take priority over align-items
let has_auto_v = item.style.margin.has_auto_vertical();
let y_offset = if has_auto_v {
let fixed_v = item.style.margin.vertical();
let slack = (line_height - item_height - fixed_v).max(0.0);
let auto_top = item.style.margin.top.is_auto();
let auto_bottom = item.style.margin.bottom.is_auto();
match (auto_top, auto_bottom) {
(true, true) => slack / 2.0,
(true, false) => slack,
(false, true) => 0.0,
(false, false) => 0.0,
}
} else {
match align {
AlignItems::FlexStart => 0.0,
AlignItems::FlexEnd => {
line_height - item_height - item.style.margin.vertical()
}
AlignItems::Center => {
(line_height - item_height - item.style.margin.vertical()) / 2.0
}
AlignItems::Stretch => 0.0,
AlignItems::Baseline => 0.0,
}
};
// When stretch applies and item has no explicit height, pass
// the cross-axis height so inner layout sees a fixed container.
// Auto margins prevent stretch.
let cross_h = if matches!(align, AlignItems::Stretch)
&& matches!(item.style.height, SizeConstraint::Auto)
&& !has_auto_v
{
let stretch_h = line_height - item.style.margin.vertical();
if stretch_h > item_height {
Some(stretch_h)
} else {
None
}
} else {
None
};
let saved_y = cursor.y;
cursor.y = row_start_y + y_offset;
self.layout_node(
item.node,
cursor,
pages,
x,
available_width,
parent_style,
font_context,
cross_h,
Some(fw),
);
cursor.y = saved_y;
x += fw;
}
if line_items.len() > 1 && pages.len() > line_start_pages {
let near = line_items
.iter()
.find_map(|it| first_text_snippet(it.node))
.map(|t| format!(" (row beginning \"{t}\")"))
.unwrap_or_default();
self.defect(format!(
"render defect: a flex row crossing a page boundary lays its children sequentially — a column taller than the page does not continue side by side{near}"
));
}
cursor.y = row_start_y + line_height;
line_infos.push((line_elem_start, cursor.elements.len(), line_height));
}
// Apply align-content redistribution for wrapped flex lines
if pages.len() == initial_pages_count && !line_infos.is_empty() {
let align_content = parent_style.map(|s| s.align_content).unwrap_or_default();
if !matches!(align_content, AlignContent::FlexStart)
&& !matches!(flex_wrap, FlexWrap::NoWrap)
{
if let Some(parent) = parent_style {
if let SizeConstraint::Fixed(container_h) = parent.height {
let inner_h = container_h
- parent.padding.vertical()
- parent.border_width.vertical();
let total_used = cursor.y - flex_start_y;
let slack = inner_h - total_used;
if slack > 0.0 {
let n = line_infos.len();
let offsets: Vec<f64> = match align_content {
AlignContent::FlexEnd => vec![slack; n],
AlignContent::Center => vec![slack / 2.0; n],
AlignContent::SpaceBetween => {
if n <= 1 {
vec![0.0; n]
} else {
let per_gap = slack / (n - 1) as f64;
(0..n).map(|i| i as f64 * per_gap).collect()
}
}
AlignContent::SpaceAround => {
let space = slack / n as f64;
(0..n).map(|i| space / 2.0 + i as f64 * space).collect()
}
AlignContent::SpaceEvenly => {
let space = slack / (n + 1) as f64;
(0..n).map(|i| (i + 1) as f64 * space).collect()
}
AlignContent::Stretch => {
let extra = slack / n as f64;
(0..n).map(|i| i as f64 * extra).collect()
}
AlignContent::FlexStart => vec![0.0; n],
};
for (i, &(start, end, _)) in line_infos.iter().enumerate() {
let dy = offsets[i];
if dy.abs() > 0.001 {
for j in start..end {
offset_element_y(&mut cursor.elements[j], dy);
}
}
}
cursor.y += *offsets.last().unwrap_or(&0.0);
}
}
}
}
}
}
// ─── Lists ─────────────────────────────────────────────────────
#[allow(clippy::too_many_arguments)]
fn layout_list(
&self,
node: &Node,
ordered: bool,
marker_type: ListMarkerType,
start: u32,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
font_context: &FontContext,
) {
let margin = &style.margin.to_edges();
let padding = &style.padding;
cursor.y += margin.top;
let list_x = x + margin.left;
let outer_width = available_width - margin.horizontal();
let inner_width = outer_width - padding.horizontal();
// Count items so we can size the marker gutter for the widest
// marker the list will produce (e.g. "12." needs more space than "1.")
let n_items = node
.children
.iter()
.filter(|c| matches!(c.kind, NodeKind::ListItem))
.count() as u32;
let marker_gutter =
compute_marker_gutter_width(ordered, marker_type, start, n_items, style);
let list_inner_x = list_x + padding.left;
let content_x = list_inner_x + marker_gutter;
let content_width = (inner_width - marker_gutter).max(0.0);
// Snapshot for wrapping the items in a single List container
// element (so tagged-PDF picks up the /L role on the whole list).
let snapshot = cursor.elements.len();
let list_start_y = cursor.content_y + cursor.y;
cursor.y += padding.top;
let mut item_index: u32 = 0;
for child in &node.children {
if !matches!(child.kind, NodeKind::ListItem) {
continue;
}
let marker_idx = start + item_index;
self.layout_list_item(
child,
marker_idx,
ordered,
marker_type,
marker_gutter,
style,
cursor,
pages,
list_inner_x,
content_x,
content_width,
font_context,
);
item_index += 1;
}
cursor.y += padding.bottom;
// Wrap collected item elements in a List container
let item_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
let list_height = cursor.content_y + cursor.y - list_start_y;
cursor.elements.push(LayoutElement {
x: list_x,
y: list_start_y,
width: outer_width,
height: list_height,
draw: DrawCommand::None,
children: item_elements,
node_type: Some("List".to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: None,
bookmark: node.bookmark.clone(),
alt: None,
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += margin.bottom;
}
#[allow(clippy::too_many_arguments)]
fn layout_list_item(
&self,
item: &Node,
marker_idx: u32,
ordered: bool,
marker_type: ListMarkerType,
marker_gutter: f64,
parent_style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
list_inner_x: f64,
content_x: f64,
content_width: f64,
font_context: &FontContext,
) {
let item_style = item.style.resolve(Some(parent_style), content_width);
let item_margin = item_style.margin.to_edges();
cursor.y += item_margin.top;
let item_start_y = cursor.content_y + cursor.y;
let item_snapshot = cursor.elements.len();
// 1. Render the marker. Save cursor.y, lay out marker as a tiny
// Text node at list_inner_x with width = marker_gutter, then
// restore cursor.y so the content lays out at the same line.
let marker_str = format_marker(marker_idx, ordered, marker_type);
if !marker_str.is_empty() {
let saved_y = cursor.y;
self.layout_text(
&marker_str,
None,
&[],
&item_style,
cursor,
pages,
list_inner_x,
marker_gutter,
font_context,
None,
None,
Some("Lbl"),
);
cursor.y = saved_y;
}
// 2. Lay out item children at content_x using the standard
// layout_children path. Wrapping inside a long item naturally
// indents to content_x for every line because that's the x
// we hand to layout_children — no special hanging-indent
// logic required, since the marker is a separate element.
self.layout_children(
&item.children,
&item.style,
cursor,
pages,
content_x,
content_width,
Some(&item_style),
font_context,
);
// 3. Wrap marker + content in a ListItem container element
// (tagged PDF picks up /LI from the node_type).
let item_children: Vec<LayoutElement> = cursor.elements.drain(item_snapshot..).collect();
let item_height = cursor.content_y + cursor.y - item_start_y;
let item_width = content_x + content_width - list_inner_x;
cursor.elements.push(LayoutElement {
x: list_inner_x,
y: item_start_y,
width: item_width,
height: item_height,
draw: DrawCommand::None,
children: item_children,
node_type: Some("ListItem".to_string()),
resolved_style: Some(item_style.clone()),
source_location: item.source_location.clone(),
href: None,
bookmark: item.bookmark.clone(),
alt: None,
is_header_row: false,
col_span: 1,
overflow: item_style.overflow,
opacity: item_style.opacity,
});
cursor.y += item_margin.bottom;
}
#[allow(clippy::too_many_arguments)]
fn layout_table(
&self,
node: &Node,
style: &ResolvedStyle,
column_defs: &[ColumnDef],
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
font_context: &FontContext,
) {
let padding = &style.padding;
let margin = &style.margin.to_edges();
let border = &style.border_width;
let table_x = x + margin.left;
let table_width = match style.width {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => available_width - margin.horizontal(),
};
let inner_width = table_width - padding.horizontal() - border.horizontal();
let col_widths = self.resolve_column_widths(
column_defs,
inner_width,
&node.children,
style,
font_context,
);
// Column assignments for every row (colspan + rowspan occupancy),
// computed once over the authored row order and carried alongside
// each row through partitioning.
let all_offsets = Self::table_column_offsets(&node.children);
let mut header_rows: Vec<(&Node, &[usize])> = Vec::new();
let mut body_rows: Vec<(&Node, &[usize])> = Vec::new();
for (child, offs) in node.children.iter().zip(&all_offsets) {
match &child.kind {
NodeKind::TableRow { is_header: true } => header_rows.push((child, offs)),
_ => body_rows.push((child, offs)),
}
}
// break-inside: avoid (wrap: false). Row-by-row pagination below
// ignores breakability, so an unbreakable table that doesn't fit
// must move to a fresh page here — whole — before any row lands.
// A table taller than a full page falls through to normal
// pagination: breaking is unavoidable and splitting beats clipping.
if !style.breakable {
let total_height: f64 = node
.children
.iter()
.zip(&all_offsets)
.map(|(r, o)| self.measure_table_row_height(r, &col_widths, o, style, font_context))
.sum::<f64>()
+ padding.vertical()
+ border.vertical();
let fresh_page_available = cursor.content_height
- cursor.fixed_header.iter().map(|(_, h)| *h).sum::<f64>()
- cursor.fixed_footer.iter().map(|(_, h)| *h).sum::<f64>();
if total_height > cursor.remaining_height()
&& total_height <= fresh_page_available
&& cursor.y > 0.0
{
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
}
// Snapshot-and-collect state for the Table wrapper element (same
// clone-semantics fragment wrapping as layout_breakable_view). Two
// consumers need a real Table container: table-level border and
// background have no paint target without one, and structural
// consumers (tagged PDF /Table, pdf-testkit's extractor) otherwise
// have to synthesize the table from loose rows.
let initial_page_count = pages.len();
let snapshot = cursor.elements.len();
let rect_start_y = cursor.content_y + cursor.y + margin.top;
cursor.y += margin.top + padding.top + border.top;
let cell_x_start = table_x + padding.left + border.left;
// Initial-header pre-fit check. Covers three related symptoms:
//
// * Original issue 4 ("doubled, sliding column"): table starts low
// enough that the header didn't fit. Each header cell's inner
// content triggered a widow/orphan page-break via layout_text,
// and layout_table_row's cell-overflow path committed those
// breaks as spurious "trial" pages.
// * Orphan header: header fits in remaining space but the first
// body row doesn't, so the header gets drawn at the bottom of
// the current page with no rows beneath it, then redrawn on
// the next page above the actual rows.
// * Long-token header (issue 2 reproduction): a single header
// cell wraps to many lines because of a no-break-opportunity
// token. Even though the pre-check would fire on header height
// alone, including the first body row makes the fit decision
// symmetric with body-row checks below and avoids edge cases
// where rounding leaves the header just barely fitting while
// no body row will ever land on the same page.
//
// Fold the first body row into the fit calculation so we never
// leave an orphan header behind. Cap at fresh-page available
// height: if the combined block is genuinely taller than a page,
// page-breaking can't help — fall through and let the
// `!is_header` cell-overflow guard in layout_table_row handle it.
if !header_rows.is_empty() {
let total_header_h: f64 = header_rows
.iter()
.map(|(r, o)| self.measure_table_row_height(r, &col_widths, o, style, font_context))
.sum();
let first_body_h = body_rows
.first()
.map(|(r, o)| self.measure_table_row_height(r, &col_widths, o, style, font_context))
.unwrap_or(0.0);
let needed = total_header_h + first_body_h;
let fresh_page_available = cursor.content_height
- cursor.fixed_header.iter().map(|(_, h)| *h).sum::<f64>()
- cursor.fixed_footer.iter().map(|(_, h)| *h).sum::<f64>();
if needed > cursor.remaining_height() && needed <= fresh_page_available {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
cursor.y += padding.top + border.top;
}
}
for (header_row, offs) in &header_rows {
self.layout_table_row(
header_row,
&col_widths,
offs,
style,
cursor,
cell_x_start,
font_context,
pages,
);
}
for (body_row, offs) in &body_rows {
let row_height =
self.measure_table_row_height(body_row, &col_widths, offs, style, font_context);
// Break only when a fresh page actually buys room. A row taller
// than any page (the email-template idiom: everything in one
// <tr>) used to force a break even at the top of an empty page,
// emitting blank pages before itself (template-compat 11). Row
// atomicity stands — the row is placed whole and overflows — but
// that's a render defect worth saying out loud, not a reason to
// print empty pages.
let fresh_page_available = cursor.content_height
- cursor.fixed_header.iter().map(|(_, h)| *h).sum::<f64>()
- cursor.fixed_footer.iter().map(|(_, h)| *h).sum::<f64>();
if row_height > fresh_page_available {
self.defect(format!(
"render defect: table row needs {row_height:.0}pt but a page holds {fresh_page_available:.0}pt — rows are atomic, so it is placed whole and overflows",
));
}
if row_height > cursor.remaining_height()
&& cursor.remaining_height() < fresh_page_available - 0.5
{
pages.push(cursor.finalize());
*cursor = cursor.new_page();
cursor.y += padding.top + border.top;
for (header_row, h_offs) in &header_rows {
self.layout_table_row(
header_row,
&col_widths,
h_offs,
style,
cursor,
cell_x_start,
font_context,
pages,
);
}
}
self.layout_table_row(
body_row,
&col_widths,
offs,
style,
cursor,
cell_x_start,
font_context,
pages,
);
}
// Wrap the laid-out rows in a Table container element. Always
// emitted (structural consumers need it even without visuals); the
// draw command is a Rect only when there's something to paint.
let has_visual = style.background_color.is_some()
|| style.background.is_some()
|| style.border_width.top > 0.0
|| style.border_width.right > 0.0
|| style.border_width.bottom > 0.0
|| style.border_width.left > 0.0;
let draw_cmd = if has_visual {
DrawCommand::Rect {
background: style.background_color,
border_width: style.border_width,
border_color: style.border_color,
border_style: style.border_style,
border_radius: style.border_radius,
opacity: 1.0,
box_shadow: style.box_shadow.map(Box::new),
background_gradient: style.background.clone().map(Box::new),
}
} else {
DrawCommand::None
};
let make_wrapper =
|y: f64, height: f64, children: Vec<LayoutElement>, draw| LayoutElement {
x: table_x,
y,
width: table_width,
height,
draw,
children,
node_type: Some(node_kind_name(&node.kind).to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: style.opacity,
};
let table_bottom_y = cursor.content_y + cursor.y + padding.bottom + border.bottom;
if pages.len() == initial_page_count {
// No page breaks: simple wrap.
let child_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
cursor.elements.push(make_wrapper(
rect_start_y,
table_bottom_y - rect_start_y,
child_elements,
draw_cmd,
));
} else {
// Page breaks occurred: clone-semantics fragment per page,
// mirroring layout_breakable_view.
//
// STREAMING-LAYOUT NOTE (investigated 2026-09, parked — see
// scripts/parity/benchmarks.mjs trackedFixes "Streaming layout"):
// this retroactive reach-back into `pages[initial_page_count..]` is
// THE reason large-doc peak memory can't be streamed away. A
// document-spanning table (e.g. ledger-500p: one table, 500 pages)
// holds every page it covered resident until it closes here at
// end-of-document, so streaming the producer/serializer saves
// nothing. The fix is to emit each page's wrapper FORWARD at page
// finalize (open-container stack on the cursor: record draw_cmd +
// per-page start-y; wrap the finalizing page from start-y; reset
// start-y to content_top on new_page). Byte-identical (each wrapper
// below uses only its own page's geometry), but it must cover all
// four container types (table, breakable_view, flex, paragraph).
// A. The page the table started on — wrap from the snapshot.
let page = &mut pages[initial_page_count];
let footer_h: f64 = page.fixed_footer.iter().map(|(_, h)| *h).sum();
let page_content_bottom =
page.config.margin.top + (page.height - page.config.margin.vertical()) - footer_h;
let our_elements: Vec<LayoutElement> = page.elements.drain(snapshot..).collect();
if !our_elements.is_empty() {
page.elements.push(make_wrapper(
rect_start_y,
page_content_bottom - rect_start_y,
our_elements,
draw_cmd.clone(),
));
}
// B. Intermediate pages — entirely table content.
for page in &mut pages[initial_page_count + 1..] {
let header_h: f64 = page.fixed_header.iter().map(|(_, h)| *h).sum();
let content_top = page.config.margin.top + header_h;
let footer_h: f64 = page.fixed_footer.iter().map(|(_, h)| *h).sum();
let content_bottom = page.config.margin.top
+ (page.height - page.config.margin.vertical())
- footer_h;
let all_elements: Vec<LayoutElement> = std::mem::take(&mut page.elements);
if !all_elements.is_empty() {
page.elements.push(make_wrapper(
content_top,
content_bottom - content_top,
all_elements,
draw_cmd.clone(),
));
}
}
// C. Current page — everything on it is table content.
let all_elements: Vec<LayoutElement> = std::mem::take(&mut cursor.elements);
if !all_elements.is_empty() {
let header_h: f64 = cursor.fixed_header.iter().map(|(_, h)| *h).sum();
let content_top = cursor.content_y + header_h;
cursor.elements.push(make_wrapper(
content_top,
table_bottom_y - content_top,
all_elements,
draw_cmd,
));
}
}
cursor.y += padding.bottom + border.bottom + margin.bottom;
}
/// True if any node in this subtree can *force* a page break during flow
/// layout: an explicit `PageBreak` or `PageName` marker, or a node with
/// `break-before` set. Height-overflow breaks are NOT covered here — those
/// are bounded separately by the caller's row-fits check. Used to decide
/// whether a table row needs a per-cell rollback checkpoint (Fix 3-B): a
/// row that fits and forces no break cannot break any cell, so its
/// checkpoints are dead. Conservative — a new forced-break source not
/// listed here would be missed, which the `row_may_break` invariant assert
/// and the byte-identity corpus are positioned to catch.
fn subtree_forces_break(node: &Node) -> bool {
if matches!(node.kind, NodeKind::PageBreak | NodeKind::PageName { .. }) {
return true;
}
if node.style.break_before == Some(true) {
return true;
}
node.children.iter().any(Self::subtree_forces_break)
}
/// Occupancy-aware column count: the widest row's last assigned column
/// plus its span — includes columns carried by rowspans, so the DEFS
/// path and the automatic path agree with layout's assignments (the
/// defs path counting with a plain colspan sum starved template-compat
/// 05's value column to zero width).
fn occupancy_column_count(children: &[Node]) -> usize {
let offsets = Self::table_column_offsets(children);
children
.iter()
.zip(&offsets)
.map(|(row, offs)| {
row.children
.iter()
.zip(offs)
.map(|(cell, &start)| start + Self::cell_col_span(cell))
.max()
.unwrap_or(0)
})
.max()
.unwrap_or(1)
.max(1)
}
/// Per-row, per-cell starting column for a table's rows, honoring BOTH
/// colspan advancement and ROWSPAN OCCUPANCY: a cell with rowspan=N
/// keeps its columns occupied for the following N-1 rows, so those
/// rows' cells start past it. Without this, the Anvil idiom — a
/// rowspan'd name cell beside per-row address lines — assigned the
/// address lines to column 1 and right-aligned them mid-page
/// (template-compat 02). Pure function of the node tree, so every
/// consumer (layout, row measurement, column-content distribution,
/// column counting) derives identical assignments.
fn table_column_offsets(rows: &[Node]) -> Vec<Vec<usize>> {
fn spans(cell: &Node) -> (usize, u32) {
match &cell.kind {
NodeKind::TableCell { col_span, row_span } => {
((*col_span).max(1) as usize, (*row_span).max(1))
}
_ => (1, 1),
}
}
let mut pending: Vec<u32> = Vec::new();
let mut out = Vec::with_capacity(rows.len());
for row in rows {
let mut offsets = Vec::with_capacity(row.children.len());
let mut col = 0usize;
for cell in &row.children {
let (span, rspan) = spans(cell);
while pending.get(col).copied().unwrap_or(0) > 0 {
col += 1;
}
offsets.push(col);
if rspan > 1 {
if pending.len() < col + span {
pending.resize(col + span, 0);
}
for slot in pending.iter_mut().take(col + span).skip(col) {
*slot = (*slot).max(rspan);
}
}
col += span;
}
out.push(offsets);
for p in pending.iter_mut() {
*p = p.saturating_sub(1);
}
}
out
}
#[allow(clippy::too_many_arguments)]
fn layout_table_row(
&self,
row: &Node,
col_widths: &[f64],
col_offsets: &[usize],
parent_style: &ResolvedStyle,
cursor: &mut PageCursor,
start_x: f64,
font_context: &FontContext,
pages: &mut Vec<LayoutPage>,
) {
let row_style = row
.style
.resolve(Some(parent_style), col_widths.iter().sum());
let row_height =
self.measure_table_row_height(row, col_widths, col_offsets, parent_style, font_context);
let row_bl = self.row_baseline(row, &row_style, col_widths, col_offsets);
let row_y = cursor.content_y + cursor.y;
let total_width: f64 = col_widths.iter().sum();
let is_header = matches!(row.kind, NodeKind::TableRow { is_header: true });
// Snapshot before laying out cells — we'll collect them as row children
let row_snapshot = cursor.elements.len();
// Rollback-checkpoint elision (Fix 3-B). Each cell below snapshots the
// full cursor (`cursor.clone()`, which deep-copies every element on the
// page so far) to restore if the cell's content triggers a page break.
// dhat flagged that single clone as ~76% of all allocated bytes. A cell
// can only break for two reasons: its content overflows the remaining
// page height, or a forced break fires inside it. If the WHOLE row fits
// in the remaining height (`row_height` bounds every cell's content) AND
// the row subtree contains no forced break, no cell can break — so the
// checkpoint is dead and we skip cloning it. Evaluated once here, at the
// row's top `y`, before the loop advances the cursor; conservative by
// construction (any doubt ⇒ clone), so output stays byte-identical.
let row_may_break =
row_height > cursor.remaining_height() || Self::subtree_forces_break(row);
let mut all_overflow_pages: Vec<LayoutPage> = Vec::new();
// Column assignment comes from table_column_offsets (colspan
// advancement + rowspan occupancy); x and width derive from the
// assigned column, never from cell position.
for (cell_i, cell) in row.children.iter().enumerate() {
let span = match &cell.kind {
NodeKind::TableCell { col_span, .. } => (*col_span).max(1) as usize,
_ => 1,
};
let start_col = col_offsets.get(cell_i).copied().unwrap_or(0);
let col_width: f64 = col_widths.iter().skip(start_col).take(span).copied().sum();
let cell_x = start_x + col_widths.iter().take(start_col).copied().sum::<f64>();
let cell_style = cell.style.resolve(Some(&row_style), col_width);
// Snapshot before cell content — we'll collect as cell children
let cell_snapshot = cursor.elements.len();
let inner_width =
col_width - cell_style.padding.horizontal() - cell_style.border_width.horizontal();
let content_x = cell_x + cell_style.padding.left + cell_style.border_width.left;
let saved_y = cursor.y;
cursor.y += cell_style.padding.top + cell_style.border_width.top;
// vertical-align: middle/bottom/baseline — the row box height is
// already resolved (measured above the loop), so offset this cell's
// content within it. Top is the default and costs nothing.
if !matches!(cell_style.vertical_align, crate::style::VerticalAlign::Top) {
let content_h: f64 = cell
.children
.iter()
.map(|ch| {
let ch_style = ch.style.resolve(Some(&cell_style), inner_width);
self.measure_node_height(ch, inner_width, &ch_style, font_context)
})
.sum();
let inner_row =
row_height - cell_style.padding.vertical() - cell_style.border_width.vertical();
let slack = (inner_row - content_h).max(0.0);
cursor.y += match cell_style.vertical_align {
crate::style::VerticalAlign::Middle => slack / 2.0,
crate::style::VerticalAlign::Bottom => slack,
// Shove this cell down so its first baseline lands on the
// row baseline (the max first-baseline distance across the
// row's baseline cells). measure_table_row_height grew the
// row to fit this, so it never clips.
crate::style::VerticalAlign::Baseline => row_bl
.map(|b| {
let d = self.cell_baseline_distance(cell, &cell_style, inner_width);
(b - d).max(0.0)
})
.unwrap_or(0.0),
crate::style::VerticalAlign::Top => 0.0,
};
}
// Save cursor state in case cell content triggers page breaks — but
// only when a break is actually possible (see `row_may_break`). When
// the row provably fits with no forced break, this clone is dead, so
// we skip the deep copy of the page's element vec.
let cursor_before_cell = if row_may_break {
Some(cursor.clone())
} else {
None
};
let mut cell_pages: Vec<LayoutPage> = Vec::new();
for child in &cell.children {
self.layout_node(
child,
cursor,
&mut cell_pages,
content_x,
inner_width,
Some(&cell_style),
font_context,
None,
None,
);
}
// If cell content triggered page breaks, collect overflow and restore cursor
if !cell_pages.is_empty() {
let post_break_elements = std::mem::take(&mut cursor.elements);
if let Some(last_page) = cell_pages.last_mut() {
last_page.elements.extend(post_break_elements);
}
// Belt-and-suspenders for issue 4: header rows are designed to
// be re-emitted on each continuation page and must never
// legitimately produce mid-row page breaks. If they somehow do
// (e.g. a future regression that puts headers in a tight spot
// again), drop the trial pages rather than committing them.
if !is_header {
all_overflow_pages.extend(cell_pages);
}
// A break occurred, so the checkpoint MUST exist: `row_may_break`
// is a conservative over-approximation of "a cell can break", so
// any real break implies we took the clone. If this ever fires,
// the fits/forced-break guard missed a break source — a bug to
// fix in the guard, not to paper over.
*cursor = cursor_before_cell
.expect("table cell broke but no rollback checkpoint was taken (row_may_break under-approximated)");
}
cursor.y = saved_y;
// Collect cell content elements
let cell_children: Vec<LayoutElement> =
cursor.elements.drain(cell_snapshot..).collect();
// Always push a cell element (with or without visual styling) to preserve hierarchy
cursor.elements.push(LayoutElement {
x: cell_x,
y: row_y,
width: col_width,
height: row_height,
draw: if cell_style.background_color.is_some()
|| cell_style.border_width.horizontal() > 0.0
|| cell_style.border_width.vertical() > 0.0
{
DrawCommand::Rect {
background: cell_style.background_color,
border_width: cell_style.border_width,
border_color: cell_style.border_color,
border_style: cell_style.border_style,
border_radius: cell_style.border_radius,
opacity: 1.0,
box_shadow: cell_style.box_shadow.map(Box::new),
background_gradient: cell_style.background.clone().map(Box::new),
}
} else {
DrawCommand::None
},
children: cell_children,
node_type: Some("TableCell".to_string()),
resolved_style: Some(cell_style.clone()),
source_location: cell.source_location.clone(),
href: None,
bookmark: cell.bookmark.clone(),
alt: None,
is_header_row: is_header,
col_span: span as u32,
overflow: Overflow::default(),
opacity: 1.0,
});
}
// Collect all cell elements as row children
let row_children: Vec<LayoutElement> = cursor.elements.drain(row_snapshot..).collect();
let row_element = LayoutElement {
x: start_x,
y: row_y,
width: total_width,
height: row_height,
draw: if let Some(bg) = row_style.background_color {
DrawCommand::Rect {
background: Some(bg),
border_width: Edges::default(),
border_color: EdgeValues::uniform(Color::BLACK),
border_style: EdgeValues::uniform(crate::style::BorderStyle::Solid),
border_radius: CornerValues::uniform(0.0),
opacity: 1.0,
box_shadow: row_style.box_shadow.map(Box::new),
background_gradient: row_style.background.clone().map(Box::new),
}
} else {
DrawCommand::None
},
children: row_children,
node_type: Some("TableRow".to_string()),
resolved_style: Some(row_style.clone()),
source_location: row.source_location.clone(),
href: None,
bookmark: row.bookmark.clone(),
alt: None,
is_header_row: is_header,
col_span: 1,
overflow: row_style.overflow,
opacity: row_style.opacity,
};
if let Some(first_overflow) = all_overflow_pages.first_mut() {
// The row's content lives in the overflow pages (cell content
// that exceeded the page split there and the cursor was rolled
// back) — so the wrapper belongs on the FIRST of them, where the
// row visually starts. Pushing it onto the restored cursor page
// instead, and advancing the cursor by the full row height, used
// to strand a container-only (visually blank) trailing page and
// push everything after the table off-page (template-compat 11's
// empty pages). The restored page stays at the row's start y for
// whatever follows the table.
first_overflow.elements.push(row_element);
} else {
cursor.elements.push(row_element);
cursor.y += row_height;
}
// Append any overflow pages from cells that exceeded page height
pages.extend(all_overflow_pages);
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments)]
fn layout_text(
&self,
content: &str,
href: Option<&str>,
runs: &[TextRun],
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
font_context: &FontContext,
source_location: Option<&SourceLocation>,
bookmark: Option<&str>,
// Optional node_type label for the wrapping Text element. Defaults
// to "Text". Headings pass "H1".."H6" so tagged-PDF picks up the
// semantic role; everything else passes None.
node_type_override: Option<&str>,
) {
// Text nodes paint glyphs and decorations only — borders and
// backgrounds render exclusively on container views. A style that
// asks for one here is silently unpaintable, which is exactly the
// defect channel's question (found live: @page margin-box styles
// landing on the band's text node dropped the running header's
// rule without a word).
if style.border_width.top > 0.0
|| style.border_width.right > 0.0
|| style.border_width.bottom > 0.0
|| style.border_width.left > 0.0
{
self.defect(
"render defect: a border on a text node is not painted (wrap the text in a container element)".to_string(),
);
}
if style.background_color.is_some() {
self.defect(
"render defect: a background on a text node is not painted (wrap the text in a container element)".to_string(),
);
}
let margin = &style.margin.to_edges();
let text_x = x + margin.left;
// Honor an explicit/resolved fixed width for the text box; only fall back
// to available_width when width is Auto. In a flex row, available_width is
// the parent row's content width (used for percentage resolution) while the
// child's own distributed width arrives via style.width — see layout_node's
// forced_outer_width. layout_view already works this way; this keeps leaf
// text consistent so textAlign/justify use the real box, not the row width.
let text_width = match style.width {
SizeConstraint::Fixed(w) => (w - margin.horizontal()).max(0.0),
SizeConstraint::Auto => available_width - margin.horizontal(),
};
cursor.y += margin.top;
// Runs path: if runs are provided, use multi-style line breaking
if !runs.is_empty() {
self.layout_text_runs(
runs,
href,
style,
cursor,
pages,
text_x,
text_width,
font_context,
source_location,
bookmark,
node_type_override,
);
cursor.y += margin.bottom;
return;
}
let content = substitute_page_placeholders(content);
let transformed = apply_text_transform(&content, style.text_transform);
let justify = matches!(style.text_align, TextAlign::Justify);
let lines = match style.line_breaking {
LineBreaking::Optimal => self.text_layout.break_into_lines_optimal(
font_context,
&transformed,
text_width,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
style.letter_spacing,
style.hyphens,
style.lang.as_deref(),
justify,
),
LineBreaking::Greedy => self.text_layout.break_into_lines(
font_context,
&transformed,
text_width,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
style.letter_spacing,
style.hyphens,
style.lang.as_deref(),
),
};
// Apply text overflow truncation (single-line modes)
let lines = match style.text_overflow {
TextOverflow::Ellipsis => self.text_layout.truncate_with_ellipsis(
font_context,
lines,
text_width,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
style.letter_spacing,
),
TextOverflow::Clip => self.text_layout.truncate_clip(
font_context,
lines,
text_width,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
style.letter_spacing,
),
TextOverflow::Wrap => lines,
};
let line_height = style.font_size * style.line_height;
// Widow/orphan control: decide how to break before placing lines
let line_heights: Vec<f64> = vec![line_height; lines.len()];
let decision = page_break::decide_break(
cursor.remaining_height(),
&line_heights,
true,
style.min_orphan_lines as usize,
style.min_widow_lines as usize,
);
// Snapshot-and-collect: accumulate line elements, wrap in parent
let mut snapshot = cursor.elements.len();
let mut container_start_y = cursor.content_y + cursor.y;
let mut is_first_element = true;
// Handle move-to-next-page decision (orphan control)
if matches!(decision, page_break::BreakDecision::MoveToNextPage) {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
snapshot = cursor.elements.len();
container_start_y = cursor.content_y + cursor.y;
}
// For split decisions, track the widow/orphan-adjusted first break point
let forced_break_at = match decision {
page_break::BreakDecision::Split {
items_on_current_page,
} => Some(items_on_current_page),
_ => None,
};
let mut first_break_done = false;
for (line_idx, line) in lines.iter().enumerate() {
// Widow/orphan-controlled first break, then normal overflow checks
let needs_break = if let Some(break_at) = forced_break_at {
if !first_break_done && line_idx == break_at {
true
} else {
line_height > cursor.remaining_height()
}
} else {
line_height > cursor.remaining_height()
};
if needs_break {
first_break_done = true;
// Flush accumulated lines into a Text container on this page
let line_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
if !line_elements.is_empty() {
let container_height = cursor.content_y + cursor.y - container_start_y;
cursor.elements.push(LayoutElement {
x: text_x,
y: container_start_y,
width: text_width,
height: container_height,
draw: DrawCommand::None,
children: line_elements,
node_type: Some(node_type_override.unwrap_or("Text").to_string()),
resolved_style: Some(style.clone()),
source_location: source_location.cloned(),
href: href.map(|s| s.to_string()),
bookmark: if is_first_element {
bookmark.map(|s| s.to_string())
} else {
None
},
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
is_first_element = false;
}
pages.push(cursor.finalize());
*cursor = cursor.new_page();
// Reset snapshot for new page
snapshot = cursor.elements.len();
container_start_y = cursor.content_y + cursor.y;
}
let glyphs = self.build_positioned_glyphs_single_style(line, style, href, font_context);
// Use actual rendered width from glyphs for alignment (may differ from
// line.width when per-char measurement is used for line breaking but
// shaping is used for glyph placement).
let rendered_width = if glyphs.is_empty() {
line.width
} else {
let last = &glyphs[glyphs.len() - 1];
(last.x_offset + last.x_advance).max(line.width * 0.5)
};
let line_x = match style.text_align {
TextAlign::Left => text_x,
TextAlign::Right => text_x + text_width - rendered_width,
TextAlign::Center => text_x + (text_width - rendered_width) / 2.0,
TextAlign::Justify => text_x,
};
// Justify: compute extra word spacing so the line fills the column width.
// Use the sum of natural glyph advances (what PDF Tj actually renders)
// rather than KP-adjusted positions, which bake justification into
// char_positions and make slack ≈ 0.
//
// User-set `word_spacing` is the base; when text is justified, the
// computed slack-per-space is added on top.
let is_last_line = line_idx == lines.len() - 1;
let user_ws = style.word_spacing;
let (justified_width, word_spacing) =
if matches!(style.text_align, TextAlign::Justify) && !is_last_line {
let last_non_space = glyphs.iter().rposition(|g| g.char_value != ' ');
let (natural_width, space_count) = if let Some(idx) = last_non_space {
let w: f64 = glyphs[..=idx].iter().map(|g| g.x_advance).sum();
let s = glyphs[..=idx]
.iter()
.filter(|g| g.char_value == ' ')
.count();
(w, s)
} else {
(0.0, 0)
};
let slack = text_width - natural_width;
let ws = if space_count > 0 && slack.abs() > 0.01 {
slack / space_count as f64
} else {
0.0
};
(text_width, user_ws + ws)
} else {
(rendered_width, user_ws)
};
let text_line = TextLine {
x: line_x,
// Half-leading: the line box's extra space over the glyph block
// splits evenly above and below (CSS line box model). The
// baseline therefore sits half the leading further down —
// this is also what makes the pre-flexbox centering idiom
// (line-height matched to a box height) actually center.
y: cursor.content_y
+ cursor.y
+ (line_height - style.font_size) / 2.0
+ style.font_size,
glyphs,
width: justified_width,
height: line_height,
word_spacing,
};
cursor.elements.push(LayoutElement {
x: line_x,
y: cursor.content_y + cursor.y,
width: justified_width,
height: line_height,
draw: DrawCommand::Text {
lines: vec![text_line],
color: style.color,
text_decoration: style.text_decoration,
opacity: 1.0,
},
children: vec![],
node_type: Some("TextLine".to_string()),
resolved_style: Some(style.clone()),
source_location: None,
href: href.map(|s| s.to_string()),
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
cursor.y += line_height;
}
// Wrap remaining lines into a Text container
let line_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
if !line_elements.is_empty() {
let container_height = cursor.content_y + cursor.y - container_start_y;
cursor.elements.push(LayoutElement {
x: text_x,
y: container_start_y,
width: text_width,
height: container_height,
draw: DrawCommand::None,
children: line_elements,
node_type: Some(node_type_override.unwrap_or("Text").to_string()),
resolved_style: Some(style.clone()),
source_location: source_location.cloned(),
href: href.map(|s| s.to_string()),
bookmark: if is_first_element {
bookmark.map(|s| s.to_string())
} else {
None
},
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
}
cursor.y += margin.bottom;
}
/// Layout text runs with per-run styling.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments)]
fn layout_text_runs(
&self,
runs: &[TextRun],
parent_href: Option<&str>,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
text_x: f64,
text_width: f64,
font_context: &FontContext,
source_location: Option<&SourceLocation>,
bookmark: Option<&str>,
// Same role as in layout_text — None defaults to "Text".
node_type_override: Option<&str>,
) {
// Build StyledChar list from runs
let mut styled_chars: Vec<StyledChar> = Vec::new();
for run in runs {
let run_style = run.style.resolve(Some(style), text_width);
let run_href = run.href.as_deref().or(parent_href);
let transform = run_style.text_transform;
let run_content = substitute_page_placeholders(&run.content);
let mut prev_is_whitespace = true;
for ch in run_content.chars() {
let transformed_ch = apply_char_transform(ch, transform, prev_is_whitespace);
prev_is_whitespace = ch.is_whitespace();
styled_chars.push(StyledChar {
ch: transformed_ch,
font_family: run_style.font_family.clone(),
font_size: run_style.font_size,
font_weight: run_style.font_weight,
font_style: run_style.font_style,
color: run_style.color,
href: run_href.map(|s| s.to_string()),
text_decoration: run_style.text_decoration,
letter_spacing: run_style.letter_spacing,
});
}
}
// Break into lines
let justify = matches!(style.text_align, TextAlign::Justify);
let broken_lines = match style.line_breaking {
LineBreaking::Optimal => self.text_layout.break_runs_into_lines_optimal(
font_context,
&styled_chars,
text_width,
style.hyphens,
style.lang.as_deref(),
justify,
),
LineBreaking::Greedy => self.text_layout.break_runs_into_lines(
font_context,
&styled_chars,
text_width,
style.hyphens,
style.lang.as_deref(),
),
};
// Apply text overflow truncation (single-line modes)
let broken_lines = match style.text_overflow {
TextOverflow::Ellipsis => {
self.text_layout
.truncate_runs_with_ellipsis(font_context, broken_lines, text_width)
}
TextOverflow::Clip => {
self.text_layout
.truncate_runs_clip(font_context, broken_lines, text_width)
}
TextOverflow::Wrap => broken_lines,
};
let line_height = style.font_size * style.line_height;
// Widow/orphan control for text runs
let line_heights: Vec<f64> = vec![line_height; broken_lines.len()];
let decision = page_break::decide_break(
cursor.remaining_height(),
&line_heights,
true,
style.min_orphan_lines as usize,
style.min_widow_lines as usize,
);
let mut snapshot = cursor.elements.len();
let mut container_start_y = cursor.content_y + cursor.y;
let mut is_first_element = true;
if matches!(decision, page_break::BreakDecision::MoveToNextPage) {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
snapshot = cursor.elements.len();
container_start_y = cursor.content_y + cursor.y;
}
let forced_break_at = match decision {
page_break::BreakDecision::Split {
items_on_current_page,
} => Some(items_on_current_page),
_ => None,
};
let mut first_break_done = false;
for (line_idx, run_line) in broken_lines.iter().enumerate() {
let needs_break = if let Some(break_at) = forced_break_at {
if !first_break_done && line_idx == break_at {
true
} else {
line_height > cursor.remaining_height()
}
} else {
line_height > cursor.remaining_height()
};
if needs_break {
first_break_done = true;
let line_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
if !line_elements.is_empty() {
let container_height = cursor.content_y + cursor.y - container_start_y;
cursor.elements.push(LayoutElement {
x: text_x,
y: container_start_y,
width: text_width,
height: container_height,
draw: DrawCommand::None,
children: line_elements,
node_type: Some(node_type_override.unwrap_or("Text").to_string()),
resolved_style: Some(style.clone()),
source_location: source_location.cloned(),
href: parent_href.map(|s| s.to_string()),
bookmark: if is_first_element {
bookmark.map(|s| s.to_string())
} else {
None
},
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
is_first_element = false;
}
pages.push(cursor.finalize());
*cursor = cursor.new_page();
snapshot = cursor.elements.len();
container_start_y = cursor.content_y + cursor.y;
}
let line_x = match style.text_align {
TextAlign::Left => text_x,
TextAlign::Right => text_x + text_width - run_line.width,
TextAlign::Center => text_x + (text_width - run_line.width) / 2.0,
TextAlign::Justify => text_x,
};
let glyphs = self.build_positioned_glyphs_runs(run_line, font_context, style.direction);
// Justify: compute extra word spacing so the line fills the column width.
// Use the sum of natural glyph advances (what PDF Tj actually renders)
// rather than KP-adjusted line width.
//
// User-set `word_spacing` is the base; when text is justified, the
// computed slack-per-space is added on top.
let is_last_line = line_idx == broken_lines.len() - 1;
let user_ws = style.word_spacing;
let (justified_width, word_spacing) =
if matches!(style.text_align, TextAlign::Justify) && !is_last_line {
let last_non_space = glyphs.iter().rposition(|g| g.char_value != ' ');
let (natural_width, space_count) = if let Some(idx) = last_non_space {
let w: f64 = glyphs[..=idx].iter().map(|g| g.x_advance).sum();
let s = glyphs[..=idx]
.iter()
.filter(|g| g.char_value == ' ')
.count();
(w, s)
} else {
(0.0, 0)
};
let slack = text_width - natural_width;
let ws = if space_count > 0 && slack.abs() > 0.01 {
slack / space_count as f64
} else {
0.0
};
(text_width, user_ws + ws)
} else {
(run_line.width, user_ws)
};
let text_line = TextLine {
x: line_x,
// Half-leading: the line box's extra space over the glyph block
// splits evenly above and below (CSS line box model). The
// baseline therefore sits half the leading further down —
// this is also what makes the pre-flexbox centering idiom
// (line-height matched to a box height) actually center.
y: cursor.content_y
+ cursor.y
+ (line_height - style.font_size) / 2.0
+ style.font_size,
glyphs,
width: justified_width,
height: line_height,
word_spacing,
};
// Determine text decoration: use the run's decoration if any glyph has one
let text_dec = run_line
.chars
.iter()
.find(|sc| !matches!(sc.text_decoration, TextDecoration::None))
.map(|sc| sc.text_decoration)
.unwrap_or(style.text_decoration);
cursor.elements.push(LayoutElement {
x: line_x,
y: cursor.content_y + cursor.y,
width: justified_width,
height: line_height,
draw: DrawCommand::Text {
lines: vec![text_line],
color: style.color,
text_decoration: text_dec,
opacity: 1.0,
},
children: vec![],
node_type: Some("TextLine".to_string()),
resolved_style: Some(style.clone()),
source_location: None,
href: parent_href.map(|s| s.to_string()),
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
cursor.y += line_height;
}
let line_elements: Vec<LayoutElement> = cursor.elements.drain(snapshot..).collect();
if !line_elements.is_empty() {
let container_height = cursor.content_y + cursor.y - container_start_y;
cursor.elements.push(LayoutElement {
x: text_x,
y: container_start_y,
width: text_width,
height: container_height,
draw: DrawCommand::None,
children: line_elements,
node_type: Some(node_type_override.unwrap_or("Text").to_string()),
resolved_style: Some(style.clone()),
source_location: source_location.cloned(),
href: parent_href.map(|s| s.to_string()),
bookmark: if is_first_element {
bookmark.map(|s| s.to_string())
} else {
None
},
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
}
}
/// Build PositionedGlyphs for a single-style BrokenLine.
/// For custom fonts, shapes the line text to get real glyph IDs.
/// For standard fonts, uses char-as-u16 glyph IDs.
fn build_positioned_glyphs_single_style(
&self,
line: &BrokenLine,
style: &ResolvedStyle,
href: Option<&str>,
font_context: &FontContext,
) -> Vec<PositionedGlyph> {
let italic = matches!(style.font_style, FontStyle::Italic | FontStyle::Oblique);
let line_text: String = line.chars.iter().collect();
let direction = style.direction;
// Check if BiDi processing is needed
let has_bidi = !bidi::is_pure_ltr(&line_text, direction);
// Segment by font — handles both explicit fallback chains and
// automatic builtin font fallback (Noto Sans for non-Latin chars)
let font_runs = crate::font::fallback::segment_by_font(
&line.chars,
&style.font_family,
style.font_weight,
italic,
font_context.registry(),
);
let needs_per_char_fallback = font_runs.len() > 1
|| (font_runs.len() == 1 && font_runs[0].family != style.font_family);
// Per-char fallback path: segment by font within each BiDi run
if needs_per_char_fallback {
let bidi_runs = if has_bidi {
bidi::analyze_bidi(&line_text, direction)
} else {
vec![crate::text::bidi::BidiRun {
char_start: 0,
char_end: line.chars.len(),
level: unicode_bidi::Level::ltr(),
is_rtl: false,
}]
};
let mut all_glyphs = Vec::new();
let mut bidi_levels = Vec::new();
let mut x = 0.0_f64;
// Process each BiDi run
for bidi_run in &bidi_runs {
// Within this BiDi run, sub-segment by font
for font_run in &font_runs {
// Intersect font_run with bidi_run
let start = font_run.start.max(bidi_run.char_start);
let end = font_run.end.min(bidi_run.char_end);
if start >= end {
continue;
}
let sub_chars: Vec<char> = line.chars[start..end].to_vec();
let sub_text: String = sub_chars.iter().collect();
let resolved_family = &font_run.family;
if let Some(font_data) =
font_context.font_data(resolved_family, style.font_weight, italic)
{
if let Some(shaped) = shaping::shape_text_with_direction(
&sub_text,
font_data,
bidi_run.is_rtl,
) {
let units_per_em = font_context.units_per_em(
resolved_family,
style.font_weight,
italic,
);
let scale = style.font_size / units_per_em as f64;
for sg in &shaped {
let cluster = sg.cluster as usize;
let char_value = sub_chars.get(cluster).copied().unwrap_or(' ');
let cluster_text = if shaped.len() < sub_chars.len() {
let cluster_end =
self.find_cluster_end(&shaped, sg, sub_chars.len());
if cluster_end > cluster + 1 {
Some(
sub_chars[cluster..cluster_end]
.iter()
.collect::<String>(),
)
} else {
None
}
} else {
None
};
let glyph_x = x + sg.x_offset as f64 * scale;
let glyph_y = sg.y_offset as f64 * scale;
let advance = sg.x_advance as f64 * scale + style.letter_spacing;
all_glyphs.push(PositionedGlyph {
glyph_id: sg.glyph_id,
x_offset: glyph_x,
y_offset: glyph_y,
x_advance: advance,
font_size: style.font_size,
font_family: Arc::from(resolved_family.as_str()),
font_weight: style.font_weight,
font_style: style.font_style,
char_value,
color: Some(style.color),
href: href.map(|s| s.to_string()),
text_decoration: style.text_decoration,
letter_spacing: style.letter_spacing,
cluster_text,
});
bidi_levels.push(bidi_run.level);
x += advance;
}
continue;
}
}
// Fallback: standard font or shaping failure for this sub-segment
for i in start..end {
let ch = line.chars[i];
let glyph_x = x;
let char_width = font_context.char_width(
ch,
resolved_family,
style.font_weight,
italic,
style.font_size,
);
let advance = char_width + style.letter_spacing;
all_glyphs.push(PositionedGlyph {
glyph_id: ch as u16,
x_offset: glyph_x,
y_offset: 0.0,
x_advance: advance,
font_size: style.font_size,
font_family: Arc::from(resolved_family.as_str()),
font_weight: style.font_weight,
font_style: style.font_style,
char_value: ch,
color: Some(style.color),
href: href.map(|s| s.to_string()),
text_decoration: style.text_decoration,
letter_spacing: style.letter_spacing,
cluster_text: None,
});
bidi_levels.push(bidi_run.level);
x += advance;
}
}
}
// Apply BiDi visual reordering if needed
if has_bidi && !all_glyphs.is_empty() {
all_glyphs = bidi::reorder_line_glyphs(all_glyphs, &bidi_levels);
bidi::reposition_after_reorder(&mut all_glyphs, 0.0);
}
return all_glyphs;
}
// Original single-font path (no comma in font_family)
// Try shaping for custom fonts
if let Some(font_data) =
font_context.font_data(&style.font_family, style.font_weight, italic)
{
if has_bidi {
// BiDi path: analyze runs, shape each with correct direction
let bidi_runs = bidi::analyze_bidi(&line_text, direction);
let units_per_em =
font_context.units_per_em(&style.font_family, style.font_weight, italic);
let scale = style.font_size / units_per_em as f64;
let mut all_glyphs = Vec::new();
let mut bidi_levels = Vec::new();
let mut x = 0.0_f64;
for run in &bidi_runs {
let run_chars: Vec<char> = line.chars[run.char_start..run.char_end].to_vec();
let run_text: String = run_chars.iter().collect();
if let Some(shaped) =
shaping::shape_text_with_direction(&run_text, font_data, run.is_rtl)
{
for sg in &shaped {
let cluster = sg.cluster as usize;
let char_value = run_chars.get(cluster).copied().unwrap_or(' ');
let cluster_text = if shaped.len() < run_chars.len() {
let cluster_end =
self.find_cluster_end(&shaped, sg, run_chars.len());
if cluster_end > cluster + 1 {
Some(run_chars[cluster..cluster_end].iter().collect::<String>())
} else {
None
}
} else {
None
};
let glyph_x = x + sg.x_offset as f64 * scale;
let glyph_y = sg.y_offset as f64 * scale;
let advance = sg.x_advance as f64 * scale + style.letter_spacing;
all_glyphs.push(PositionedGlyph {
glyph_id: sg.glyph_id,
x_offset: glyph_x,
y_offset: glyph_y,
x_advance: advance,
font_size: style.font_size,
font_family: Arc::from(style.font_family.as_str()),
font_weight: style.font_weight,
font_style: style.font_style,
char_value,
color: Some(style.color),
href: href.map(|s| s.to_string()),
text_decoration: style.text_decoration,
letter_spacing: style.letter_spacing,
cluster_text,
});
bidi_levels.push(run.level);
x += advance;
}
}
}
// Reorder glyphs visually and reposition
let mut glyphs = bidi::reorder_line_glyphs(all_glyphs, &bidi_levels);
bidi::reposition_after_reorder(&mut glyphs, 0.0);
return glyphs;
}
// Pure LTR path: shape normally
if let Some(shaped) = shaping::shape_text(&line_text, font_data) {
let units_per_em =
font_context.units_per_em(&style.font_family, style.font_weight, italic);
let scale = style.font_size / units_per_em as f64;
return self.shaped_glyphs_to_positioned(
&shaped,
&line.chars,
&line.char_positions,
scale,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
Some(style.color),
href,
style.text_decoration,
style.letter_spacing,
);
}
}
// Fallback: standard fonts or shaping failure
let mut glyphs: Vec<PositionedGlyph> = line
.chars
.iter()
.enumerate()
.map(|(j, ch)| {
let glyph_x = line.char_positions.get(j).copied().unwrap_or(0.0);
let char_width = font_context.char_width(
*ch,
&style.font_family,
style.font_weight,
italic,
style.font_size,
);
PositionedGlyph {
glyph_id: *ch as u16,
x_offset: glyph_x,
y_offset: 0.0,
x_advance: char_width,
font_size: style.font_size,
font_family: Arc::from(style.font_family.as_str()),
font_weight: style.font_weight,
font_style: style.font_style,
char_value: *ch,
color: Some(style.color),
href: href.map(|s| s.to_string()),
text_decoration: style.text_decoration,
letter_spacing: style.letter_spacing,
cluster_text: None,
}
})
.collect();
// For standard fonts with BiDi text, still reorder visually
if has_bidi && !glyphs.is_empty() {
let bidi_runs = bidi::analyze_bidi(&line_text, direction);
let mut levels = Vec::with_capacity(glyphs.len());
let mut char_idx = 0;
for run in &bidi_runs {
for _ in run.char_start..run.char_end {
if char_idx < glyphs.len() {
levels.push(run.level);
char_idx += 1;
}
}
}
// Pad if needed
while levels.len() < glyphs.len() {
levels.push(unicode_bidi::Level::ltr());
}
glyphs = bidi::reorder_line_glyphs(glyphs, &levels);
bidi::reposition_after_reorder(&mut glyphs, 0.0);
}
glyphs
}
/// Build PositionedGlyphs for a multi-style RunBrokenLine.
/// Shapes contiguous runs of the same custom font, with BiDi support.
/// When a StyledChar has a comma-separated font_family, resolves each
/// character to a single font before grouping for shaping.
fn build_positioned_glyphs_runs(
&self,
run_line: &RunBrokenLine,
font_context: &FontContext,
direction: Direction,
) -> Vec<PositionedGlyph> {
let chars = &run_line.chars;
if chars.is_empty() {
return vec![];
}
// Pre-resolve per-char font families — the same rule as
// segment_by_font (the single-style path) and char_width
// (measurement): the declared family when it covers the char,
// per-char resolution otherwise. This path used to skip per-char
// resolution entirely for comma-less families, so a non-WinAnsi
// char in a TextRun rendered "?" on the base-14 path while the
// identical char in single-style Text reached builtin Noto Sans —
// measurement and rendering disagreeing about the char's font.
let resolved_families: Vec<String> = chars
.iter()
.map(|sc| {
let italic = matches!(sc.font_style, FontStyle::Italic | FontStyle::Oblique);
if !sc.font_family.contains(',') {
let primary =
font_context
.registry()
.resolve(&sc.font_family, sc.font_weight, italic);
if sc.ch.is_whitespace()
|| sc.ch == PAGE_NUMBER_SENTINEL
|| sc.ch == TOTAL_PAGES_SENTINEL
|| primary.has_char(sc.ch)
{
return sc.font_family.clone();
}
}
let (_, family) = font_context.registry().resolve_for_char(
&sc.font_family,
sc.ch,
sc.font_weight,
italic,
);
family
})
.collect();
let line_text: String = chars.iter().map(|c| c.ch).collect();
let has_bidi = !bidi::is_pure_ltr(&line_text, direction);
let bidi_runs = if has_bidi {
Some(bidi::analyze_bidi(&line_text, direction))
} else {
None
};
let mut glyphs = Vec::new();
let mut bidi_levels = Vec::new();
let mut i = 0;
while i < chars.len() {
let sc = &chars[i];
let italic = matches!(sc.font_style, FontStyle::Italic | FontStyle::Oblique);
let resolved_family = &resolved_families[i];
// Determine if this char is in an RTL BiDi run
let is_rtl = bidi_runs.as_ref().is_some_and(|runs| {
runs.iter()
.any(|r| i >= r.char_start && i < r.char_end && r.is_rtl)
});
// Check for custom font with shaping (using resolved single family)
if let Some(font_data) = font_context.font_data(resolved_family, sc.font_weight, italic)
{
// Find contiguous run with same resolved font AND same BiDi direction
let run_start = i;
let mut run_end = i + 1;
while run_end < chars.len() {
let next = &chars[run_end];
let next_italic =
matches!(next.font_style, FontStyle::Italic | FontStyle::Oblique);
let next_is_rtl = bidi_runs.as_ref().is_some_and(|runs| {
runs.iter()
.any(|r| run_end >= r.char_start && run_end < r.char_end && r.is_rtl)
});
// Group by resolved family, not original comma chain
if resolved_families[run_end] == *resolved_family
&& next.font_weight == sc.font_weight
&& next_italic == italic
&& (next.font_size - sc.font_size).abs() < 0.001
&& next_is_rtl == is_rtl
{
run_end += 1;
} else {
break;
}
}
let run_text: String = chars[run_start..run_end].iter().map(|c| c.ch).collect();
if let Some(shaped) =
shaping::shape_text_with_direction(&run_text, font_data, is_rtl)
{
let units_per_em =
font_context.units_per_em(resolved_family, sc.font_weight, italic);
let scale = sc.font_size / units_per_em as f64;
// Build char positions for this run segment
let run_chars: Vec<char> =
chars[run_start..run_end].iter().map(|c| c.ch).collect();
let run_positions: Vec<f64> = (run_start..run_end)
.map(|j| run_line.char_positions.get(j).copied().unwrap_or(0.0))
.collect();
// Build glyphs with resolved single family on each glyph
let mut run_glyphs = self.shaped_glyphs_to_positioned_runs(
&shaped,
&chars[run_start..run_end],
&run_chars,
&run_positions,
scale,
);
// Override font_family to the resolved single family
let resolved_family_arc: Arc<str> = Arc::from(resolved_family.as_str());
for g in &mut run_glyphs {
g.font_family = resolved_family_arc.clone();
}
// Track BiDi levels for each glyph
let run_level = if is_rtl {
unicode_bidi::Level::rtl()
} else {
unicode_bidi::Level::ltr()
};
for _ in &run_glyphs {
bidi_levels.push(run_level);
}
glyphs.extend(run_glyphs);
i = run_end;
continue;
}
}
// Fallback: unshaped glyph (using resolved family)
let glyph_x = run_line.char_positions.get(i).copied().unwrap_or(0.0);
let char_width = font_context.char_width(
sc.ch,
resolved_family,
sc.font_weight,
italic,
sc.font_size,
);
glyphs.push(PositionedGlyph {
glyph_id: sc.ch as u16,
x_offset: glyph_x,
y_offset: 0.0,
x_advance: char_width,
font_size: sc.font_size,
font_family: Arc::from(resolved_family.as_str()),
font_weight: sc.font_weight,
font_style: sc.font_style,
char_value: sc.ch,
color: Some(sc.color),
href: sc.href.clone(),
text_decoration: sc.text_decoration,
letter_spacing: sc.letter_spacing,
cluster_text: None,
});
bidi_levels.push(if is_rtl {
unicode_bidi::Level::rtl()
} else {
unicode_bidi::Level::ltr()
});
i += 1;
}
// Apply BiDi visual reordering if needed
if has_bidi && !glyphs.is_empty() {
glyphs = bidi::reorder_line_glyphs(glyphs, &bidi_levels);
bidi::reposition_after_reorder(&mut glyphs, 0.0);
}
glyphs
}
/// Convert shaped glyphs to PositionedGlyphs for single-style text.
#[allow(clippy::too_many_arguments)]
fn shaped_glyphs_to_positioned(
&self,
shaped: &[shaping::ShapedGlyph],
chars: &[char],
_char_positions: &[f64],
scale: f64,
font_size: f64,
font_family: &str,
font_weight: u32,
font_style: FontStyle,
color: Option<Color>,
href: Option<&str>,
text_decoration: TextDecoration,
letter_spacing: f64,
) -> Vec<PositionedGlyph> {
let mut result = Vec::with_capacity(shaped.len());
let mut x = 0.0_f64;
for sg in shaped {
let cluster = sg.cluster as usize;
let char_value = chars.get(cluster).copied().unwrap_or(' ');
// Determine cluster text for ligatures
let cluster_text = if shaped.len() < chars.len() {
// There are fewer glyphs than chars: likely ligatures.
// Find end of this cluster.
let cluster_end = self.find_cluster_end(shaped, sg, chars.len());
if cluster_end > cluster + 1 {
Some(chars[cluster..cluster_end].iter().collect::<String>())
} else {
None
}
} else {
None
};
// Use shaped position
let glyph_x = x + sg.x_offset as f64 * scale;
let glyph_y = sg.y_offset as f64 * scale;
let advance = sg.x_advance as f64 * scale + letter_spacing;
result.push(PositionedGlyph {
glyph_id: sg.glyph_id,
x_offset: glyph_x,
y_offset: glyph_y,
x_advance: advance,
font_size,
font_family: Arc::from(font_family),
font_weight,
font_style,
char_value,
color,
href: href.map(|s| s.to_string()),
text_decoration,
letter_spacing,
cluster_text,
});
x += advance;
}
result
}
/// Convert shaped glyphs to PositionedGlyphs for multi-style runs.
fn shaped_glyphs_to_positioned_runs(
&self,
shaped: &[shaping::ShapedGlyph],
styled_chars: &[StyledChar],
chars: &[char],
char_positions: &[f64],
scale: f64,
) -> Vec<PositionedGlyph> {
let mut result = Vec::with_capacity(shaped.len());
// Use the first char position as the base offset for this run
let base_x = char_positions.first().copied().unwrap_or(0.0);
let mut x = 0.0_f64;
for sg in shaped {
let cluster = sg.cluster as usize;
let sc = styled_chars.get(cluster).unwrap_or(&styled_chars[0]);
let char_value = chars.get(cluster).copied().unwrap_or(' ');
let cluster_text = if shaped.len() < chars.len() {
let cluster_end = self.find_cluster_end(shaped, sg, chars.len());
if cluster_end > cluster + 1 {
Some(chars[cluster..cluster_end].iter().collect::<String>())
} else {
None
}
} else {
None
};
let glyph_x = base_x + x + sg.x_offset as f64 * scale;
let glyph_y = sg.y_offset as f64 * scale;
let advance = sg.x_advance as f64 * scale + sc.letter_spacing;
result.push(PositionedGlyph {
glyph_id: sg.glyph_id,
x_offset: glyph_x,
y_offset: glyph_y,
x_advance: advance,
font_size: sc.font_size,
font_family: Arc::from(sc.font_family.as_str()),
font_weight: sc.font_weight,
font_style: sc.font_style,
char_value,
color: Some(sc.color),
href: sc.href.clone(),
text_decoration: sc.text_decoration,
letter_spacing: sc.letter_spacing,
cluster_text,
});
x += advance;
}
result
}
/// Find the end index of a cluster in shaped glyphs.
fn find_cluster_end(
&self,
shaped: &[shaping::ShapedGlyph],
current: &shaping::ShapedGlyph,
num_chars: usize,
) -> usize {
// Find the next glyph's cluster value
for sg in shaped {
if sg.cluster > current.cluster {
return sg.cluster as usize;
}
}
// Last glyph: cluster extends to end of text
num_chars
}
/// The ONE image sizing ladder — used by both `layout_image` and
/// `measure_node_height`, so measurement and layout agree by
/// construction (the measure/layout agreement family: an earlier
/// version measured small images at container width while layout
/// drew them at intrinsic size, reserving container-sized phantom
/// space — template-compat 01/05/07). Chrome semantics: style width
/// (percents already resolved) > explicit prop > intrinsic;
/// max/min-width clamp; height follows the real aspect ratio unless
/// given.
fn image_display_size(
&self,
src: &str,
style: &ResolvedStyle,
explicit_width: Option<f64>,
explicit_height: Option<f64>,
available_width: f64,
) -> (f64, f64) {
let dims = if src.is_empty() {
None
} else {
self.get_image_dimensions(src)
};
let aspect = dims
.map(|(w, h)| {
if w > 0 {
f64::from(h) / f64::from(w)
} else {
0.75
}
})
.unwrap_or(0.75);
let style_w = match style.width {
SizeConstraint::Fixed(w) => Some(w),
SizeConstraint::Auto => None,
};
let style_h = match style.height {
SizeConstraint::Fixed(h) => Some(h),
SizeConstraint::Auto => None,
};
let clamp = |w: f64| w.min(style.max_width).max(style.min_width);
let width_source = style_w.or(explicit_width);
let height_source = style_h.or(explicit_height);
match (width_source, height_source) {
(Some(w), Some(h)) => (clamp(w), h),
(Some(w), None) => {
let w = clamp(w);
(w, w * aspect)
}
(None, Some(h)) => (clamp(h / aspect), h),
(None, None) => {
// Intrinsic size, shrunk to fit the container. An
// unloadable image keeps the container-width placeholder.
let w = clamp(
dims.map(|(w, _)| f64::from(w))
.unwrap_or(available_width)
.min(available_width),
);
(w, w * aspect)
}
}
}
#[allow(clippy::too_many_arguments)]
fn layout_image(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
explicit_width: Option<f64>,
explicit_height: Option<f64>,
) {
let margin = &style.margin.to_edges();
// Try to load the image from the node's src field
let src = match &node.kind {
NodeKind::Image { src, .. } => src.as_str(),
_ => "",
};
let loaded = if !src.is_empty() {
crate::image_loader::load_image(src).ok()
} else {
None
};
let (img_width, img_height) = self.image_display_size(
src,
style,
explicit_width,
explicit_height,
available_width - margin.horizontal(),
);
let total_height = img_height + margin.vertical();
if total_height > cursor.remaining_height() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
cursor.y += margin.top;
let draw = if let Some(image_data) = loaded {
DrawCommand::Image { image_data }
} else {
DrawCommand::ImagePlaceholder
};
cursor.elements.push(LayoutElement {
x: x + margin.left,
y: cursor.content_y + cursor.y,
width: img_width,
height: img_height,
draw,
children: vec![],
node_type: Some(node_kind_name(&node.kind).to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: node.bookmark.clone(),
alt: node.alt.clone(),
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += img_height + margin.bottom;
}
/// Layout an SVG element as a fixed-size box.
#[allow(clippy::too_many_arguments)]
fn layout_svg(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
_available_width: f64,
svg_width: f64,
svg_height: f64,
view_box: Option<&str>,
content: &str,
) {
let margin = &style.margin.to_edges();
let total_height = svg_height + margin.vertical();
if total_height > cursor.remaining_height() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
cursor.y += margin.top;
let vb = view_box
.and_then(crate::svg::parse_view_box)
.unwrap_or(crate::svg::ViewBox {
min_x: 0.0,
min_y: 0.0,
width: svg_width,
height: svg_height,
});
let commands = crate::svg::parse_svg(content, vb, svg_width, svg_height);
cursor.elements.push(LayoutElement {
x: x + margin.left,
y: cursor.content_y + cursor.y,
width: svg_width,
height: svg_height,
draw: DrawCommand::Svg {
commands,
width: svg_width,
height: svg_height,
viewbox_min_x: vb.min_x,
viewbox_min_y: vb.min_y,
viewbox_width: vb.width,
viewbox_height: vb.height,
clip: false,
},
children: vec![],
node_type: Some("Svg".to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: node.bookmark.clone(),
alt: node.alt.clone(),
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += svg_height + margin.bottom;
}
/// Convert CanvasOps to SvgCommands, reusing the existing SVG rendering pipeline.
fn canvas_ops_to_svg_commands(operations: &[CanvasOp]) -> Vec<crate::svg::SvgCommand> {
use crate::svg::SvgCommand;
let mut commands = Vec::new();
let mut cur_x = 0.0_f64;
let mut cur_y = 0.0_f64;
for op in operations {
match op {
CanvasOp::MoveTo { x, y } => {
commands.push(SvgCommand::MoveTo(*x, *y));
cur_x = *x;
cur_y = *y;
}
CanvasOp::LineTo { x, y } => {
commands.push(SvgCommand::LineTo(*x, *y));
cur_x = *x;
cur_y = *y;
}
CanvasOp::BezierCurveTo {
cp1x,
cp1y,
cp2x,
cp2y,
x,
y,
} => {
commands.push(SvgCommand::CurveTo(*cp1x, *cp1y, *cp2x, *cp2y, *x, *y));
cur_x = *x;
cur_y = *y;
}
CanvasOp::QuadraticCurveTo { cpx, cpy, x, y } => {
// Convert quadratic to cubic bezier
let cp1x = cur_x + 2.0 / 3.0 * (*cpx - cur_x);
let cp1y = cur_y + 2.0 / 3.0 * (*cpy - cur_y);
let cp2x = *x + 2.0 / 3.0 * (*cpx - *x);
let cp2y = *y + 2.0 / 3.0 * (*cpy - *y);
commands.push(SvgCommand::CurveTo(cp1x, cp1y, cp2x, cp2y, *x, *y));
cur_x = *x;
cur_y = *y;
}
CanvasOp::ClosePath => {
commands.push(SvgCommand::ClosePath);
}
CanvasOp::Rect {
x,
y,
width,
height,
} => {
commands.push(SvgCommand::MoveTo(*x, *y));
commands.push(SvgCommand::LineTo(*x + *width, *y));
commands.push(SvgCommand::LineTo(*x + *width, *y + *height));
commands.push(SvgCommand::LineTo(*x, *y + *height));
commands.push(SvgCommand::ClosePath);
cur_x = *x;
cur_y = *y;
}
CanvasOp::Circle { cx, cy, r } => {
commands.extend(crate::svg::ellipse_commands(*cx, *cy, *r, *r));
}
CanvasOp::Ellipse { cx, cy, rx, ry } => {
commands.extend(crate::svg::ellipse_commands(*cx, *cy, *rx, *ry));
}
CanvasOp::Arc {
cx,
cy,
r,
start_angle,
end_angle,
counterclockwise,
} => {
// Approximate arc with line segments matching HTML Canvas arc() semantics.
// Canvas coords are Y-down (like HTML Canvas), and the PDF Y-flip
// preserves visual positions, so standard trig (cy + r*sin) is correct.
let steps = 32;
let mut sweep = end_angle - start_angle;
if !counterclockwise && sweep < 0.0 {
sweep += 2.0 * std::f64::consts::PI;
}
if *counterclockwise && sweep > 0.0 {
sweep -= 2.0 * std::f64::consts::PI;
}
for i in 0..=steps {
let t = *start_angle + sweep * (i as f64 / steps as f64);
let px = cx + r * t.cos();
let py = cy + r * t.sin();
if i == 0 {
commands.push(SvgCommand::MoveTo(px, py));
} else {
commands.push(SvgCommand::LineTo(px, py));
}
}
}
CanvasOp::Stroke => commands.push(SvgCommand::Stroke),
CanvasOp::Fill => commands.push(SvgCommand::Fill),
CanvasOp::FillAndStroke => commands.push(SvgCommand::FillAndStroke),
CanvasOp::SetFillColor { r, g, b } => {
// Canvas API uses 0-255, PDF/SVG pipeline uses 0-1
commands.push(SvgCommand::SetFill(r / 255.0, g / 255.0, b / 255.0));
}
CanvasOp::SetStrokeColor { r, g, b } => {
commands.push(SvgCommand::SetStroke(r / 255.0, g / 255.0, b / 255.0));
}
CanvasOp::SetLineWidth { width } => {
commands.push(SvgCommand::SetStrokeWidth(*width));
}
CanvasOp::SetLineCap { cap } => {
commands.push(SvgCommand::SetLineCap(*cap));
}
CanvasOp::SetLineJoin { join } => {
commands.push(SvgCommand::SetLineJoin(*join));
}
CanvasOp::Save => commands.push(SvgCommand::SaveState),
CanvasOp::Restore => commands.push(SvgCommand::RestoreState),
}
}
commands
}
/// Layout a canvas element as a fixed-size box with vector graphics.
#[allow(clippy::too_many_arguments)]
fn layout_canvas(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
_available_width: f64,
canvas_width: f64,
canvas_height: f64,
operations: &[CanvasOp],
) {
let margin = style.margin.to_edges();
let total_height = canvas_height + margin.top + margin.bottom;
// Page break check
if cursor.remaining_height() < total_height && cursor.y > 0.0 {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
cursor.y += margin.top;
let svg_commands = Self::canvas_ops_to_svg_commands(operations);
cursor.elements.push(LayoutElement {
x: x + margin.left,
y: cursor.content_y + cursor.y,
width: canvas_width,
height: canvas_height,
draw: DrawCommand::Svg {
commands: svg_commands,
width: canvas_width,
height: canvas_height,
// Canvas constructs commands in display coordinates, so the
// viewBox matches the display box 1:1 — scale comes out to 1.
viewbox_min_x: 0.0,
viewbox_min_y: 0.0,
viewbox_width: canvas_width,
viewbox_height: canvas_height,
clip: true,
},
children: vec![],
node_type: Some("Canvas".to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: node.bookmark.clone(),
alt: node.alt.clone(),
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += canvas_height + margin.bottom;
}
/// Layout a 1D barcode as a row of vector rectangles.
#[allow(clippy::too_many_arguments)]
/// Layout a chart as a single unbreakable block of drawing primitives.
#[allow(clippy::too_many_arguments)]
fn layout_chart(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
chart_width: f64,
chart_height: f64,
primitives: Vec<crate::chart::ChartPrimitive>,
node_type_name: &str,
) {
let margin = &style.margin.to_edges();
let total_height = chart_height + margin.vertical();
if total_height > cursor.remaining_height() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
cursor.y += margin.top;
let draw = DrawCommand::Chart { primitives };
cursor.elements.push(LayoutElement {
x: x + margin.left,
y: cursor.content_y + cursor.y,
width: chart_width,
height: chart_height,
draw,
children: vec![],
node_type: Some(node_type_name.to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: node.bookmark.clone(),
alt: node.alt.clone(),
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += chart_height + margin.bottom;
}
/// Layout a form field as a fixed-size leaf node.
#[allow(clippy::too_many_arguments)]
fn layout_form_field(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
field_width: f64,
field_height: f64,
draw: DrawCommand,
node_type_name: &str,
) {
let margin = &style.margin.to_edges();
let total_height = field_height + margin.vertical();
if total_height > cursor.remaining_height() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
cursor.y += margin.top;
cursor.elements.push(LayoutElement {
x: x + margin.left,
y: cursor.content_y + cursor.y,
width: field_width,
height: field_height,
draw,
children: vec![],
node_type: Some(node_type_name.to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: node.bookmark.clone(),
alt: node.alt.clone(),
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += field_height + margin.bottom;
}
#[allow(clippy::too_many_arguments)]
fn layout_barcode(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
data: &str,
format: crate::barcode::BarcodeFormat,
explicit_width: Option<f64>,
bar_height: f64,
) {
let margin = &style.margin.to_edges();
let display_width = explicit_width.unwrap_or(available_width - margin.horizontal());
let total_height = bar_height + margin.vertical();
if total_height > cursor.remaining_height() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
cursor.y += margin.top;
let draw = match crate::barcode::generate_barcode(data, format) {
Ok(barcode_data) => {
let bar_width = if barcode_data.bars.is_empty() {
0.0
} else {
display_width / barcode_data.bars.len() as f64
};
DrawCommand::Barcode {
bars: barcode_data.bars,
bar_width,
height: bar_height,
color: style.color,
}
}
Err(_) => DrawCommand::None,
};
cursor.elements.push(LayoutElement {
x: x + margin.left,
y: cursor.content_y + cursor.y,
width: display_width,
height: bar_height,
draw,
children: vec![],
node_type: Some("Barcode".to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: node.bookmark.clone(),
alt: node.alt.clone(),
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += bar_height + margin.bottom;
}
/// Layout a QR code as a square block of vector rectangles.
#[allow(clippy::too_many_arguments)]
fn layout_qrcode(
&self,
node: &Node,
style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
data: &str,
explicit_size: Option<f64>,
) {
let margin = &style.margin.to_edges();
let display_size = explicit_size.unwrap_or(available_width - margin.horizontal());
let total_height = display_size + margin.vertical();
if total_height > cursor.remaining_height() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
cursor.y += margin.top;
let draw = match crate::qrcode::generate_qr(data) {
Ok(matrix) => {
let module_size = display_size / matrix.size as f64;
DrawCommand::QrCode {
modules: matrix.modules,
module_size,
color: style.color,
}
}
Err(_) => DrawCommand::None,
};
cursor.elements.push(LayoutElement {
x: x + margin.left,
y: cursor.content_y + cursor.y,
width: display_size,
height: display_size,
draw,
children: vec![],
node_type: Some("QrCode".to_string()),
resolved_style: Some(style.clone()),
source_location: node.source_location.clone(),
href: node.href.clone(),
bookmark: node.bookmark.clone(),
alt: node.alt.clone(),
is_header_row: false,
col_span: 1,
overflow: style.overflow,
opacity: style.opacity,
});
cursor.y += display_size + margin.bottom;
}
// ── Measurement helpers ─────────────────────────────────────
fn measure_node_height(
&self,
node: &Node,
available_width: f64,
style: &ResolvedStyle,
font_context: &FontContext,
) -> f64 {
match &node.kind {
// Headings lay out exactly like Text (see the layout arm), so they
// must measure the same way — otherwise a heading falls through to
// the container `_` arm, measures ~0 (it has no children), and a
// parent's auto-height omits it.
NodeKind::Text { content, runs, .. } | NodeKind::Heading { content, runs, .. } => {
// Mirror layout_text: a fixed width drives line-breaking, so height
// measurement must use the same width or it will under-count lines.
let measure_width = match style.width {
SizeConstraint::Fixed(w) => (w - style.margin.horizontal()).max(0.0),
SizeConstraint::Auto => available_width - style.margin.horizontal(),
};
// Measurement must reach the same line count layout will:
// same text transform, same breaker (greedy vs Knuth-Plass —
// the two can disagree at boundary widths, where optimal
// accepts a slightly-overfull line greedy would wrap).
// Divergence here is exactly what FORME_MEASURE_CHECK exists
// to catch.
if !runs.is_empty() {
let mut styled_chars: Vec<StyledChar> = Vec::new();
for run in runs {
let run_style = run.style.resolve(Some(style), measure_width);
let transform = run_style.text_transform;
let run_content = substitute_page_placeholders(&run.content);
let mut prev_is_whitespace = true;
for ch in run_content.chars() {
let transformed_ch =
apply_char_transform(ch, transform, prev_is_whitespace);
prev_is_whitespace = ch.is_whitespace();
styled_chars.push(StyledChar {
ch: transformed_ch,
font_family: run_style.font_family.clone(),
font_size: run_style.font_size,
font_weight: run_style.font_weight,
font_style: run_style.font_style,
color: run_style.color,
href: None,
text_decoration: run_style.text_decoration,
letter_spacing: run_style.letter_spacing,
});
}
}
let justify = matches!(style.text_align, TextAlign::Justify);
let broken_lines = match style.line_breaking {
LineBreaking::Optimal => self.text_layout.break_runs_into_lines_optimal(
font_context,
&styled_chars,
measure_width,
style.hyphens,
style.lang.as_deref(),
justify,
),
LineBreaking::Greedy => self.text_layout.break_runs_into_lines(
font_context,
&styled_chars,
measure_width,
style.hyphens,
style.lang.as_deref(),
),
};
let line_height = style.font_size * style.line_height;
(broken_lines.len() as f64) * line_height + style.padding.vertical()
} else {
let content = substitute_page_placeholders(content);
let transformed = apply_text_transform(&content, style.text_transform);
let justify = matches!(style.text_align, TextAlign::Justify);
let lines = match style.line_breaking {
LineBreaking::Optimal => self.text_layout.break_into_lines_optimal(
font_context,
&transformed,
measure_width,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
style.letter_spacing,
style.hyphens,
style.lang.as_deref(),
justify,
),
LineBreaking::Greedy => self.text_layout.break_into_lines(
font_context,
&transformed,
measure_width,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
style.letter_spacing,
style.hyphens,
style.lang.as_deref(),
),
};
let line_height = style.font_size * style.line_height;
(lines.len() as f64) * line_height + style.padding.vertical()
}
}
NodeKind::Image {
src,
width: explicit_w,
height: explicit_h,
} => {
// Same ladder layout_image uses — agreement by construction.
let (_, h) = self.image_display_size(
src,
style,
*explicit_w,
*explicit_h,
available_width - style.margin.horizontal(),
);
h + style.padding.vertical()
}
NodeKind::Svg { height, .. } => *height + style.margin.vertical(),
NodeKind::Barcode { height, .. } => *height + style.margin.vertical(),
NodeKind::QrCode { size, .. } => {
let display_size = size.unwrap_or(available_width - style.margin.horizontal());
display_size + style.margin.vertical()
}
NodeKind::Canvas { height, .. } => *height + style.margin.vertical(),
NodeKind::BarChart { height, .. }
| NodeKind::LineChart { height, .. }
| NodeKind::PieChart { height, .. }
| NodeKind::AreaChart { height, .. }
| NodeKind::DotPlot { height, .. } => *height + style.margin.vertical(),
NodeKind::TextField { height, .. }
| NodeKind::Checkbox { height, .. }
| NodeKind::Dropdown { height, .. }
| NodeKind::RadioButton { height, .. } => *height + style.margin.vertical(),
NodeKind::Watermark { .. } => 0.0, // Watermarks take zero layout height
NodeKind::Table { columns } => {
// Use the same column-resolution + per-row max-of-cells helpers
// that `layout_table` uses, so measurement matches what the
// engine actually renders. Without this arm, Table fell into the
// generic `_` branch which column-summed each row's children,
// and (since TableRow also lacked an arm) over-counted row
// heights by a factor of (cell count).
if let SizeConstraint::Fixed(h) = style.height {
return h;
}
let outer_width = match style.width {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => available_width - style.margin.horizontal(),
};
let inner_width =
outer_width - style.padding.horizontal() - style.border_width.horizontal();
let col_widths = self.resolve_column_widths(
columns,
inner_width,
&node.children,
style,
font_context,
);
let row_gap = style.row_gap;
let offsets = Self::table_column_offsets(&node.children);
let mut total = 0.0;
for (i, row) in node.children.iter().enumerate() {
if i > 0 {
total += row_gap;
}
total += self.measure_table_row_height(
row,
&col_widths,
&offsets[i],
style,
font_context,
);
}
total + style.padding.vertical() + style.border_width.vertical()
}
NodeKind::TableRow { .. } => {
// Standalone-row fallback (rare): a TableRow measured outside
// a Table context has no ColumnDef source, so split
// available_width evenly across cells — matches what
// resolve_column_widths does when its defs vec is empty.
let n = node.children.len().max(1);
let usable = (available_width - style.margin.horizontal()).max(0.0);
let col_w = usable / n as f64;
let col_widths = vec![col_w; n];
let offsets = Self::table_column_offsets(std::slice::from_ref(node));
self.measure_table_row_height(node, &col_widths, &offsets[0], style, font_context)
}
_ => {
// If a fixed height is specified, use it directly
if let SizeConstraint::Fixed(h) = style.height {
return h;
}
// Match layout_view: when width is Auto, margin reduces the
// outer width; min/max clamp identically or measured heights
// disagree with laid-out widths.
let outer_width = match style.width {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => available_width - style.margin.horizontal(),
}
.min(style.max_width)
.max(style.min_width);
let inner_width =
outer_width - style.padding.horizontal() - style.border_width.horizontal();
let children_height =
self.measure_children_height(&node.children, inner_width, style, font_context);
(children_height + style.padding.vertical() + style.border_width.vertical())
.max(style.min_height)
}
}
}
fn measure_children_height(
&self,
children: &[Node],
available_width: f64,
parent_style: &ResolvedStyle,
font_context: &FontContext,
) -> f64 {
// Absolutely-positioned children are out of flow: layout_children
// partitions them off and they never advance the cursor, so counting
// them here reserves phantom space equal to their height in every
// auto-height ancestor. Caught by FORME_MEASURE_CHECK. Clone-filter
// only in the rare case one is present.
if children
.iter()
.any(|c| matches!(c.style.position, Some(Position::Absolute)))
{
let flow: Vec<Node> = children
.iter()
.filter(|c| !matches!(c.style.position, Some(Position::Absolute)))
.cloned()
.collect();
return self.measure_children_height(
&flow,
available_width,
parent_style,
font_context,
);
}
// Grid layout: measure using actual grid placement instead of stacking
if matches!(parent_style.display, Display::Grid) {
if let Some(template_cols) = &parent_style.grid_template_columns {
let num_columns = template_cols.len();
if num_columns > 0 && !children.is_empty() {
let col_gap = parent_style.column_gap;
let row_gap = parent_style.row_gap;
let content_sizes: Vec<f64> = template_cols
.iter()
.map(|track| {
if matches!(track, GridTrackSize::Auto) {
available_width / num_columns as f64
} else {
0.0
}
})
.collect();
let col_widths = grid::resolve_tracks(
template_cols,
available_width,
col_gap,
&content_sizes,
);
let placements: Vec<Option<&GridPlacement>> = children
.iter()
.map(|child| child.style.grid_placement.as_ref())
.collect();
let item_placements = grid::place_items(&placements, num_columns);
let num_rows = grid::compute_num_rows(&item_placements);
if num_rows == 0 {
return 0.0;
}
let mut row_heights = vec![0.0_f64; num_rows];
for placement in &item_placements {
let cell_width = grid::span_width(
placement.col_start,
placement.col_end,
&col_widths,
col_gap,
);
let child = &children[placement.child_index];
let child_style = child.style.resolve(Some(parent_style), cell_width);
let h =
self.measure_node_height(child, cell_width, &child_style, font_context);
let span = placement.row_end - placement.row_start;
let per_row = h / span as f64;
for rh in row_heights
.iter_mut()
.take(placement.row_end.min(num_rows))
.skip(placement.row_start)
{
if per_row > *rh {
*rh = per_row;
}
}
}
let total_row_gap = row_gap * (num_rows as f64 - 1.0).max(0.0);
return row_heights.iter().sum::<f64>() + total_row_gap;
}
}
}
let direction = parent_style.flex_direction;
let row_gap = parent_style.row_gap;
let column_gap = parent_style.column_gap;
match direction {
FlexDirection::Row | FlexDirection::RowReverse => {
// Measure base widths for all children
// flex_basis takes precedence over width (matching layout_flex_row)
let styles: Vec<ResolvedStyle> = children
.iter()
.map(|child| child.style.resolve(Some(parent_style), available_width))
.collect();
let base_widths: Vec<f64> = children
.iter()
.zip(&styles)
.map(|(child, style)| match style.flex_basis {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => match style.width {
SizeConstraint::Fixed(w) => w,
SizeConstraint::Auto => self
.measure_intrinsic_width(child, style, font_context)
.min(available_width),
},
})
.collect();
let lines = match parent_style.flex_wrap {
FlexWrap::NoWrap => {
vec![flex::WrapLine {
start: 0,
end: children.len(),
}]
}
FlexWrap::Wrap | FlexWrap::WrapReverse => {
flex::partition_into_lines(&base_widths, column_gap, available_width)
}
};
// Apply flex grow/shrink to get final widths (matching layout_flex_row)
let mut final_widths = base_widths.clone();
for line in &lines {
let line_count = line.end - line.start;
let line_gap = column_gap * (line_count as f64 - 1.0).max(0.0);
let distributable = available_width - line_gap;
let total_base: f64 = base_widths[line.start..line.end].iter().sum();
let remaining = distributable - total_base;
if remaining > 0.0 {
let total_grow: f64 = styles[line.start..line.end]
.iter()
.map(|s| s.flex_grow)
.sum();
if total_grow > 0.0 {
for (j, s) in styles[line.start..line.end].iter().enumerate() {
final_widths[line.start + j] = base_widths[line.start + j]
+ remaining * (s.flex_grow / total_grow);
}
}
} else if remaining < 0.0 {
let total_shrink: f64 = styles[line.start..line.end]
.iter()
.enumerate()
.map(|(j, s)| s.flex_shrink * base_widths[line.start + j])
.sum();
if total_shrink > 0.0 {
for (j, s) in styles[line.start..line.end].iter().enumerate() {
let factor =
(s.flex_shrink * base_widths[line.start + j]) / total_shrink;
let w = base_widths[line.start + j] + remaining * factor;
final_widths[line.start + j] = w.max(s.min_width);
}
}
}
}
let mut total = 0.0;
for (i, line) in lines.iter().enumerate() {
let line_height: f64 = children[line.start..line.end]
.iter()
.enumerate()
.map(|(j, child)| {
let fw = final_widths[line.start + j];
// Resolve against the CONTAINER's width, not the
// child's own final width: a child's percent width
// (and percent margins/padding — CSS resolves them
// against the containing block) must not resolve
// against itself. Resolving `width: 27%` against
// fw made it 27% of 27%, so text measured at a
// quarter width — one word per line — and rows
// measured 2.5-4x taller than layout produced.
let child_style =
child.style.resolve(Some(parent_style), available_width);
self.measure_node_height(child, fw, &child_style, font_context)
+ child_style.margin.vertical()
})
.fold(0.0f64, f64::max);
total += line_height;
if i > 0 {
total += row_gap;
}
}
total
}
FlexDirection::Column | FlexDirection::ColumnReverse => {
let mut total = 0.0;
for (i, child) in children.iter().enumerate() {
let child_style = child.style.resolve(Some(parent_style), available_width);
let child_height = self.measure_node_height(
child,
available_width,
&child_style,
font_context,
);
total += child_height + child_style.margin.vertical();
if i > 0 {
total += row_gap;
}
}
total
}
}
}
/// Measure intrinsic width of a node (used for flex row sizing).
fn measure_intrinsic_width(
&self,
node: &Node,
style: &ResolvedStyle,
font_context: &FontContext,
) -> f64 {
match &node.kind {
NodeKind::Svg { width, .. } => {
*width + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Text { content, runs, .. } | NodeKind::Heading { content, runs, .. } => {
// Runs-based text measures per run with each run's own
// resolved style — `content` is empty (or a shadow copy)
// when runs are present, so measuring it alone reports a
// zero/approximate width and flex rows collapse the node
// to one character per line.
let text_width = if !runs.is_empty() {
runs.iter()
.map(|run| {
let run_style = run.style.resolve(Some(style), 0.0);
let run_content = substitute_page_placeholders(&run.content);
let transformed =
apply_text_transform(&run_content, run_style.text_transform);
let italic = matches!(
run_style.font_style,
FontStyle::Italic | FontStyle::Oblique
);
// A hard break ('\n') restarts the line: the
// intrinsic width of multi-line text is the
// widest line, so measure segments separately.
transformed
.split('\n')
.map(|segment| {
font_context.measure_string(
segment,
&run_style.font_family,
run_style.font_weight,
italic,
run_style.font_size,
run_style.letter_spacing,
)
})
.fold(0.0f64, f64::max)
})
.sum()
} else {
let content = substitute_page_placeholders(content);
let transformed = apply_text_transform(&content, style.text_transform);
let italic = matches!(style.font_style, FontStyle::Italic | FontStyle::Oblique);
transformed
.split('\n')
.map(|segment| {
font_context.measure_string(
segment,
&style.font_family,
style.font_weight,
italic,
style.font_size,
style.letter_spacing,
)
})
.fold(0.0f64, f64::max)
};
// Add tiny epsilon to prevent exact-boundary line wrapping when
// this width is later used as max_width for line breaking
text_width + 0.01 + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Image {
src, width, height, ..
} => {
let w = if let SizeConstraint::Fixed(w) = style.width {
w
} else if let Some(w) = width {
*w
} else if let Some((iw, ih)) = self.get_image_dimensions(src) {
let pixel_w = iw as f64;
let pixel_h = ih as f64;
let aspect = if pixel_w > 0.0 {
pixel_h / pixel_w
} else {
0.75
};
// Check for height constraint (style or node prop)
let constrained_h = match style.height {
SizeConstraint::Fixed(h) => Some(h),
SizeConstraint::Auto => *height,
};
if let Some(h) = constrained_h {
h / aspect
} else {
pixel_w
}
} else {
100.0
};
w + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Barcode { width, .. } => {
let w = width.unwrap_or(0.0);
w + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::QrCode { size, .. } => {
let display_size = size.unwrap_or(0.0);
display_size + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Canvas { width, .. } => {
*width + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::BarChart { width, .. }
| NodeKind::LineChart { width, .. }
| NodeKind::PieChart { width, .. }
| NodeKind::AreaChart { width, .. }
| NodeKind::DotPlot { width, .. } => {
*width + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::TextField { width, .. } | NodeKind::Dropdown { width, .. } => {
*width + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Table { columns } => {
// A table's max-content width is the SUM of its columns'
// max-content (the default max-of-children arm below
// reports only the widest cell, which made shrink-to-fit
// containers crush tables to one column's width).
let num_cols = node
.children
.iter()
.map(|row| row.children.iter().map(Self::cell_col_span).sum::<usize>())
.max()
.unwrap_or(1)
.max(columns.len().max(1));
let (_, col_max) =
self.measure_column_content(&node.children, num_cols, 0.0, style, font_context);
col_max.iter().sum::<f64>()
+ style.padding.horizontal()
+ style.margin.horizontal()
+ style.border_width.horizontal()
}
NodeKind::Checkbox { width, .. } | NodeKind::RadioButton { width, .. } => {
*width + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Watermark { .. } => 0.0, // Watermarks take zero width
_ => {
// Recursively measure children's intrinsic widths
if node.children.is_empty() {
style.padding.horizontal() + style.margin.horizontal()
} else {
let direction = style.flex_direction;
let gap = style.gap;
let mut total = 0.0f64;
for (i, child) in node.children.iter().enumerate() {
let child_style = child.style.resolve(Some(style), 0.0);
let child_width =
self.measure_intrinsic_width(child, &child_style, font_context);
match direction {
FlexDirection::Row | FlexDirection::RowReverse => {
total += child_width;
if i > 0 {
total += gap;
}
}
_ => {
total = total.max(child_width);
}
}
}
total
+ style.padding.horizontal()
+ style.margin.horizontal()
+ style.border_width.horizontal()
}
}
}
}
/// Measure the min-content width of a node — the minimum width needed
/// to render without breaking unbreakable words. For Text nodes this is
/// the widest single word; for containers it's the max of children.
pub fn measure_min_content_width(
&self,
node: &Node,
style: &ResolvedStyle,
font_context: &FontContext,
) -> f64 {
match &node.kind {
NodeKind::Table { columns } => {
// Min-content of a table = sum of per-column min-content
// (mirrors the intrinsic-width Table arm).
let num_cols = node
.children
.iter()
.map(|row| row.children.iter().map(Self::cell_col_span).sum::<usize>())
.max()
.unwrap_or(1)
.max(columns.len().max(1));
let (col_min, _) =
self.measure_column_content(&node.children, num_cols, 0.0, style, font_context);
col_min.iter().sum::<f64>()
+ style.padding.horizontal()
+ style.margin.horizontal()
+ style.border_width.horizontal()
}
NodeKind::Text { content, runs, .. } | NodeKind::Heading { content, runs, .. } => {
let word_width = if !runs.is_empty() {
// For styled runs, measure each run's widest word
runs.iter()
.map(|run| {
let run_style = run.style.resolve(Some(style), 0.0);
let run_content = substitute_page_placeholders(&run.content);
let transformed =
apply_text_transform(&run_content, run_style.text_transform);
self.text_layout.measure_widest_word(
font_context,
&transformed,
run_style.font_size,
&run_style.font_family,
run_style.font_weight,
run_style.font_style,
run_style.letter_spacing,
style.hyphens,
style.lang.as_deref(),
)
})
.fold(0.0f64, f64::max)
} else {
let content = substitute_page_placeholders(content);
let transformed = apply_text_transform(&content, style.text_transform);
self.text_layout.measure_widest_word(
font_context,
&transformed,
style.font_size,
&style.font_family,
style.font_weight,
style.font_style,
style.letter_spacing,
style.hyphens,
style.lang.as_deref(),
)
};
word_width + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Image { width, .. } => {
width.unwrap_or(0.0) + style.padding.horizontal() + style.margin.horizontal()
}
NodeKind::Svg { width, .. } => {
*width + style.padding.horizontal() + style.margin.horizontal()
}
_ => {
if node.children.is_empty() {
style.padding.horizontal()
+ style.margin.horizontal()
+ style.border_width.horizontal()
} else {
let mut max_child_min = 0.0f64;
for child in &node.children {
let child_style = child.style.resolve(Some(style), 0.0);
let child_min =
self.measure_min_content_width(child, &child_style, font_context);
max_child_min = max_child_min.max(child_min);
}
max_child_min
+ style.padding.horizontal()
+ style.margin.horizontal()
+ style.border_width.horizontal()
}
}
}
}
/// The first-baseline offset of a cell's first text line from its line-box
/// top: half-leading plus font size (the engine's baseline model — there is
/// no font-ascent metric, `font_size` stands in for the glyph block).
/// Walks to the first text-producing descendant; falls back to the cell's
/// own style when there is none.
fn cell_first_baseline_in_line(&self, cell: &Node, cell_style: &ResolvedStyle, w: f64) -> f64 {
fn first(node: &Node, parent: &ResolvedStyle, w: f64) -> Option<(f64, f64)> {
for ch in &node.children {
let s = ch.style.resolve(Some(parent), w);
match &ch.kind {
NodeKind::Text { .. } | NodeKind::Heading { .. } => {
return Some((s.font_size, s.line_height))
}
_ => {
if let Some(f) = first(ch, &s, w) {
return Some(f);
}
}
}
}
None
}
let (fs, lh) =
first(cell, cell_style, w).unwrap_or((cell_style.font_size, cell_style.line_height));
(fs * lh - fs) / 2.0 + fs
}
/// Distance from a cell's border-box top to its first text baseline:
/// `padding.top + border.top + half-leading + first-line font_size` —
/// matching exactly where layout_text places the glyphs, or baseline
/// alignment drifts by half the leading.
fn cell_baseline_distance(
&self,
cell: &Node,
cell_style: &ResolvedStyle,
inner_width: f64,
) -> f64 {
cell_style.padding.top
+ cell_style.border_width.top
+ self.cell_first_baseline_in_line(cell, cell_style, inner_width)
}
/// The row baseline: the max first-baseline distance across the row's
/// `vertical-align: baseline` cells. `None` when no cell asks for baseline.
fn row_baseline(
&self,
row: &Node,
row_style: &ResolvedStyle,
col_widths: &[f64],
col_offsets: &[usize],
) -> Option<f64> {
let mut b: Option<f64> = None;
for (cell_i, cell) in row.children.iter().enumerate() {
let span = match &cell.kind {
NodeKind::TableCell { col_span, .. } => (*col_span).max(1) as usize,
_ => 1,
};
let start_col = col_offsets.get(cell_i).copied().unwrap_or(0);
let col_width: f64 = col_widths.iter().skip(start_col).take(span).copied().sum();
let cell_style = cell.style.resolve(Some(row_style), col_width);
if matches!(cell_style.vertical_align, VerticalAlign::Baseline) {
let iw = col_width
- cell_style.padding.horizontal()
- cell_style.border_width.horizontal();
let d = self.cell_baseline_distance(cell, &cell_style, iw);
b = Some(b.map_or(d, |m: f64| m.max(d)));
}
}
b
}
fn measure_table_row_height(
&self,
row: &Node,
col_widths: &[f64],
col_offsets: &[usize],
parent_style: &ResolvedStyle,
font_context: &FontContext,
) -> f64 {
let row_style = row
.style
.resolve(Some(parent_style), col_widths.iter().sum());
let mut max_height: f64 = 0.0;
// Precompute the row baseline so a baseline-shoved cell can grow the row
// rather than clip (the risk site).
let row_bl = self.row_baseline(row, &row_style, col_widths, col_offsets);
for (cell_i, cell) in row.children.iter().enumerate() {
let span = match &cell.kind {
NodeKind::TableCell { col_span, .. } => (*col_span).max(1) as usize,
_ => 1,
};
let start_col = col_offsets.get(cell_i).copied().unwrap_or(0);
let col_width: f64 = col_widths.iter().skip(start_col).take(span).copied().sum();
let cell_style = cell.style.resolve(Some(&row_style), col_width);
let inner_width =
col_width - cell_style.padding.horizontal() - cell_style.border_width.horizontal();
let mut cell_content_height = 0.0;
for child in &cell.children {
let child_style = child.style.resolve(Some(&cell_style), inner_width);
cell_content_height +=
self.measure_node_height(child, inner_width, &child_style, font_context);
}
let mut total = cell_content_height
+ cell_style.padding.vertical()
+ cell_style.border_width.vertical();
// A baseline cell is shoved down by `row_baseline - its own baseline
// distance`; the row must be tall enough to fit that shove, or the
// cell content clips.
if matches!(cell_style.vertical_align, VerticalAlign::Baseline) {
if let Some(b) = row_bl {
let d = self.cell_baseline_distance(cell, &cell_style, inner_width);
total += (b - d).max(0.0);
}
}
// CSS 2.1 §17.5.3: `height` on a table cell is a MINIMUM — the cell
// grows to fit its content but never shrinks below the specified
// height. This is the slack `vertical-align: middle/bottom` needs to
// be visible. Auto-height cells are unaffected; content taller than
// the height still wins. No clipping, and rows stay atomic (an
// over-tall row overflows whole, it is not sliced).
if let SizeConstraint::Fixed(h) = cell_style.height {
total = total.max(h);
}
max_height = max_height.max(total);
}
max_height.max(row_style.min_height)
}
/// How many columns a cell spans (colspan, min 1).
fn cell_col_span(cell: &Node) -> usize {
match &cell.kind {
NodeKind::TableCell { col_span, .. } => (*col_span).max(1) as usize,
_ => 1,
}
}
/// Per-column min-content / max-content, gathered across ALL rows.
/// Spanning cells contribute an even share per column — the standard
/// simplification. An explicit cell width pins the column's preferred
/// size (still never below min-content).
fn measure_column_content(
&self,
children: &[Node],
num_cols: usize,
available_width: f64,
table_style: &ResolvedStyle,
font_context: &FontContext,
) -> (Vec<f64>, Vec<f64>) {
let mut col_min = vec![0.0f64; num_cols];
let mut col_max = vec![0.0f64; num_cols];
let offsets = Self::table_column_offsets(children);
for (row_i, row_node) in children.iter().enumerate() {
for (cell_i, cell) in row_node.children.iter().enumerate() {
let col = offsets[row_i].get(cell_i).copied().unwrap_or(0);
let span = Self::cell_col_span(cell);
let cell_style = cell.style.resolve(Some(table_style), available_width);
let chrome = cell_style.padding.horizontal() + cell_style.border_width.horizontal();
let mut cmin = 0.0f64;
let mut cmax = 0.0f64;
for child in &cell.children {
let child_style = child.style.resolve(Some(&cell_style), 0.0);
cmin =
cmin.max(self.measure_min_content_width(child, &child_style, font_context));
cmax =
cmax.max(self.measure_intrinsic_width(child, &child_style, font_context));
}
cmin += chrome;
let mut cmax = cmax.max(cmin) + chrome;
if let SizeConstraint::Fixed(w) = cell_style.width {
cmax = w.max(cmin);
}
let per_min = cmin / span as f64;
let per_max = cmax / span as f64;
for k in col..(col + span).min(num_cols) {
col_min[k] = col_min[k].max(per_min);
col_max[k] = col_max[k].max(per_max);
}
}
}
(col_min, col_max)
}
/// Resolve table column widths.
///
/// With explicit defs: fixed/fraction as given, Auto shares the rest
/// (clamped — overflowing fixed widths are a render defect, never a
/// negative share). With NO defs: CSS-style automatic table layout —
/// column count is the widest row's colspan sum (the old first-row
/// cell count turned every banner-row invoice into a one-column table
/// and shredded the rest, per template-compat/REPORT.md), and widths
/// distribute by min/max content like a browser.
fn resolve_column_widths(
&self,
defs: &[ColumnDef],
available_width: f64,
children: &[Node],
table_style: &ResolvedStyle,
font_context: &FontContext,
) -> Vec<f64> {
if defs.is_empty() {
let num_cols = Self::occupancy_column_count(children);
let (col_min, col_max) = self.measure_column_content(
children,
num_cols,
available_width,
table_style,
font_context,
);
let sum_min: f64 = col_min.iter().sum();
let sum_max: f64 = col_max.iter().sum();
let w = available_width;
return if sum_max <= w {
// Everything fits at preferred size: surplus distributes
// proportionally to max-content (browser behavior for
// width:100% tables).
if sum_max <= f64::EPSILON {
vec![w / num_cols as f64; num_cols]
} else {
col_max
.iter()
.map(|m| m + (w - sum_max) * (m / sum_max))
.collect()
}
} else if sum_min <= w {
// Squeeze between min and max, proportional to each
// column's flexibility.
let denom = (sum_max - sum_min).max(f64::EPSILON);
col_min
.iter()
.zip(&col_max)
.map(|(mn, mx)| mn + (w - sum_min) * ((mx - mn) / denom))
.collect()
} else {
// The content genuinely cannot fit. Scale mins down and
// SAY SO — this used to be the silent shred.
self.defect(format!(
"render defect: table columns need {:.0}pt at min-content but only {:.0}pt is available — text will wrap tighter than intended",
sum_min, w
));
let scale = w / sum_min.max(f64::EPSILON);
col_min.iter().map(|m| m * scale).collect()
};
}
// Defs can under-specify the table: a rowspan-spacer or short
// first row yields fewer defs than the widest row has cells (the
// InvoicePlane date block, template-compat/REPORT.md). Cells
// beyond the defs used to get NO width at all — extend with Auto
// columns to the true column count instead.
let num_cols = Self::occupancy_column_count(children).max(defs.len());
let mut defs_vec: Vec<ColumnDef> = defs.to_vec();
while defs_vec.len() < num_cols {
defs_vec.push(ColumnDef {
width: ColumnWidth::Auto,
});
}
let defs = &defs_vec[..];
let mut widths = Vec::new();
let mut remaining = available_width;
let mut auto_count = 0;
for def in defs {
match def.width {
ColumnWidth::Fixed(w) => {
widths.push(w);
remaining -= w;
}
ColumnWidth::Fraction(f) => {
let w = available_width * f;
widths.push(w);
remaining -= w;
}
ColumnWidth::Auto => {
widths.push(0.0);
auto_count += 1;
}
}
}
if remaining < 0.0 {
// Fixed/fraction widths exceed the table: Auto columns would
// have gone NEGATIVE. Clamp, and report the defect.
self.defect(format!(
"render defect: table column widths total {:.0}pt but only {:.0}pt is available — remaining columns were clamped to their minimum",
available_width - remaining,
available_width
));
remaining = 0.0;
}
if auto_count > 0 {
let auto_width = remaining / auto_count as f64;
for (i, def) in defs.iter().enumerate() {
if matches!(def.width, ColumnWidth::Auto) {
widths[i] = auto_width;
}
}
}
// Specified widths are suggestions, not laws (browser auto table
// layout): a column squeezed below its min-content — the classic
// over-specified-width template — is floored at min-content, and
// the deficit comes out of columns with surplus, proportionally.
// A table where every column already fits is returned EXACTLY as
// specified (byte-stable for the shipped templates).
let (col_min, _) = self.measure_column_content(
children,
widths.len(),
available_width,
table_style,
font_context,
);
let needs_floor = widths.iter().zip(&col_min).any(|(w, m)| *w + 0.01 < *m);
if needs_floor {
let sum_min: f64 = col_min.iter().sum();
if sum_min > available_width {
self.defect(format!(
"render defect: table columns need {:.0}pt at min-content but only {:.0}pt is available — text will wrap tighter than intended",
sum_min, available_width
));
let scale = available_width / sum_min.max(f64::EPSILON);
return col_min.iter().map(|m| m * scale).collect();
}
let deficit: f64 = widths
.iter()
.zip(&col_min)
.map(|(w, m)| (m - w).max(0.0))
.sum();
let surplus: f64 = widths
.iter()
.zip(&col_min)
.map(|(w, m)| (w - m).max(0.0))
.sum();
let take = if surplus > 0.0 {
deficit / surplus
} else {
0.0
};
widths = widths
.iter()
.zip(&col_min)
.map(|(w, m)| if *w < *m { *m } else { w - (w - m) * take })
.collect();
}
widths
}
fn inject_fixed_elements(&self, pages: &mut [LayoutPage], font_context: &FontContext) {
for (page_index, page) in pages.iter_mut().enumerate() {
// Inject watermarks behind all content
if !page.watermarks.is_empty() {
let (page_w, page_h) = page.config.size.dimensions();
let cx = page_w / 2.0;
let cy = page_h / 2.0;
let mut watermark_elements = Vec::new();
for wm_node in &page.watermarks {
if let NodeKind::Watermark {
text,
font_size,
angle,
} = &wm_node.kind
{
let style = wm_node.style.resolve(None, page_w);
let color = style.color;
let opacity = style.opacity;
let angle_rad = angle.to_radians();
// Build positioned glyphs for the watermark text
let italic =
matches!(style.font_style, FontStyle::Italic | FontStyle::Oblique);
// Try shaping, fall back to per-char measurement
let shaped = self.text_layout.shape_text(
font_context,
text,
&style.font_family,
style.font_weight,
style.font_style,
);
let mut glyphs = Vec::new();
let mut x_pos = 0.0;
let text_chars: Vec<char> = text.chars().collect();
if let Some(shaped_glyphs) = shaped {
// Use shaped glyphs (custom fonts)
let units_per_em = font_context.units_per_em(
&style.font_family,
style.font_weight,
italic,
) as f64;
for sg in &shaped_glyphs {
let advance = sg.x_advance as f64 / units_per_em * *font_size;
let cluster_idx = sg.cluster as usize;
let ch = text_chars.get(cluster_idx).copied().unwrap_or(' ');
glyphs.push(PositionedGlyph {
glyph_id: sg.glyph_id,
char_value: ch,
x_offset: x_pos,
y_offset: 0.0,
x_advance: advance,
font_size: *font_size,
font_family: Arc::from(style.font_family.as_str()),
font_weight: style.font_weight,
font_style: style.font_style,
color: Some(color),
href: None,
text_decoration: TextDecoration::None,
letter_spacing: style.letter_spacing,
cluster_text: None,
});
x_pos += advance + style.letter_spacing;
}
} else {
// Per-char measurement (standard fonts)
for &ch in &text_chars {
let w = font_context.char_width(
ch,
&style.font_family,
style.font_weight,
italic,
*font_size,
);
glyphs.push(PositionedGlyph {
glyph_id: ch as u16,
char_value: ch,
x_offset: x_pos,
y_offset: 0.0,
x_advance: w,
font_size: *font_size,
font_family: Arc::from(style.font_family.as_str()),
font_weight: style.font_weight,
font_style: style.font_style,
color: Some(color),
href: None,
text_decoration: TextDecoration::None,
letter_spacing: style.letter_spacing,
cluster_text: None,
});
x_pos += w + style.letter_spacing;
}
}
let text_width = x_pos;
let line = TextLine {
x: 0.0,
y: 0.0,
glyphs,
width: text_width,
height: *font_size,
word_spacing: 0.0,
};
watermark_elements.push(LayoutElement {
x: cx,
y: cy,
width: text_width,
height: *font_size,
draw: DrawCommand::Watermark {
lines: vec![line],
color,
opacity,
angle_rad,
font_family: style.font_family.clone(),
},
children: vec![],
node_type: Some("Watermark".to_string()),
resolved_style: None,
source_location: None,
href: None,
bookmark: None,
alt: None,
is_header_row: false,
col_span: 1,
overflow: Overflow::default(),
opacity: 1.0,
});
}
}
// Prepend watermark elements so they render behind all content
watermark_elements.append(&mut page.elements);
page.elements = watermark_elements;
page.watermarks.clear();
}
if page.fixed_header.is_empty() && page.fixed_footer.is_empty() {
continue;
}
// Lay out headers at top of content area
if !page.fixed_header.is_empty() {
let mut hdr_cursor = PageCursor::new(&page.config);
for (node, _h) in &page.fixed_header {
// The enumerate index is the authoritative page number
// for First/NotFirst filtering.
if !fixed_applies_on(node, page_index, page.page_name.as_deref()) {
continue;
}
let cw = hdr_cursor.content_width;
let cx = hdr_cursor.content_x;
let style = node.style.resolve(None, cw);
self.layout_view(
node,
&style,
&mut hdr_cursor,
&mut Vec::new(),
cx,
cw,
font_context,
);
}
// Prepend header elements so they draw behind body content
let mut combined = hdr_cursor.elements;
combined.append(&mut page.elements);
page.elements = combined;
}
// Lay out footers at bottom of content area.
// We lay out from y=0 (so there's plenty of room and no spurious
// page breaks), then shift all resulting elements down to the
// correct footer position.
if !page.fixed_footer.is_empty() {
let mut ftr_cursor = PageCursor::new(&page.config);
let total_ftr: f64 = page
.fixed_footer
.iter()
.filter(|(n, _)| fixed_applies_on(n, page_index, page.page_name.as_deref()))
.map(|(_, h)| *h)
.sum();
let target_y = ftr_cursor.content_height - total_ftr;
// Layout from y=0
for (node, _h) in &page.fixed_footer {
if !fixed_applies_on(node, page_index, page.page_name.as_deref()) {
continue;
}
let cw = ftr_cursor.content_width;
let cx = ftr_cursor.content_x;
let style = node.style.resolve(None, cw);
self.layout_view(
node,
&style,
&mut ftr_cursor,
&mut Vec::new(),
cx,
cw,
font_context,
);
}
// Shift all footer elements down to the target position.
// Elements already have content_y baked in, so we just offset
// by target_y (which is relative to content area top).
for el in &mut ftr_cursor.elements {
offset_element_y(el, target_y);
}
page.elements.extend(ftr_cursor.elements);
}
// Clean up internal fields
page.fixed_header.clear();
page.fixed_footer.clear();
}
}
/// Layout children as a CSS Grid.
///
/// Uses the grid track definitions from the parent style to create a 2D grid,
/// places children into cells, and lays out each child within its cell bounds.
#[allow(clippy::too_many_arguments)]
fn layout_grid_children(
&self,
children: &[Node],
parent_style: &ResolvedStyle,
cursor: &mut PageCursor,
pages: &mut Vec<LayoutPage>,
x: f64,
available_width: f64,
font_context: &FontContext,
) {
let template_cols = match &parent_style.grid_template_columns {
Some(cols) => cols,
None => return, // No columns defined, nothing to do
};
let num_columns = template_cols.len();
if num_columns == 0 || children.is_empty() {
return;
}
let col_gap = parent_style.column_gap;
let row_gap = parent_style.row_gap;
// Resolve column widths
// For auto tracks, we need content sizes. Use a rough measure.
let content_sizes: Vec<f64> = template_cols
.iter()
.map(|track| {
if matches!(track, GridTrackSize::Auto) {
// Measure the widest child that falls in this column
// (approximation: use available_width / num_columns)
available_width / num_columns as f64
} else {
0.0
}
})
.collect();
let col_widths =
grid::resolve_tracks(template_cols, available_width, col_gap, &content_sizes);
// Collect grid placements from children's styles
let placements: Vec<Option<&GridPlacement>> = children
.iter()
.map(|child| child.style.grid_placement.as_ref())
.collect();
// Place items in the grid
let item_placements = grid::place_items(&placements, num_columns);
let num_rows = grid::compute_num_rows(&item_placements);
if num_rows == 0 {
return;
}
// Measure each item's height at its resolved cell width
let mut item_heights: Vec<f64> = vec![0.0; children.len()];
for placement in &item_placements {
let cell_width =
grid::span_width(placement.col_start, placement.col_end, &col_widths, col_gap);
let child = &children[placement.child_index];
let child_style = child.style.resolve(Some(parent_style), cell_width);
item_heights[placement.child_index] =
self.measure_node_height(child, cell_width, &child_style, font_context);
}
// Compute row heights: max height of all items in each row
let template_rows = parent_style.grid_template_rows.as_deref();
let mut row_heights = vec![0.0_f64; num_rows];
for placement in &item_placements {
let h = item_heights[placement.child_index];
let span = placement.row_end - placement.row_start;
let per_row = h / span as f64;
for rh in row_heights
.iter_mut()
.take(placement.row_end.min(num_rows))
.skip(placement.row_start)
{
if per_row > *rh {
*rh = per_row;
}
}
}
// Apply template row sizes if provided
if let Some(template) = template_rows {
let auto_row = parent_style.grid_auto_rows.as_ref();
for (r, rh) in row_heights.iter_mut().enumerate() {
let track = template.get(r).or(auto_row);
if let Some(track) = track {
match track {
GridTrackSize::Pt(pts) => *rh = *pts,
GridTrackSize::Auto => {} // keep computed
_ => {} // Fr for rows is complex, skip for now
}
}
}
}
// Layout each row
for (row, &row_height) in row_heights.iter().enumerate().take(num_rows) {
// Check page break: treat each row as unbreakable. The whole row
// moves to the next page so all columns share the same baseline
// (otherwise each cell's layout_node would page-break individually
// and scatter the columns across separate pages).
if row_height > cursor.remaining_height() {
pages.push(cursor.finalize());
*cursor = cursor.new_page();
}
let row_start_y = cursor.y;
// Layout items in this row
for placement in &item_placements {
if placement.row_start != row {
continue; // Only process items starting in this row
}
let cell_x = x + grid::column_x_offset(placement.col_start, &col_widths, col_gap);
let cell_width =
grid::span_width(placement.col_start, placement.col_end, &col_widths, col_gap);
let child = &children[placement.child_index];
self.layout_node(
child,
cursor,
pages,
cell_x,
cell_width,
Some(parent_style),
font_context,
None,
None,
);
// Restore y to row baseline (items don't affect each other's y)
cursor.y = row_start_y;
}
cursor.y = row_start_y + row_height + row_gap;
}
// Remove trailing gap
if num_rows > 0 {
cursor.y -= row_gap;
}
}
}
struct FlexItem<'a> {
node: &'a Node,
style: ResolvedStyle,
base_width: f64,
min_content_width: f64,
}
/// First bit of text content under a node, for naming elements in
/// render-defect messages (the engine's Node has no id/class).
fn first_text_snippet(node: &Node) -> Option<String> {
fn walk(n: &Node) -> Option<&str> {
match &n.kind {
NodeKind::Text { content, runs, .. } | NodeKind::Heading { content, runs, .. } => {
if !content.trim().is_empty() {
return Some(content.trim());
}
if let Some(r) = runs.iter().find(|r| !r.content.trim().is_empty()) {
return Some(r.content.trim());
}
None
}
_ => n.children.iter().find_map(walk),
}
}
walk(node).map(|t| {
let mut s: String = t.chars().take(32).collect();
if t.chars().count() > 32 {
s.push('…');
}
s
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::font::FontContext;
fn make_text(content: &str, font_size: f64) -> Node {
Node {
kind: NodeKind::Text {
content: content.to_string(),
href: None,
runs: vec![],
},
style: Style {
font_size: Some(font_size),
..Default::default()
},
children: vec![],
id: None,
source_location: None,
bookmark: None,
href: None,
alt: None,
}
}
fn make_styled_view(style: Style, children: Vec<Node>) -> Node {
Node {
kind: NodeKind::View,
style,
children,
id: None,
source_location: None,
bookmark: None,
href: None,
alt: None,
}
}
fn make_runs_text(runs: Vec<crate::model::TextRun>) -> Node {
Node {
kind: NodeKind::Text {
content: String::new(),
href: None,
runs,
},
style: Style::default(),
children: vec![],
id: None,
source_location: None,
bookmark: None,
href: None,
alt: None,
}
}
#[test]
fn intrinsic_width_measures_runs_not_just_content() {
// Found by the HTML input path: a runs-based Text node (empty
// `content`) used to measure ~0 intrinsic width, so flex rows
// collapsed it to one character per line.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let runs_node = make_runs_text(vec![
crate::model::TextRun {
content: "Hello ".to_string(),
style: Style::default(),
href: None,
},
crate::model::TextRun {
content: "World".to_string(),
style: Style {
font_weight: Some(700),
..Default::default()
},
href: None,
},
]);
let plain_node = make_text("Hello World", 12.0);
let runs_style = runs_node.style.resolve(None, 0.0);
let plain_style = plain_node.style.resolve(None, 0.0);
let runs_w = engine.measure_intrinsic_width(&runs_node, &runs_style, &font_context);
let plain_w = engine.measure_intrinsic_width(&plain_node, &plain_style, &font_context);
// Must be in the same ballpark as the plain-content equivalent
// (slightly wider: the second run is bold).
assert!(
runs_w >= plain_w,
"runs width ({runs_w}) must not undershoot plain width ({plain_w})"
);
assert!(
runs_w < plain_w * 1.5,
"runs width ({runs_w}) should be close to plain width ({plain_w})"
);
}
#[test]
fn intrinsic_width_of_multiline_text_is_widest_line() {
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let multiline = make_text("123 Main St\nSpringfield, IL 62704", 12.0);
let widest = make_text("Springfield, IL 62704", 12.0);
let m_style = multiline.style.resolve(None, 0.0);
let w_style = widest.style.resolve(None, 0.0);
let m_w = engine.measure_intrinsic_width(&multiline, &m_style, &font_context);
let w_w = engine.measure_intrinsic_width(&widest, &w_style, &font_context);
assert!(
(m_w - w_w).abs() < 0.01,
"multiline intrinsic width ({m_w}) must equal its widest line ({w_w})"
);
}
#[test]
fn intrinsic_width_of_heading_measures_its_text() {
// Heading used to fall through to the children-recursion arm and
// measure zero (headings are leaves).
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let heading = Node {
kind: NodeKind::Heading {
level: 1,
content: "Invoice #2024-001".to_string(),
href: None,
runs: vec![],
},
style: Style {
font_size: Some(24.0),
..Default::default()
},
children: vec![],
id: None,
source_location: None,
bookmark: None,
href: None,
alt: None,
};
let style = heading.style.resolve(None, 0.0);
let w = engine.measure_intrinsic_width(&heading, &style, &font_context);
assert!(w > 100.0, "24pt heading text must measure wide, got {w}");
}
#[test]
fn measure_node_height_of_wrapping_heading_matches_text() {
// A heading that wraps to multiple lines must contribute its full
// height to a parent's auto-height, exactly like Text. Previously
// Heading had no arm in `measure_node_height` and fell through to the
// container `_` arm (children-recursion), measuring ~0 — so an
// auto-height View wrapping a multi-line heading collapsed, shifting
// every sibling below it.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let content = "Annual Performance Review";
let heading = Node {
kind: NodeKind::Heading {
level: 1,
content: content.to_string(),
href: None,
runs: vec![],
},
style: Style {
font_size: Some(32.0),
..Default::default()
},
children: vec![],
id: None,
source_location: None,
bookmark: None,
href: None,
alt: None,
};
let text = make_text(content, 32.0);
// A width narrow enough to force the 32pt title onto more than one line.
let width = 200.0;
let h_style = heading.style.resolve(None, width);
let t_style = text.style.resolve(None, width);
let h_height = engine.measure_node_height(&heading, width, &h_style, &font_context);
let t_height = engine.measure_node_height(&text, width, &t_style, &font_context);
assert!(
h_height > 32.0,
"a wrapping 32pt heading must measure more than one line, got {h_height}"
);
assert!(
(h_height - t_height).abs() < 0.01,
"heading height ({h_height}) must equal the same text's height ({t_height})"
);
}
#[test]
fn intrinsic_width_flex_row_sums_children() {
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let child1 = make_text("Hello", 14.0);
let child2 = make_text("World", 14.0);
let child1_style = child1.style.resolve(None, 0.0);
let child2_style = child2.style.resolve(None, 0.0);
let child1_w = engine.measure_intrinsic_width(&child1, &child1_style, &font_context);
let child2_w = engine.measure_intrinsic_width(&child2, &child2_style, &font_context);
let row = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Row),
..Default::default()
},
vec![make_text("Hello", 14.0), make_text("World", 14.0)],
);
let row_style = row.style.resolve(None, 0.0);
let row_w = engine.measure_intrinsic_width(&row, &row_style, &font_context);
assert!(
(row_w - (child1_w + child2_w)).abs() < 0.01,
"Row intrinsic width ({}) should equal sum of children ({} + {})",
row_w,
child1_w,
child2_w
);
}
#[test]
fn intrinsic_width_flex_column_takes_max() {
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let short = make_text("Hi", 14.0);
let long = make_text("Hello World", 14.0);
let short_style = short.style.resolve(None, 0.0);
let long_style = long.style.resolve(None, 0.0);
let short_w = engine.measure_intrinsic_width(&short, &short_style, &font_context);
let long_w = engine.measure_intrinsic_width(&long, &long_style, &font_context);
let col = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
..Default::default()
},
vec![make_text("Hi", 14.0), make_text("Hello World", 14.0)],
);
let col_style = col.style.resolve(None, 0.0);
let col_w = engine.measure_intrinsic_width(&col, &col_style, &font_context);
assert!(
(col_w - long_w).abs() < 0.01,
"Column intrinsic width ({}) should equal max child ({}, short was {})",
col_w,
long_w,
short_w
);
}
#[test]
fn intrinsic_width_nested_containers() {
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let inner = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Row),
..Default::default()
},
vec![make_text("A", 12.0), make_text("B", 12.0)],
);
let inner_style = inner.style.resolve(None, 0.0);
let inner_w = engine.measure_intrinsic_width(&inner, &inner_style, &font_context);
let outer = make_styled_view(
Style::default(),
vec![make_styled_view(
Style {
flex_direction: Some(FlexDirection::Row),
..Default::default()
},
vec![make_text("A", 12.0), make_text("B", 12.0)],
)],
);
let outer_style = outer.style.resolve(None, 0.0);
let outer_w = engine.measure_intrinsic_width(&outer, &outer_style, &font_context);
assert!(
(outer_w - inner_w).abs() < 0.01,
"Nested container ({}) should match inner container ({})",
outer_w,
inner_w
);
}
#[test]
fn intrinsic_width_row_with_gap() {
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let no_gap = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Row),
..Default::default()
},
vec![make_text("A", 12.0), make_text("B", 12.0)],
);
let with_gap = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Row),
gap: Some(10.0),
..Default::default()
},
vec![make_text("A", 12.0), make_text("B", 12.0)],
);
let no_gap_style = no_gap.style.resolve(None, 0.0);
let with_gap_style = with_gap.style.resolve(None, 0.0);
let no_gap_w = engine.measure_intrinsic_width(&no_gap, &no_gap_style, &font_context);
let with_gap_w = engine.measure_intrinsic_width(&with_gap, &with_gap_style, &font_context);
assert!(
(with_gap_w - no_gap_w - 10.0).abs() < 0.01,
"Gap should add 10pt: with_gap={}, no_gap={}",
with_gap_w,
no_gap_w
);
}
#[test]
fn intrinsic_width_empty_container() {
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let padding = 8.0;
let empty = make_styled_view(
Style {
padding: Some(Edges::uniform(padding)),
..Default::default()
},
vec![],
);
let style = empty.style.resolve(None, 0.0);
let w = engine.measure_intrinsic_width(&empty, &style, &font_context);
assert!(
(w - padding * 2.0).abs() < 0.01,
"Empty container width ({}) should equal horizontal padding ({})",
w,
padding * 2.0
);
}
// ── Fix 1: min-content width prevents text wrapping in flex shrink ──
#[test]
fn flex_shrink_respects_min_content_width() {
// A flex row with a short-text child ("SALE") and a large sibling.
// The shrink algorithm should not compress the short-text child below
// the width of the word "SALE".
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let sale_text = make_text("SALE", 12.0);
let sale_style = sale_text.style.resolve(None, 0.0);
let sale_word_width =
engine.measure_min_content_width(&sale_text, &sale_style, &font_context);
assert!(
sale_word_width > 0.0,
"SALE should have non-zero min-content width"
);
// Row with 100pt available; child1 wants 80pt, child2 (SALE) wants 60pt.
// Total = 140pt, overflow = 40pt. Without floor, SALE would shrink below word width.
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Row),
width: Some(Dimension::Pt(100.0)),
..Default::default()
},
vec![
make_styled_view(
Style {
width: Some(Dimension::Pt(80.0)),
flex_shrink: Some(1.0),
..Default::default()
},
vec![],
),
make_styled_view(
Style {
width: Some(Dimension::Pt(60.0)),
flex_shrink: Some(1.0),
..Default::default()
},
vec![make_text("SALE", 12.0)],
),
],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
assert!(!pages.is_empty());
// The SALE child (second flex item) should not be narrower than its min-content width
// Walk the layout tree: Page -> View (container) -> second child
let page = &pages[0];
// Find the container (the View with children)
let container_el = page.elements.iter().find(|e| e.children.len() == 2);
assert!(
container_el.is_some(),
"Should find container with 2 children"
);
let sale_child = &container_el.unwrap().children[1];
assert!(
sale_child.width >= sale_word_width - 0.01,
"SALE child width ({}) should be >= min-content width ({})",
sale_child.width,
sale_word_width
);
}
// ── Fix 2: column justify-content and align-items ──
#[test]
fn column_justify_content_center() {
// A column container with fixed height 200pt and a single child of ~20pt.
// With justify-content: center, the child should be roughly centered vertically.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(200.0)),
justify_content: Some(JustifyContent::Center),
..Default::default()
},
vec![make_text("Centered", 12.0)],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
// The container should have one child, and that child should be
// offset roughly to the vertical center
let container_el = page.elements.iter().find(|e| !e.children.is_empty());
assert!(
container_el.is_some(),
"Should find container with children"
);
let container_el = container_el.unwrap();
let child = &container_el.children[0];
// Child y should be container.y + roughly (200 - child_height) / 2
let child_offset = child.y - container_el.y;
let expected_offset = (200.0 - child.height) / 2.0;
assert!(
(child_offset - expected_offset).abs() < 2.0,
"Child offset ({}) should be near center ({})",
child_offset,
expected_offset
);
}
#[test]
fn column_align_items_center() {
// A column container with a narrow text child.
// With align-items: center, the child should be horizontally centered.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
width: Some(Dimension::Pt(300.0)),
align_items: Some(AlignItems::Center),
..Default::default()
},
vec![make_text("Hi", 12.0)],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page.elements.iter().find(|e| !e.children.is_empty());
assert!(container_el.is_some());
let container_el = container_el.unwrap();
let child = &container_el.children[0];
// Child should be centered within the 300pt container
let child_center = child.x + child.width / 2.0;
let container_center = container_el.x + container_el.width / 2.0;
assert!(
(child_center - container_center).abs() < 2.0,
"Child center ({}) should be near container center ({})",
child_center,
container_center
);
}
// ── Fix 3: absolute positioning relative to parent ──
#[test]
fn absolute_child_positioned_relative_to_parent() {
// A POSITIONED parent (position: relative) with an absolute child using
// top: 10, left: 10. The child resolves against the parent — now the
// correct CSS behavior, since the parent is a positioned ancestor.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let parent = make_styled_view(
Style {
position: Some(crate::model::Position::Relative),
margin: Some(MarginEdges::from_edges(Edges {
top: 50.0,
left: 50.0,
..Default::default()
})),
width: Some(Dimension::Pt(200.0)),
height: Some(Dimension::Pt(200.0)),
..Default::default()
},
vec![make_styled_view(
Style {
position: Some(crate::model::Position::Absolute),
top: Some(10.0),
left: Some(10.0),
width: Some(Dimension::Pt(50.0)),
height: Some(Dimension::Pt(50.0)),
..Default::default()
},
vec![],
)],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![parent],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
// Find the parent container (has the absolute child inside it or as sibling)
// Absolute children are added to cursor.elements, so they'll be inside the parent
let parent_el = page
.elements
.iter()
.find(|e| e.width > 190.0 && e.width < 210.0);
assert!(parent_el.is_some(), "Should find the 200x200 parent");
let parent_el = parent_el.unwrap();
// The absolute child should be at parent.x + 10, parent.y + 10
let abs_child = parent_el
.children
.iter()
.find(|e| e.width > 45.0 && e.width < 55.0);
assert!(abs_child.is_some(), "Should find 50x50 absolute child");
let abs_child = abs_child.unwrap();
let expected_x = parent_el.x + 10.0;
let expected_y = parent_el.y + 10.0;
assert!(
(abs_child.x - expected_x).abs() < 1.0,
"Absolute child x ({}) should be parent.x + 10 ({})",
abs_child.x,
expected_x
);
assert!(
(abs_child.y - expected_y).abs() < 1.0,
"Absolute child y ({}) should be parent.y + 10 ({})",
abs_child.y,
expected_y
);
}
#[test]
fn absolute_escapes_unpositioned_parent_to_page() {
// Same shape, but the parent is UNpositioned. Under browser semantics
// the absolute child resolves against the nearest positioned ancestor —
// here none exists, so the page content box, NOT the parent. This is
// the retired v0 divergence.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let parent = make_styled_view(
Style {
margin: Some(MarginEdges::from_edges(Edges {
top: 50.0,
left: 50.0,
..Default::default()
})),
width: Some(Dimension::Pt(200.0)),
height: Some(Dimension::Pt(200.0)),
..Default::default()
},
vec![make_styled_view(
Style {
position: Some(crate::model::Position::Absolute),
top: Some(10.0),
left: Some(10.0),
width: Some(Dimension::Pt(50.0)),
height: Some(Dimension::Pt(50.0)),
..Default::default()
},
vec![],
)],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![parent],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let parent_el = page
.elements
.iter()
.find(|e| e.width > 190.0 && e.width < 210.0)
.expect("parent");
let abs_child = parent_el
.children
.iter()
.find(|e| e.width > 45.0 && e.width < 55.0)
.expect("abs child");
let page_left = PageConfig::default().margin.left;
let page_top = PageConfig::default().margin.top;
assert!(
(abs_child.x - (page_left + 10.0)).abs() < 1.0,
"absolute escapes to the page: x {} should be page_left + 10 ({})",
abs_child.x,
page_left + 10.0
);
assert!(
(abs_child.y - (page_top + 10.0)).abs() < 1.0,
"absolute escapes to the page: y {} should be page_top + 10 ({})",
abs_child.y,
page_top + 10.0
);
assert!(
abs_child.x < parent_el.x,
"child must no longer be parent-relative (parent is 50pt further in)"
);
}
#[test]
fn text_transform_none_passthrough() {
assert_eq!(
apply_text_transform("Hello World", TextTransform::None),
"Hello World"
);
}
#[test]
fn text_transform_uppercase() {
assert_eq!(
apply_text_transform("hello world", TextTransform::Uppercase),
"HELLO WORLD"
);
}
#[test]
fn text_transform_lowercase() {
assert_eq!(
apply_text_transform("HELLO WORLD", TextTransform::Lowercase),
"hello world"
);
}
#[test]
fn text_transform_capitalize() {
assert_eq!(
apply_text_transform("hello world", TextTransform::Capitalize),
"Hello World"
);
assert_eq!(
apply_text_transform(" hello world ", TextTransform::Capitalize),
" Hello World "
);
assert_eq!(
apply_text_transform("already Capitalized", TextTransform::Capitalize),
"Already Capitalized"
);
}
#[test]
fn text_transform_capitalize_empty() {
assert_eq!(apply_text_transform("", TextTransform::Capitalize), "");
}
#[test]
fn apply_char_transform_uppercase() {
assert_eq!(
apply_char_transform('a', TextTransform::Uppercase, false),
'A'
);
assert_eq!(
apply_char_transform('A', TextTransform::Uppercase, false),
'A'
);
}
#[test]
fn apply_char_transform_capitalize_word_start() {
assert_eq!(
apply_char_transform('h', TextTransform::Capitalize, true),
'H'
);
assert_eq!(
apply_char_transform('h', TextTransform::Capitalize, false),
'h'
);
}
// ── flex-grow in column direction ──
#[test]
fn column_flex_grow_single_child_fills_container() {
// A column container with fixed height 300pt and a single child with flex_grow: 1.
// The child should expand to fill the entire 300pt.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let child = make_styled_view(
Style {
flex_grow: Some(1.0),
..Default::default()
},
vec![make_text("Short", 12.0)],
);
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(300.0)),
..Default::default()
},
vec![child],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page.elements.iter().find(|e| !e.children.is_empty());
assert!(container_el.is_some());
let container_el = container_el.unwrap();
assert!(
(container_el.height - 300.0).abs() < 1.0,
"Container should be 300pt, got {}",
container_el.height
);
let child_el = &container_el.children[0];
assert!(
(child_el.height - 300.0).abs() < 1.0,
"flex-grow child should expand to 300pt, got {}",
child_el.height
);
}
#[test]
fn column_flex_grow_two_children_proportional() {
// Two children: one with flex_grow: 1, one with flex_grow: 2.
// They should share remaining space proportionally (1:2).
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let child1 = make_styled_view(
Style {
flex_grow: Some(1.0),
..Default::default()
},
vec![make_text("A", 12.0)],
);
let child2 = make_styled_view(
Style {
flex_grow: Some(2.0),
..Default::default()
},
vec![make_text("B", 12.0)],
);
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(300.0)),
..Default::default()
},
vec![child1, child2],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page
.elements
.iter()
.find(|e| e.children.len() == 2)
.expect("Should find container with two children");
let c1 = &container_el.children[0];
let c2 = &container_el.children[1];
// Both children have the same natural height (one line of text).
// The slack is split 1:2 between them.
// So child2 should be roughly twice as much taller than child1's growth.
let total = c1.height + c2.height;
assert!(
(total - 300.0).abs() < 2.0,
"Children should sum to ~300pt, got {}",
total
);
// child2.height should be roughly 2x child1.height
// (not exact because natural heights are equal, but growth is 1:2)
let ratio = c2.height / c1.height;
assert!(
ratio > 1.3 && ratio < 2.5,
"child2/child1 ratio should be between 1.3 and 2.5, got {}",
ratio
);
}
#[test]
fn column_flex_grow_mixed_grow_and_fixed() {
// One fixed child (no flex_grow) and one flex_grow child.
// The flex_grow child takes all remaining space.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let fixed_child = make_styled_view(
Style {
height: Some(Dimension::Pt(50.0)),
..Default::default()
},
vec![make_text("Fixed", 12.0)],
);
let grow_child = make_styled_view(
Style {
flex_grow: Some(1.0),
..Default::default()
},
vec![make_text("Grow", 12.0)],
);
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(300.0)),
..Default::default()
},
vec![fixed_child, grow_child],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page
.elements
.iter()
.find(|e| e.children.len() == 2)
.expect("Should find container with two children");
let fixed_el = &container_el.children[0];
let grow_el = &container_el.children[1];
// Fixed child stays at 50pt
assert!(
(fixed_el.height - 50.0).abs() < 1.0,
"Fixed child should stay at 50pt, got {}",
fixed_el.height
);
// Grow child takes remaining ~250pt
assert!(
(grow_el.height - 250.0).abs() < 2.0,
"Grow child should expand to ~250pt, got {}",
grow_el.height
);
}
#[test]
fn column_flex_grow_page_level() {
// flex_grow: 1 on a direct Page child should fill the page content area.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let grow_child = make_styled_view(
Style {
flex_grow: Some(1.0),
..Default::default()
},
vec![make_text("Fill page", 12.0)],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![grow_child],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
// The child should fill the page content height
assert!(
!page.elements.is_empty(),
"Page should have at least one element"
);
let content_height = page.height - page.config.margin.top - page.config.margin.bottom;
let el = &page.elements[0];
assert!(
(el.height - content_height).abs() < 2.0,
"Page-level flex-grow child should fill content height ({}), got {}",
content_height,
el.height
);
}
#[test]
fn column_flex_grow_with_justify_content() {
// flex-grow and justify-content: center should work together.
// A fixed child + a grow child + justify-content: center.
// After grow fills the space, there's no slack left for justify, so positions stay as-is.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let fixed_child = make_styled_view(
Style {
height: Some(Dimension::Pt(50.0)),
..Default::default()
},
vec![make_text("Top", 12.0)],
);
let grow_child = make_styled_view(
Style {
flex_grow: Some(1.0),
..Default::default()
},
vec![make_text("Fill", 12.0)],
);
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(300.0)),
justify_content: Some(JustifyContent::Center),
..Default::default()
},
vec![fixed_child, grow_child],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page
.elements
.iter()
.find(|e| e.children.len() == 2)
.expect("Should find container");
// After flex-grow absorbs all slack, justify-content has nothing to distribute.
// First child should be at the top of the container.
let first_child = &container_el.children[0];
assert!(
(first_child.y - container_el.y).abs() < 1.0,
"First child should be at top of container"
);
// Children should still sum to container height
let total = container_el.children[0].height + container_el.children[1].height;
assert!(
(total - 300.0).abs() < 2.0,
"Children should fill container, got {}",
total
);
}
#[test]
fn column_flex_grow_child_justify_content_center() {
// A flex-grow child with justify-content: center should vertically center its content.
// This is the cover-page bug: the inner View grows via flex but its children stay at top.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
// Inner content: a small fixed-height box
let inner_box = make_styled_view(
Style {
height: Some(Dimension::Pt(40.0)),
..Default::default()
},
vec![make_text("Centered", 12.0)],
);
// The grow child: flex: 1, justify-content: center
let grow_child = make_styled_view(
Style {
flex_grow: Some(1.0),
flex_direction: Some(FlexDirection::Column),
justify_content: Some(JustifyContent::Center),
..Default::default()
},
vec![inner_box],
);
// Outer column container with fixed height
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(400.0)),
..Default::default()
},
vec![grow_child],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
// Find the container (has 1 child = the grow child)
let container_el = page
.elements
.iter()
.find(|e| e.height > 350.0 && e.children.len() == 1)
.expect("Should find outer container");
let grow_el = &container_el.children[0];
assert!(
(grow_el.height - 400.0).abs() < 2.0,
"Grow child should expand to 400, got {}",
grow_el.height
);
// The inner box should be vertically centered within the grow child
let inner_el = &grow_el.children[0];
let expected_center = grow_el.y + grow_el.height / 2.0;
let actual_center = inner_el.y + inner_el.height / 2.0;
assert!(
(actual_center - expected_center).abs() < 2.0,
"Inner box should be vertically centered. Expected center ~{}, got ~{}",
expected_center,
actual_center
);
}
#[test]
fn column_flex_grow_child_justify_content_flex_end() {
// A flex-grow child with justify-content: flex-end should push content to the bottom.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let inner_box = make_styled_view(
Style {
height: Some(Dimension::Pt(30.0)),
..Default::default()
},
vec![make_text("Bottom", 12.0)],
);
let grow_child = make_styled_view(
Style {
flex_grow: Some(1.0),
flex_direction: Some(FlexDirection::Column),
justify_content: Some(JustifyContent::FlexEnd),
..Default::default()
},
vec![inner_box],
);
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(300.0)),
..Default::default()
},
vec![grow_child],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page
.elements
.iter()
.find(|e| e.height > 250.0 && e.children.len() == 1)
.expect("Should find outer container");
let grow_el = &container_el.children[0];
let inner_el = &grow_el.children[0];
// Inner box should be near the bottom of the grow child
let inner_bottom = inner_el.y + inner_el.height;
let grow_bottom = grow_el.y + grow_el.height;
assert!(
(inner_bottom - grow_bottom).abs() < 2.0,
"Inner box bottom ({}) should align with grow child bottom ({})",
inner_bottom,
grow_bottom
);
}
#[test]
fn column_flex_grow_child_no_justify_unchanged() {
// Regression: flex-grow with default FlexStart should keep content at top.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let inner_box = make_styled_view(
Style {
height: Some(Dimension::Pt(50.0)),
..Default::default()
},
vec![make_text("Top", 12.0)],
);
let grow_child = make_styled_view(
Style {
flex_grow: Some(1.0),
flex_direction: Some(FlexDirection::Column),
// No justify-content set — defaults to FlexStart
..Default::default()
},
vec![inner_box],
);
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(300.0)),
..Default::default()
},
vec![grow_child],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page
.elements
.iter()
.find(|e| e.height > 250.0 && e.children.len() == 1)
.expect("Should find outer container");
let grow_el = &container_el.children[0];
let inner_el = &grow_el.children[0];
// Inner box should stay at the top of the grow child
assert!(
(inner_el.y - grow_el.y).abs() < 2.0,
"Inner box ({}) should be at top of grow child ({})",
inner_el.y,
grow_el.y
);
}
#[test]
fn column_flex_grow_child_align_items_center() {
// A flex-grown View with align_items: Center should horizontally center its Text child.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
let text = make_text("Hello", 12.0);
let grow_child = make_styled_view(
Style {
flex_grow: Some(1.0),
flex_direction: Some(FlexDirection::Column),
align_items: Some(AlignItems::Center),
..Default::default()
},
vec![text],
);
let container = make_styled_view(
Style {
flex_direction: Some(FlexDirection::Column),
height: Some(Dimension::Pt(300.0)),
..Default::default()
},
vec![grow_child],
);
let doc = Document {
children: vec![Node::page(
PageConfig::default(),
Style::default(),
vec![container],
)],
metadata: Default::default(),
default_page: PageConfig::default(),
first_page: None,
left_page: None,
right_page: None,
named_pages: Default::default(),
attachments: vec![],
zugferd: None,
fonts: vec![],
tagged: false,
pdfa: None,
default_style: None,
embedded_data: None,
flatten_forms: false,
pdf_ua: false,
certification: None,
};
let pages = engine.layout(&doc, &font_context);
let page = &pages[0];
let container_el = page
.elements
.iter()
.find(|e| e.height > 250.0 && e.children.len() == 1)
.expect("Should find outer container");
let grow_el = &container_el.children[0];
assert!(
!grow_el.children.is_empty(),
"Grow child should have text child"
);
let text_el = &grow_el.children[0];
let text_center = text_el.x + text_el.width / 2.0;
let grow_center = grow_el.x + grow_el.width / 2.0;
assert!(
(text_center - grow_center).abs() < 2.0,
"Text center ({}) should be near grow child center ({})",
text_center,
grow_center
);
}
#[test]
fn image_intrinsic_width_respects_height_constraint() {
// An Image with only a height prop should compute intrinsic width from
// aspect ratio, not return the raw pixel width. This ensures align-items:
// center can correctly center images.
let engine = LayoutEngine::new();
let font_context = FontContext::new();
// Use a 1x1 PNG data URI (known dimensions: 1x1 pixels)
let one_px_png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
let image_node = Node {
kind: NodeKind::Image {
src: one_px_png.to_string(),
width: None,
height: Some(36.0),
},
style: Style::default(),
children: vec![],
id: None,
source_location: None,
bookmark: None,
href: None,
alt: None,
};
let resolved = image_node.style.resolve(None, 0.0);
let intrinsic = engine.measure_intrinsic_width(&image_node, &resolved, &font_context);
// 1x1 pixel image with height: 36 should give width = 36 / (1/1) = 36
assert!(
(intrinsic - 36.0).abs() < 1.0,
"Intrinsic width should be ~36 for 1:1 aspect image with height 36, got {}",
intrinsic
);
}
}