rdocx-layout 0.10.1

Layout engine for converting DOCX flow model to positioned frames
Documentation
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
//! Pagination: distribute blocks across pages with constraints.
//!
//! Handles page breaks, widow/orphan control, keep-with-next,
//! keep-lines-together, and header/footer placement.

use crate::block::{
    AnchoredContent, AnchoredDrawing, CellBlockSemantics, LayoutBlock, LayoutBlockLike,
    ParagraphBlock, ParagraphView, ShapePreset, SharedLayoutBlock,
};
use std::collections::HashMap;

use oxml_layout::{
    Align, Color, FontManager, GlyphRun, GroupElement, LayoutLine, LineItem, MediaId, NoteRef,
    NoteStream, OutlineEntry, PageFrame, Path, Point, PositionedElement, Rect, Transform,
    Underline, break_into_lines,
};

use rdocx_oxml::drawing::{
    AnchorAlignH, AnchorAlignV, ST_RelativeFromH, ST_RelativeFromV, WrapType,
};
use rdocx_oxml::shared::ST_Border;

use crate::input::{ImageData, MediaRegistry};
use crate::notes::{
    NOTE_INDENT, NOTE_SEPARATOR_OFFSET, NoteLayout, NoteRegistry, SEPARATOR_WIDTH_FRACTION,
};

/// A wrapping drawing that has been placed on the page being built.
#[derive(Debug, Clone, Copy)]
struct PlacedWrap {
    rect: Rect,
    wrap: WrapType,
    dist_top: f64,
    dist_bottom: f64,
    dist_left: f64,
    dist_right: f64,
}

impl PlacedWrap {
    /// Top of the band this drawing keeps text out of.
    fn keep_out_top(&self) -> f64 {
        self.rect.y - self.dist_top
    }

    /// Bottom of the band this drawing keeps text out of.
    fn keep_out_bottom(&self) -> f64 {
        self.rect.y + self.rect.height + self.dist_bottom
    }
}

/// A resolved border edge: (thickness in pt, color, optional dash pattern as (dash, gap)).
type BorderEdge = (f64, Color, Option<(f64, f64)>);

/// Page geometry derived from section properties.
#[derive(Debug, Clone, Copy)]
pub struct PageGeometry {
    pub page_width: f64,
    pub page_height: f64,
    pub margin_top: f64,
    pub margin_right: f64,
    pub margin_bottom: f64,
    pub margin_left: f64,
    pub header_distance: f64,
    pub footer_distance: f64,
}

impl PageGeometry {
    /// Content area width.
    pub fn content_width(&self) -> f64 {
        self.page_width - self.margin_left - self.margin_right
    }

    /// Content area height.
    pub fn content_height(&self) -> f64 {
        self.page_height - self.margin_top - self.margin_bottom
    }
}

impl Default for PageGeometry {
    fn default() -> Self {
        // US Letter with 1" margins
        PageGeometry {
            page_width: 612.0,
            page_height: 792.0,
            margin_top: 72.0,
            margin_right: 72.0,
            margin_bottom: 72.0,
            margin_left: 72.0,
            header_distance: 36.0,
            footer_distance: 36.0,
        }
    }
}

/// Header/footer content already laid out as paragraph blocks.
pub struct HeaderFooterContent {
    pub header_blocks: Vec<ParagraphBlock>,
    pub footer_blocks: Vec<ParagraphBlock>,
    /// First-page header blocks (used when title_pg is true).
    pub first_header_blocks: Vec<ParagraphBlock>,
    /// First-page footer blocks (used when title_pg is true).
    pub first_footer_blocks: Vec<ParagraphBlock>,
    /// Even-page header blocks.
    pub even_header_blocks: Vec<ParagraphBlock>,
    /// Even-page footer blocks.
    pub even_footer_blocks: Vec<ParagraphBlock>,
    /// Whether Word selects the even header and footer variants.
    pub even_headers_active: bool,
    /// Default-header watermark, already positioned in page coordinates.
    pub watermark: Option<oxml_layout::GroupElement>,
    /// First-page-header watermark.
    pub first_watermark: Option<oxml_layout::GroupElement>,
    /// Even-page-header watermark.
    pub even_watermark: Option<oxml_layout::GroupElement>,
}

/// A section with its blocks, geometry, and header/footer content.
pub struct Section {
    pub blocks: Vec<LayoutBlock>,
    pub geometry: PageGeometry,
    pub header_footer: Option<HeaderFooterContent>,
    /// Whether this section uses a different first page header/footer.
    pub title_pg: bool,
    /// Displayed page number assigned to the first page of this section.
    pub page_number_start: Option<usize>,
}

pub(crate) struct SharedSection {
    pub blocks: Vec<SharedLayoutBlock>,
    pub geometry: PageGeometry,
    pub header_footer: Option<HeaderFooterContent>,
    pub title_pg: bool,
    pub page_number_start: Option<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PaginationCheckpoint {
    pub next_block_index: usize,
    pub page_count: usize,
    pub next_header_page_number: usize,
}

pub(crate) struct RecordedPagination {
    pub pages: Vec<PageFrame>,
    pub outlines: Vec<OutlineEntry>,
    pub checkpoints: Vec<PaginationCheckpoint>,
    pub stopped_at: Option<PaginationCheckpoint>,
}

/// Paginate across multiple sections, each with its own geometry and header/footer.
pub fn paginate_sections(
    sections: &[Section],
    fm: &FontManager,
    media: &MediaRegistry,
    notes: &NoteRegistry,
) -> (Vec<PageFrame>, Vec<OutlineEntry>) {
    let media = media.media();
    if sections.is_empty() {
        return (
            vec![PageFrame::new(1, 612.0, 792.0, Vec::new())],
            Vec::new(),
        );
    }

    // For a single section, delegate to the existing paginate function
    if sections.len() == 1 {
        let s = &sections[0];
        return paginate_with_media(
            &s.blocks,
            s.geometry,
            s.header_footer.as_ref(),
            s.title_pg,
            fm,
            media,
            notes,
            1,
            s.page_number_start.unwrap_or(1),
        );
    }

    // Multi-section pagination
    let mut all_pages = Vec::new();
    let mut all_outlines = Vec::new();
    let mut page_offset = 0;
    let mut next_section_page_number = 1usize;

    for section in sections {
        let section_page_number = section
            .page_number_start
            .unwrap_or(next_section_page_number);
        let (mut pages, mut outlines) = paginate_with_media(
            &section.blocks,
            section.geometry,
            section.header_footer.as_ref(),
            section.title_pg,
            fm,
            media,
            notes,
            page_offset + 1,
            section_page_number,
        );

        next_section_page_number = section_page_number.saturating_add(pages.len());
        page_offset += pages.len();
        all_pages.append(&mut pages);
        all_outlines.append(&mut outlines);
    }

    // If a section produced no pages (empty blocks), we might have duplicates
    // Renumber pages sequentially
    for (i, page) in all_pages.iter_mut().enumerate() {
        page.page_number = i + 1;
    }

    (all_pages, all_outlines)
}

pub(crate) fn paginate_shared_sections(
    sections: &[SharedSection],
    fm: &FontManager,
    media: &MediaRegistry,
    notes: &NoteRegistry,
) -> (Vec<PageFrame>, Vec<OutlineEntry>) {
    let media = media.media();
    if sections.is_empty() {
        return (
            vec![PageFrame::new(1, 612.0, 792.0, Vec::new())],
            Vec::new(),
        );
    }
    if sections.len() == 1 {
        let section = &sections[0];
        return paginate_with_media(
            &section.blocks,
            section.geometry,
            section.header_footer.as_ref(),
            section.title_pg,
            fm,
            media,
            notes,
            1,
            section.page_number_start.unwrap_or(1),
        );
    }

    let mut pages = Vec::new();
    let mut outlines = Vec::new();
    let mut page_offset = 0;
    let mut next_section_page_number = 1usize;
    for section in sections {
        let section_page_number = section
            .page_number_start
            .unwrap_or(next_section_page_number);
        let (mut section_pages, mut section_outlines) = paginate_with_media(
            &section.blocks,
            section.geometry,
            section.header_footer.as_ref(),
            section.title_pg,
            fm,
            media,
            notes,
            page_offset + 1,
            section_page_number,
        );
        next_section_page_number = section_page_number.saturating_add(section_pages.len());
        page_offset += section_pages.len();
        pages.append(&mut section_pages);
        outlines.append(&mut section_outlines);
    }
    for (index, page) in pages.iter_mut().enumerate() {
        page.page_number = index + 1;
    }
    (pages, outlines)
}

pub(crate) fn paginate_shared_single_section_recorded(
    section: &SharedSection,
    fm: &FontManager,
    media: &MediaRegistry,
    notes: &NoteRegistry,
    restart: Option<PaginationCheckpoint>,
    stop_at: Option<PaginationCheckpoint>,
) -> RecordedPagination {
    let checkpoint = restart.unwrap_or(PaginationCheckpoint {
        next_block_index: 0,
        page_count: 0,
        next_header_page_number: section.page_number_start.unwrap_or(1),
    });
    let context = PassContext {
        geometry: section.geometry,
        header_footer: section.header_footer.as_ref(),
        title_pg: section.title_pg,
        fm,
        media: media.media(),
        notes,
        first_page_number: checkpoint.page_count + 1,
        first_header_page_number: checkpoint.next_header_page_number,
    };
    let result = paginate_pass_from(
        &section.blocks,
        &context,
        &ResolvedWraps::new(),
        checkpoint.next_block_index,
        checkpoint.page_count == 0,
        stop_at,
    );
    let mut checkpoints = result.checkpoints;
    if checkpoint.page_count == 0 {
        checkpoints.insert(0, checkpoint);
    }
    RecordedPagination {
        pages: result.pages,
        outlines: result.outlines,
        checkpoints,
        stopped_at: result.stopped_at,
    }
}

/// Paginate a sequence of blocks into pages.
pub fn paginate(
    blocks: &[LayoutBlock],
    geometry: PageGeometry,
    header_footer: Option<&HeaderFooterContent>,
    title_pg: bool,
    _fm: &FontManager,
    media: &MediaRegistry,
    notes: &NoteRegistry,
) -> (Vec<PageFrame>, Vec<OutlineEntry>) {
    paginate_with_media(
        blocks,
        geometry,
        header_footer,
        title_pg,
        _fm,
        media.media(),
        notes,
        1,
        1,
    )
}

/// Where a pass placed the wrapping drawings whose vertical anchor is their own
/// paragraph, keyed by block index and the drawing's index within that block.
///
/// The key is stable across passes because both passes walk the same block list
/// in the same order.
type ResolvedWraps = HashMap<(usize, usize), (usize, PlacedWrap)>;

/// Whether any block anchors a wrapping drawing to its own paragraph or line.
///
/// A document without one paginates in a single pass, which is every sample and
/// every corpus document today.
fn has_paragraph_relative_wrap<B: LayoutBlockLike>(blocks: &[B]) -> bool {
    blocks.iter().any(|block| {
        let Some(para) = block.paragraph() else {
            return false;
        };
        para.anchored.iter().any(is_paragraph_relative_wrap)
    })
}

/// The filter both the look-ahead and the two-pass predicate agree on.
fn is_paragraph_relative_wrap(anchored: &AnchoredDrawing) -> bool {
    anchored.wrap != WrapType::None
        && matches!(
            anchored.rel_v,
            ST_RelativeFromV::Paragraph | ST_RelativeFromV::Line
        )
}

fn paginate_with_media<B: LayoutBlockLike>(
    blocks: &[B],
    geometry: PageGeometry,
    header_footer: Option<&HeaderFooterContent>,
    title_pg: bool,
    _fm: &FontManager,
    media: &HashMap<MediaId, ImageData>,
    notes: &NoteRegistry,
    first_page_number: usize,
    first_header_page_number: usize,
) -> (Vec<PageFrame>, Vec<OutlineEntry>) {
    let context = PassContext {
        geometry,
        header_footer,
        title_pg,
        fm: _fm,
        media,
        notes,
        first_page_number,
        first_header_page_number,
    };
    let first = paginate_pass(blocks, &context, &ResolvedWraps::new());

    // A paragraph-relative drawing has no vertical position until its own
    // paragraph is placed, so the first pass cannot offer one to the text above
    // it. The second pass can, because the first recorded where each landed.
    //
    // Two passes, not a fixed point. The second pass reflows earlier text, which
    // can move the drawing's own paragraph, so the rect it offered may be
    // slightly stale. Iterating is not guaranteed to terminate: growing a
    // paragraph can push a drawing to the next page, which shrinks the
    // paragraph, which pulls it back.
    if !has_paragraph_relative_wrap(blocks) {
        return (first.pages, first.outlines);
    }

    let second = paginate_pass(blocks, &context, &first.resolved);
    (second.pages, second.outlines)
}

/// One pagination pass, and what it learned about paragraph-relative wraps.
struct PassResult {
    pages: Vec<PageFrame>,
    outlines: Vec<OutlineEntry>,
    resolved: ResolvedWraps,
    checkpoints: Vec<PaginationCheckpoint>,
    stopped_at: Option<PaginationCheckpoint>,
}

/// Everything a pass needs that is the same for both passes.
///
/// Built once and borrowed twice, so the eight-value argument list appears in
/// one place rather than at each call.
struct PassContext<'a> {
    geometry: PageGeometry,
    header_footer: Option<&'a HeaderFooterContent>,
    title_pg: bool,
    fm: &'a FontManager,
    media: &'a HashMap<MediaId, ImageData>,
    notes: &'a NoteRegistry,
    first_page_number: usize,
    first_header_page_number: usize,
}

fn paginate_pass<B: LayoutBlockLike>(
    blocks: &[B],
    context: &PassContext,
    resolved_in: &ResolvedWraps,
) -> PassResult {
    paginate_pass_from(blocks, context, resolved_in, 0, true, None)
}

fn paginate_pass_from<B: LayoutBlockLike>(
    blocks: &[B],
    context: &PassContext,
    resolved_in: &ResolvedWraps,
    first_block_index: usize,
    is_first_page: bool,
    stop_at: Option<PaginationCheckpoint>,
) -> PassResult {
    if first_block_index >= blocks.len() && !is_first_page {
        return PassResult {
            pages: Vec::new(),
            outlines: Vec::new(),
            resolved: resolved_in.clone(),
            checkpoints: Vec::new(),
            stopped_at: None,
        };
    }
    let geometry = context.geometry;
    let mut pager = Pager::new(
        geometry,
        context.header_footer,
        context.title_pg,
        context.media,
        context.notes,
        context.fm,
        resolved_in,
        context.first_page_number,
        context.first_header_page_number,
        is_first_page,
        stop_at,
    );

    for (block_idx, block) in blocks.iter().enumerate().skip(first_block_index) {
        // Check for page break before
        if block.page_break_before() && pager.has_content() {
            pager.finish_page_before(block_idx);
            if pager.stopped_at.is_some() {
                break;
            }
        }

        if let Some(para) = block.paragraph() {
            // Record heading outline entry before rendering
            if let (Some(level), Some(title)) = (para.heading_level, &para.heading_text) {
                pager.outlines.push(OutlineEntry {
                    title: title.clone(),
                    level,
                    page_index: pager.page_number - 1,
                    y_position: pager.geometry.margin_top + pager.cursor_y,
                });
            }
            paginate_paragraph(para, block_idx, blocks, &mut pager);
            if pager.stopped_at.is_some() {
                break;
            }
        } else if let Some(table) = block.table() {
            let table_x = geometry.margin_left + table.table_indent;
            let tbl_borders = table.borders.as_ref();

            for (row_idx, row) in table.rows.iter().enumerate() {
                let row_semantics = table
                    .semantics
                    .and_then(|semantics| semantics.rows.get(row_idx));
                if pager.cursor_y + row.height > pager.available_height() && pager.has_content() {
                    pager.finish_page();

                    // Repeat header rows
                    for &hdr_idx in &table.header_row_indices {
                        if hdr_idx < row_idx {
                            let hdr_row = &table.rows[hdr_idx];
                            render_table_row(
                                hdr_row,
                                table
                                    .semantics
                                    .and_then(|semantics| semantics.rows.get(hdr_idx)),
                                &table.col_widths,
                                table_x,
                                pager.geometry.margin_top + pager.cursor_y,
                                &pager.geometry,
                                pager.page_number,
                                tbl_borders,
                                &mut pager.elements,
                                &mut pager.behind_elements,
                                pager.media,
                            );
                            pager.cursor_y += hdr_row.height;
                            pager.mark_content();
                        }
                    }
                }

                render_table_row(
                    row,
                    row_semantics,
                    &table.col_widths,
                    table_x,
                    pager.geometry.margin_top + pager.cursor_y,
                    &pager.geometry,
                    pager.page_number,
                    tbl_borders,
                    &mut pager.elements,
                    &mut pager.behind_elements,
                    pager.media,
                );
                pager.cursor_y += row.height;
                pager.mark_content();
            }
        }
    }

    let resolved = std::mem::take(&mut pager.resolved_out);
    let checkpoints = std::mem::take(&mut pager.checkpoints);
    let stopped_at = pager.stopped_at;
    let (pages, outlines) = if stopped_at.is_some() {
        (
            std::mem::take(&mut pager.pages),
            std::mem::take(&mut pager.outlines),
        )
    } else {
        pager.flush()
    };
    PassResult {
        pages,
        outlines,
        resolved,
        checkpoints,
        stopped_at,
    }
}

/// Helper struct to track page state during pagination.
struct Pager<'a> {
    pages: Vec<PageFrame>,
    elements: Vec<PositionedElement>,
    /// Anchored drawings marked behindDoc. Held apart from the normal element
    /// list so they can be emitted before everything else on the page, which
    /// is what puts them underneath the text.
    behind_elements: Vec<PositionedElement>,
    cursor_y: f64,
    page_number: usize,
    header_page_number: usize,
    content_height: f64,
    geometry: PageGeometry,
    header_footer: Option<&'a HeaderFooterContent>,
    has_content_flag: bool,
    outlines: Vec<OutlineEntry>,
    /// Whether the current page is the first page of the section.
    is_first_page: bool,
    /// Whether this section uses different first page header/footer.
    title_pg: bool,
    media: &'a HashMap<MediaId, ImageData>,
    /// Every note the document defines, laid out once before pagination.
    notes: &'a NoteRegistry,
    /// Notes first referenced by a line placed on the page being built, in
    /// reference order. Line counts are decided when the page is finished,
    /// since that is when the leftover height is known.
    page_note_ids: Vec<NoteRef>,
    /// Note content that did not fit on the previous page, as (id, next line).
    /// Placed before this page's own notes, and drawn without a marker.
    pending_notes: Vec<(NoteRef, usize)>,
    /// Re-breaking a paragraph around a drawing needs the shaper.
    fm: &'a FontManager,
    /// Rectangles of the wrapping drawings already placed on this page, with
    /// the wrap mode and text distances each one asks for.
    page_wraps: Vec<PlacedWrap>,
    /// Where the body's last mark sits, ignoring trailing paragraph spacing.
    ///
    /// `cursor_y` includes the space after the final paragraph, and that space
    /// collapses at a page break. Measuring the note area from `cursor_y`
    /// would let it eat into the height that was reserved, which is enough to
    /// push a note off the page its own reference sits on.
    ink_bottom: f64,
    /// Where the previous pass placed each paragraph-relative wrapping drawing.
    /// Empty on the first pass, which is what makes that pass identical to a
    /// single-pass run.
    resolved_in: &'a ResolvedWraps,
    /// Where this pass is placing them, for the pass that follows.
    resolved_out: ResolvedWraps,
    checkpoints: Vec<PaginationCheckpoint>,
    stop_at: Option<PaginationCheckpoint>,
    stopped_at: Option<PaginationCheckpoint>,
}

impl<'a> Pager<'a> {
    fn new(
        geometry: PageGeometry,
        header_footer: Option<&'a HeaderFooterContent>,
        title_pg: bool,
        media: &'a HashMap<MediaId, ImageData>,
        notes: &'a NoteRegistry,
        fm: &'a FontManager,
        resolved_in: &'a ResolvedWraps,
        first_page_number: usize,
        first_header_page_number: usize,
        is_first_page: bool,
        stop_at: Option<PaginationCheckpoint>,
    ) -> Self {
        Pager {
            pages: Vec::new(),
            elements: Vec::new(),
            behind_elements: Vec::new(),
            cursor_y: 0.0,
            page_number: first_page_number,
            header_page_number: first_header_page_number,
            content_height: geometry.content_height(),
            geometry,
            header_footer,
            has_content_flag: false,
            outlines: Vec::new(),
            is_first_page,
            title_pg,
            media,
            notes,
            page_note_ids: Vec::new(),
            pending_notes: Vec::new(),
            fm,
            page_wraps: Vec::new(),
            ink_bottom: 0.0,
            resolved_in,
            resolved_out: ResolvedWraps::new(),
            checkpoints: Vec::new(),
            stop_at,
            stopped_at: None,
        }
    }

    fn has_content(&self) -> bool {
        self.has_content_flag
    }

    /// Height the note area needs for a given set of notes, in full.
    ///
    /// Zero when there are none, so a page without notes keeps every point of
    /// its content height.
    fn reserve_for(&self, carried: &[(NoteRef, usize)], fresh: &[NoteRef]) -> f64 {
        if carried.is_empty() && fresh.is_empty() {
            return 0.0;
        }
        let carried_height: f64 = carried
            .iter()
            .filter_map(|(id, first)| {
                self.notes
                    .get(*id, self.geometry.content_width())
                    .map(|note| note.height_from(*first))
            })
            .sum();
        let fresh_height: f64 = fresh
            .iter()
            .filter_map(|id| {
                self.notes
                    .get(*id, self.geometry.content_width())
                    .map(NoteLayout::height)
            })
            .sum();
        NOTE_SEPARATOR_OFFSET + carried_height + fresh_height
    }

    /// The note area currently committed for the page being built.
    fn reserved_height(&self) -> f64 {
        self.reserve_for(&self.pending_notes, &self.page_note_ids)
    }

    /// Content height still usable by body text on this page.
    fn available_height(&self) -> f64 {
        (self.content_height - self.reserved_height()).max(0.0)
    }

    /// What the note area would cost if `lines` were placed on this page,
    /// without committing to placing them.
    ///
    /// A paragraph is measured before anyone knows which page it lands on, so
    /// its notes must be priced without being claimed. Claiming first and
    /// moving the paragraph afterwards leaves the note stranded on the page
    /// before its own reference.
    fn available_height_for(&self, lines: &[LayoutLine]) -> f64 {
        let mut fresh = self.page_note_ids.clone();
        for line in lines {
            for id in page_foot_notes_in_line(line) {
                if self.notes.get(id, self.geometry.content_width()).is_some()
                    && !fresh.contains(&id)
                    && !self.pending_notes.iter().any(|(pending, _)| *pending == id)
                {
                    fresh.push(id);
                }
            }
        }
        (self.content_height - self.reserve_for(&self.pending_notes, &fresh)).max(0.0)
    }

    /// Record the footnotes referenced by lines about to be placed.
    ///
    /// Endnotes are ignored here. They are emitted at the document end, so
    /// they cost the page carrying their reference nothing.
    fn claim_notes(&mut self, lines: &[LayoutLine]) {
        for id in lines.iter().flat_map(page_foot_notes_in_line) {
            {
                if self.notes.get(id, self.geometry.content_width()).is_some()
                    && !self.page_note_ids.contains(&id)
                    && !self.pending_notes.iter().any(|(pending, _)| *pending == id)
                {
                    self.page_note_ids.push(id);
                }
            }
        }
    }

    /// How many of `lines` fit, once the note area their references demand is
    /// taken out of the page.
    ///
    /// A line is admitted only if the whole note area still fits after it, so
    /// a note is not split merely because body text was greedy. The one
    /// exception is a page that has placed nothing yet: there the line goes
    /// down regardless and the note splits, because a page that admits neither
    /// body nor note makes no progress and pagination would not terminate.
    fn count_lines_that_fit_with_notes(&self, lines: &[LayoutLine], start_y: f64) -> usize {
        let mut fresh = self.page_note_ids.clone();
        let mut used = 0.0;

        for (index, line) in lines.iter().enumerate() {
            for id in page_foot_notes_in_line(line) {
                if self.notes.get(id, self.geometry.content_width()).is_some()
                    && !fresh.contains(&id)
                    && !self.pending_notes.iter().any(|(pending, _)| *pending == id)
                {
                    fresh.push(id);
                }
            }

            let reserve = self.reserve_for(&self.pending_notes, &fresh);
            if start_y + used + line.height > self.content_height - reserve + 0.01 {
                let page_is_empty = !self.has_content() && used == 0.0 && index == 0;
                if !page_is_empty {
                    return index;
                }
            }
            used += line.height;
        }

        lines.len()
    }

    fn mark_content(&mut self) {
        self.has_content_flag = true;
    }

    /// Resolve the wrapping drawings a paragraph carries, without placing
    /// them. Measuring a paragraph needs to know what it must flow around
    /// before anything is committed to the page.
    fn wrap_rects_for(
        &self,
        anchored: &[AnchoredDrawing],
        para_top: f64,
        indent_left: f64,
    ) -> Vec<PlacedWrap> {
        anchored
            .iter()
            .filter(|a| a.wrap != WrapType::None)
            .map(|a| PlacedWrap {
                rect: Rect {
                    x: resolve_anchor_h(
                        a.rel_h,
                        a.off_h,
                        a.align_h,
                        a.width,
                        &self.geometry,
                        indent_left,
                    ),
                    y: resolve_anchor_v(
                        a.rel_v,
                        a.off_v,
                        a.align_v,
                        a.height,
                        &self.geometry,
                        para_top,
                    ),
                    width: a.width,
                    height: a.height,
                },
                wrap: a.wrap,
                dist_top: a.dist_top,
                dist_bottom: a.dist_bottom,
                dist_left: a.dist_left,
                dist_right: a.dist_right,
            })
            .collect()
    }

    /// Wrapping drawings anchored to blocks after `block_idx`, positioned well
    /// enough to flow this block's text around them.
    ///
    /// A drawing anchored to a later paragraph still pushes earlier text aside,
    /// and Word documents do this routinely: the arrow beside a paragraph is
    /// often anchored to the paragraph after it. Where its position comes from
    /// depends on the frame it is measured against.
    ///
    /// A drawing framed by the page or a margin is positioned here, because
    /// that needs nothing from the block that owns it. A drawing framed by its
    /// own paragraph has no position until that paragraph is placed, so the
    /// first pass offers nothing for it and the second offers what the first
    /// recorded, for the drawings the first put on the page being built now.
    fn lookahead_wraps<B: LayoutBlockLike>(
        &self,
        block_idx: usize,
        blocks: &[B],
    ) -> Vec<PlacedWrap> {
        let mut out = Vec::new();
        let mut height = self.cursor_y;

        for (offset, block) in blocks.iter().enumerate().skip(block_idx + 1) {
            if block.page_break_before() || height > self.content_height {
                break;
            }
            height += block.space_before() + block.content_height() + block.space_after();

            let Some(para) = block.paragraph() else {
                continue;
            };
            for (anchor_idx, a) in para.anchored.iter().enumerate() {
                if a.wrap == WrapType::None {
                    continue;
                }
                if is_paragraph_relative_wrap(a) {
                    // Resolved by the previous pass, or not at all. The page
                    // check is what stops a drawing that landed overleaf from
                    // pushing this page's text aside.
                    if let Some((page, placed)) = self.resolved_in.get(&(offset, anchor_idx))
                        && *page == self.page_number
                    {
                        out.push(*placed);
                    }
                    continue;
                }
                out.extend(self.wrap_rects_for(std::slice::from_ref(a), 0.0, para.indent_left));
            }
        }

        out
    }

    /// Place the drawings anchored to a paragraph whose top sits at `para_top`,
    /// measured from the top of the content area.
    ///
    /// `block_idx` identifies the owning block, so a paragraph-relative
    /// wrapping drawing can be recorded for the pass that follows this one.
    fn place_anchored(
        &mut self,
        anchored: &[AnchoredDrawing],
        para_top: f64,
        indent_left: f64,
        block_idx: usize,
    ) {
        for (anchor_idx, a) in anchored.iter().enumerate() {
            let x = resolve_anchor_h(
                a.rel_h,
                a.off_h,
                a.align_h,
                a.width,
                &self.geometry,
                indent_left,
            );
            let y = resolve_anchor_v(
                a.rel_v,
                a.off_v,
                a.align_v,
                a.height,
                &self.geometry,
                para_top,
            );
            let rect = Rect {
                x,
                y,
                width: a.width,
                height: a.height,
            };

            if a.wrap != WrapType::None {
                let placed = PlacedWrap {
                    rect,
                    wrap: a.wrap,
                    dist_top: a.dist_top,
                    dist_bottom: a.dist_bottom,
                    dist_left: a.dist_left,
                    dist_right: a.dist_right,
                };
                if is_paragraph_relative_wrap(a) {
                    self.resolved_out
                        .insert((block_idx, anchor_idx), (self.page_number, placed));
                }
                self.page_wraps.push(placed);
            }

            let mut produced = anchored_elements(a, rect, &self.geometry, self.media);

            if a.behind_doc {
                self.behind_elements.append(&mut produced);
            } else {
                self.elements.append(&mut produced);
            }
        }
    }

    /// Draw the note area for the page being built, and carry what did not
    /// fit onto the next one.
    ///
    /// Notes sit above the bottom margin and grow upward, so the body text
    /// above them was already kept clear by `available_height`.
    fn place_page_notes(&mut self) {
        let mut queue: Vec<(NoteRef, usize, bool)> = self
            .pending_notes
            .drain(..)
            .map(|(id, first)| (id, first, true))
            .collect();
        queue.extend(self.page_note_ids.drain(..).map(|id| (id, 0usize, false)));

        if queue.is_empty() {
            return;
        }

        let opens_with_continuation = queue[0].2;
        let available = (self.content_height - self.ink_bottom - NOTE_SEPARATOR_OFFSET).max(0.0);

        // Decide how much of each note this page can hold.
        let mut placed: Vec<(NoteRef, usize, usize, bool)> = Vec::new();
        let mut used = 0.0;
        let mut carried: Vec<(NoteRef, usize)> = Vec::new();

        for (id, first, continued) in queue {
            let Some(note) = self.notes.get(id, self.geometry.content_width()) else {
                continue;
            };
            if !carried.is_empty() {
                // An earlier note already ran out of room, so everything
                // after it waits too, or the notes would be reordered.
                carried.push((id, first));
                continue;
            }

            let mut count = 0;
            for line in note.lines.iter().skip(first) {
                if used + line.height > available + 0.01 {
                    break;
                }
                used += line.height;
                count += 1;
            }

            if count > 0 {
                placed.push((id, first, count, continued));
            }
            if first + count < note.lines.len() {
                carried.push((id, first + count));
            }
        }

        self.pending_notes = carried;

        if placed.is_empty() {
            return;
        }

        let total: f64 = placed
            .iter()
            .filter_map(|(id, first, count, _)| {
                self.notes
                    .get(*id, self.geometry.content_width())
                    .map(|n| n.height_of(*first, *count))
            })
            .sum();

        let separator_y =
            self.geometry.page_height - self.geometry.margin_bottom - total - NOTE_SEPARATOR_OFFSET;

        // A page opening with carried content gets the full-width rule, which
        // is how Word says "this continues from the previous page". A document
        // that never defined one keeps the short rule.
        let separator_width = if opens_with_continuation && self.notes.has_continuation_separator()
        {
            self.geometry.content_width()
        } else {
            self.geometry.content_width() * SEPARATOR_WIDTH_FRACTION
        };

        self.elements.push(PositionedElement::Line {
            start: Point {
                x: self.geometry.margin_left,
                y: separator_y,
            },
            end: Point {
                x: self.geometry.margin_left + separator_width,
                y: separator_y,
            },
            width: 0.5,
            color: Color::BLACK,
            dash_pattern: None,
        });

        let mut cursor_y = separator_y + NOTE_SEPARATOR_OFFSET;
        for (id, first, count, continued) in placed {
            let Some(note) = self.notes.get(id, self.geometry.content_width()) else {
                continue;
            };
            cursor_y += draw_note(
                &mut self.elements,
                &self.geometry,
                note,
                first,
                count,
                continued,
                cursor_y,
                self.page_number,
            );
        }
    }

    fn finish_page(&mut self) {
        self.place_page_notes();
        let mut all_elements = Vec::new();

        if let Some(hf) = self.header_footer {
            let watermark = if self.is_first_page && self.title_pg {
                hf.first_watermark.as_ref()
            } else if hf.even_headers_active && self.header_page_number.is_multiple_of(2) {
                hf.even_watermark.as_ref()
            } else {
                hf.watermark.as_ref()
            };
            if let Some(watermark) = watermark {
                all_elements.push(PositionedElement::Group(watermark.clone()));
            }
        }

        // behindDoc drawings render underneath everything else on the page.
        all_elements.append(&mut self.behind_elements);

        if let Some(hf) = self.header_footer {
            // Choose header blocks: first-page or default
            let header_blocks = if self.is_first_page && self.title_pg {
                &hf.first_header_blocks
            } else if hf.even_headers_active && self.header_page_number.is_multiple_of(2) {
                &hf.even_header_blocks
            } else {
                &hf.header_blocks
            };
            if !header_blocks.is_empty() {
                let header_y = self.geometry.header_distance;
                render_hf_blocks(
                    header_blocks,
                    &self.geometry,
                    header_y,
                    self.page_number,
                    &mut all_elements,
                    self.media,
                );
            }
        }

        all_elements.append(&mut self.elements);

        if let Some(hf) = self.header_footer {
            // Choose footer blocks: first-page or default
            let footer_blocks = if self.is_first_page && self.title_pg {
                &hf.first_footer_blocks
            } else if hf.even_headers_active && self.header_page_number.is_multiple_of(2) {
                &hf.even_footer_blocks
            } else {
                &hf.footer_blocks
            };
            if !footer_blocks.is_empty() {
                let footer_height: f64 = footer_blocks.iter().map(|b| b.content_height()).sum();
                let footer_y =
                    self.geometry.page_height - self.geometry.footer_distance - footer_height;
                render_hf_blocks(
                    footer_blocks,
                    &self.geometry,
                    footer_y,
                    self.page_number,
                    &mut all_elements,
                    self.media,
                );
            }
        }

        self.pages.push(PageFrame::new(
            self.page_number,
            self.geometry.page_width,
            self.geometry.page_height,
            all_elements,
        ));
        self.page_number += 1;
        self.header_page_number += 1;
        self.cursor_y = 0.0;
        self.page_wraps.clear();
        self.ink_bottom = 0.0;
        self.has_content_flag = false;
        self.is_first_page = false;
    }

    fn finish_page_before(&mut self, next_block_index: usize) {
        self.finish_page();
        if self.pending_notes.is_empty()
            && self.page_note_ids.is_empty()
            && self.page_wraps.is_empty()
            && self.resolved_out.is_empty()
        {
            self.checkpoints.push(PaginationCheckpoint {
                next_block_index,
                page_count: self.page_number - 1,
                next_header_page_number: self.header_page_number,
            });
            if self.stop_at == self.checkpoints.last().copied() {
                self.stopped_at = self.checkpoints.last().copied();
            }
        }
    }

    fn flush(mut self) -> (Vec<PageFrame>, Vec<OutlineEntry>) {
        // Always create at least one page
        if self.has_content() || self.pages.is_empty() {
            self.finish_page();
        }
        // A note that ran past the last page of body text still has to land
        // somewhere, so keep making pages until the queue drains. Each page
        // places at least one note line, so this terminates.
        while !self.pending_notes.is_empty() {
            let before = self.pending_notes.clone();
            self.finish_page();
            if self.pending_notes == before {
                // Every page places at least one note line, so this is
                // unreachable. It exists so a future change that breaks that
                // guarantee stops rather than spins, and the assertion makes
                // it loud in tests instead of silently losing note text.
                debug_assert!(
                    false,
                    "a page placed no note content, dropping {:?}",
                    self.pending_notes
                );
                break;
            }
        }
        (self.pages, self.outlines)
    }
}

fn anchored_elements(
    anchor: &AnchoredDrawing,
    rect: Rect,
    geometry: &PageGeometry,
    media: &HashMap<MediaId, ImageData>,
) -> Vec<PositionedElement> {
    let mut produced = Vec::new();
    match &anchor.content {
        AnchoredContent::Image { media_id } => {
            let image = media.get(media_id);
            produced.push(PositionedElement::Image {
                rect,
                data: image.map_or_else(Vec::new, |image| image.data.clone()),
                content_type: image.map_or_else(String::new, |image| image.content_type.clone()),
                media_id: *media_id,
            });
        }
        AnchoredContent::Group(group) => {
            let mut positioned = group.clone();
            positioned.transform = positioned.transform.then(oxml_layout::Transform {
                e: rect.x,
                f: rect.y,
                ..oxml_layout::Transform::IDENTITY
            });
            produced.push(PositionedElement::Group(positioned));
        }
        AnchoredContent::Shape { preset, fill, text } => {
            match (preset, fill) {
                (ShapePreset::Rect, Some(color)) => {
                    produced.push(PositionedElement::FilledRect {
                        rect,
                        color: *color,
                    });
                }
                (ShapePreset::Line, Some(color)) => {
                    produced.push(PositionedElement::Line {
                        start: Point {
                            x: rect.x,
                            y: rect.y,
                        },
                        end: Point {
                            x: rect.x + anchor.width,
                            y: rect.y + anchor.height,
                        },
                        width: 1.0,
                        color: *color,
                        dash_pattern: None,
                    });
                }
                _ => {}
            }
            produced.extend(render_shape_text(text, geometry, rect, media));
        }
    }
    produced
        .into_iter()
        .map(|element| PositionedElement::MarkedContent {
            structure: anchor.structure_id,
            children: vec![element],
        })
        .collect()
}

/// Draw one note, or one slice of one, with its top edge at `top`.
///
/// Returns the height consumed. Shared by the page foot and the document end
/// so the two regions cannot drift apart in how a note looks.
fn draw_note(
    elements: &mut Vec<PositionedElement>,
    geometry: &PageGeometry,
    note: &NoteLayout,
    first: usize,
    count: usize,
    continued: bool,
    top: f64,
    page_number: usize,
) -> f64 {
    let baseline = top + note.lines.get(first).map_or(0.0, |line| line.ascent);

    // A continuation does not repeat the marker.
    if !continued {
        elements.push(PositionedElement::Text(GlyphRun {
            origin: Point {
                x: geometry.margin_left,
                y: baseline - note.marker_rise,
            },
            font_id: note.marker.font_id,
            font_size: note.marker.font_size,
            glyph_ids: note.marker.glyph_ids.clone(),
            advances: note.marker.advances.clone(),
            text: note.marker.text.clone(),
            source: None,
            color: note.marker.color,
            bold: note.marker.bold,
            italic: note.marker.italic,
            field_kind: None,
            note: None,
        }));
    }

    let mut cursor_y = top;
    for line in note.lines.iter().skip(first).take(count) {
        let line_baseline = cursor_y + line.ascent;
        let mut x = geometry.margin_left + NOTE_INDENT;
        for item in &line.items {
            let (segment, advance) = match item {
                LineItem::Text(seg) | LineItem::Marker(seg) => (Some(seg), seg.width),
                LineItem::Tab { width, .. }
                | LineItem::Image { width, .. }
                | LineItem::Group { width, .. } => (None, *width),
                _ => (None, item.width()),
            };
            if let Some(seg) = segment {
                let adjusted_baseline = line_baseline - seg.baseline_offset;
                if let Some(color) = seg.highlight {
                    elements.push(PositionedElement::FilledRect {
                        rect: Rect {
                            x,
                            y: cursor_y,
                            width: seg.width,
                            height: line.height,
                        },
                        color,
                    });
                }
                elements.push(PositionedElement::Text(GlyphRun {
                    origin: Point {
                        x,
                        y: adjusted_baseline,
                    },
                    font_id: seg.font_id,
                    font_size: seg.font_size,
                    glyph_ids: seg.glyph_ids.clone(),
                    advances: seg.advances.clone(),
                    text: seg.text.clone(),
                    source: seg.source,
                    color: seg.color,
                    bold: seg.bold,
                    italic: seg.italic,
                    field_kind: None,
                    note: None,
                }));
                if let Some(underline) = seg.underline {
                    let underline_y = adjusted_baseline + seg.descent * 0.3;
                    let thickness = match underline {
                        Underline::Thick => seg.font_size / 12.0,
                        Underline::Double => seg.font_size / 24.0,
                        _ => seg.font_size / 18.0,
                    };
                    elements.push(PositionedElement::Line {
                        start: Point { x, y: underline_y },
                        end: Point {
                            x: x + seg.width,
                            y: underline_y,
                        },
                        width: thickness,
                        color: seg.color,
                        dash_pattern: None,
                    });
                    if underline == Underline::Double {
                        let second_y = underline_y + thickness * 2.5;
                        elements.push(PositionedElement::Line {
                            start: Point { x, y: second_y },
                            end: Point {
                                x: x + seg.width,
                                y: second_y,
                            },
                            width: thickness,
                            color: seg.color,
                            dash_pattern: None,
                        });
                    }
                }
                if seg.strike {
                    let strike_y = adjusted_baseline - seg.ascent * 0.3;
                    let thickness = seg.font_size / 24.0;
                    elements.push(PositionedElement::Line {
                        start: Point { x, y: strike_y },
                        end: Point {
                            x: x + seg.width,
                            y: strike_y,
                        },
                        width: thickness,
                        color: seg.color,
                        dash_pattern: None,
                    });
                }
                if seg.dstrike {
                    let strike_y = adjusted_baseline - seg.ascent * 0.3;
                    let thickness = seg.font_size / 24.0;
                    let gap = thickness * 2.0;
                    for y in [strike_y - gap / 2.0, strike_y + gap / 2.0] {
                        elements.push(PositionedElement::Line {
                            start: Point { x, y },
                            end: Point {
                                x: x + seg.width,
                                y,
                            },
                            width: thickness,
                            color: seg.color,
                            dash_pattern: None,
                        });
                    }
                }
            }
            x += advance;
        }
        cursor_y += line.height;
    }

    for range in &note.revision_ranges {
        let visible_start = range.start.max(first);
        let visible_end = range.end.min(first + count);
        if visible_start >= visible_end {
            continue;
        }
        let offset = note
            .lines
            .iter()
            .skip(first)
            .take(visible_start - first)
            .map(|line| line.height)
            .sum::<f64>();
        let height = note
            .lines
            .iter()
            .skip(visible_start)
            .take(visible_end - visible_start)
            .map(|line| line.height)
            .sum::<f64>();
        render_change_bar_at(top + offset, height, geometry, page_number, elements);
    }

    cursor_y - top
}

/// Append the document's endnotes as pages after the last body page.
///
/// Endnotes are flow content read at the end, not marginalia, so they start at
/// the top of a fresh page and carry no separator rule. There is no body text
/// on these pages for a rule to divide them from.
pub fn append_endnote_pages(
    pages: &mut Vec<PageFrame>,
    notes: &NoteRegistry,
    geometry: PageGeometry,
) {
    // First-reference order across the document, which is the order a reader
    // met them in.
    let mut ordered: Vec<NoteRef> = Vec::new();
    for page in pages.iter() {
        oxml_layout::walk(&page.elements, &mut |element, _| {
            if let PositionedElement::Text(run) = element
                && let Some(note) = run.note
                && note.stream == NoteStream::Endnote
                && notes.get(note, geometry.content_width()).is_some()
                && !ordered.contains(&note)
            {
                ordered.push(note);
            }
        });
    }

    if ordered.is_empty() {
        return;
    }

    let content_height = geometry.content_height();
    let mut elements: Vec<PositionedElement> = Vec::new();
    let mut cursor_y = 0.0;
    let mut page_number = pages.len() + 1;

    let mut flush = |elements: &mut Vec<PositionedElement>, page_number: &mut usize| {
        pages.push(PageFrame::new(
            *page_number,
            geometry.page_width,
            geometry.page_height,
            std::mem::take(elements),
        ));
        *page_number += 1;
    };

    for note_ref in ordered {
        let Some(note) = notes.get(note_ref, geometry.content_width()) else {
            continue;
        };

        let mut first = 0;
        let mut continued = false;
        while first < note.lines.len() {
            let mut count = 0;
            let mut used = cursor_y;
            for line in note.lines.iter().skip(first) {
                if used + line.height > content_height + 0.01 {
                    break;
                }
                used += line.height;
                count += 1;
            }

            if count == 0 {
                // Nothing more fits on this page. Start a fresh one, unless
                // the page is already empty. An empty page that still cannot
                // take a line means the line is taller than the page, so it is
                // placed and allowed to overflow rather than looping forever.
                // Overflowing beats dropping the text, and body text on a page
                // of its own behaves the same way.
                if cursor_y == 0.0 {
                    count = 1;
                } else {
                    flush(&mut elements, &mut page_number);
                    cursor_y = 0.0;
                    continue;
                }
            }

            cursor_y += draw_note(
                &mut elements,
                &geometry,
                note,
                first,
                count,
                continued,
                geometry.margin_top + cursor_y,
                page_number,
            );
            first += count;
            continued = true;
        }
    }

    if !elements.is_empty() {
        flush(&mut elements, &mut page_number);
    }
}

/// The notes referenced by the segments on one line.
fn notes_in_line(line: &LayoutLine) -> impl Iterator<Item = NoteRef> + '_ {
    line.items.iter().filter_map(|item| match item {
        LineItem::Text(seg) | LineItem::Marker(seg) => seg.note,
        _ => None,
    })
}

/// The notes on one line that belong at the foot of its page.
///
/// Endnotes are excluded. They are emitted at the document end and take no
/// height from the page their reference sits on.
fn page_foot_notes_in_line(line: &LayoutLine) -> impl Iterator<Item = NoteRef> + '_ {
    notes_in_line(line).filter(|note| note.stream == NoteStream::Footnote)
}

/// Paginate a single paragraph, handling splitting across pages.
/// Shift a positioned element by a fixed offset.
///
/// Paragraph rendering always lays out against the page margins, so a text box
/// is rendered at the margin first and then moved to where the shape sits.
fn translate_element(element: &mut PositionedElement, dx: f64, dy: f64) {
    match element {
        PositionedElement::Text(run) => {
            run.origin.x += dx;
            run.origin.y += dy;
        }
        PositionedElement::Line { start, end, .. } => {
            start.x += dx;
            start.y += dy;
            end.x += dx;
            end.y += dy;
        }
        PositionedElement::FilledRect { rect, .. }
        | PositionedElement::Image { rect, .. }
        | PositionedElement::LinkAnnotation { rect, .. } => {
            rect.x += dx;
            rect.y += dy;
        }
        _ => {}
    }
}

/// Render a shape's text box inside `rect`.
///
/// The paragraphs arrive already laid out at the shape's width. They are
/// rendered as if they sat at the left margin and then translated onto the
/// shape, which keeps all the justification and indent handling in one place.
fn render_shape_text(
    text: &[ParagraphBlock],
    geometry: &PageGeometry,
    rect: Rect,
    media: &HashMap<MediaId, ImageData>,
) -> Vec<PositionedElement> {
    if text.is_empty() {
        return Vec::new();
    }

    let mut local = Vec::new();
    let mut y = 0.0;
    for para in text {
        render_paragraph_lines(
            &para.lines,
            ParagraphView {
                block: para,
                semantics: None,
            },
            geometry,
            y,
            &mut local,
            media,
        );
        y += para.content_height();
    }

    // render_paragraph_lines works in content-area coordinates, so undo the
    // margin it applied and then move onto the shape.
    let dx = rect.x - geometry.margin_left;
    let dy = rect.y - geometry.margin_top;
    for element in &mut local {
        translate_element(element, dx, dy);
    }
    local
}

/// Resolve a horizontal anchor offset against the frame it is measured from.
///
/// An offset says nothing on its own. The same number lands somewhere
/// different depending on the frame, and treating every offset as a page
/// coordinate put anchored drawings in the corner of the sheet.
fn frame_h(rel: ST_RelativeFromH, g: &PageGeometry, indent_left: f64) -> (f64, f64) {
    let text_width = g.page_width - g.margin_left - g.margin_right;
    match rel {
        ST_RelativeFromH::Page | ST_RelativeFromH::LeftMargin => (0.0, g.page_width),
        ST_RelativeFromH::RightMargin | ST_RelativeFromH::OutsideMargin => {
            (g.page_width - g.margin_right, g.margin_right)
        }
        ST_RelativeFromH::InsideMargin => (g.margin_left, g.margin_left),
        // A character-relative offset starts where the text does on the line.
        ST_RelativeFromH::Character => (g.margin_left + indent_left, text_width),
        // Margin and column both start at the left edge of the text area.
        // Multiple columns are not laid out yet, so the two coincide.
        ST_RelativeFromH::Margin | ST_RelativeFromH::Column => (g.margin_left, text_width),
    }
}

fn resolve_anchor_h(
    rel: ST_RelativeFromH,
    off: f64,
    align: Option<AnchorAlignH>,
    width: f64,
    g: &PageGeometry,
    indent_left: f64,
) -> f64 {
    let (start, size) = frame_h(rel, g, indent_left);
    match align {
        // Inside and outside mean binding-side and outer-edge, which differ on
        // facing pages. Facing pages are not modelled, so the odd-page reading
        // stands in for both.
        Some(AnchorAlignH::Left | AnchorAlignH::Inside) => start,
        Some(AnchorAlignH::Center) => start + (size - width) / 2.0,
        Some(AnchorAlignH::Right | AnchorAlignH::Outside) => start + size - width,
        None => start + off,
    }
}

/// Resolve a vertical anchor offset against the frame it is measured from.
///
/// `para_top` is the top of the anchoring paragraph, measured from the top of
/// the content area.
fn frame_v(rel: ST_RelativeFromV, g: &PageGeometry, para_top: f64) -> (f64, f64) {
    let text_height = g.page_height - g.margin_top - g.margin_bottom;
    match rel {
        ST_RelativeFromV::Page | ST_RelativeFromV::TopMargin => (0.0, g.page_height),
        ST_RelativeFromV::BottomMargin | ST_RelativeFromV::OutsideMargin => {
            (g.page_height - g.margin_bottom, g.margin_bottom)
        }
        ST_RelativeFromV::Margin | ST_RelativeFromV::InsideMargin => (g.margin_top, text_height),
        // Paragraph and line are both relative to where this paragraph landed.
        // Per-line anchoring would need the line box, which is finer than we
        // track here, so the paragraph top stands in for both.
        ST_RelativeFromV::Paragraph | ST_RelativeFromV::Line => {
            (g.margin_top + para_top, text_height)
        }
    }
}

fn resolve_anchor_v(
    rel: ST_RelativeFromV,
    off: f64,
    align: Option<AnchorAlignV>,
    height: f64,
    g: &PageGeometry,
    para_top: f64,
) -> f64 {
    let (start, size) = frame_v(rel, g, para_top);
    match align {
        Some(AnchorAlignV::Top | AnchorAlignV::Inside) => start,
        Some(AnchorAlignV::Center) => start + (size - height) / 2.0,
        Some(AnchorAlignV::Bottom | AnchorAlignV::Outside) => start + size - height,
        None => start + off,
    }
}

/// Re-break a paragraph so its text flows around the wrapping drawings that
/// share its band of the page.
///
/// `para_top` is where the paragraph's content starts, measured from the top of
/// the content area. Returns `None` when nothing applies, so the caller keeps
/// the paragraph it already has.
fn reflow_around_wraps(
    para: &ParagraphBlock,
    wraps: &[PlacedWrap],
    para_top: f64,
    geometry: &PageGeometry,
    fm: &FontManager,
) -> Option<ParagraphBlock> {
    let reflow = para.reflow.as_ref()?;
    if wraps.is_empty() {
        return None;
    }

    let mut lines = para.lines.clone();
    let mut offset_top = 0.0;

    // Two passes. The first reserves against the paragraph as laid out, the
    // second against the heights the first produced, which is what settles a
    // drawing that only overlaps once the text has moved.
    for _ in 0..2 {
        let mut prefix: Vec<f64> = Vec::new();
        let mut suffix: Vec<f64> = Vec::new();

        // Vertical clearance is resolved first, because it moves the lines the
        // horizontal reservations are then measured against.
        let paragraph_top = geometry.margin_top + para_top;
        let mut next_offset_top: f64 = 0.0;
        for wrap in wraps.iter().filter(|w| w.wrap == WrapType::TopAndBottom) {
            if wrap.keep_out_top() <= paragraph_top + 1.0 && wrap.keep_out_bottom() > paragraph_top
            {
                next_offset_top = next_offset_top.max(wrap.keep_out_bottom() - paragraph_top);
            }
        }

        for wrap in wraps.iter().filter(|w| w.wrap != WrapType::TopAndBottom) {
            // Square, and the outline wraps approximated as square.
            let text_left = geometry.margin_left + para.indent_left;
            let text_right = geometry.page_width - geometry.margin_right - para.indent_right;
            let drawing_centre = wrap.rect.x + wrap.rect.width / 2.0;
            let on_the_left = drawing_centre < (text_left + text_right) / 2.0;

            let reserve = if on_the_left {
                (wrap.rect.x + wrap.rect.width + wrap.dist_right - text_left).max(0.0)
            } else {
                (text_right - (wrap.rect.x - wrap.dist_left)).max(0.0)
            };
            if reserve <= 0.0 {
                continue;
            }

            let mut line_top = geometry.margin_top + para_top + next_offset_top;
            for (index, line) in lines.iter().enumerate() {
                let line_bottom = line_top + line.height;
                if line_bottom > wrap.keep_out_top() && line_top < wrap.keep_out_bottom() {
                    let target = if on_the_left {
                        &mut prefix
                    } else {
                        &mut suffix
                    };
                    if target.len() <= index {
                        target.resize(index + 1, 0.0);
                    }
                    target[index] += reserve;
                }
                line_top = line_bottom;
            }
        }

        if prefix.is_empty() && suffix.is_empty() && next_offset_top == 0.0 {
            return None;
        }

        let mut params = reflow.params.clone();
        params.line_prefix_widths = prefix;
        params.line_suffix_widths = suffix;

        let Ok(reflowed) = break_into_lines(&reflow.items, &params, fm) else {
            return None;
        };
        lines = reflowed;
        offset_top = next_offset_top;
    }

    let mut adjusted = para.clone();
    adjusted.lines = lines;
    adjusted.content_offset_top = offset_top;
    // The paragraph has been reflowed. Re-entering would reserve twice.
    adjusted.reflow = None;
    Some(adjusted)
}

fn paginate_paragraph<B: LayoutBlockLike>(
    para: ParagraphView<'_>,
    block_idx: usize,
    blocks: &[B],
    pager: &mut Pager,
) {
    let space_before = if pager.cursor_y == 0.0 {
        0.0
    } else {
        para.space_before
    };

    // Flow the paragraph around anything floating in its band of the page,
    // before anything is measured. A reflow changes the paragraph's height, so
    // doing it after the fitting decision would measure the wrong thing.
    let reflowed = {
        let para_top = pager.cursor_y + space_before;
        let mut wraps = pager.page_wraps.clone();
        wraps.extend(pager.wrap_rects_for(&para.anchored, para_top, para.indent_left));
        wraps.extend(pager.lookahead_wraps(block_idx, blocks));
        reflow_around_wraps(para.block, &wraps, para_top, &pager.geometry, pager.fm)
    };
    let para = reflowed.as_ref().map_or(para, |block| ParagraphView {
        block,
        semantics: para.semantics,
    });

    // Check if paragraph fits on current page. The note area its references
    // will demand is priced in, but not claimed: the paragraph may yet move to
    // the next page, and its notes must move with it.
    let total_needed = space_before + para.content_height();
    let remaining = pager.available_height_for(&para.lines) - pager.cursor_y;

    if total_needed > remaining && pager.has_content() {
        // Paragraph doesn't fit. Decide: move whole or split.
        if para.keep_lines || para.lines.len() <= 2 {
            pager.finish_page_before(block_idx);
            if pager.stopped_at.is_some() {
                return;
            }
            // Re-call with fresh page
            paginate_paragraph(para, block_idx, blocks, pager);
            return;
        }

        // The lines start below any drawing the paragraph must clear, so the
        // counter has to be told where they actually begin.
        let lines_that_fit = pager.count_lines_that_fit_with_notes(
            &para.lines,
            pager.cursor_y + space_before + para.content_offset_top,
        );

        if para.widow_control && lines_that_fit < 2 {
            // Can't fit enough lines — move whole paragraph
            pager.finish_page_before(block_idx);
            if pager.stopped_at.is_some() {
                return;
            }
            paginate_paragraph(para, block_idx, blocks, pager);
            return;
        }

        let lines_remaining = para.lines.len() - lines_that_fit;
        if para.widow_control && lines_remaining < 2 && lines_that_fit >= 3 {
            // Would leave orphan — move one line to next page
            let split_at = lines_that_fit - 1;
            render_para_split(para, split_at, space_before, pager, block_idx);
            return;
        }

        if lines_that_fit > 0 {
            render_para_split(para, lines_that_fit, space_before, pager, block_idx);
            return;
        }

        // No lines fit (shouldn't happen since we checked has_content above)
        pager.finish_page_before(block_idx);
        if pager.stopped_at.is_some() {
            return;
        }
        paginate_paragraph(para, block_idx, blocks, pager);
        return;
    }

    // Paragraph fits OR we're at the top of a page
    // If it doesn't fit and we're at the top, we must split line by line
    if total_needed > pager.available_height_for(&para.lines) && pager.cursor_y == 0.0 {
        // Paragraph is taller than a page; split line by line
        let lines_that_fit =
            pager.count_lines_that_fit_with_notes(&para.lines, para.content_offset_top);
        if lines_that_fit > 0 && lines_that_fit < para.lines.len() {
            render_para_split(para, lines_that_fit, 0.0, pager, block_idx);
            return;
        }
    }

    // Check keep-with-next
    if para.keep_next && block_idx + 1 < blocks.len() {
        let next = &blocks[block_idx + 1];
        let next_first = next.paragraph().map_or_else(
            || {
                next.table().map_or(0.0, |table| {
                    table.rows.first().map_or(0.0, |row| row.height)
                })
            },
            |paragraph| paragraph.lines.first().map_or(0.0, |line| line.height),
        );
        if pager.cursor_y + space_before + para.content_height() + next_first
            > pager.available_height_for(&para.lines)
            && pager.has_content()
        {
            pager.finish_page_before(block_idx);
            if pager.stopped_at.is_some() {
                return;
            }
        }
    }

    // Render the paragraph
    let space = if pager.cursor_y == 0.0 {
        0.0
    } else {
        para.space_before
    };
    pager.cursor_y += space;

    if let Some(shading) = para.shading {
        pager.elements.push(PositionedElement::FilledRect {
            rect: Rect {
                x: pager.geometry.margin_left + para.indent_left,
                y: pager.geometry.margin_top + pager.cursor_y,
                width: pager.geometry.content_width() - para.indent_left - para.indent_right,
                height: para.content_height(),
            },
            color: shading,
        });
    }

    // Render paragraph borders
    if let Some(ref borders) = para.borders {
        let border_x = pager.geometry.margin_left + para.indent_left;
        let border_y = pager.geometry.margin_top + pager.cursor_y;
        let border_w = pager.geometry.content_width() - para.indent_left - para.indent_right;
        let border_h = para.content_height();
        render_border_edges(
            borders,
            border_x,
            border_y,
            border_w,
            border_h,
            &mut pager.elements,
        );
    }

    // Anchored drawings resolve against the paragraph's position, so place
    // them now that the page and the cursor are settled.
    pager.place_anchored(&para.anchored, pager.cursor_y, para.indent_left, block_idx);

    render_paragraph_lines(
        &para.lines,
        para,
        &pager.geometry,
        pager.cursor_y,
        &mut pager.elements,
        pager.media,
    );
    render_change_bar(
        para.block,
        pager.cursor_y,
        para.content_height(),
        &pager.geometry,
        pager.page_number,
        &mut pager.elements,
    );
    pager.claim_notes(&para.lines);
    pager.cursor_y += para.content_height();
    pager.ink_bottom = pager.cursor_y;
    pager.cursor_y += para.space_after;
    pager.mark_content();
}

/// Split a paragraph at the given line index, rendering first part on current page
/// and continuing the rest on a new page (recursively if needed).
fn render_para_split(
    para: ParagraphView<'_>,
    split_at: usize,
    space_before: f64,
    pager: &mut Pager,
    block_idx: usize,
) {
    // Render lines before split on current page
    pager.cursor_y += space_before;
    // A split paragraph anchors its drawings to where it starts.
    pager.place_anchored(&para.anchored, pager.cursor_y, para.indent_left, block_idx);
    render_paragraph_lines(
        &para.lines[..split_at],
        para,
        &pager.geometry,
        pager.cursor_y,
        &mut pager.elements,
        pager.media,
    );
    let first_height = para.content_offset_top
        + para.lines[..split_at]
            .iter()
            .map(|line| line.height)
            .sum::<f64>();
    render_change_bar(
        para.block,
        pager.cursor_y,
        first_height,
        &pager.geometry,
        pager.page_number,
        &mut pager.elements,
    );
    // Only the lines placed on this page count toward its notes. The rest of
    // the paragraph, and any note it references, belong to the next page.
    pager.claim_notes(&para.lines[..split_at]);
    pager.ink_bottom = pager.cursor_y
        + para.content_offset_top
        + para.lines[..split_at].iter().map(|l| l.height).sum::<f64>();
    pager.mark_content();
    pager.finish_page();

    // Handle remaining lines, which may themselves need splitting
    let remaining_lines = &para.lines[split_at..];
    let remaining_height: f64 = remaining_lines.iter().map(|l| l.height).sum();

    if remaining_height > pager.available_height_for(remaining_lines) {
        // Still too tall — split again
        let lines_that_fit = pager.count_lines_that_fit_with_notes(remaining_lines, 0.0);
        if lines_that_fit > 0 && lines_that_fit < remaining_lines.len() {
            // Build a temporary para with remaining lines
            let temp_para = ParagraphBlock {
                // The anchors were placed with the first part of the
                // paragraph, so the continuation must not place them again.
                anchored: Vec::new(),
                has_visible_revision: para.has_visible_revision,
                lines: remaining_lines.to_vec(),
                space_before: 0.0,
                space_after: para.space_after,
                borders: para.borders.clone(),
                shading: para.shading,
                indent_left: para.indent_left,
                indent_right: para.indent_right,
                jc: para.jc,
                keep_next: para.keep_next,
                keep_lines: false,
                page_break_before: false,
                widow_control: para.widow_control,
                heading_level: None,
                heading_text: None,
                list: para.list,
                structure_id: para.structure_id(),
                // The continuation was already reflowed as part of the whole
                // paragraph, so it must not be reflowed again.
                reflow: None,
                content_offset_top: 0.0,
            };
            render_para_split(
                ParagraphView {
                    block: &temp_para,
                    semantics: para.semantics,
                },
                lines_that_fit,
                0.0,
                pager,
                block_idx,
            );
            return;
        }
    }

    // Remaining fits on the new page
    render_paragraph_lines(
        remaining_lines,
        para,
        &pager.geometry,
        0.0,
        &mut pager.elements,
        pager.media,
    );
    render_change_bar(
        para.block,
        0.0,
        remaining_height,
        &pager.geometry,
        pager.page_number,
        &mut pager.elements,
    );
    pager.claim_notes(remaining_lines);
    pager.ink_bottom = remaining_height;
    pager.cursor_y = remaining_height + para.space_after;
    pager.mark_content();
}

/// Render paragraph lines as positioned elements.
fn render_paragraph_lines(
    lines: &[LayoutLine],
    para: ParagraphView<'_>,
    geometry: &PageGeometry,
    start_y: f64,
    elements: &mut Vec<PositionedElement>,
    media: &HashMap<MediaId, ImageData>,
) {
    let first_element = elements.len();
    // A drawing this paragraph must clear rather than flow beside pushes its
    // first line down. `content_height` already counts the same offset.
    let mut y = start_y + para.content_offset_top;
    for line in lines {
        let baseline_y = geometry.margin_top + y + line.ascent;

        // Compute x offset based on justification
        let text_width: f64 = line.items.iter().map(|item| item.width()).sum();
        let remaining_width = line.available_width - text_width;

        // For justified text (Both), compute extra space per gap
        let justify_extra =
            if para.jc == Some(Align::Justify) && !line.is_last && remaining_width > 0.0 {
                // Count inter-word gaps: spaces between items + spaces within text segments
                let gap_count = count_word_gaps(&line.items);
                if gap_count > 0 {
                    remaining_width / gap_count as f64
                } else {
                    0.0
                }
            } else {
                0.0
            };

        let x_offset = match para.jc {
            Some(Align::Center) => geometry.margin_left + line.indent_left + remaining_width / 2.0,
            Some(Align::End) => geometry.margin_left + line.indent_left + remaining_width,
            Some(Align::Justify) if !line.is_last && justify_extra > 0.0 => {
                // Justified: start from left margin (extra space distributed in gaps)
                geometry.margin_left + line.indent_left
            }
            _ => geometry.margin_left + line.indent_left,
        };

        let mut x = x_offset;
        let mut _accumulated_extra = 0.0;

        for item in &line.items {
            match item {
                LineItem::Text(seg) | LineItem::Marker(seg) => {
                    let adjusted_baseline = baseline_y - seg.baseline_offset;

                    // For justified text, compute the extra width from spaces in this segment
                    let segment_spaces = if justify_extra > 0.0 {
                        seg.text.chars().filter(|c| *c == ' ').count()
                    } else {
                        0
                    };
                    let segment_extra = segment_spaces as f64 * justify_extra;
                    let effective_width = seg.width + segment_extra;

                    // Render highlight background
                    if let Some(hl_color) = seg.highlight {
                        elements.push(PositionedElement::FilledRect {
                            rect: Rect {
                                x,
                                y: geometry.margin_top + y,
                                width: effective_width,
                                height: line.height,
                            },
                            color: hl_color,
                        });
                    }

                    // Render text, adjusting advances for justified text
                    let advances = if justify_extra > 0.0 && segment_spaces > 0 {
                        // Widen advances for space glyphs
                        distribute_justify_advances(&seg.text, &seg.advances, justify_extra)
                    } else {
                        seg.advances.clone()
                    };

                    elements.push(PositionedElement::Text(GlyphRun {
                        origin: Point {
                            x,
                            y: adjusted_baseline,
                        },
                        font_id: seg.font_id,
                        font_size: seg.font_size,
                        glyph_ids: seg.glyph_ids.clone(),
                        advances,
                        text: seg.text.clone(),
                        source: match para.source_node() {
                            Some(source_node) => seg.source.and_then(|mut source| {
                                source.node = source_node?;
                                Some(source)
                            }),
                            None => seg.source,
                        },
                        color: seg.color,
                        bold: seg.bold,
                        italic: seg.italic,
                        field_kind: seg.field_kind,
                        note: seg.note,
                    }));

                    // Render underline
                    if let Some(ul_style) = seg.underline {
                        let ul_y = adjusted_baseline + seg.descent * 0.3;
                        let ul_thickness = match ul_style {
                            Underline::Thick => seg.font_size / 12.0,
                            Underline::Double => seg.font_size / 24.0,
                            _ => seg.font_size / 18.0,
                        };
                        elements.push(PositionedElement::Line {
                            start: Point { x, y: ul_y },
                            end: Point {
                                x: x + effective_width,
                                y: ul_y,
                            },
                            width: ul_thickness,
                            color: seg.color,
                            dash_pattern: None,
                        });
                        // Second line for double underline
                        if ul_style == Underline::Double {
                            let ul_y2 = ul_y + ul_thickness * 2.5;
                            elements.push(PositionedElement::Line {
                                start: Point { x, y: ul_y2 },
                                end: Point {
                                    x: x + effective_width,
                                    y: ul_y2,
                                },
                                width: ul_thickness,
                                color: seg.color,
                                dash_pattern: None,
                            });
                        }
                    }

                    // Render strikethrough
                    if seg.strike {
                        let strike_y = adjusted_baseline - seg.ascent * 0.3;
                        let strike_thickness = seg.font_size / 24.0;
                        elements.push(PositionedElement::Line {
                            start: Point { x, y: strike_y },
                            end: Point {
                                x: x + effective_width,
                                y: strike_y,
                            },
                            width: strike_thickness,
                            color: seg.color,
                            dash_pattern: None,
                        });
                    }

                    // Render double strikethrough
                    if seg.dstrike {
                        let strike_y = adjusted_baseline - seg.ascent * 0.3;
                        let strike_thickness = seg.font_size / 24.0;
                        let gap = strike_thickness * 2.0;
                        elements.push(PositionedElement::Line {
                            start: Point {
                                x,
                                y: strike_y - gap / 2.0,
                            },
                            end: Point {
                                x: x + effective_width,
                                y: strike_y - gap / 2.0,
                            },
                            width: strike_thickness,
                            color: seg.color,
                            dash_pattern: None,
                        });
                        elements.push(PositionedElement::Line {
                            start: Point {
                                x,
                                y: strike_y + gap / 2.0,
                            },
                            end: Point {
                                x: x + effective_width,
                                y: strike_y + gap / 2.0,
                            },
                            width: strike_thickness,
                            color: seg.color,
                            dash_pattern: None,
                        });
                    }

                    // Render hyperlink annotation
                    if let Some(ref url) = seg.hyperlink_url {
                        elements.push(PositionedElement::LinkAnnotation {
                            rect: Rect {
                                x,
                                y: geometry.margin_top + y,
                                width: effective_width,
                                height: line.height,
                            },
                            url: url.clone(),
                        });
                    }

                    _accumulated_extra += segment_extra;
                    x += effective_width;
                }
                LineItem::Tab { width, leader } => {
                    if let Some(leader_seg) = leader {
                        // Render the pre-shaped leader text
                        let baseline_y = geometry.margin_top + y + line.ascent;
                        elements.push(PositionedElement::Text(GlyphRun {
                            origin: Point { x, y: baseline_y },
                            font_id: leader_seg.font_id,
                            font_size: leader_seg.font_size,
                            glyph_ids: leader_seg.glyph_ids.clone(),
                            advances: leader_seg.advances.clone(),
                            text: leader_seg.text.clone(),
                            source: None,
                            color: leader_seg.color,
                            bold: leader_seg.bold,
                            italic: leader_seg.italic,
                            field_kind: None,
                            note: None,
                        }));
                    }
                    x += width;
                }
                LineItem::Image {
                    width,
                    height,
                    media_id,
                } => {
                    let image = media.get(media_id);
                    // Image positioned at current x, top-aligned with line
                    let image = PositionedElement::Image {
                        rect: Rect {
                            x,
                            y: geometry.margin_top + y,
                            width: *width,
                            height: *height,
                        },
                        data: image.map_or_else(Vec::new, |image| image.data.clone()),
                        content_type: image
                            .map_or_else(String::new, |image| image.content_type.clone()),
                        media_id: *media_id,
                    };
                    elements.push(image);
                    x += width;
                }
                LineItem::Group { width, group, .. } => {
                    let mut positioned = group.clone();
                    positioned.transform = positioned.transform.then(oxml_layout::Transform {
                        e: x,
                        f: geometry.margin_top + y,
                        ..oxml_layout::Transform::IDENTITY
                    });
                    let group = PositionedElement::Group(positioned);
                    elements.push(group);
                    x += width;
                }
                LineItem::Figure {
                    item, structure_id, ..
                } => {
                    let figure = match item.as_ref() {
                        LineItem::Image {
                            width,
                            height,
                            media_id,
                        } => {
                            let image = media.get(media_id);
                            PositionedElement::Image {
                                rect: Rect {
                                    x,
                                    y: geometry.margin_top + y,
                                    width: *width,
                                    height: *height,
                                },
                                data: image.map_or_else(Vec::new, |image| image.data.clone()),
                                content_type: image
                                    .map_or_else(String::new, |image| image.content_type.clone()),
                                media_id: *media_id,
                            }
                        }
                        LineItem::Group { group, .. } => {
                            let mut positioned = group.clone();
                            positioned.transform =
                                positioned.transform.then(oxml_layout::Transform {
                                    e: x,
                                    f: geometry.margin_top + y,
                                    ..oxml_layout::Transform::IDENTITY
                                });
                            PositionedElement::Group(positioned)
                        }
                        _ => {
                            x += item.width();
                            continue;
                        }
                    };
                    elements.push(PositionedElement::MarkedContent {
                        structure: *structure_id,
                        children: vec![figure],
                    });
                    x += item.width();
                }
                _ => x += item.width(),
            }
        }

        y += line.height;
    }

    if let Some(structure_id) = para.structure_id() {
        let produced = elements.split_off(first_element);
        elements.extend(produced.into_iter().map(|element| match &element {
            PositionedElement::Text(run) if !(run.text.is_empty() && run.glyph_ids.is_empty()) => {
                PositionedElement::MarkedContent {
                    structure: Some(structure_id),
                    children: vec![element],
                }
            }
            PositionedElement::Image { .. } | PositionedElement::Group(_) => {
                PositionedElement::MarkedContent {
                    structure: None,
                    children: vec![element],
                }
            }
            PositionedElement::MarkedContent { .. } => element,
            PositionedElement::LinkAnnotation { .. } => element,
            _ => PositionedElement::MarkedContent {
                structure: None,
                children: vec![element],
            },
        }));
    }
}

fn render_change_bar(
    para: &ParagraphBlock,
    start_y: f64,
    height: f64,
    geometry: &PageGeometry,
    page_number: usize,
    elements: &mut Vec<PositionedElement>,
) {
    if !para.has_visible_revision || !height.is_finite() || height <= 0.0 {
        return;
    }
    render_change_bar_at(
        geometry.margin_top + start_y,
        height,
        geometry,
        page_number,
        elements,
    );
}

fn render_change_bar_at(
    start_y: f64,
    height: f64,
    geometry: &PageGeometry,
    page_number: usize,
    elements: &mut Vec<PositionedElement>,
) {
    if !height.is_finite() || height <= 0.0 {
        return;
    }
    let x = if page_number.is_multiple_of(2) {
        geometry.margin_left / 2.0
    } else {
        geometry.page_width - geometry.margin_right / 2.0
    };
    if !x.is_finite() || !start_y.is_finite() || !(start_y + height).is_finite() {
        return;
    }
    elements.push(PositionedElement::Line {
        start: Point { x, y: start_y },
        end: Point {
            x,
            y: start_y + height,
        },
        width: 1.5,
        color: Color::BLACK,
        dash_pattern: None,
    });
}

/// Render header/footer blocks.
fn render_hf_blocks(
    blocks: &[ParagraphBlock],
    geometry: &PageGeometry,
    start_y: f64,
    page_number: usize,
    elements: &mut Vec<PositionedElement>,
    media: &HashMap<MediaId, ImageData>,
) {
    let mut y = start_y - geometry.margin_top; // Convert to relative
    for para in blocks {
        render_paragraph_lines(
            &para.lines,
            ParagraphView {
                block: para,
                semantics: None,
            },
            geometry,
            y,
            elements,
            media,
        );
        render_change_bar(
            para,
            y,
            para.content_height(),
            geometry,
            page_number,
            elements,
        );
        y += para.content_height();
    }
}

/// Render a table row.
fn render_table_row(
    row: &crate::table::TableRow,
    row_semantics: Option<&crate::block::RowSemantics>,
    _col_widths: &[f64],
    table_x: f64,
    row_y: f64,
    geometry: &PageGeometry,
    page_number: usize,
    table_borders: Option<&rdocx_oxml::table::CT_TblBorders>,
    elements: &mut Vec<PositionedElement>,
    behind_elements: &mut Vec<PositionedElement>,
    media: &HashMap<MediaId, ImageData>,
) {
    let mut cell_x = table_x;
    let num_cells = row.cells.len();

    for (cell_idx, cell) in row.cells.iter().enumerate() {
        let cell_semantics = row_semantics.and_then(|row| row.cells.get(cell_idx));
        if cell.is_vmerge_continue {
            cell_x += cell.width;
            continue;
        }
        let paint_height = cell.merged_height;
        // Render cell shading
        if let Some(ref shading) = cell.shading {
            elements.push(PositionedElement::FilledRect {
                rect: Rect {
                    x: cell_x,
                    y: row_y,
                    width: cell.width,
                    height: paint_height,
                },
                color: *shading,
            });
        }

        // Render cell borders
        render_cell_borders(
            cell_x,
            row_y,
            cell.width,
            paint_height,
            &cell.borders,
            table_borders,
            cell_idx,
            num_cells,
            cell.is_first_row,
            cell.is_last_row,
            elements,
        );

        let content_element_start = elements.len();
        let behind_element_start = behind_elements.len();

        let content_height = cell
            .blocks
            .iter()
            .map(crate::table::CellBlock::total_height)
            .sum::<f64>();
        let v_offset = match cell.v_align {
            Some(rdocx_oxml::table::ST_VerticalJc::Center) => {
                ((paint_height - cell.margin_top - content_height) / 2.0).max(0.0)
            }
            Some(rdocx_oxml::table::ST_VerticalJc::Bottom) => {
                (paint_height - cell.margin_top - content_height).max(0.0)
            }
            _ => 0.0,
        };
        let mut content_y = row_y - geometry.margin_top + cell.margin_top + v_offset;
        for (block_index, block) in cell.blocks.iter().enumerate() {
            let block_semantics = cell_semantics.and_then(|cell| cell.blocks.get(block_index));
            match block {
                crate::table::CellBlock::Paragraph(paragraph) => {
                    let semantics = match block_semantics {
                        Some(CellBlockSemantics::Paragraph(semantics)) => Some(semantics),
                        _ => None,
                    };
                    let cell_geometry = PageGeometry {
                        margin_left: cell_x + cell.margin_left,
                        margin_right: 0.0,
                        page_width: cell_x + cell.width - cell.margin_right,
                        ..*geometry
                    };
                    render_paragraph_lines(
                        &paragraph.lines,
                        ParagraphView {
                            block: paragraph,
                            semantics,
                        },
                        &cell_geometry,
                        content_y,
                        elements,
                        media,
                    );
                    place_cell_anchored(
                        &paragraph.anchored,
                        geometry,
                        &cell_geometry,
                        content_y,
                        paragraph.indent_left,
                        elements,
                        behind_elements,
                        media,
                    );
                    render_change_bar(
                        paragraph,
                        content_y,
                        paragraph.content_height(),
                        geometry,
                        page_number,
                        elements,
                    );
                }
                crate::table::CellBlock::Table(table) => {
                    let semantics = match block_semantics {
                        Some(CellBlockSemantics::Table(semantics)) => Some(semantics),
                        _ => None,
                    };
                    let nested_x = cell_x + cell.margin_left + table.table_indent;
                    let mut nested_y = geometry.margin_top + content_y;
                    for (nested_row_index, nested_row) in table.rows.iter().enumerate() {
                        render_table_row(
                            nested_row,
                            semantics.and_then(|semantics| semantics.rows.get(nested_row_index)),
                            &table.col_widths,
                            nested_x,
                            nested_y,
                            geometry,
                            page_number,
                            table.borders.as_ref(),
                            elements,
                            behind_elements,
                            media,
                        );
                        nested_y += nested_row.height;
                    }
                }
            }
            content_y += block.total_height();
        }
        if cell.clip_content {
            let clip = Some(Path::rect(Rect {
                x: cell_x,
                y: row_y,
                width: cell.width,
                height: paint_height,
            }));
            let children = elements.split_off(content_element_start);
            elements.push(PositionedElement::Group(GroupElement {
                transform: Transform::IDENTITY,
                clip: clip.clone(),
                opacity: 1.0,
                effects: Vec::new(),
                children,
            }));
            let children = behind_elements.split_off(behind_element_start);
            if !children.is_empty() {
                behind_elements.push(PositionedElement::Group(GroupElement {
                    transform: Transform::IDENTITY,
                    clip,
                    opacity: 1.0,
                    effects: Vec::new(),
                    children,
                }));
            }
        }
        cell_x += cell.width;
    }
}

fn place_cell_anchored(
    anchors: &[AnchoredDrawing],
    page_geometry: &PageGeometry,
    cell_geometry: &PageGeometry,
    paragraph_top: f64,
    paragraph_indent: f64,
    elements: &mut Vec<PositionedElement>,
    behind_elements: &mut Vec<PositionedElement>,
    media: &HashMap<MediaId, ImageData>,
) {
    for anchor in anchors {
        let horizontal_geometry = match anchor.rel_h {
            ST_RelativeFromH::Column | ST_RelativeFromH::Character => cell_geometry,
            _ => page_geometry,
        };
        let x = resolve_anchor_h(
            anchor.rel_h,
            anchor.off_h,
            anchor.align_h,
            anchor.width,
            horizontal_geometry,
            paragraph_indent,
        );
        let y = resolve_anchor_v(
            anchor.rel_v,
            anchor.off_v,
            anchor.align_v,
            anchor.height,
            page_geometry,
            paragraph_top,
        );
        let rect = Rect {
            x,
            y,
            width: anchor.width,
            height: anchor.height,
        };
        let mut produced = anchored_elements(anchor, rect, page_geometry, media);
        if anchor.behind_doc {
            behind_elements.append(&mut produced);
        } else {
            elements.append(&mut produced);
        }
    }
}

/// Render borders for a table cell.
fn render_cell_borders(
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    cell_borders: &Option<rdocx_oxml::table::CT_TblBorders>,
    table_borders: Option<&rdocx_oxml::table::CT_TblBorders>,
    cell_idx: usize,
    num_cells: usize,
    is_first_row: bool,
    is_last_row: bool,
    elements: &mut Vec<PositionedElement>,
) {
    // Determine effective border for each edge (cell overrides table)
    let get_edge = |cell_edge: Option<&rdocx_oxml::borders::CT_BorderEdge>,
                    table_edge: Option<&rdocx_oxml::borders::CT_BorderEdge>,
                    outer_edge: bool|
     -> Option<BorderEdge> {
        let edge = match cell_edge {
            Some(edge) if edge.val == ST_Border::None && outer_edge => table_edge?,
            Some(edge) => edge,
            None => table_edge?,
        };
        if edge.val == ST_Border::None {
            return None;
        }
        let thickness = edge.sz.unwrap_or(4) as f64 / 8.0; // sz is in 1/8 pt
        let color = edge
            .color
            .as_ref()
            .filter(|c| c.as_str() != "auto")
            .map(|c| Color::from_hex(c))
            .unwrap_or(Color::BLACK);
        let dash = border_dash_pattern(edge.val, thickness);
        Some((thickness, color, dash))
    };

    // Top border: use table top for first row, table insideH otherwise
    let table_top = table_borders.and_then(|b| {
        if is_first_row {
            b.top.as_ref()
        } else {
            b.inside_h.as_ref()
        }
    });
    let cell_top = cell_borders.as_ref().and_then(|b| b.top.as_ref());
    if let Some((thickness, color, dash_pattern)) = get_edge(cell_top, table_top, is_first_row) {
        elements.push(PositionedElement::Line {
            start: Point { x, y },
            end: Point { x: x + w, y },
            width: thickness,
            color,
            dash_pattern,
        });
    }

    // Bottom border: use table bottom for last row, table insideH otherwise
    let table_bottom = table_borders.and_then(|b| {
        if is_last_row {
            b.bottom.as_ref()
        } else {
            b.inside_h.as_ref()
        }
    });
    let cell_bottom = cell_borders.as_ref().and_then(|b| b.bottom.as_ref());
    if let Some((thickness, color, dash_pattern)) = get_edge(cell_bottom, table_bottom, is_last_row)
    {
        elements.push(PositionedElement::Line {
            start: Point { x, y: y + h },
            end: Point { x: x + w, y: y + h },
            width: thickness,
            color,
            dash_pattern,
        });
    }

    // Left border: use table left for first cell, table insideV otherwise
    let table_left = table_borders.and_then(|b| {
        if cell_idx == 0 {
            b.left.as_ref()
        } else {
            b.inside_v.as_ref()
        }
    });
    let cell_left = cell_borders.as_ref().and_then(|b| b.left.as_ref());
    if let Some((thickness, color, dash_pattern)) = get_edge(cell_left, table_left, cell_idx == 0) {
        elements.push(PositionedElement::Line {
            start: Point { x, y },
            end: Point { x, y: y + h },
            width: thickness,
            color,
            dash_pattern,
        });
    }

    // Right border: use table right for last cell, table insideV otherwise
    let table_right = table_borders.and_then(|b| {
        if cell_idx == num_cells - 1 {
            b.right.as_ref()
        } else {
            b.inside_v.as_ref()
        }
    });
    let cell_right = cell_borders.as_ref().and_then(|b| b.right.as_ref());
    if let Some((thickness, color, dash_pattern)) =
        get_edge(cell_right, table_right, cell_idx == num_cells - 1)
    {
        elements.push(PositionedElement::Line {
            start: Point { x: x + w, y },
            end: Point { x: x + w, y: y + h },
            width: thickness,
            color,
            dash_pattern,
        });
    }
}

/// Render paragraph border edges as positioned lines.
fn render_border_edges(
    borders: &rdocx_oxml::borders::CT_PBdr,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    elements: &mut Vec<PositionedElement>,
) {
    let render_edge = |edge: &rdocx_oxml::borders::CT_BorderEdge,
                       start: Point,
                       end: Point,
                       elements: &mut Vec<PositionedElement>| {
        if edge.val == ST_Border::None {
            return;
        }
        let thickness = edge.sz.unwrap_or(4) as f64 / 8.0; // sz is in eighths of a point
        let color = edge
            .color
            .as_ref()
            .filter(|c| c.as_str() != "auto")
            .map(|c| Color::from_hex(c))
            .unwrap_or(Color::BLACK);
        let dash_pattern = border_dash_pattern(edge.val, thickness);

        if edge.val == ST_Border::Double {
            // Double border: emit two parallel lines
            let gap = thickness * 2.0;
            let dx = end.x - start.x;
            let dy = end.y - start.y;
            let len = (dx * dx + dy * dy).sqrt();
            let (nx, ny) = if len > 0.0 {
                (-dy / len, dx / len)
            } else {
                (0.0, 1.0)
            };
            let offset = gap / 2.0;
            elements.push(PositionedElement::Line {
                start: Point {
                    x: start.x + nx * offset,
                    y: start.y + ny * offset,
                },
                end: Point {
                    x: end.x + nx * offset,
                    y: end.y + ny * offset,
                },
                width: thickness,
                color,
                dash_pattern: None,
            });
            elements.push(PositionedElement::Line {
                start: Point {
                    x: start.x - nx * offset,
                    y: start.y - ny * offset,
                },
                end: Point {
                    x: end.x - nx * offset,
                    y: end.y - ny * offset,
                },
                width: thickness,
                color,
                dash_pattern: None,
            });
        } else {
            elements.push(PositionedElement::Line {
                start,
                end,
                width: thickness,
                color,
                dash_pattern,
            });
        }
    };

    if let Some(ref edge) = borders.top {
        let space = edge.space.unwrap_or(0) as f64;
        render_edge(
            edge,
            Point { x, y: y - space },
            Point {
                x: x + w,
                y: y - space,
            },
            elements,
        );
    }
    if let Some(ref edge) = borders.bottom {
        let space = edge.space.unwrap_or(0) as f64;
        render_edge(
            edge,
            Point {
                x,
                y: y + h + space,
            },
            Point {
                x: x + w,
                y: y + h + space,
            },
            elements,
        );
    }
    if let Some(ref edge) = borders.left {
        let space = edge.space.unwrap_or(0) as f64;
        render_edge(
            edge,
            Point { x: x - space, y },
            Point {
                x: x - space,
                y: y + h,
            },
            elements,
        );
    }
    if let Some(ref edge) = borders.right {
        let space = edge.space.unwrap_or(0) as f64;
        render_edge(
            edge,
            Point {
                x: x + w + space,
                y,
            },
            Point {
                x: x + w + space,
                y: y + h,
            },
            elements,
        );
    }
}

/// Map a border style to a dash pattern (dash_on, dash_off) in points.
/// Returns None for solid lines (Single, Thick, Double, etc.).
fn border_dash_pattern(style: ST_Border, thickness: f64) -> Option<(f64, f64)> {
    match style {
        ST_Border::Dashed => Some((3.0 * thickness, 2.0 * thickness)),
        ST_Border::Dotted => Some((thickness, thickness)),
        ST_Border::DotDash | ST_Border::DotDotDash => Some((3.0 * thickness, thickness)),
        _ => None,
    }
}

/// Count inter-word gap positions in a line (spaces within text segments).
fn count_word_gaps(items: &[LineItem]) -> usize {
    let mut count = 0;
    for item in items {
        match item {
            LineItem::Text(seg) | LineItem::Marker(seg) => {
                count += seg.text.chars().filter(|c| *c == ' ').count();
            }
            LineItem::Tab { .. } => {
                count += 1;
            }
            _ => {}
        }
    }
    count
}

/// Distribute extra justify space across advances by widening space-character advances.
fn distribute_justify_advances(text: &str, advances: &[f64], extra_per_gap: f64) -> Vec<f64> {
    let chars: Vec<char> = text.chars().collect();
    let mut result = advances.to_vec();

    if chars.len() == result.len() {
        // 1:1 char-to-glyph mapping
        for (i, &ch) in chars.iter().enumerate() {
            if ch == ' ' {
                result[i] += extra_per_gap;
            }
        }
    } else {
        // Fallback: distribute evenly across all glyphs
        let total_extra = extra_per_gap * text.chars().filter(|c| *c == ' ').count() as f64;
        if !result.is_empty() {
            let per_glyph = total_extra / result.len() as f64;
            for a in &mut result {
                *a += per_glyph;
            }
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::block::ParagraphBlock;
    use oxml_layout::LayoutLine;

    fn empty_media() -> MediaRegistry {
        MediaRegistry::new(&HashMap::new())
    }

    fn make_line(height: f64) -> LayoutLine {
        LayoutLine {
            items: vec![],
            width: 100.0,
            ascent: height * 0.77,
            descent: height * 0.23,
            line_gap: 0.0,
            height,
            indent_left: 0.0,
            available_width: 468.0,
            is_last: true,
        }
    }

    fn make_para(line_count: usize, line_height: f64) -> ParagraphBlock {
        let mut lines = Vec::new();
        for _ in 0..line_count {
            lines.push(make_line(line_height));
        }
        ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines,
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        }
    }

    #[test]
    fn descriptionless_inline_drawings_are_paragraph_artifacts() {
        let mut paragraph = make_para(1, 14.0);
        paragraph.structure_id = oxml_layout::StructureId::new(1);
        paragraph.lines[0].items = vec![
            LineItem::Image {
                width: 10.0,
                height: 10.0,
                media_id: MediaId(1),
            },
            LineItem::Group {
                width: 10.0,
                height: 10.0,
                group: oxml_layout::GroupElement {
                    transform: oxml_layout::Transform::IDENTITY,
                    clip: None,
                    opacity: 1.0,
                    effects: Vec::new(),
                    children: vec![PositionedElement::FilledRect {
                        rect: Rect {
                            x: 0.0,
                            y: 0.0,
                            width: 10.0,
                            height: 10.0,
                        },
                        color: Color::BLACK,
                    }],
                },
            },
        ];
        let mut elements = Vec::new();
        let media = HashMap::new();

        render_paragraph_lines(
            &paragraph.lines,
            ParagraphView {
                block: &paragraph,
                semantics: None,
            },
            &PageGeometry::default(),
            0.0,
            &mut elements,
            &media,
        );

        assert_eq!(elements.len(), 2);
        assert!(elements.iter().all(|element| matches!(
            element,
            PositionedElement::MarkedContent {
                structure: None,
                children,
            } if matches!(
                children.as_slice(),
                [PositionedElement::Image { .. }] | [PositionedElement::Group(_)]
            )
        )));
    }

    #[test]
    fn single_page_layout() {
        let fm = FontManager::new();
        let blocks = vec![LayoutBlock::Paragraph(make_para(3, 14.0))];
        let geom = PageGeometry::default();
        let (pages, _outlines) = paginate(
            &blocks,
            geom,
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        assert_eq!(pages.len(), 1);
        assert_eq!(pages[0].page_number, 1);
    }

    #[test]
    fn multi_page_overflow() {
        let fm = FontManager::new();
        // 648pt content height / 14pt per line ≈ 46 lines per page
        let blocks = vec![LayoutBlock::Paragraph(make_para(100, 14.0))];
        let geom = PageGeometry::default();
        let (pages, _outlines) = paginate(
            &blocks,
            geom,
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        assert!(pages.len() >= 2);
    }

    #[test]
    fn forced_page_break() {
        let fm = FontManager::new();
        let mut para2 = make_para(3, 14.0);
        para2.page_break_before = true;
        let blocks = vec![
            LayoutBlock::Paragraph(make_para(3, 14.0)),
            LayoutBlock::Paragraph(para2),
        ];
        let geom = PageGeometry::default();
        let (pages, _outlines) = paginate(
            &blocks,
            geom,
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        assert_eq!(pages.len(), 2);
    }

    #[test]
    fn page_dimensions() {
        let fm = FontManager::new();
        let blocks = vec![LayoutBlock::Paragraph(make_para(1, 14.0))];
        let geom = PageGeometry::default();
        let (pages, _outlines) = paginate(
            &blocks,
            geom,
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        assert!((pages[0].width - 612.0).abs() < 0.01);
        assert!((pages[0].height - 792.0).abs() < 0.01);
    }

    fn make_text_line(height: f64, underline: Option<Underline>, strike: bool) -> LayoutLine {
        use oxml_layout::TextSegment;
        let seg = TextSegment {
            text: "Hello".to_string(),
            source: None,
            font_id: oxml_layout::FontId(0),
            font_size: 12.0,
            glyph_ids: vec![1, 2, 3],
            advances: vec![6.0, 6.0, 6.0],
            width: 40.0,
            ascent: height * 0.77,
            descent: height * 0.23,
            line_gap: 0.0,
            color: Color::BLACK,
            bold: false,
            italic: false,
            underline,
            strike,
            dstrike: false,
            highlight: None,
            baseline_offset: 0.0,
            hyperlink_url: None,
            field_kind: None,
            note: None,
        };
        LayoutLine {
            items: vec![LineItem::Text(seg)],
            width: 40.0,
            ascent: height * 0.77,
            descent: height * 0.23,
            line_gap: 0.0,
            height,
            indent_left: 0.0,
            available_width: 468.0,
            is_last: true,
        }
    }

    #[test]
    fn underline_renders_line_element() {
        let fm = FontManager::new();
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![make_text_line(14.0, Some(Underline::Single), false)],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };
        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        // Should have Text + Line (underline)
        let lines: Vec<_> = pages[0]
            .elements
            .iter()
            .filter(|e| matches!(e, PositionedElement::Line { .. }))
            .collect();
        assert_eq!(lines.len(), 1, "expected 1 underline line");
    }

    #[test]
    fn strikethrough_renders_line_element() {
        let fm = FontManager::new();
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![make_text_line(14.0, None, true)],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };
        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        let lines: Vec<_> = pages[0]
            .elements
            .iter()
            .filter(|e| matches!(e, PositionedElement::Line { .. }))
            .collect();
        assert_eq!(lines.len(), 1, "expected 1 strikethrough line");
    }

    #[test]
    fn highlight_renders_filled_rect() {
        use oxml_layout::TextSegment;
        let fm = FontManager::new();
        let seg = TextSegment {
            text: "Hi".to_string(),
            source: None,
            font_id: oxml_layout::FontId(0),
            font_size: 12.0,
            glyph_ids: vec![1],
            advances: vec![10.0],
            width: 20.0,
            ascent: 10.0,
            descent: 3.0,
            line_gap: 0.0,
            color: Color::BLACK,
            bold: false,
            italic: false,
            underline: None,
            strike: false,
            dstrike: false,
            highlight: Some(Color {
                r: 1.0,
                g: 1.0,
                b: 0.0,
                a: 1.0,
            }),
            baseline_offset: 0.0,
            hyperlink_url: None,
            field_kind: None,
            note: None,
        };
        let line = LayoutLine {
            items: vec![LineItem::Text(seg)],
            width: 20.0,
            ascent: 10.0,
            descent: 3.0,
            line_gap: 0.0,
            height: 13.0,
            indent_left: 0.0,
            available_width: 468.0,
            is_last: true,
        };
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![line],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };
        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        let rects: Vec<_> = pages[0]
            .elements
            .iter()
            .filter(|e| matches!(e, PositionedElement::FilledRect { .. }))
            .collect();
        assert_eq!(rects.len(), 1, "expected 1 highlight rect");
    }

    #[test]
    fn paragraph_borders_render_lines() {
        use rdocx_oxml::borders::{CT_BorderEdge, CT_PBdr};
        let fm = FontManager::new();
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![make_line(14.0)],
            space_before: 0.0,
            space_after: 0.0,
            borders: Some(CT_PBdr {
                top: Some(CT_BorderEdge {
                    val: ST_Border::Single,
                    sz: Some(4),
                    space: Some(1),
                    color: Some("000000".to_string()),
                }),
                bottom: Some(CT_BorderEdge {
                    val: ST_Border::Single,
                    sz: Some(4),
                    space: Some(1),
                    color: Some("000000".to_string()),
                }),
                ..Default::default()
            }),
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };
        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        let lines: Vec<_> = pages[0]
            .elements
            .iter()
            .filter(|e| matches!(e, PositionedElement::Line { .. }))
            .collect();
        assert_eq!(lines.len(), 2, "expected 2 border lines (top + bottom)");
    }

    #[test]
    fn paragraph_shading_renders_filled_rect() {
        let fm = FontManager::new();
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![make_line(14.0)],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: Some(Color {
                r: 1.0,
                g: 1.0,
                b: 0.0,
                a: 1.0,
            }),
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };
        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        let rects: Vec<_> = pages[0]
            .elements
            .iter()
            .filter(|e| matches!(e, PositionedElement::FilledRect { .. }))
            .collect();
        assert_eq!(rects.len(), 1, "expected 1 paragraph shading rect");
    }

    #[test]
    fn double_underline_renders_two_lines() {
        let fm = FontManager::new();
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![make_text_line(14.0, Some(Underline::Double), false)],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };
        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        let lines: Vec<_> = pages[0]
            .elements
            .iter()
            .filter(|e| matches!(e, PositionedElement::Line { .. }))
            .collect();
        assert_eq!(lines.len(), 2, "expected 2 lines for double underline");
    }

    fn make_justified_line(text: &str, seg_width: f64, is_last: bool) -> LayoutLine {
        use oxml_layout::TextSegment;
        let seg = TextSegment {
            text: text.to_string(),
            source: None,
            font_id: oxml_layout::FontId(0),
            font_size: 12.0,
            glyph_ids: vec![1; text.len()],
            advances: vec![seg_width / text.len() as f64; text.len()],
            width: seg_width,
            ascent: 10.0,
            descent: 3.0,
            line_gap: 0.0,
            color: Color::BLACK,
            bold: false,
            italic: false,
            underline: None,
            strike: false,
            dstrike: false,
            highlight: None,
            baseline_offset: 0.0,
            hyperlink_url: None,
            field_kind: None,
            note: None,
        };
        LayoutLine {
            items: vec![LineItem::Text(seg)],
            width: seg_width,
            ascent: 10.0,
            descent: 3.0,
            line_gap: 0.0,
            height: 13.0,
            indent_left: 0.0,
            available_width: 468.0,
            is_last,
        }
    }

    #[test]
    fn hyperlink_emits_link_annotation() {
        use oxml_layout::TextSegment;
        let fm = FontManager::new();
        let seg = TextSegment {
            text: "Click me".to_string(),
            source: None,
            font_id: oxml_layout::FontId(0),
            font_size: 12.0,
            glyph_ids: vec![1, 2, 3],
            advances: vec![8.0, 8.0, 8.0],
            width: 60.0,
            ascent: 10.0,
            descent: 3.0,
            line_gap: 0.0,
            color: Color::BLACK,
            bold: false,
            italic: false,
            underline: None,
            strike: false,
            dstrike: false,
            highlight: None,
            baseline_offset: 0.0,
            hyperlink_url: Some("https://example.com".to_string()),
            field_kind: None,
            note: None,
        };
        let line = LayoutLine {
            items: vec![LineItem::Text(seg)],
            width: 60.0,
            ascent: 10.0,
            descent: 3.0,
            line_gap: 0.0,
            height: 13.0,
            indent_left: 0.0,
            available_width: 468.0,
            is_last: true,
        };
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![line],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: None,
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };
        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );
        let annotations: Vec<_> = pages[0]
            .elements
            .iter()
            .filter(|e| matches!(e, PositionedElement::LinkAnnotation { .. }))
            .collect();
        assert_eq!(annotations.len(), 1, "expected 1 link annotation");
        if let PositionedElement::LinkAnnotation { url, .. } = annotations[0] {
            assert_eq!(url, "https://example.com");
        }
    }

    #[test]
    fn justified_text_fills_line_width() {
        let fm = FontManager::new();
        // Line with "Hello World" (1 space = 1 gap), width 200 out of 468 available
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![
                make_justified_line("Hello World", 200.0, false),
                make_justified_line("End.", 40.0, true),
            ],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: Some(Align::Justify),
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };

        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );

        // The first line's text run should have widened advances
        let first_text = pages[0].elements.iter().find_map(|e| {
            if let PositionedElement::Text(run) = e {
                Some(run)
            } else {
                None
            }
        });
        assert!(first_text.is_some());
        let run = first_text.unwrap();
        // The total advance should be wider than the original 200pt
        let total_advance: f64 = run.advances.iter().sum();
        assert!(
            total_advance > 200.0,
            "justified text should be wider than original: {total_advance}"
        );
    }

    #[test]
    fn justified_last_line_stays_left_aligned() {
        let fm = FontManager::new();
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![
                make_justified_line("Hello World Test", 200.0, false),
                make_justified_line("End.", 40.0, true),
            ],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: Some(Align::Justify),
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };

        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );

        // Find the second text run (last line)
        let text_runs: Vec<_> = pages[0]
            .elements
            .iter()
            .filter_map(|e| {
                if let PositionedElement::Text(run) = e {
                    Some(run)
                } else {
                    None
                }
            })
            .collect();

        assert!(text_runs.len() >= 2);
        // Last line should NOT be stretched — advances should sum to original width
        let last_advance: f64 = text_runs[1].advances.iter().sum();
        assert!(
            (last_advance - 40.0).abs() < 0.1,
            "last line should stay at original width: {last_advance}"
        );
    }

    #[test]
    fn justified_single_word_not_stretched() {
        let fm = FontManager::new();
        // A line with a single word (no spaces) should not be stretched
        let para = ParagraphBlock {
            anchored: Vec::new(),
            has_visible_revision: false,
            lines: vec![
                make_justified_line("Superlongword", 100.0, false),
                make_justified_line("End.", 40.0, true),
            ],
            space_before: 0.0,
            space_after: 0.0,
            borders: None,
            shading: None,
            indent_left: 0.0,
            indent_right: 0.0,
            jc: Some(Align::Justify),
            keep_next: false,
            keep_lines: false,
            page_break_before: false,
            widow_control: true,
            heading_level: None,
            heading_text: None,
            list: None,
            structure_id: None,
            reflow: None,
            content_offset_top: 0.0,
        };

        let blocks = vec![LayoutBlock::Paragraph(para)];
        let (pages, _outlines) = paginate(
            &blocks,
            PageGeometry::default(),
            None,
            false,
            &fm,
            &empty_media(),
            &NoteRegistry::default(),
        );

        let first_text = pages[0].elements.iter().find_map(|e| {
            if let PositionedElement::Text(run) = e {
                Some(run)
            } else {
                None
            }
        });
        assert!(first_text.is_some());
        let run = first_text.unwrap();
        let total_advance: f64 = run.advances.iter().sum();
        // No spaces → no stretching
        assert!(
            (total_advance - 100.0).abs() < 0.1,
            "single word should not be stretched: {total_advance}"
        );
    }

    /// A wp:anchor offset means nothing without the frame it is measured from.
    /// Treating every offset as a page coordinate put anchored drawings in the
    /// corner of the sheet instead of beside their paragraph.
    #[test]
    fn anchor_offsets_resolve_against_their_frame() {
        let g = PageGeometry::default(); // 612 x 792, 72pt margins
        let para_top = 100.0;
        let off = 10.0;

        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::Page, off, None, 0.0, &g, 0.0),
            10.0
        );
        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::LeftMargin, off, None, 0.0, &g, 0.0),
            10.0
        );
        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::Margin, off, None, 0.0, &g, 0.0),
            82.0,
            "margin-relative starts at the left margin"
        );
        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::Column, off, None, 0.0, &g, 0.0),
            82.0,
            "column-relative starts at the text area"
        );
        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::RightMargin, off, None, 0.0, &g, 0.0),
            550.0,
            "right-margin-relative starts at the right margin edge"
        );
        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::Character, off, None, 0.0, &g, 36.0),
            118.0,
            "character-relative includes the paragraph indent"
        );

        assert_eq!(
            resolve_anchor_v(ST_RelativeFromV::Page, off, None, 0.0, &g, para_top),
            10.0
        );
        assert_eq!(
            resolve_anchor_v(ST_RelativeFromV::TopMargin, off, None, 0.0, &g, para_top),
            10.0
        );
        assert_eq!(
            resolve_anchor_v(ST_RelativeFromV::Margin, off, None, 0.0, &g, para_top),
            82.0
        );
        assert_eq!(
            resolve_anchor_v(ST_RelativeFromV::Paragraph, off, None, 0.0, &g, para_top),
            182.0,
            "paragraph-relative follows the paragraph down the page"
        );
        assert_eq!(
            resolve_anchor_v(ST_RelativeFromV::Line, off, None, 0.0, &g, para_top),
            182.0
        );
        assert_eq!(
            resolve_anchor_v(ST_RelativeFromV::BottomMargin, off, None, 0.0, &g, para_top),
            730.0
        );
    }

    #[test]
    fn cell_anchors_use_cell_coordinates_and_page_behind_order() {
        let page = PageGeometry::default();
        let cell = PageGeometry {
            margin_left: 200.0,
            margin_right: 0.0,
            page_width: 300.0,
            ..page
        };
        let anchor = |behind_doc| AnchoredDrawing {
            behind_doc,
            rel_h: ST_RelativeFromH::Column,
            off_h: 5.0,
            rel_v: ST_RelativeFromV::Paragraph,
            off_v: 4.0,
            width: 20.0,
            height: 10.0,
            wrap: WrapType::None,
            dist_top: 0.0,
            dist_bottom: 0.0,
            dist_left: 0.0,
            dist_right: 0.0,
            align_h: None,
            align_v: None,
            content: AnchoredContent::Shape {
                preset: ShapePreset::Rect,
                fill: Some(Color::from_hex("CC0000")),
                text: Vec::new(),
            },
            alternate_text: Some("cell stamp".to_owned()),
            structure_id: None,
        };
        let mut foreground = Vec::new();
        let mut behind = Vec::new();
        place_cell_anchored(
            &[anchor(false)],
            &page,
            &cell,
            30.0,
            0.0,
            &mut foreground,
            &mut behind,
            &HashMap::new(),
        );
        let PositionedElement::MarkedContent { children, .. } = &foreground[0] else {
            panic!("foreground anchor remains marked content");
        };
        let PositionedElement::FilledRect { rect, .. } = children[0] else {
            panic!("foreground stamp rectangle");
        };
        assert_eq!(rect.x, 205.0);
        assert_eq!(rect.y, page.margin_top + 34.0);
        assert!(behind.is_empty());

        let mut character_anchor = anchor(false);
        character_anchor.rel_h = ST_RelativeFromH::Character;
        let mut character_elements = Vec::new();
        place_cell_anchored(
            &[character_anchor],
            &page,
            &cell,
            30.0,
            12.0,
            &mut character_elements,
            &mut behind,
            &HashMap::new(),
        );
        let PositionedElement::MarkedContent { children, .. } = &character_elements[0] else {
            panic!("character anchor remains marked content");
        };
        let PositionedElement::FilledRect { rect, .. } = children[0] else {
            panic!("character stamp rectangle");
        };
        assert_eq!(rect.x, 217.0, "character origin includes paragraph indent");

        place_cell_anchored(
            &[anchor(true)],
            &page,
            &cell,
            30.0,
            0.0,
            &mut foreground,
            &mut behind,
            &HashMap::new(),
        );
        assert_eq!(foreground.len(), 1);
        assert_eq!(behind.len(), 1);
        let mut page_order = behind;
        page_order.extend(foreground);
        let PositionedElement::MarkedContent { children, .. } = &page_order[0] else {
            panic!("behind anchor remains marked content");
        };
        assert!(matches!(children[0], PositionedElement::FilledRect { .. }));
    }

    #[test]
    fn exact_height_cell_content_is_group_clipped_to_the_row() {
        let mut paragraph = make_para(2, 12.0);
        paragraph.lines = vec![
            make_text_line(12.0, None, false),
            make_text_line(12.0, None, false),
        ];
        let row = crate::table::TableRow {
            structure_id: None,
            cells: vec![crate::table::TableCell {
                structure_id: None,
                blocks: vec![crate::table::CellBlock::Paragraph(paragraph)],
                width: 40.0,
                height: 10.0,
                grid_span: 1,
                is_vmerge_continue: false,
                starts_vmerge: false,
                merged_height: 10.0,
                merge_with_below: false,
                clip_content: true,
                col_index: 0,
                borders: None,
                shading: None,
                margin_left: 0.0,
                margin_right: 0.0,
                margin_top: 0.0,
                margin_bottom: 0.0,
                is_first_row: true,
                is_last_row: true,
                v_align: None,
            }],
            height: 10.0,
            is_header: false,
        };
        let mut elements = Vec::new();
        render_table_row(
            &row,
            None,
            &[40.0],
            10.0,
            20.0,
            &PageGeometry::default(),
            0,
            None,
            &mut elements,
            &mut Vec::new(),
            &HashMap::new(),
        );
        let [PositionedElement::Group(group)] = elements.as_slice() else {
            panic!("exact cell content is one clipped group: {elements:?}");
        };
        assert!(group.clip.is_some());
        assert_eq!(
            group.children.len(),
            2,
            "both overflow lines remain in the clip"
        );
    }

    #[test]
    fn outer_nil_border_matches_word_without_changing_interior_nil() {
        use rdocx_oxml::borders::CT_BorderEdge;
        use rdocx_oxml::table::CT_TblBorders;

        let mut visible = CT_BorderEdge::new(ST_Border::Single);
        visible.sz = Some(8);
        visible.color = Some("112233".to_owned());
        let nil = CT_BorderEdge::new(ST_Border::None);
        let table = CT_TblBorders {
            top: Some(visible.clone()),
            bottom: Some(visible.clone()),
            left: Some(visible.clone()),
            right: Some(visible.clone()),
            inside_h: Some(visible.clone()),
            inside_v: Some(visible),
        };
        let cell = Some(CT_TblBorders {
            top: Some(nil.clone()),
            bottom: Some(nil.clone()),
            left: Some(nil.clone()),
            right: Some(nil),
            inside_h: None,
            inside_v: None,
        });

        let mut outer = Vec::new();
        render_cell_borders(
            10.0,
            20.0,
            30.0,
            40.0,
            &cell,
            Some(&table),
            0,
            1,
            true,
            true,
            &mut outer,
        );
        assert_eq!(outer.len(), 4, "four outer edges fall back to the table");

        let mut interior = Vec::new();
        render_cell_borders(
            10.0,
            20.0,
            30.0,
            40.0,
            &cell,
            Some(&table),
            1,
            3,
            false,
            false,
            &mut interior,
        );
        assert!(interior.is_empty(), "interior nil remains suppressive");
    }

    /// The same offset must land somewhere different once the paragraph moves.
    /// This is the property the old code could not express at all.
    #[test]
    fn paragraph_relative_anchor_tracks_the_paragraph() {
        let g = PageGeometry::default();
        let near_top = resolve_anchor_v(ST_RelativeFromV::Paragraph, 5.0, None, 0.0, &g, 0.0);
        let further_down = resolve_anchor_v(ST_RelativeFromV::Paragraph, 5.0, None, 0.0, &g, 300.0);
        assert_eq!(near_top, 77.0);
        assert_eq!(further_down, 377.0);
        assert!(further_down > near_top);
    }

    // F-X016, alignment placement and text wrapping.

    #[test]
    fn an_aligned_anchor_resolves_against_its_frame() {
        let g = PageGeometry::default();
        let width = 100.0;
        let height = 50.0;

        // Margin frame: the text area.
        let text_left = g.margin_left;
        let text_width = g.page_width - g.margin_left - g.margin_right;

        assert_eq!(
            resolve_anchor_h(
                ST_RelativeFromH::Margin,
                999.0,
                Some(AnchorAlignH::Left),
                width,
                &g,
                0.0
            ),
            text_left,
            "an alignment replaces the offset rather than adding to it"
        );
        assert_eq!(
            resolve_anchor_h(
                ST_RelativeFromH::Margin,
                0.0,
                Some(AnchorAlignH::Right),
                width,
                &g,
                0.0
            ),
            text_left + text_width - width
        );
        assert_eq!(
            resolve_anchor_h(
                ST_RelativeFromH::Margin,
                0.0,
                Some(AnchorAlignH::Center),
                width,
                &g,
                0.0
            ),
            text_left + (text_width - width) / 2.0
        );

        // Page frame, vertical axis.
        assert_eq!(
            resolve_anchor_v(
                ST_RelativeFromV::Page,
                0.0,
                Some(AnchorAlignV::Top),
                height,
                &g,
                0.0
            ),
            0.0
        );
        assert_eq!(
            resolve_anchor_v(
                ST_RelativeFromV::Page,
                0.0,
                Some(AnchorAlignV::Bottom),
                height,
                &g,
                0.0
            ),
            g.page_height - height
        );
    }

    #[test]
    fn an_anchor_without_an_alignment_still_uses_its_offset() {
        // This is what keeps every existing baseline still.
        let g = PageGeometry::default();
        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::Page, 10.0, None, 100.0, &g, 0.0),
            10.0
        );
        assert_eq!(
            resolve_anchor_h(ST_RelativeFromH::Margin, 10.0, None, 100.0, &g, 0.0),
            g.margin_left + 10.0
        );
        assert_eq!(
            resolve_anchor_v(ST_RelativeFromV::Paragraph, 5.0, None, 50.0, &g, 300.0),
            g.margin_top + 300.0 + 5.0
        );
    }

    // F-X019, paragraph-relative drawings in later blocks should wrap.

    fn wrapping_drawing(rel_v: ST_RelativeFromV) -> AnchoredDrawing {
        AnchoredDrawing {
            behind_doc: false,
            rel_h: ST_RelativeFromH::Margin,
            off_h: 0.0,
            rel_v,
            off_v: 0.0,
            width: 100.0,
            height: 50.0,
            wrap: WrapType::Square,
            dist_top: 0.0,
            dist_bottom: 0.0,
            dist_left: 0.0,
            dist_right: 0.0,
            align_h: None,
            align_v: None,
            content: AnchoredContent::Image {
                media_id: MediaId(1),
            },
            alternate_text: None,
            structure_id: None,
        }
    }

    fn para_anchoring(rel_v: ST_RelativeFromV) -> LayoutBlock {
        let mut para = make_para(1, 14.0);
        para.anchored = vec![wrapping_drawing(rel_v)];
        LayoutBlock::Paragraph(para)
    }

    #[test]
    fn the_two_pass_predicate_matches_only_paragraph_relative_wraps() {
        assert!(!has_paragraph_relative_wrap(&[LayoutBlock::Paragraph(
            make_para(3, 14.0)
        )]));
        assert!(!has_paragraph_relative_wrap(&[para_anchoring(
            ST_RelativeFromV::Page
        )]));
        assert!(has_paragraph_relative_wrap(&[para_anchoring(
            ST_RelativeFromV::Paragraph
        )]));
        assert!(has_paragraph_relative_wrap(&[para_anchoring(
            ST_RelativeFromV::Line
        )]));

        // A paragraph-relative drawing that does not wrap pushes nothing
        // aside, so it must not buy the document a second pass.
        let mut still = wrapping_drawing(ST_RelativeFromV::Paragraph);
        still.wrap = WrapType::None;
        let mut para = make_para(1, 14.0);
        para.anchored = vec![still];
        assert!(!has_paragraph_relative_wrap(&[LayoutBlock::Paragraph(
            para
        )]));
    }

    #[test]
    fn pass_one_ignores_paragraph_relative_anchors() {
        let fm = FontManager::new();
        let media = HashMap::new();
        let notes = NoteRegistry::default();
        let empty = ResolvedWraps::new();
        let blocks = vec![
            LayoutBlock::Paragraph(make_para(3, 14.0)),
            para_anchoring(ST_RelativeFromV::Paragraph),
            para_anchoring(ST_RelativeFromV::Page),
        ];
        let pager = Pager::new(
            PageGeometry::default(),
            None,
            false,
            &media,
            &notes,
            &fm,
            &empty,
            1,
            1,
            true,
            None,
        );

        // With nothing resolved, the look-ahead offers the page-relative
        // drawing and nothing else, which is what it did before this story.
        assert_eq!(pager.lookahead_wraps(0, &blocks).len(), 1);
    }

    #[test]
    fn the_lookahead_offers_a_resolved_rect_only_on_its_own_page() {
        let fm = FontManager::new();
        let media = HashMap::new();
        let notes = NoteRegistry::default();
        let blocks = vec![
            LayoutBlock::Paragraph(make_para(3, 14.0)),
            para_anchoring(ST_RelativeFromV::Paragraph),
        ];
        let placed = PlacedWrap {
            rect: Rect {
                x: 100.0,
                y: 200.0,
                width: 100.0,
                height: 50.0,
            },
            wrap: WrapType::Square,
            dist_top: 0.0,
            dist_bottom: 0.0,
            dist_left: 0.0,
            dist_right: 0.0,
        };

        for (recorded_page, expected) in [(1usize, 1usize), (2, 0)] {
            let mut resolved = ResolvedWraps::new();
            resolved.insert((1, 0), (recorded_page, placed));
            let pager = Pager::new(
                PageGeometry::default(),
                None,
                false,
                &media,
                &notes,
                &fm,
                &resolved,
                1,
                1,
                true,
                None,
            );

            // The pager is building page one. A drawing the previous pass put
            // on page two must not push page one's text aside.
            assert_eq!(
                pager.lookahead_wraps(0, &blocks).len(),
                expected,
                "recorded on page {recorded_page}"
            );
        }
    }

    #[test]
    fn a_placed_paragraph_relative_wrap_is_recorded_for_the_next_pass() {
        let fm = FontManager::new();
        let media = HashMap::new();
        let notes = NoteRegistry::default();
        let empty = ResolvedWraps::new();
        let blocks = vec![
            LayoutBlock::Paragraph(make_para(3, 14.0)),
            para_anchoring(ST_RelativeFromV::Paragraph),
            para_anchoring(ST_RelativeFromV::Page),
        ];

        let context = PassContext {
            geometry: PageGeometry::default(),
            header_footer: None,
            title_pg: false,
            fm: &fm,
            media: &media,
            notes: &notes,
            first_page_number: 1,
            first_header_page_number: 1,
        };
        let pass = paginate_pass(&blocks, &context, &empty);

        // Only the paragraph-relative one is recorded. The page-relative one
        // needs no second pass to be known.
        assert_eq!(pass.resolved.len(), 1);
        let (page, placed) = pass.resolved.get(&(1, 0)).expect("block one, anchor zero");
        assert_eq!(*page, 1);
        assert_eq!(placed.wrap, WrapType::Square);
    }
}