rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
//! 도형/글상자/그룹 개체 레이아웃

mod affine_line;
mod compound_rectangle;
mod connector_style;
mod curve_geometry;
mod line_direction;
mod overlay_textbox;
mod path_stroke_arrows;
mod source_line_frame;
mod textbox_reflow;

use super::super::composer::{
    captioned_shape_height_px, compose_paragraph, reflow_line_segs, shape_caption_for_layout,
    ComposedParagraph, ParagraphBox,
};
use super::super::page_layout::LayoutRect;
use super::super::pagination::PageItem;
use super::super::render_tree::*;
use super::super::style_resolver::ResolvedStyleSet;
use super::super::{
    hwpunit_to_px, px_to_hwpunit, PathCommand, ShapeStyle, TextStyle, HWPUNIT_PER_INCH,
};
use super::paragraph_layout::{
    center_alignment_excludes_trailing_space, trailing_space_width_after_last_inline_object,
};
use super::text_measurement::{
    estimate_text_width, is_cjk_char, is_vertical_rotate_char, resolved_to_text_style,
    vertical_substitute_char,
};
use super::utils::{
    drawing_to_line_style, drawing_to_shape_style, extract_shape_transform, find_bin_data,
    find_bin_data_bytes,
};
use super::LayoutEngine;
use super::{CellContext, CellPathEntry};

/// 여러 단 걸침 개체의 원본 자리차지 높이와 실제 Square 배제 상자(HU).
/// Square는 폭/높이만 재추정하지 않고 조판이 사용하는 ObjectPlacementFrame 결과를 소비한다.
#[derive(Default)]
pub(crate) struct PageSpanningFloatFrames {
    pub(crate) topbottom_heights: Vec<i32>,
    pub(crate) square_exclusions: Vec<crate::renderer::layout_frame::FrameExclusion>,
}

/// 묶음의 자식별 글상자 번호를 모든 편집 소비 지점에 같은 원문 순서로 전달한다.
/// 좌표·clip·paint는 변경하지 않는다. 중첩 묶음에서 이미 구분한 자식 번호에는 바깥 오프셋만 더한다.
fn offset_group_textbox_sources(node: &mut RenderNode, depth: usize, offset: usize) {
    fn adjust(ctx: &mut CellContext, depth: usize, offset: usize) {
        if let Some(entry) = ctx.path.get_mut(depth) {
            entry.cell_index += offset;
        }
    }
    if let Some((_, ctx)) = &mut node.textbox_source {
        adjust(ctx, depth, offset);
    }
    let context = match &mut node.node_type {
        RenderNodeType::TextRun(run) => run.cell_context.as_mut(),
        RenderNodeType::Table(table) => table.cell_context.as_mut(),
        RenderNodeType::Image(image) => image.cell_context.as_mut(),
        RenderNodeType::RawSvg(svg) => svg.cell_context.as_mut(),
        RenderNodeType::Placeholder(placeholder) => placeholder.cell_context.as_mut(),
        _ => None,
    };
    if let Some(ctx) = context {
        adjust(ctx, depth, offset);
    }
    if let RenderNodeType::Image(image) = &mut node.node_type {
        if let Some(ctx) = &image.cell_context {
            (
                image.cell_index,
                image.cell_para_index,
                image.outer_table_control_index,
            ) = ctx.last_image_indices();
        }
    }
    for child in &mut node.children {
        offset_group_textbox_sources(child, depth, offset);
    }
}
use crate::model::bin_data::BinDataContent;
use crate::model::control::Control;
use crate::model::paragraph::Paragraph;
use crate::model::shape::{Caption, CommonObjAttr, DrawingObjAttr, ShapeObject, TextBox};
use crate::model::shape::{HorzAlign, HorzRelTo, TextWrap, VertAlign, VertRelTo};
use crate::model::style::{Alignment, FillType};

/// 묶음 자식의 AABB에서 부호 있는 점 좌표 원점과 배율을 복원한다.
/// 음수 축의 원점은 오른쪽/아래쪽 변이다. 상자·텍스트 소속은 이동하지 않고
/// 실제 경로 점에만 대칭을 적용하며 비대각 회전은 기존 affine 경로가 담당한다.
fn group_point_frame(
    sa: &crate::model::shape::ShapeComponentAttr,
    matrix_positioned: bool,
    origin: (f64, f64),
    size: (f64, f64),
    scale: (f64, f64),
) -> (f64, f64, f64, f64) {
    let flip_x = matrix_positioned && sa.render_sx < 0.0;
    let flip_y = matrix_positioned && sa.render_sy < 0.0;
    (
        origin.0 + if flip_x { size.0 } else { 0.0 },
        origin.1 + if flip_y { size.1 } else { 0.0 },
        if flip_x { -scale.0 } else { scale.0 },
        if flip_y { -scale.1 } else { scale.1 },
    )
}

/// 저장한 화살촉이 있으면 모양·크기·끝점 소유를 그대로 사용한다.
/// 연결선 종류의 기본 화살표는 장식 정보가 전혀 없는 생성 경로에만 적용한다.
fn connector_line_style(
    drawing: &DrawingObjAttr,
    link_type: crate::model::shape::LinkLineType,
) -> super::super::LineStyle {
    use super::super::ArrowStyle;
    let style = drawing_to_line_style(drawing);
    if style.start_arrow == ArrowStyle::None && style.end_arrow == ArrowStyle::None {
        connector_style::with_direction(style, link_type)
    } else {
        style
    }
}

/// 글상자에 공백이 아닌 실제 텍스트가 한 글자라도 있는지.
/// 그림을 원래 크기로 상자 안 한 자리에 놓는 채우기 모드.
fn is_placement_fill_mode(mode: crate::model::style::ImageFillMode) -> bool {
    use crate::model::style::ImageFillMode as M;
    matches!(
        mode,
        M::Center
            | M::CenterTop
            | M::CenterBottom
            | M::LeftCenter
            | M::LeftTop
            | M::LeftBottom
            | M::RightCenter
            | M::RightTop
            | M::RightBottom
    )
}

fn textbox_contains_non_tac_picture(text_box: &TextBox) -> bool {
    text_box.paragraphs.iter().any(|para| {
        para.controls
            .iter()
            .any(|control| matches!(control, Control::Picture(pic) if !pic.common.treat_as_char))
    })
}

fn textbox_vpos_origin_hu(common: &CommonObjAttr, matrix_positioned: bool) -> Option<i32> {
    if matrix_positioned || common.treat_as_char {
        return None;
    }
    if !matches!(common.vert_rel_to, VertRelTo::Paper | VertRelTo::Page)
        || !matches!(common.vert_align, VertAlign::Top | VertAlign::Inside)
    {
        return None;
    }

    let origin = crate::renderer::float_placement::signed_hwpunit(common.vertical_offset);
    // 쪽 오프셋이 상자 자체 높이 안에 있으면 저장 줄 vpos를 쪽 좌표로 단정할 수 없다.
    // 이 경우 첫 줄의 상자 내부 여백을 보존한다. 쪽 좌표가 분명한 오프셋만 재기저화한다.
    (origin > 0 && origin >= common.height as i32).then_some(origin)
}

fn normalize_textbox_vpos_hu(vertical_pos: i32, origin_hu: Option<i32>) -> i32 {
    match origin_hu {
        Some(origin) if origin > 0 && vertical_pos >= origin => vertical_pos - origin,
        _ => vertical_pos,
    }
}

fn textbox_vpos_px(vertical_pos: i32, origin_hu: Option<i32>, dpi: f64) -> f64 {
    hwpunit_to_px(normalize_textbox_vpos_hu(vertical_pos, origin_hu), dpi)
}

/// 글상자 안 글앞으로/글뒤로 표의 (가로, 세로) 오프셋(px). 오프셋에 표 바깥 여백(왼쪽·위)을 더한다.
/// 가로 단·문단 기준 왼쪽 정렬, 세로 문단 기준만 다룬다. 그 밖의 배치는 None 이며 기존처럼 문단 정렬로 놓는다.
fn textbox_floating_table_offset_px(
    common: &CommonObjAttr,
    outer_margin_left: i16,
    outer_margin_top: i16,
    unstored: bool,
    dpi: f64,
) -> Option<(f64, f64)> {
    let floating = matches!(
        common.text_wrap,
        TextWrap::InFrontOfText | TextWrap::BehindText
    );
    let horz = matches!(common.horz_rel_to, HorzRelTo::Column | HorzRelTo::Para)
        && common.horz_align == HorzAlign::Left;
    let vert = common.vert_rel_to == VertRelTo::Para && common.vert_align == VertAlign::Top;
    (!common.treat_as_char && floating && horz && vert).then(|| {
        // 저장 줄 없는 자유 배치 표는 정렬할 글 흐름·바깥 여백을 소유하지 않는다.
        let free = unstored && !common.flow_with_text;
        let margin_left = if free {
            0.0
        } else {
            f64::from(outer_margin_left)
        };
        let margin_top = if free {
            0.0
        } else {
            f64::from(outer_margin_top)
        };
        (
            // 부호 있는 저장 오프셋과 여백은 합계가 i32 범위를 넘을 수 있다.
            // f64는 이 정수 범위를 정확히 표현하므로 좌표를 자르거나 감싸지 않는다.
            (common.horizontal_offset as i32 as f64 + margin_left) * dpi / HWPUNIT_PER_INCH,
            (if unstored && common.flow_with_text {
                // 글상자 안 영역 제한은 음수 문단 오프셋을 내용 위끝에서 제한한다.
                f64::from((common.vertical_offset as i32).max(0))
            } else {
                common.vertical_offset as i32 as f64
            } + margin_top)
                * dpi
                / HWPUNIT_PER_INCH,
        )
    })
}

/// [PK-40987] 저장 줄 없는 글상자 문단에 놓인 문단 기준 자리차지(위아래) 표의 띠.
///
/// 한컴(웹한글기안기 인쇄·화면 실측)은 이 표를 `문단 위끝 + 세로 오프셋 + 바깥 위 여백` 에 놓고, 다음
/// 문단을 `표 바닥 + 바깥 아래 여백` 에서 시작한다. 빈 앵커 문단의 자기 줄은 그 띠에 흡수되고,
/// 글 있는 앵커 문단은 띠에 걸리는 줄만 띠 아래로 간다(띠 위의 줄은 제자리).
/// 가로·세로 정렬은 단·문단 기준 왼쪽, 문단 기준 위만 다룬다. 앵커 문단의 컨트롤은 이런 표뿐이어야 한다.
/// 돌려주는 값은 문단 위끝 기준 (가로 오프셋, 표 위 오프셋, 띠 아래끝) px 이며, 해당하지 않으면 `None` 이다.
fn textbox_topbottom_table_band_px(
    para: &Paragraph,
    table: &crate::model::table::Table,
    dpi: f64,
) -> Option<(f64, f64, f64)> {
    let common = &table.common;
    if !textbox_topbottom_table_shape(table)
        || !crate::renderer::para_has_no_stored_line_segs(para)
        || !para.controls.iter().all(|control| match control {
            Control::Table(other) => textbox_topbottom_table_shape(other),
            _ => false,
        })
    {
        return None;
    }
    let px = |hu: f64| hu * dpi / HWPUNIT_PER_INCH;
    let top = common.vertical_offset as i32 as f64 + f64::from(table.outer_margin_top);
    let bottom = top + f64::from(common.height) + f64::from(table.outer_margin_bottom);
    Some((
        px(common.horizontal_offset as i32 as f64 + f64::from(table.outer_margin_left)),
        px(top),
        px(bottom),
    ))
}

/// [PK-40987] 띠 계약이 다루는 표 형상(글자처럼 아님, 자리차지, 문단 기준 위, 단·문단 기준 왼쪽).
fn textbox_topbottom_table_shape(table: &crate::model::table::Table) -> bool {
    let common = &table.common;
    !common.treat_as_char
        && common.text_wrap == TextWrap::TopAndBottom
        && common.vert_rel_to == VertRelTo::Para
        && common.vert_align == VertAlign::Top
        && matches!(common.horz_rel_to, HorzRelTo::Column | HorzRelTo::Para)
        && common.horz_align == HorzAlign::Left
}

/// [PK-40987] 문단이 가진 띠 표들의 (가장 위 표 위, 가장 아래 띠 끝)(문단 위끝 기준 px).
fn textbox_topbottom_table_band_extent_px(para: &Paragraph, dpi: f64) -> Option<(f64, f64)> {
    para.controls
        .iter()
        .filter_map(|control| match control {
            Control::Table(table) => textbox_topbottom_table_band_px(para, table, dpi),
            _ => None,
        })
        .map(|(_, top, bottom)| (top, bottom))
        .reduce(|(t0, b0), (t1, b1)| (t0.min(t1), b0.max(b1)))
}

/// [PK-40987] 저장 줄 있는 글상자의 세로 정렬 높이에 드는 비글자처럼 표의 바닥(문단 저장 vpos 기준 HU).
/// 문단 기준 위 정렬의 글 앞으로·글 뒤로·자리차지 표만 다룬다: 세로 오프셋 + 바깥 위 + 높이 + 바깥 아래.
fn textbox_stored_table_bottom_hu(table: &crate::model::table::Table) -> Option<i32> {
    let common = &table.common;
    (!common.treat_as_char
        && matches!(
            common.text_wrap,
            TextWrap::InFrontOfText | TextWrap::BehindText | TextWrap::TopAndBottom
        )
        && common.vert_rel_to == VertRelTo::Para
        && common.vert_align == VertAlign::Top)
        .then(|| {
            (common.vertical_offset as i32)
                .saturating_add(i32::from(table.outer_margin_top))
                .saturating_add(common.height as i32)
                .saturating_add(i32::from(table.outer_margin_bottom))
        })
}

/// [PK-40987] 저장 줄 있는 글상자 문단의 앵커 위끝이 첫 저장 줄보다 위에 있는 양(HU, 0 이상).
///
/// 한컴은 자리차지 표 띠가 앵커 문단의 줄을 밀면 그 줄을 띠 아래에 저장한다(실문서: 앞 문단 끝
/// 44967 + 오프셋 164 + 바깥 위 283 + 높이 11650 + 바깥 아래 283 = 앵커 줄 57347). 표 자리와 내용
/// 높이는 줄이 아니라 앞 문단 끝(앞 문단 마지막 줄 vpos + 줄 높이 + 줄 간격)을 문단 위끝으로 쓴다.
/// 앞 문단이 없거나 줄이 밀리지 않았으면 0 이다.
fn textbox_stored_anchor_lift_hu(paragraphs: &[Paragraph], index: usize) -> i32 {
    let Some(own) = paragraphs
        .get(index)
        .and_then(|para| para.line_segs.first())
        .map(|line| line.vertical_pos)
    else {
        return 0;
    };
    let Some(previous_end) = index
        .checked_sub(1)
        .and_then(|prev| paragraphs.get(prev))
        .and_then(|para| para.line_segs.last())
        .map(|line| {
            line.vertical_pos
                .saturating_add(line.line_height)
                .saturating_add(line.line_spacing)
        })
    else {
        return 0;
    };
    own.saturating_sub(previous_end).max(0)
}

/// [PK-40987] 저장 줄 있는 글상자 문단의 자리차지 표 자리(가로·세로 오프셋 + 바깥 여백, px).
/// 저장 줄이 뒤 흐름을 이미 담으므로 표 자리만 글 앞으로 표와 같은 오프셋에 놓는다. 띠가 앵커 줄을
/// 민 문단은 앞 문단 끝을 문단 위끝으로 쓴다(`anchor_lift_hu`).
fn textbox_stored_topbottom_table_offset_px(
    para: &Paragraph,
    table: &crate::model::table::Table,
    anchor_lift_hu: i32,
    dpi: f64,
) -> Option<(f64, f64)> {
    let common = &table.common;
    (textbox_topbottom_table_shape(table) && !crate::renderer::para_has_no_stored_line_segs(para))
        .then(|| {
            (
                (common.horizontal_offset as i32 as f64 + f64::from(table.outer_margin_left)) * dpi
                    / HWPUNIT_PER_INCH,
                (common.vertical_offset as i32 as f64 + f64::from(table.outer_margin_top)
                    - f64::from(anchor_lift_hu))
                    * dpi
                    / HWPUNIT_PER_INCH,
            )
        })
}

fn push_placeholder_render_node(
    tree: &mut PageLayoutContext,
    parent: &mut RenderNode,
    bbox: BoundingBox,
    fill_color: u32,
    stroke_color: u32,
    label: String,
) {
    let node_id = tree.next_id();
    let node = RenderNode::new(
        node_id,
        RenderNodeType::Placeholder(crate::renderer::render_tree::PlaceholderNode::new(
            fill_color,
            stroke_color,
            label,
        )),
        bbox,
    );
    parent.children.push(node);
}

/// [#4694] 셀/글상자 안 ole 의 컨테이너 문맥. 비어 있으면(본문 직속) None —
/// 방출도 비어 selection ref 가 3좌표로 유지된다(회귀 0).
fn ole_cell_context(
    parent_cell_path: &[CellPathEntry],
    para_index: usize,
) -> Option<crate::renderer::layout::CellContext> {
    (!parent_cell_path.is_empty()).then(|| crate::renderer::layout::CellContext {
        in_textbox: false,
        parent_para_index: para_index,
        path: parent_cell_path.to_vec(),
    })
}

fn push_ole_placeholder_render_node(
    tree: &mut PageLayoutContext,
    parent: &mut RenderNode,
    bbox: BoundingBox,
    fill_color: u32,
    stroke_color: u32,
    label: String,
    section_index: usize,
    para_index: usize,
    control_index: usize,
    parent_cell_path: &[CellPathEntry],
) {
    let node_id = tree.next_id();
    let node = RenderNode::new(
        node_id,
        RenderNodeType::Placeholder(crate::renderer::render_tree::PlaceholderNode::ole(
            fill_color,
            stroke_color,
            label,
            section_index,
            para_index,
            control_index,
            ole_cell_context(parent_cell_path, para_index),
        )),
        bbox,
    );
    parent.children.push(node);
}

fn push_raw_svg_render_node(
    tree: &mut PageLayoutContext,
    parent: &mut RenderNode,
    bbox: BoundingBox,
    svg: String,
) {
    let node_id = tree.next_id();
    let node = RenderNode::new(
        node_id,
        RenderNodeType::RawSvg(crate::renderer::render_tree::RawSvgNode::new(svg)),
        bbox,
    );
    parent.children.push(node);
}

fn push_ole_raw_svg_render_node(
    tree: &mut PageLayoutContext,
    parent: &mut RenderNode,
    bbox: BoundingBox,
    svg: String,
    section_index: usize,
    para_index: usize,
    control_index: usize,
    parent_cell_path: &[CellPathEntry],
) {
    let node_id = tree.next_id();
    let node = RenderNode::new(
        node_id,
        RenderNodeType::RawSvg(crate::renderer::render_tree::RawSvgNode::ole(
            svg,
            section_index,
            para_index,
            control_index,
            ole_cell_context(parent_cell_path, para_index),
        )),
        bbox,
    );
    parent.children.push(node);
}

fn push_ole_empty_para_end_anchor(
    tree: &mut PageLayoutContext,
    parent: &mut RenderNode,
    anchor_x: f64,
    anchor_y: f64,
    para: &Paragraph,
    section_index: usize,
    para_index: usize,
    styles: &ResolvedStyleSet,
) {
    let char_shape_id = para.char_shape_id_at(0).unwrap_or(0);
    let style = resolved_to_text_style(styles, char_shape_id, 0);
    let line_height = para
        .line_segs
        .first()
        .map(|line| hwpunit_to_px(line.line_height, crate::renderer::DEFAULT_DPI))
        .filter(|height| *height > 0.0)
        .unwrap_or_else(|| (style.font_size * 1.2).max(12.0));
    let baseline = para
        .line_segs
        .first()
        .map(|line| hwpunit_to_px(line.baseline_distance, crate::renderer::DEFAULT_DPI))
        .filter(|baseline| *baseline > 0.0)
        .unwrap_or(style.font_size * 0.85);

    let node = RenderNode::new(
        tree.next_id(),
        RenderNodeType::TextRun(TextRunNode {
            text: String::new(),
            style,
            char_shape_id: Some(char_shape_id),
            para_shape_id: Some(para.para_shape_id),
            section_index: Some(section_index),
            para_index: Some(para_index),
            char_start: Some(0),
            cell_context: None,
            is_para_end: true,
            is_line_break_end: false,
            rotation: 0.0,
            is_vertical: false,
            char_overlap: None,
            border_fill_id: 0,
            baseline,
            field_marker: FieldMarkerType::None,
            layout_positions: None,
            display_text: None,
        }),
        BoundingBox::new(anchor_x, anchor_y, 0.0, line_height),
    );
    parent.children.push(node);
}

fn ole_chart_fallback_label(message: impl AsRef<str>, bin_data_id: u32) -> String {
    format!("{} (BinData #{bin_data_id})", message.as_ref())
}

fn measure_composed_text_range_width(
    composed: &ComposedParagraph,
    styles: &ResolvedStyleSet,
    start: usize,
    end: usize,
    space_advance_override: Option<f64>,
) -> f64 {
    match measure_composed_text_range_width_with_storage(
        composed,
        styles,
        start,
        end,
        space_advance_override,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn measure_composed_text_range_width_with_storage<S: crate::storage::Storage>(
    composed: &ComposedParagraph,
    styles: &ResolvedStyleSet,
    start: usize,
    end: usize,
    space_advance_override: Option<f64>,
    storage: &S,
) -> Result<f64, S::Error> {
    Ok({
        if start >= end {
            return Ok(0.0);
        }

        let tab_width = styles
            .para_styles
            .get(composed.para_style_id as usize)
            .map(|s| styles.default_tab_width(s.default_tab_width))
            .unwrap_or(0.0);
        let mut width = 0.0;

        for line in &composed.lines {
            let mut run_start = line.char_start;
            for run in &line.runs {
                let run_len = run.text.chars().count();
                let run_end = run_start + run_len;
                let seg_start = start.max(run_start);
                let seg_end = end.min(run_end);

                if seg_start < seg_end {
                    let seg_text = storage.chars(
                        run.text
                            .chars()
                            .skip(seg_start - run_start)
                            .take(seg_end - seg_start),
                    )?;
                    if let Some(space_advance) = space_advance_override {
                        let space_count = seg_text.chars().filter(|&ch| ch == ' ').count();
                        if space_count > 0 && seg_text.chars().all(|ch| ch == ' ') {
                            width += space_advance * space_count as f64;
                            run_start = run_end;
                            continue;
                        }
                    }
                    let mut style = run.try_text_style(styles, storage)?;
                    style.default_tab_width = tab_width;
                    width += super::text_measurement::estimate_text_width_with_storage(
                        &seg_text, &style, storage,
                    )?;
                }

                run_start = run_end;
            }
        }

        width
    })
}

fn textbox_tac_space_advance_override(
    para: &Paragraph,
    composed: &ComposedParagraph,
    total_inline_width: f64,
    alignment: Alignment,
    dpi: f64,
) -> Option<f64> {
    if !matches!(alignment, Alignment::Left)
        || total_inline_width <= 0.0
        // A table's leading spaces are a text prefix, not spacing distributed
        // between the picture glyphs of a stored logo line.
        || para.controls.iter().any(|control| {
            matches!(control, Control::Table(table) if table.common.treat_as_char)
        })
    {
        return None;
    }

    let first_line = composed.lines.first()?;
    let mut space_count = 0usize;
    let mut has_non_space_text = false;
    for run in &first_line.runs {
        for ch in run.text.chars() {
            if ch == ' ' {
                space_count += 1;
            } else {
                has_non_space_text = true;
            }
        }
    }
    if space_count == 0 || has_non_space_text {
        return None;
    }

    let line_width_hu = para
        .line_segs
        .first()
        .map(|seg| seg.segment_width)
        .unwrap_or(first_line.segment_width);
    if line_width_hu <= 0 {
        return None;
    }

    // HWPX 글상자 안의 TAC 그림 사이 공백은 직접 run charPr의 음수 자간으로
    // 압축하지 않고, 문단 스타일(예: 바탕글)로 이미 조판된 lineSeg 폭을 따른다.
    // 순수 공백 + TAC 컨트롤만 있는 라인은 lineSeg.horzsize가 한컴의 공백
    // advance 계약값이므로, 남은 폭을 공백 개수로 나눠 사용한다.
    let line_width = hwpunit_to_px(line_width_hu, dpi);
    let remaining = line_width - total_inline_width;
    if remaining > 0.0 {
        Some(remaining / space_count as f64)
    } else {
        None
    }
}

fn matrix_textbox_lines_need_reflow(para: &Paragraph) -> bool {
    para.controls.is_empty()
        && !para.text.is_empty()
        && !para.text.contains('\n')
        && para.line_segs.len() > 1
}

/// [#9076] 글자 없는 문단의 저장 줄이 미기입 누름틀 안내문을 넣고 나눈 사다리이고, 그 문단에
/// 글자처럼 취급 개체가 있는가.
///
/// 한/글은 안내문을 문단 글자로 저장하고 인쇄에서는 안내문 없이 줄을 다시 나눈다(#9005).
/// 안내문만 있던 줄이 사라지고 개체가 앞 줄로 올라오므로 저장 줄로는 개체의 줄을 정할 수 없다.
/// 개체 줄은 높이가 개체에서 나와, 다시 나눈 사다리가 안내문 없는 한/글 저장값과 같다.
/// 글자가 있는 문단은 다시 나누면 한/글의 글자 줄 높이를 잃으므로 저장 줄을 그대로 쓴다.
fn hidden_guide_object_rows_need_reflow(para: &Paragraph) -> bool {
    para.text.is_empty()
        && para.stored_rows_include_hidden_guide()
        && para.controls.iter().any(Control::is_treat_as_char_object)
}

/// A content-grown, unprotected inline textbox may retain a wrapped cache after
/// its full text fits the unchanged width. Project both its text and host frame
/// together; a paint-only collapse would leave the old height in pagination.
pub(crate) fn normalized_single_line_inline_textbox_host(
    host: &Paragraph,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> Option<Paragraph> {
    match normalized_single_line_inline_textbox_host_with_storage(
        host,
        styles,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn normalized_single_line_inline_textbox_host_with_storage<
    S: crate::storage::Storage,
>(
    host: &Paragraph,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<Option<Paragraph>, S::Error> {
    crate::storage::with_optional(|failure| {
        let [host_line] = host.line_segs.as_slice() else {
            return None;
        };
        let [Control::Shape(shape)] = host.controls.as_slice() else {
            return None;
        };
        let common = shape.common();
        let attr = shape.shape_attr();
        let drawing = shape.drawing()?;
        let text_box = drawing.text_box.as_ref()?;
        let [paragraph] = text_box.paragraphs.as_slice() else {
            return None;
        };
        let first = paragraph.line_segs.first()?;
        let last = paragraph.line_segs.last()?;
        if !host.text.is_empty()
            || host.stored_text_partition_is_dirty()
            || host.cell_format_vpos_dirty
            || host_line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
            || !common.treat_as_char
            || common.size_protect
            || drawing.caption.is_some()
            || common.height == 0
            || common.height > i32::MAX as u32
            || common.width == 0
            || common.width > i32::MAX as u32
            || attr.group_level != 0
            || attr.rotation_angle != 0
            || attr.render_b.abs() > 1e-6
            || attr.render_c.abs() > 1e-6
            || attr.render_ty.abs() > 1e-6
            || (attr.render_sx - 1.0).abs() > 1e-6
            || attr.original_width != common.width
            || attr.current_width != common.width
            || attr.original_height != common.height
            || attr.current_height <= common.height
            || attr.current_height > i32::MAX as u32
            || (attr.render_sy - f64::from(attr.current_height) / f64::from(attr.original_height))
                .abs()
                > 1e-6
            || host_line.line_height != shape.flow_height_hu()
            || host_line.segment_width <= 0
            || text_box.list_attr & 0x07 != 0
            || text_box.raw_list_header_extra.iter().any(|&byte| byte != 0)
            || [
                text_box.margin_left,
                text_box.margin_right,
                text_box.margin_top,
                text_box.margin_bottom,
            ]
            .iter()
            .any(|&margin| margin < 0)
            || !matrix_textbox_lines_need_reflow(paragraph)
            || paragraph.text.contains(['\r', '\t'])
            || paragraph.stored_text_partition_is_dirty()
            || first.vertical_pos != 0
            || first.text_start != 0
            || paragraph.line_segs.iter().any(|line| {
                line.line_height <= 0
                    || line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
            })
            || paragraph.line_seg_text_start(paragraph.line_segs.len() - 1)
                >= paragraph.char_offsets.last().copied()?.saturating_add(1)
        {
            return None;
        }
        let padding = i32::from(text_box.margin_top) + i32::from(text_box.margin_bottom);
        let cached_height = last
            .vertical_pos
            .checked_add(last.line_height)?
            .checked_add(padding)?;
        if cached_height != attr.current_height as i32 {
            return None;
        }
        let para_style = styles.para_styles.get(paragraph.para_shape_id as usize)?;
        let inner_width = hwpunit_to_px(
            common.width as i32
                - i32::from(text_box.margin_left)
                - i32::from(text_box.margin_right),
            dpi,
        ) - para_style.margin_left
            - para_style.margin_right
            - para_style.indent.max(0.0);
        let composed = crate::storage::optional(
            crate::renderer::composer::compose_paragraph_in_context_with_storage(
                paragraph, styles, storage,
            ),
            failure,
        )?;
        let width = crate::storage::optional(
            measure_composed_text_range_width_with_storage(
                &composed,
                styles,
                0,
                paragraph.text.chars().count(),
                None,
                storage,
            ),
            failure,
        )?;
        let height = first
            .line_height
            .checked_add(padding)?
            .max(common.height as i32);
        if inner_width <= 0.0
            || !width.is_finite()
            || width > inner_width
            || height >= attr.current_height as i32
        {
            return None;
        }
        let mut projected = crate::storage::optional(storage.clone_paragraph(host), failure)?;
        let Control::Shape(shape) = &mut projected.controls[0] else {
            return None;
        };
        let mut single_line =
            crate::storage::optional(crate::storage::try_clone(first, storage), failure)?;
        single_line.segment_width = px_to_hwpunit(inner_width, dpi);
        single_line.tag |= crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY;
        shape.drawing_mut()?.text_box.as_mut()?.paragraphs[0].replace_line_segs(
            crate::storage::optional(storage.collect([single_line]), failure)?,
        );
        let attr = shape.shape_attr_mut();
        attr.current_height = height as u32;
        attr.render_sy = f64::from(height) / f64::from(attr.original_height);
        attr.rotation_center.y = height / 2;
        crate::storage::optional(
            crate::renderer::composer::try_reflow_line_segs(
                &mut projected,
                ParagraphBox::content_width_px(hwpunit_to_px(host_line.segment_width, dpi), dpi),
                styles,
                dpi,
                storage,
            ),
            failure,
        )?;
        for line in &mut projected.line_segs {
            line.tag |= crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY;
        }
        Some(projected)
    })
}

fn matrix_textbox_lines_overflow_height(para: &Paragraph, available_height: f64, dpi: f64) -> bool {
    para.line_segs.last().is_some_and(|seg| {
        hwpunit_to_px(seg.vertical_pos.saturating_add(seg.line_height), dpi)
            > available_height + 0.5
    })
}

fn should_reflow_matrix_textbox_lines(
    matrix_positioned: bool,
    drawing: &DrawingObjAttr,
    text_box: &TextBox,
    text_direction: u8,
    available_width: f64,
    available_height: f64,
    dpi: f64,
) -> bool {
    if text_direction != 0 || available_width <= 0.0 || available_height <= 0.0 {
        return false;
    }

    if !matrix_positioned {
        return false;
    }

    let sa = &drawing.shape_attr;
    let has_axis_scale =
        (sa.render_sx.abs() - 1.0).abs() > 0.001 || (sa.render_sy.abs() - 1.0).abs() > 0.001;
    let has_rotation_or_shear = sa.render_b.abs() > 1e-6 || sa.render_c.abs() > 1e-6;
    // Y-only 축소(sy<1, sx≈1)는 저장 줄의 가로폭을 바꾸지 않는다. groupLevel>0 만으로
    // 재래핑하면 행정업무운영편람 바탕쪽 "업무관리시스템"처럼 저장 1글자×7줄이
    // 가용 폭(lastWidth 2374 HU) 기준 2글자 줄로 합쳐져 세로 제목이 깨진다.
    let width_compressed_group_child =
        sa.group_level > 0 && sa.render_sx > 0.0 && sa.render_sx < 0.99;
    has_axis_scale
        && !has_rotation_or_shear
        && text_box.paragraphs.iter().any(|para| {
            matrix_textbox_lines_need_reflow(para)
                && (width_compressed_group_child
                    || matrix_textbox_lines_overflow_height(para, available_height, dpi))
        })
}

fn reflow_matrix_textbox_para(
    para: &mut Paragraph,
    available_width: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
) {
    if !matrix_textbox_lines_need_reflow(para) {
        return;
    }

    textbox_reflow::in_frame(para, available_width, styles, dpi);
}

impl LayoutEngine {
    fn push_hwpx_hmapsi_preview_clip_node(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        bbox: BoundingBox,
        cfb_data: &[u8],
        section_index: usize,
        para_index: usize,
        control_index: usize,
        parent_cell_path: &[CellPathEntry],
    ) -> bool {
        if !self.profile.get().hwpx_stored_layout()
            || !crate::parser::ole_container::is_hmapsi_ole_container(cfb_data)
        {
            return false;
        }
        // [#4277] 페이지 기하는 프레임에서 읽는다 — 페인트 root 를 거치지 않는다.
        if tree.page_index() != 0 {
            return false;
        }
        let (page_width, page_height) = tree.page_size();
        let preview = self.hwpx_page_preview.borrow();
        let Some(preview) = preview.as_ref() else {
            return false;
        };

        use base64::Engine;
        let node_id = tree.next_id();
        let clip_id = format!("hmapsi-preview-clip-{node_id}");
        let href = format!(
            "data:{};base64,{}",
            preview.mime,
            base64::engine::general_purpose::STANDARD.encode(&preview.data)
        );
        let svg = format!(
            "<defs><clipPath id=\"{}\" clipPathUnits=\"userSpaceOnUse\"><rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\"/></clipPath></defs>\
<image x=\"0\" y=\"0\" width=\"{:.2}\" height=\"{:.2}\" preserveAspectRatio=\"none\" clip-path=\"url(#{})\" xlink:href=\"{}\" href=\"{}\"/>",
            clip_id,
            bbox.x,
            bbox.y,
            bbox.width,
            bbox.height,
            page_width,
            page_height,
            clip_id,
            href,
            href
        );
        let node = RenderNode::new(
            node_id,
            // HMapsi preview도 다른 OLE preview와 동일하게 원본 control을 보존한다.
            // 화면에는 이미 그려졌지만 ref가 없으면 getPageControlLayout()이 이를 `ole`
            // 선택 대상으로 방출하지 않아 Studio 클릭이 텍스트 hit-test로 빠진다 (#3319).
            RenderNodeType::RawSvg(crate::renderer::render_tree::RawSvgNode::ole(
                svg,
                section_index,
                para_index,
                control_index,
                ole_cell_context(parent_cell_path, para_index),
            )),
            bbox,
        );
        parent.children.push(node);
        true
    }

    pub(crate) fn scan_textbox_overflow(
        &self,
        paragraphs: &[Paragraph],
        shape_items: &[(i32, usize, usize, f64, Alignment)],
    ) -> std::collections::HashMap<(usize, usize), Vec<Paragraph>> {
        use crate::model::shape::ShapeObject;

        // 1단계: 오버플로우 문단 수집 (소스 텍스트박스에서)
        let mut overflow_paras: Vec<(i32, Vec<Paragraph>)> = Vec::new(); // (target_sw, paragraphs)
                                                                         // 빈 텍스트박스 수집 (타겟 후보)
        let mut empty_targets: Vec<(usize, usize, i32)> = Vec::new(); // (para_idx, ctrl_idx, inner_sw)

        for &(_, pi, ci, _, _) in shape_items {
            let para = match paragraphs.get(pi) {
                Some(p) => p,
                None => continue,
            };
            let ctrl = match para.controls.get(ci) {
                Some(c) => c,
                None => continue,
            };
            let drawing = match ctrl {
                Control::Shape(s) => match s.as_ref() {
                    ShapeObject::Rectangle(r) => &r.drawing,
                    _ => continue,
                },
                _ => continue,
            };
            let tb = match &drawing.text_box {
                Some(tb) => tb,
                None => continue,
            };

            // 텍스트가 있는 문단 수
            let has_text = tb.paragraphs.iter().any(|p| !p.text.is_empty());
            if !has_text {
                // 빈 텍스트박스: 첫 문단의 line_seg sw를 inner_sw로 사용하거나 계산
                // 실제로는 오버플로우 문단이 렌더링될 때 sw를 사용
                let inner_sw = tb
                    .paragraphs
                    .first()
                    .and_then(|p| p.line_segs.first())
                    .map(|ls| ls.segment_width)
                    .unwrap_or(0);
                empty_targets.push((pi, ci, inner_sw));
                continue;
            }

            // 오버플로우 감지: 첫 문단의 sw와 다른 sw를 가진 문단 찾기
            let first_sw = tb
                .paragraphs
                .first()
                .and_then(|p| p.line_segs.first())
                .map(|ls| ls.segment_width)
                .unwrap_or(0);
            let mut max_vpos_end: i32 = 0;
            let mut overflow_idx: Option<usize> = None;
            for (tpi, tp) in tb.paragraphs.iter().enumerate() {
                if let Some(first_ls) = tp.line_segs.first() {
                    if tpi > 0
                        && first_ls.segment_width != first_sw
                        && first_ls.vertical_pos < max_vpos_end
                    {
                        overflow_idx = Some(tpi);
                        break;
                    }
                    if let Some(last_ls) = tp.line_segs.last() {
                        let end = last_ls.vertical_pos.saturating_add(last_ls.line_height);
                        if end > max_vpos_end {
                            max_vpos_end = end;
                        }
                    }
                }
            }
            if let Some(oi) = overflow_idx {
                let target_sw = tb.paragraphs[oi]
                    .line_segs
                    .first()
                    .map(|ls| ls.segment_width)
                    .unwrap_or(0);
                let overflow: Vec<Paragraph> = tb.paragraphs[oi..].to_vec();
                overflow_paras.push((target_sw, overflow));
            }
        }

        // 2단계: 오버플로우 문단을 빈 텍스트박스에 매핑 (sw 매칭)
        let mut result = std::collections::HashMap::new();
        for (target_sw, paras) in overflow_paras {
            // sw가 가장 가까운 빈 텍스트박스 찾기
            let best = empty_targets
                .iter()
                .enumerate()
                .min_by_key(|(_, (_, _, esw))| (target_sw - *esw).abs());
            if let Some((idx, &(pi, ci, _))) = best {
                result.insert((pi, ci), paras);
                empty_targets.remove(idx);
            }
        }
        result
    }

    /// 도형(Shape) 레이아웃 - 시각 요소 + 글상자(TextBox) 포함
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn layout_shape(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        paragraphs: &[Paragraph],
        para_index: usize,
        control_index: usize,
        section_index: usize,
        styles: &ResolvedStyleSet,
        col_area: &LayoutRect,
        body_area: &LayoutRect,
        paper_area: &LayoutRect,
        para_y: f64,
        alignment: Alignment,
        bin_data_content: &[BinDataContent],
        overflow_map: &std::collections::HashMap<(usize, usize), Vec<Paragraph>>,
        clamp_negative_para_offset: bool,
        stored_frame_origin: Option<(f64, f64)>,
    ) {
        let para = match paragraphs.get(para_index) {
            Some(p) => p,
            None => return,
        };

        let ctrl = match para.controls.get(control_index) {
            Some(c) => c,
            None => return,
        };

        // 수식 컨트롤 처리
        if let Control::Equation(eq) = ctrl {
            // 인라인 좌표가 등록되어 있으면 paragraph_layout에서 이미 렌더링됨 → 스킵
            let inline_pos =
                tree.get_inline_shape_position(section_index, para_index, control_index, None);
            if inline_pos.is_some() {
                return;
            }

            self.layout_floating_equation(
                tree,
                parent,
                eq,
                section_index,
                para_index,
                control_index,
                col_area,
                body_area,
                paper_area,
                para_y,
                alignment,
            );
            return;
        }

        // [#6266] 비-TAC 양식 개체 — 자기 배치(기준·정렬·오프셋)대로 놓는다.
        // 종전에는 IR 에 배치가 없어 인라인으로만 그려졌다.
        if let Control::Form(form) = ctrl {
            if form.common.treat_as_char {
                return;
            }
            let (form_x, form_y) =
                self.form_object_origin(&form.common, col_area, body_area, paper_area, para_y);
            let form_w = hwpunit_to_px(form.common.width.max(form.width) as i32, self.dpi);
            let form_h = hwpunit_to_px(form.common.height.max(form.height) as i32, self.dpi);
            let form_node = RenderNode::new(
                tree.next_id(),
                RenderNodeType::FormObject(FormObjectNode {
                    form_type: form.form_type,
                    caption: form.caption.clone(),
                    text: form.text.clone(),
                    display_text: FormObjectNode::form_display_text(form),
                    appearance: crate::renderer::form_appearance::FormAppearance::resolve(
                        form,
                        styles,
                        para.char_shape_id_at(
                            para.logical_control_positions()
                                .get(control_index)
                                .copied()
                                .unwrap_or(0),
                        )
                        .unwrap_or(0),
                        self.dpi,
                    ),
                    fore_color: super::paragraph_layout::form_color_to_css(form.fore_color),
                    back_color: super::paragraph_layout::form_color_to_css(form.back_color),
                    value: form.value,
                    enabled: form.enabled,
                    section_index,
                    para_index,
                    control_index,
                    name: form.name.clone(),
                    cell_location: None,
                }),
                BoundingBox::new(form_x, form_y, form_w, form_h),
            );
            parent.children.push(form_node);
            return;
        }

        let shape = match ctrl {
            Control::Shape(s) => s.as_ref(),
            _ => return,
        };

        let common = shape.common();
        // [#6185] 세로 오프셋이 **자기 높이의 정확한 음수**인 자리차지 글상자는 그
        // 값이 배치 의도가 아니라 자기 변위 잔재다 — 한글은 무시하고 문단 자리에
        // 그린다(156570535 2쪽: offset -3736 = -(높이 3736), 한글 글상자 상단
        // 514.7 로 표 하단 499.5 아래. 적용하면 465.5 로 49.8px 올라가 표 둘째
        // 행을 통째로 덮는다). #6110 의 `vpos == 그림 높이` 자기-변위 지문과 같은 축.
        //
        // 지문이 **정확 일치**일 때만 발동한다 — 임의의 음수 오프셋은 실제 위치
        // 지정이므로 종전대로 적용한다.
        let self_displacement_offset = !common.treat_as_char
            && matches!(
                common.text_wrap,
                crate::model::shape::TextWrap::TopAndBottom
            )
            && matches!(common.vert_rel_to, crate::model::shape::VertRelTo::Para)
            && matches!(
                common.vert_align,
                crate::model::shape::VertAlign::Top | crate::model::shape::VertAlign::Inside
            )
            && common.height > 0
            && i64::from(crate::renderer::float_placement::signed_hwpunit(
                common.vertical_offset,
            )) == -i64::from(common.height as i32);
        let adjusted_common;
        let common_for_position = if self_displacement_offset
            || clamp_negative_para_offset
                && !common.treat_as_char
                && matches!(common.vert_rel_to, crate::model::shape::VertRelTo::Para)
                && matches!(
                    common.vert_align,
                    crate::model::shape::VertAlign::Top | crate::model::shape::VertAlign::Inside
                )
                && (common.vertical_offset as i32) < 0
        {
            adjusted_common = {
                let mut common = common.clone();
                common.vertical_offset = 0;
                common
            };
            &adjusted_common
        } else {
            common
        };

        let (mut shape_w, mut shape_h) =
            self.resolve_object_size(common, col_area, body_area, paper_area);
        if let Some(required) = shape.restricted_textbox_table_height_hu() {
            shape_h = shape_h.max(hwpunit_to_px(required, self.dpi));
        }

        if shape
            .drawing()
            .and_then(|drawing| drawing.text_box.as_ref())
            .is_some_and(textbox_contains_non_tac_picture)
        {
            let sa = shape.shape_attr();
            let cur_w = hwpunit_to_px(sa.current_width as i32, self.dpi);
            let cur_h = hwpunit_to_px(sa.current_height as i32, self.dpi);
            if cur_w > shape_w && cur_w > 0.0 {
                shape_w = cur_w;
            }
            if cur_h > shape_h && cur_h > 0.0 {
                shape_h = cur_h;
            }
        }

        // 부동 글상자의 내용 하한은 원점을 정하기 전에 확정한다. 아래 정렬,
        // 쪽 안 제한, 캡션과 실제 paint가 같은 높이·같은 글줄을 소비한다.
        // 묶음/셀의 직접 배치는 각 로컬·아핀 프레임의 소유를 유지한다.
        let prepared_textbox = if !extract_shape_transform(shape.shape_attr()).has_transform() {
            overlay_textbox::prepare(shape, shape_w, shape_h, styles, self.dpi)
        } else {
            None
        };
        if let Some(prepared) = &prepared_textbox {
            shape_h = prepared.height;
        }
        let shape = prepared_textbox
            .as_ref()
            .map_or(shape, |prepared| &prepared.shape);

        // 문단 여백 반영: Para 기준 위치 지정 시 문단의 왼쪽/오른쪽 여백 고려
        let composed_para = paragraphs.get(para_index).and_then(|_| {
            // composed 데이터가 없으므로 paragraphs에서 직접 para_shape_id 사용
            let pid = para.para_shape_id as usize;
            styles.para_styles.get(pid)
        });
        let para_margin_left = composed_para.map(|ps| ps.margin_left).unwrap_or(0.0);
        let para_margin_right = composed_para.map(|ps| ps.margin_right).unwrap_or(0.0);

        // 인라인 Shape: paragraph_layout에서 계산된 좌표가 있으면 사용
        let inline_pos = if common.treat_as_char {
            tree.get_inline_shape_position(section_index, para_index, control_index, None)
        } else {
            None
        };
        // [Issue #476] treat_as_char Shape는 paragraph_layout이 inline_pos 등록 후
        // 본 함수가 그려야 한다. inline_pos 가 없는 경우는 paginator 가 PageItem::Shape 를
        // 잘못된 페이지(박스가 속한 line이 라우팅되지 않은 페이지)에 등록한 결과이며,
        // compute_object_position fallback 으로 그리면 절대 좌표(예: 문단 오프셋=0,0)
        // 기준의 잘못된 위치에 박스가 출현한다 (= 다른 paragraph 영역에 침범).
        // 본질 수정 전까지(paginator A 단계) fallback 그리기를 차단한다.
        // 머리말/꼬리말 HWP3 선 개체는 inline 좌표 등록 없이 들어오는 경우가 있다.
        // 본문 TAC 안전장치는 유지하되 Header/Footer 선만 기존 위치 계산으로 복원한다.
        let allow_header_footer_line_fallback =
            clamp_negative_para_offset && matches!(shape, ShapeObject::Line(_));
        if common.treat_as_char && inline_pos.is_none() && !allow_header_footer_line_fallback {
            if std::env::var("RHWP_DEBUG_LAYOUT").is_ok() {
                eprintln!(
                    "[#476 skip] inline Shape without inline_pos: sec={} para={} ci={}",
                    section_index, para_index, control_index
                );
            }
            return;
        }

        // 통합 좌표 계산 (layout_body_picture와 동일 로직)
        let shape_container = LayoutRect {
            x: col_area.x + para_margin_left,
            y: para_y,
            width: col_area.width - para_margin_left - para_margin_right,
            height: col_area.height - (para_y - col_area.y).max(0.0),
        };
        // 조판이 원본 프레임으로 확정한 잉크 원점은 paint에서 다시 추정하지 않는다.
        let (shape_x, shape_y) = if let Some(origin) =
            stored_frame_origin.filter(|_| prepared_textbox.is_none())
        {
            origin
        } else if let Some((ix, iy)) = inline_pos {
            (ix, iy)
        } else {
            let (mut x, mut y) = self.compute_object_position(
                common_for_position,
                shape_w,
                shape_h,
                &shape_container,
                col_area,
                body_area,
                paper_area,
                para_y,
                alignment,
            );
            let overlay_margin =
                crate::renderer::float_placement::overlay_shape_margin_origin_hu(common);
            x += hwpunit_to_px(overlay_margin.0, self.dpi);
            y += hwpunit_to_px(overlay_margin.1, self.dpi);
            y += hwpunit_to_px(
                crate::renderer::float_placement::topbottom_shape_top_margin_hu(common)
                    + crate::renderer::float_placement::beside_shape_top_margin_hu(common),
                self.dpi,
            );
            // [#5808] 어울림(Square) **도형**의 왼쪽 바깥여백은 한글이 가로 위치에
            // 가산한다 (156518601 1쪽 묶음: 오프셋 29138+여백 566 HU = 471.6px,
            // 한글 실측 471.3 — 미가산이면 7.2px 왼쪽). 그림은 반대 계약이 이미
            // 핀돼 있다(#3821: 그림의 om_left 는 wrap 간격이지 위치 이동이 아님) —
            // 그림 경로가 함께 쓰는 compute_object_position 이 아니라 도형 호출부
            // 에서만 가산한다. 실측이 Left 정렬뿐이라 Center/Right 는 종전 유지.
            // 위 여백(#8399)과 Tight·Through 도 같은 바깥 상자 규칙이다.
            if crate::renderer::float_placement::shape_wraps_beside_text(common)
                && matches!(
                    common.horz_align,
                    crate::model::shape::HorzAlign::Left | crate::model::shape::HorzAlign::Inside
                )
            {
                x += hwpunit_to_px(i32::from(common.margin.left), self.dpi);
            }
            // 자리차지 OLE의 위 여백은 잉크 원점과 본문 예약 높이에 함께 속한다.
            // 일반 문단도 단 이월과 동일한 확정 프레임을 소비한다.
            let y = crate::renderer::float_placement::column_ole_placement(shape, para_y, self.dpi)
                .map_or(y, |placement| placement.table_top);
            (x, y)
        };

        // 캡션 높이 및 간격 계산
        let caption_opt = shape_caption_for_layout(shape);
        let caption = caption_opt.as_ref();
        let caption_height = self.calculate_caption_height(&caption_opt, styles);
        let caption_spacing = caption
            .map(|c| hwpunit_to_px(c.spacing as i32, self.dpi))
            .unwrap_or(0.0);

        use crate::model::shape::CaptionDirection;

        // 캡션 방향에 따라 도형 위치 오프셋 계산
        let (caption_top_offset, caption_left_offset) = if let Some(c) = caption {
            match c.direction {
                CaptionDirection::Top => (caption_height + caption_spacing, 0.0),
                CaptionDirection::Left => {
                    let cw = hwpunit_to_px(c.width as i32, self.dpi);
                    (0.0, cw + caption_spacing)
                }
                _ => (0.0, 0.0),
            }
        } else {
            (0.0, 0.0)
        };
        // [Issue #2075] restrictInPage(flow_with_text, HWP5 attr bit 13) 하단 클램프.
        // layout_body_picture(PR #2033, 이슈 #2032)에는 이 클램프가 있으나 도형 경로엔
        // 빠져 있었다("layout_body_picture와 동일 로직" 주석과 달리 미갱신). vert=Para +
        // 큰 vertOffset + restrictInPage=on 인 floating 도형이 페이지 밖 좌표로 계산되면
        // 어느 페이지에도 그려지지 않아 완전 소실됐다. 표/그림 동등 로직과 동일 시멘틱으로
        // 캡션 포함 프레임 하단이 단 영역을 넘으면 안으로 끌어들인다(상단 bleed 는 유지).
        // restrictInPage=off 는 현행 유지(한컴 정합: 쪽 영역 이탈 허용).
        let shape_y = if !common.treat_as_char
            && common.flow_with_text
            && matches!(common.vert_rel_to, crate::model::shape::VertRelTo::Para)
            // 머리말·꼬리말 도형은 본문 흐름에 참여하지 않는다. 구분선처럼
            // 밴드 밖으로 뻗는 개체를 밴드 높이에 맞추면 유효한 문단 오프셋이
            // 사라져 제목을 가로지른다. 본문 개체의 단 내부 제한만 적용한다.
            && !matches!(
                parent.node_type,
                RenderNodeType::Header | RenderNodeType::Footer
            ) {
            let total_h = captioned_shape_height_px(shape_h, &caption_opt, self.dpi);
            let body_bottom = col_area.y + col_area.height - total_h;
            shape_y.min(body_bottom.max(col_area.y))
        } else {
            shape_y
        };
        let adjusted_shape_x = shape_x + caption_left_offset;
        let adjusted_shape_y = shape_y + caption_top_offset;

        // 도형 타입별 렌더 노드 생성
        self.layout_shape_object(
            tree,
            parent,
            shape,
            adjusted_shape_x,
            adjusted_shape_y,
            shape_w,
            shape_h,
            section_index,
            para_index,
            control_index,
            styles,
            bin_data_content,
            overflow_map,
            &[],
            None, // [Task #1138] 본문 도형 — 셀 정보 없음
            false,
        );

        if matches!(shape, ShapeObject::Ole(_)) && !common.treat_as_char && para.text.is_empty() {
            push_ole_empty_para_end_anchor(
                tree,
                parent,
                adjusted_shape_x + shape_w,
                adjusted_shape_y,
                para,
                section_index,
                para_index,
                styles,
            );
        }

        // 묶음 자식의 글줄은 셀 주소를 소유하며 바깥의 빈 본문 문단을 대신하지 않는다.
        // 조판이 생략한 host 줄의 캐럿은 확정된 본문 흐름 원점에 남긴다. 개체 bbox나 자식
        // 글상자 좌표로 추측하지 않고 기존 숨은 문단 표시기를 재사용하며 전진·인쇄는 바꾸지 않는다.
        if matches!(shape, ShapeObject::Group(_))
            && !common.treat_as_char
            && para.text.trim().is_empty()
            // 머리말·꼬리말·각주의 전용 편집 주소를 본문 주소로 만들지 않는다.
            && matches!(parent.node_type, RenderNodeType::Column(_) | RenderNodeType::Body { .. })
        {
            fn has_body_caret(node: &RenderNode, section: usize, para: usize) -> bool {
                matches!(&node.node_type, RenderNodeType::TextRun(run)
                    if run.section_index == Some(section) && run.para_index == Some(para)
                    && run.cell_context.is_none() && run.char_start.is_some())
                    || node
                        .children
                        .iter()
                        .any(|child| has_body_caret(child, section, para))
            }
            if !has_body_caret(parent, section_index, para_index) {
                let composed = compose_paragraph(para);
                self.layout_hidden_paragraph_marker(
                    tree,
                    parent,
                    para,
                    "",
                    &composed,
                    styles,
                    col_area,
                    para_y,
                    section_index,
                    para_index,
                );
            }
        }

        // 캡션 렌더링
        if let Some(caption) = caption {
            use crate::model::shape::CaptionVertAlign;
            let (cap_x, cap_w, cap_y) = match caption.direction {
                CaptionDirection::Top => (adjusted_shape_x, shape_w, shape_y),
                CaptionDirection::Bottom => (
                    adjusted_shape_x,
                    shape_w,
                    adjusted_shape_y + shape_h + caption_spacing,
                ),
                CaptionDirection::Left | CaptionDirection::Right => {
                    let cw = hwpunit_to_px(caption.width as i32, self.dpi);
                    let cx = if caption.direction == CaptionDirection::Left {
                        shape_x
                    } else {
                        adjusted_shape_x + shape_w + caption_spacing
                    };
                    // Left/Right 캡션의 세로 정렬
                    let cy = match caption.vert_align {
                        CaptionVertAlign::Top => adjusted_shape_y,
                        CaptionVertAlign::Center => {
                            adjusted_shape_y + (shape_h - caption_height).max(0.0) / 2.0
                        }
                        CaptionVertAlign::Bottom => {
                            adjusted_shape_y + (shape_h - caption_height).max(0.0)
                        }
                    };
                    (cx, cw, cy)
                }
            };
            self.layout_caption(
                tree,
                parent,
                caption,
                styles,
                col_area,
                cap_x,
                cap_w,
                cap_y,
                bin_data_content,
                None,
                CaptionOwner::new(
                    Some(section_index),
                    Some(para_index),
                    Some(control_index),
                    CaptionControlKind::Shape,
                ),
            );
        }
    }

    /// 회전이 있는 그룹 자식 도형을 전체 아핀 변환으로 렌더링한다.
    /// HWPX/HWP renderingInfo is already composed within the top-level group
    /// coordinate system. Apply only that top-level group anchor; nested group
    /// bboxes are structural and must not be applied as another translation.
    /// sa: 자식의 ShapeComponentAttr (아핀 행렬 포함)
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn layout_group_child_affine(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        child: &crate::model::shape::ShapeObject,
        group_origin_x: f64,
        group_origin_y: f64,
        sa: &crate::model::shape::ShapeComponentAttr,
        section_index: usize,
        para_index: usize,
        control_index: usize,
        styles: &ResolvedStyleSet,
        bin_data_content: &[BinDataContent],
        parent_cell_path: &[CellPathEntry],
    ) {
        use crate::model::shape::ShapeObject;

        // 아핀 변환: (x', y') = (a*x + b*y + tx, c*x + d*y + ty)
        // x, y는 원본 좌표(HWP units), 결과는 그룹 로컬 좌표(HWP units)
        let a = sa.render_sx;
        let b = sa.render_b;
        let tx = sa.render_tx;
        let c = sa.render_c;
        let d = sa.render_sy;
        let ty = sa.render_ty;

        // HWP 좌표를 아핀 변환 후 페이지 절대 좌표(px)로 변환하는 헬퍼.
        let transform_pt = |ox: f64, oy: f64| -> (f64, f64) {
            let gx = a * ox + b * oy + tx;
            let gy = c * ox + d * oy + ty;
            (
                group_origin_x + hwpunit_to_px(gx as i32, self.dpi),
                group_origin_y + hwpunit_to_px(gy as i32, self.dpi),
            )
        };

        match child {
            ShapeObject::Polygon(poly) => {
                let (style, gradient) = drawing_to_shape_style(&poly.drawing, self.dpi);
                let mut commands = Vec::new();
                let mut min_x = f64::MAX;
                let mut min_y = f64::MAX;
                let mut max_x = f64::MIN;
                let mut max_y = f64::MIN;
                for (i, pt) in poly.points.iter().enumerate() {
                    let (px, py) = transform_pt(pt.x as f64, pt.y as f64);
                    min_x = min_x.min(px);
                    min_y = min_y.min(py);
                    max_x = max_x.max(px);
                    max_y = max_y.max(py);
                    if i == 0 {
                        commands.push(PathCommand::MoveTo(px, py));
                    } else {
                        commands.push(PathCommand::LineTo(px, py));
                    }
                }
                if poly.points.len() >= 3 {
                    let first = &poly.points[0];
                    let last = &poly.points[poly.points.len() - 1];
                    if first.x == last.x && first.y == last.y {
                        commands.push(PathCommand::ClosePath);
                    }
                }
                let bbox_w = (max_x - min_x).max(0.0);
                let bbox_h = (max_y - min_y).max(0.0);
                let node_id = tree.next_id();
                let mut path_node = PathNode::new(commands, style, gradient);
                path_stroke_arrows::publish(&mut path_node, &poly.drawing);
                let node = RenderNode::new(
                    node_id,
                    RenderNodeType::Path(path_node),
                    BoundingBox::new(min_x, min_y, bbox_w, bbox_h),
                );
                parent.children.push(node);
            }
            ShapeObject::Line(line) => {
                let (x1, y1) = transform_pt(line.start.x as f64, line.start.y as f64);
                let (x2, y2) = transform_pt(line.end.x as f64, line.end.y as f64);
                let node_id = tree.next_id();
                let (mut kind, bbox) =
                    affine_line::rendered_line(line, (x1, y1), (x2, y2), self.dpi);
                if let RenderNodeType::Line(rendered) = &mut kind {
                    rendered.section_index = Some(section_index);
                    rendered.para_index = Some(para_index);
                    rendered.control_index = Some(control_index);
                }
                let node = RenderNode::new(node_id, kind, bbox);
                parent.children.push(node);
            }
            ShapeObject::Curve(curve) => {
                let (style, gradient) = drawing_to_shape_style(&curve.drawing, self.dpi);
                let commands = curve_geometry::commands(curve, |ox, oy| {
                    // 보간한 원본 단위를 정수로 잘라 접선과 변환 배율을 바꾸지 않는다.
                    (
                        group_origin_x + (a * ox + b * oy + tx) * self.dpi / 7200.0,
                        group_origin_y + (c * ox + d * oy + ty) * self.dpi / 7200.0,
                    )
                });
                let Some(bbox) = curve_geometry::control_bounds(&commands) else {
                    return;
                };
                let node_id = tree.next_id();
                let mut path_node = PathNode::new(commands, style, gradient);
                path_stroke_arrows::publish(&mut path_node, &curve.drawing);
                let node = RenderNode::new(node_id, RenderNodeType::Path(path_node), bbox);
                parent.children.push(node);
            }
            ShapeObject::Rectangle(rect) => {
                // 회전된 사각형: 4꼭짓점을 아핀 변환하여 다각형으로 렌더링
                let ow = sa.original_width as f64;
                let oh = sa.original_height as f64;
                let corners = [(0.0, 0.0), (ow, 0.0), (ow, oh), (0.0, oh)];
                let (style, gradient) = drawing_to_shape_style(&rect.drawing, self.dpi);
                let mut commands = Vec::new();
                let mut min_x = f64::MAX;
                let mut min_y = f64::MAX;
                let mut max_x = f64::MIN;
                let mut max_y = f64::MIN;
                for (i, &(ox, oy)) in corners.iter().enumerate() {
                    let (px, py) = transform_pt(ox, oy);
                    min_x = min_x.min(px);
                    min_y = min_y.min(py);
                    max_x = max_x.max(px);
                    max_y = max_y.max(py);
                    if i == 0 {
                        commands.push(PathCommand::MoveTo(px, py));
                    } else {
                        commands.push(PathCommand::LineTo(px, py));
                    }
                }
                commands.push(PathCommand::ClosePath);
                let node_id = tree.next_id();
                let node = RenderNode::new(
                    node_id,
                    RenderNodeType::Path(PathNode::new(commands, style, gradient)),
                    BoundingBox::new(
                        min_x,
                        min_y,
                        (max_x - min_x).max(0.0),
                        (max_y - min_y).max(0.0),
                    ),
                );
                parent.children.push(node);
            }
            ShapeObject::Ellipse(ellipse) => {
                // 회전된 타원: 원래 상자에 내접한 타원을 베지어 4개로 만들어 아핀 변환한다.
                // 아핀 변환은 베지어 제어점에 그대로 적용되므로 모양이 정확히 유지된다.
                // 두 모서리 AABB 폴백은 회전 타원을 축 정렬 타원으로 찌그러뜨렸다.
                const K: f64 = 0.552_284_749_830_793_4;
                let (rx, ry) = (
                    sa.original_width as f64 / 2.0,
                    sa.original_height as f64 / 2.0,
                );
                let pt = |ux: f64, uy: f64| transform_pt(rx + rx * ux, ry + ry * uy);
                let quarters = [
                    [(1.0, K), (K, 1.0), (0.0, 1.0)],
                    [(-K, 1.0), (-1.0, K), (-1.0, 0.0)],
                    [(-1.0, -K), (-K, -1.0), (0.0, -1.0)],
                    [(K, -1.0), (1.0, -K), (1.0, 0.0)],
                ];
                let start = pt(1.0, 0.0);
                let mut commands = vec![PathCommand::MoveTo(start.0, start.1)];
                let (mut min_x, mut min_y, mut max_x, mut max_y) =
                    (start.0, start.1, start.0, start.1);
                for q in quarters {
                    let [c1, c2, end] = q.map(|(ux, uy)| pt(ux, uy));
                    commands.push(PathCommand::CurveTo(c1.0, c1.1, c2.0, c2.1, end.0, end.1));
                    for (px, py) in [c1, c2, end] {
                        min_x = min_x.min(px);
                        min_y = min_y.min(py);
                        max_x = max_x.max(px);
                        max_y = max_y.max(py);
                    }
                }
                commands.push(PathCommand::ClosePath);
                let (style, gradient) = drawing_to_shape_style(&ellipse.drawing, self.dpi);
                let node_id = tree.next_id();
                parent.children.push(RenderNode::new(
                    node_id,
                    RenderNodeType::Path(PathNode::new(commands, style, gradient)),
                    BoundingBox::new(min_x, min_y, max_x - min_x, max_y - min_y),
                ));
            }
            _ => {
                // 그 외 도형(타원, 호, 그림 등): 기본 AABB 방식 폴백
                let (p0x, p0y) = transform_pt(0.0, 0.0);
                let (p1x, p1y) = transform_pt(sa.original_width as f64, sa.original_height as f64);
                let child_x = p0x.min(p1x);
                let child_y = p0y.min(p1y);
                let child_w = (p1x - p0x).abs();
                let child_h = (p1y - p0y).abs();
                let empty_map = std::collections::HashMap::new();
                self.layout_shape_object(
                    tree,
                    parent,
                    child,
                    child_x,
                    child_y,
                    child_w,
                    child_h,
                    section_index,
                    para_index,
                    control_index,
                    styles,
                    bin_data_content,
                    &empty_map,
                    parent_cell_path,
                    None, // [Task #1138] TODO: layout_group_child_affine 에 cell ctx propagate (별도 후속)
                    true,
                );
            }
        }
    }

    /// 개별 ShapeObject를 렌더 노드로 변환한다.
    /// base_x/y는 도형의 절대 좌표, w/h는 도형 크기.
    /// parent_cell_path: 중첩 글상자/표에서 상위 경로 (최상위 도형이면 빈 슬라이스)
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn layout_shape_object(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        shape: &crate::model::shape::ShapeObject,
        base_x: f64,
        base_y: f64,
        w: f64,
        h: f64,
        section_index: usize,
        para_index: usize,
        control_index: usize,
        styles: &ResolvedStyleSet,
        bin_data_content: &[BinDataContent],
        overflow_map: &std::collections::HashMap<(usize, usize), Vec<Paragraph>>,
        parent_cell_path: &[CellPathEntry],
        // [Task #1138] 표 셀 내 도형인 경우: (cell_idx, cell_para_idx, outer_table_ctrl_idx)
        table_cell_ref: Option<(usize, usize, usize)>,
        // 그룹 자식은 renderingInfo 행렬로 이미 위치/대칭이 반영되어 있으므로
        // ShapeComponentAttr의 flip/rotation을 다시 SVG transform으로 적용하지 않는다.
        matrix_positioned: bool,
    ) {
        self.layout_shape_object_with_group_origin(
            tree,
            parent,
            shape,
            base_x,
            base_y,
            w,
            h,
            section_index,
            para_index,
            control_index,
            styles,
            bin_data_content,
            overflow_map,
            parent_cell_path,
            table_cell_ref,
            matrix_positioned,
            None,
        );
    }

    /// 일반/연결 직선의 한 점을 HWP5 `renderingInfo` 좌표계로 변환한다.
    ///
    /// 보통의 양수 축척은 호출부가 이미 `render_w/original_size`로 적용한다. 다만
    /// 음수 축척·이동·전단이 있는 경우에는 그 절댓값만 쓰면 시작과 끝이 뒤집혀
    /// 화살표의 방향까지 반대가 된다. 묶음 자식은 이미 별도 affine 경로를 지나므로
    /// 여기서는 top-level 직선만 보정한다.
    fn line_point_in_rendering_frame(
        &self,
        line: &crate::model::shape::LineShape,
        render_x: f64,
        render_y: f64,
        sx: f64,
        sy: f64,
        matrix_positioned: bool,
        x: i32,
        y: i32,
    ) -> (f64, f64) {
        let sa = &line.drawing.shape_attr;
        let uses_signed_affine = !matrix_positioned
            && (source_line_frame::owns_axis_rotation(line)
                || sa.render_sx < 0.0
                || sa.render_sy < 0.0
                || sa.render_b.abs() > 1e-6
                || sa.render_c.abs() > 1e-6
                || sa.render_tx.abs() > 1e-6
                || sa.render_ty.abs() > 1e-6);
        if uses_signed_affine
            && [
                sa.render_sx,
                sa.render_b,
                sa.render_tx,
                sa.render_c,
                sa.render_sy,
                sa.render_ty,
            ]
            .iter()
            .all(|value| value.is_finite())
        {
            let x_hu = sa.render_sx * f64::from(x) + sa.render_b * f64::from(y) + sa.render_tx;
            let y_hu = sa.render_c * f64::from(x) + sa.render_sy * f64::from(y) + sa.render_ty;
            return (
                render_x + x_hu * self.dpi / crate::renderer::HWPUNIT_PER_INCH,
                render_y + y_hu * self.dpi / crate::renderer::HWPUNIT_PER_INCH,
            );
        }

        let (point_x, point_y, sx, sy) = group_point_frame(
            sa,
            matrix_positioned,
            (render_x, render_y),
            (
                hwpunit_to_px(sa.original_width as i32, self.dpi) * sx,
                hwpunit_to_px(sa.original_height as i32, self.dpi) * sy,
            ),
            (sx, sy),
        );
        (
            point_x + hwpunit_to_px(x, self.dpi) * sx,
            point_y + hwpunit_to_px(y, self.dpi) * sy,
        )
    }

    /// 일반 직선의 두 끝점을 HWP5 `renderingInfo` 좌표계로 변환한다.
    fn line_endpoints_in_rendering_frame(
        &self,
        line: &crate::model::shape::LineShape,
        render_x: f64,
        render_y: f64,
        sx: f64,
        sy: f64,
        matrix_positioned: bool,
    ) -> ((f64, f64), (f64, f64)) {
        line_direction::endpoints(
            line.started_right_or_bottom,
            self.line_point_in_rendering_frame(
                line,
                render_x,
                render_y,
                sx,
                sy,
                matrix_positioned,
                line.start.x,
                line.start.y,
            ),
            self.line_point_in_rendering_frame(
                line,
                render_x,
                render_y,
                sx,
                sy,
                matrix_positioned,
                line.end.x,
                line.end.y,
            ),
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn layout_shape_object_with_group_origin(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        shape: &crate::model::shape::ShapeObject,
        base_x: f64,
        base_y: f64,
        w: f64,
        h: f64,
        section_index: usize,
        para_index: usize,
        control_index: usize,
        styles: &ResolvedStyleSet,
        bin_data_content: &[BinDataContent],
        overflow_map: &std::collections::HashMap<(usize, usize), Vec<Paragraph>>,
        parent_cell_path: &[CellPathEntry],
        // [Task #1138] 표 셀 내 도형인 경우: (cell_idx, cell_para_idx, outer_table_ctrl_idx)
        table_cell_ref: Option<(usize, usize, usize)>,
        // 그룹 자식은 renderingInfo 행렬로 이미 위치/대칭이 반영되어 있으므로
        // ShapeComponentAttr의 flip/rotation을 다시 SVG transform으로 적용하지 않는다.
        matrix_positioned: bool,
        inherited_group_origin: Option<(f64, f64)>,
    ) {
        use crate::model::shape::ShapeObject;

        // 독립 개체의 배치 원점은 그림자를 포함한다. 본체와 내부 텍스트가
        // 같은 원점을 소비하도록 실제 좌표를 만들기 전에 한 번 이동한다.
        // 묶음 자식은 renderingInfo가 정한 본체 원점을 그대로 보존한다.
        let (base_x, base_y) = if !matrix_positioned {
            let origin = shape.drawing().and_then(|drawing| {
                crate::model::shape::shadow::parallel_body_origin_hu(
                    drawing.shadow_type,
                    drawing.shadow_offset_x,
                    drawing.shadow_offset_y,
                )
            });
            origin.map_or((base_x, base_y), |(x, y)| {
                let unit = self.dpi / super::super::HWPUNIT_PER_INCH;
                (base_x + x * unit, base_y + y * unit)
            })
        } else {
            (base_x, base_y)
        };

        // 공통: 회전/대칭 정보 추출
        let transform = if matrix_positioned {
            ShapeTransform::default()
        } else {
            let mut transform = extract_shape_transform(shape.shape_attr());
            if matches!(shape, ShapeObject::Line(line) if source_line_frame::owns_axis_rotation(line))
            {
                // 점 좌표와 같은 원본 프레임을 소비한다. 이미 세로/가로인
                // 선을 별도 회전으로 다른 축에 다시 놓지 않는다.
                transform.rotation = 0.0;
            }
            transform
        };

        // [Task #1138] 표 셀 내 도형 식별을 위한 cell 정보 추출 (helper)
        let cell_index = table_cell_ref.map(|(ci, _, _)| ci);
        let cell_para_index = table_cell_ref.map(|(_, cpi, _)| cpi);
        let outer_table_control_index = table_cell_ref.map(|(_, _, otci)| otci);

        // 회전/대칭이 있으면 current 크기로 중앙 배치
        // 그렇지 않으면 호출자가 전달한 w, h를 그대로 사용
        // (그룹 자식은 호출자가 render_sx/sy로 스케일 적용 후 w,h 전달)
        let (render_x, render_y, render_w, render_h) = if transform.has_transform() {
            let sa = shape.shape_attr();
            let cur_w = hwpunit_to_px(sa.current_width as i32, self.dpi);
            let cur_h = hwpunit_to_px(sa.current_height as i32, self.dpi);
            if cur_w > 0.0 && cur_h > 0.0 {
                let cx = base_x + w / 2.0;
                let cy = base_y + h / 2.0;
                (cx - cur_w / 2.0, cy - cur_h / 2.0, cur_w, cur_h)
            } else {
                (base_x, base_y, w, h)
            }
        } else {
            (base_x, base_y, w, h)
        };

        match shape {
            ShapeObject::Rectangle(rect) => {
                // 글상자의 텍스트·채우기와 선의 가시성은 별개다.
                // 그룹 자식도 원본의 명시된 SOLID/NONE을 그대로 소비한다.
                let (style, gradient) = drawing_to_shape_style(&rect.drawing, self.dpi);
                let round_px = if rect.round_rate > 0 {
                    // 한컴 곡률 50%는 반원이다. 짧은 변의 절반이 반지름이며,
                    // 백분율을 적용한 뒤 다시 2로 나누면 50%도 둥근 모서리에 그친다.
                    (rect.round_rate as f64 / 100.0) * render_w.min(render_h)
                } else {
                    0.0
                };
                let node_id = tree.next_id();
                let mut node = RenderNode::new(
                    node_id,
                    RenderNodeType::Rectangle(RectangleNode {
                        section_index: Some(section_index),
                        para_index: Some(para_index),
                        control_index: Some(control_index),
                        transform,
                        cell_index,
                        cell_para_index,
                        outer_table_control_index,
                        drawing_border_width_hu: (rect.drawing.border_line.outline_style == 0
                            && rect.drawing.fill.image.is_none())
                        .then_some(rect.drawing.border_line.width),
                        ..RectangleNode::new(round_px, style, gradient)
                    }),
                    BoundingBox::new(render_x, render_y, render_w, render_h),
                );
                // 이미지 채우기가 있으면 자식으로 이미지 노드 추가
                self.add_image_fill_node(
                    tree,
                    &mut node,
                    &rect.drawing,
                    render_x,
                    render_y,
                    render_w,
                    render_h,
                    bin_data_content,
                );
                compound_rectangle::append_border(tree, &mut node, &rect.drawing);
                // TextBox가 있으면 자식으로 텍스트 레이아웃
                self.layout_textbox_content(
                    tree,
                    &mut node,
                    &rect.drawing,
                    render_x,
                    render_y,
                    render_w,
                    render_h,
                    section_index,
                    para_index,
                    control_index,
                    styles,
                    bin_data_content,
                    overflow_map,
                    parent_cell_path,
                    shape.common().treat_as_char,
                    matrix_positioned,
                    textbox_vpos_origin_hu(shape.common(), matrix_positioned),
                );
                node.set_rectangle_control_kind(rect.control_kind());
                parent.children.push(node);
            }
            ShapeObject::Line(line) => {
                // 선 종류 "없음"(0)은 그리지 않는다. 사각형 등은 drawing_to_shape_style 이
                // 같은 규칙으로 테두리를 끈다. 노드는 남겨 개체 질의·선택은 유지한다.
                let line_visible = line.drawing.border_line.attr & 0x3F != 0;
                let sa = &line.drawing.shape_attr;
                let sx = if sa.original_width > 0 {
                    render_w / hwpunit_to_px(sa.original_width as i32, self.dpi)
                } else {
                    1.0
                };
                let sy = if sa.original_height > 0 {
                    render_h / hwpunit_to_px(sa.original_height as i32, self.dpi)
                } else {
                    1.0
                };

                // 선 없음은 남은 두께·화살촉 정보로 가시 직선이 되지 않는다.
                // 회전된 묶음 자식과 같은 경로 표현을 사용하고 소유·선택 영역은
                // 보존한다. 일반 직선의 최소 두께 fallback까지 내려가지 않는다.
                if line.drawing.border_line.attr & 0x3F == 0
                    && line
                        .connector
                        .as_ref()
                        .is_none_or(|connector| connector.control_points.is_empty())
                {
                    let (start, end) = self.line_endpoints_in_rendering_frame(
                        line,
                        render_x,
                        render_y,
                        sx,
                        sy,
                        matrix_positioned,
                    );
                    let (mut kind, bbox) = affine_line::rendered_line(line, start, end, self.dpi);
                    if let RenderNodeType::Path(path) = &mut kind {
                        path.section_index = Some(section_index);
                        path.para_index = Some(para_index);
                        path.control_index = Some(control_index);
                        path.transform = transform;
                        path.cell_index = cell_index;
                        path.cell_para_index = cell_para_index;
                        path.outer_table_control_index = outer_table_control_index;
                    }
                    parent
                        .children
                        .push(RenderNode::new(tree.next_id(), kind, bbox));
                    return;
                }

                // 연결선: 제어점이 있으면 Path로, 없으면 Line으로 렌더링
                if let Some(ref conn) = line.connector {
                    if !conn.control_points.is_empty() {
                        let line_style = connector_line_style(&line.drawing, conn.link_type);
                        // 제어점으로 경로 생성
                        let mut commands = Vec::new();
                        let (conn_x1, conn_y1) = self.line_point_in_rendering_frame(
                            line,
                            render_x,
                            render_y,
                            sx,
                            sy,
                            matrix_positioned,
                            line.start.x,
                            line.start.y,
                        );
                        let (conn_x2, conn_y2) = self.line_point_in_rendering_frame(
                            line,
                            render_x,
                            render_y,
                            sx,
                            sy,
                            matrix_positioned,
                            line.end.x,
                            line.end.y,
                        );
                        let connector_point_xy =
                            |cp: &crate::model::shape::ConnectorControlPoint| {
                                self.line_point_in_rendering_frame(
                                    line,
                                    render_x,
                                    render_y,
                                    sx,
                                    sy,
                                    matrix_positioned,
                                    cp.x,
                                    cp.y,
                                )
                            };
                        let first_control_is_start = conn
                            .control_points
                            .first()
                            .map(|cp| cp.point_type == 3)
                            .unwrap_or(false);
                        let last_control_is_end = conn
                            .control_points
                            .last()
                            .map(|cp| cp.point_type == 26)
                            .unwrap_or(false);
                        let (path_start_x, path_start_y) = if first_control_is_start {
                            connector_point_xy(&conn.control_points[0])
                        } else {
                            (conn_x1, conn_y1)
                        };
                        let mut path_end_x = conn_x2;
                        let mut path_end_y = conn_y2;
                        commands.push(PathCommand::MoveTo(path_start_x, path_start_y));

                        if conn.link_type.is_arc() {
                            // 곡선 연결선: 제어점(type=2)을 bezier 제어점으로, 나머지는 앵커로 사용
                            let cps = &conn.control_points;
                            let end_x = conn_x2;
                            let end_y = conn_y2;
                            // type=2인 제어점만 추출
                            let ctrl_pts: Vec<(f64, f64)> = cps
                                .iter()
                                .filter(|cp| cp.point_type == 2)
                                .map(connector_point_xy)
                                .collect();
                            match ctrl_pts.len() {
                                0 => {
                                    // 제어점 없음 → 직선
                                    commands.push(PathCommand::LineTo(end_x, end_y));
                                }
                                1 => {
                                    // 제어점 1개 → quadratic bezier (cubic으로 변환)
                                    let (qx, qy) = ctrl_pts[0];
                                    let (sx0, sy0) = match commands.last() {
                                        Some(PathCommand::MoveTo(x, y)) => (*x, *y),
                                        _ => (render_x, render_y),
                                    };
                                    // Q→C 변환: C = (S + 2*Q)/3, (2*Q + E)/3, E
                                    let cx1 = (sx0 + 2.0 * qx) / 3.0;
                                    let cy1 = (sy0 + 2.0 * qy) / 3.0;
                                    let cx2 = (2.0 * qx + end_x) / 3.0;
                                    let cy2 = (2.0 * qy + end_y) / 3.0;
                                    commands.push(PathCommand::CurveTo(
                                        cx1, cy1, cx2, cy2, end_x, end_y,
                                    ));
                                }
                                2 => {
                                    // 제어점 2개 → cubic bezier
                                    let (cx1, cy1) = ctrl_pts[0];
                                    let (cx2, cy2) = ctrl_pts[1];
                                    commands.push(PathCommand::CurveTo(
                                        cx1, cy1, cx2, cy2, end_x, end_y,
                                    ));
                                }
                                _ => {
                                    // 3개 이상 → 여러 cubic bezier 세그먼트
                                    let mut i = 0;
                                    while i + 1 < ctrl_pts.len() {
                                        let (cx1, cy1) = ctrl_pts[i];
                                        let (cx2, cy2) = ctrl_pts[i + 1];
                                        let (ex, ey) = if i + 2 < ctrl_pts.len() {
                                            (
                                                (cx2 + ctrl_pts[i + 2].0) / 2.0,
                                                (cy2 + ctrl_pts[i + 2].1) / 2.0,
                                            )
                                        } else {
                                            (end_x, end_y)
                                        };
                                        commands
                                            .push(PathCommand::CurveTo(cx1, cy1, cx2, cy2, ex, ey));
                                        i += 2;
                                    }
                                }
                            }
                        } else {
                            for cp in conn.control_points.iter().skip(if first_control_is_start {
                                1
                            } else {
                                0
                            }) {
                                let (cpx, cpy) = connector_point_xy(cp);
                                commands.push(PathCommand::LineTo(cpx, cpy));
                                path_end_x = cpx;
                                path_end_y = cpy;
                            }
                            if !last_control_is_end {
                                commands.push(PathCommand::LineTo(conn_x2, conn_y2));
                                path_end_x = conn_x2;
                                path_end_y = conn_y2;
                            }
                        }

                        // 비표시 연결선도 원본 제어점·선택 끝점을 유지한다.
                        // 직선 fallback으로 바꾸지 않고 획·화살촉만 제외한다.
                        let line_visible = line.drawing.border_line.attr & 0x3F != 0;
                        let style = if line_visible {
                            ShapeStyle {
                                stroke_color: Some(line_style.color),
                                stroke_width: line_style.width,
                                stroke_dash: line_style.dash.clone(),
                                fill_color: None,
                                ..Default::default()
                            }
                        } else {
                            ShapeStyle::default()
                        };
                        let node_id = tree.next_id();
                        let mut path_node = PathNode::new(commands, style, None);
                        path_node.section_index = Some(section_index);
                        path_node.para_index = Some(para_index);
                        path_node.control_index = Some(control_index);
                        path_node.transform = transform;
                        path_node.cell_index = cell_index;
                        path_node.cell_para_index = cell_para_index;
                        path_node.outer_table_control_index = outer_table_control_index;
                        // 연결선: 시작/끝 좌표 (선 선택 방식용) + 화살표
                        path_node.connector_endpoints =
                            Some((path_start_x, path_start_y, path_end_x, path_end_y));
                        if line_visible
                            && (line_style.start_arrow != super::super::ArrowStyle::None
                                || line_style.end_arrow != super::super::ArrowStyle::None)
                        {
                            path_node.line_style = Some(line_style);
                        }
                        let mut node = RenderNode::new(
                            node_id,
                            RenderNodeType::Path(path_node),
                            BoundingBox::new(render_x, render_y, render_w, render_h),
                        );
                        node.visible = line_visible;
                        parent.children.push(node);
                    } else {
                        // 제어점 없는 연결선 → 직선으로 렌더링
                        let line_style = connector_line_style(&line.drawing, conn.link_type);
                        let ((x1, y1), (x2, y2)) = self.line_endpoints_in_rendering_frame(
                            line,
                            render_x,
                            render_y,
                            sx,
                            sy,
                            matrix_positioned,
                        );
                        let node_id = tree.next_id();
                        let mut line_node = LineNode::new(x1, y1, x2, y2, line_style);
                        line_node.section_index = Some(section_index);
                        line_node.para_index = Some(para_index);
                        line_node.control_index = Some(control_index);
                        line_node.transform = transform;
                        line_node.cell_index = cell_index;
                        line_node.cell_para_index = cell_para_index;
                        line_node.outer_table_control_index = outer_table_control_index;
                        let mut node = RenderNode::new(
                            node_id,
                            RenderNodeType::Line(line_node),
                            BoundingBox::new(render_x, render_y, render_w, render_h),
                        );
                        node.visible = line_visible;
                        parent.children.push(node);
                    }
                } else {
                    // 일반 직선
                    let line_style = drawing_to_line_style(&line.drawing);
                    let ((x1, y1), (x2, y2)) = self.line_endpoints_in_rendering_frame(
                        line,
                        render_x,
                        render_y,
                        sx,
                        sy,
                        matrix_positioned,
                    );
                    let node_id = tree.next_id();
                    let mut line_node = LineNode::new(x1, y1, x2, y2, line_style);
                    line_node.section_index = Some(section_index);
                    line_node.para_index = Some(para_index);
                    line_node.control_index = Some(control_index);
                    line_node.transform = transform;
                    line_node.cell_index = cell_index;
                    line_node.cell_para_index = cell_para_index;
                    line_node.outer_table_control_index = outer_table_control_index;
                    let mut node = RenderNode::new(
                        node_id,
                        RenderNodeType::Line(line_node),
                        BoundingBox::new(render_x, render_y, render_w, render_h),
                    );
                    node.visible = line_visible;
                    parent.children.push(node);
                }
            }
            ShapeObject::Ellipse(ellipse) => {
                let (style, gradient) = drawing_to_shape_style(&ellipse.drawing, self.dpi);
                let node_id = tree.next_id();
                let mut ell_node = EllipseNode::new(style, gradient);
                ell_node.section_index = Some(section_index);
                ell_node.para_index = Some(para_index);
                ell_node.control_index = Some(control_index);
                ell_node.transform = transform;
                ell_node.cell_index = cell_index;
                ell_node.cell_para_index = cell_para_index;
                ell_node.outer_table_control_index = outer_table_control_index;
                let mut node = RenderNode::new(
                    node_id,
                    RenderNodeType::Ellipse(ell_node),
                    BoundingBox::new(render_x, render_y, render_w, render_h),
                );
                self.add_image_fill_node(
                    tree,
                    &mut node,
                    &ellipse.drawing,
                    render_x,
                    render_y,
                    render_w,
                    render_h,
                    bin_data_content,
                );
                let empty_map = std::collections::HashMap::new();
                self.layout_textbox_content(
                    tree,
                    &mut node,
                    &ellipse.drawing,
                    render_x,
                    render_y,
                    render_w,
                    render_h,
                    section_index,
                    para_index,
                    control_index,
                    styles,
                    bin_data_content,
                    &empty_map,
                    parent_cell_path,
                    shape.common().treat_as_char,
                    matrix_positioned,
                    textbox_vpos_origin_hu(shape.common(), matrix_positioned),
                );
                parent.children.push(node);
            }
            ShapeObject::Arc(arc) => {
                let (style, gradient) = drawing_to_shape_style(&arc.drawing, self.dpi);
                // 호(Arc) 좌표 계산: center, axis1, axis2를 렌더 좌표로 변환
                let sa = &arc.drawing.shape_attr;
                let sx = if sa.original_width > 0 {
                    render_w / hwpunit_to_px(sa.original_width as i32, self.dpi)
                } else {
                    1.0
                };
                let sy = if sa.original_height > 0 {
                    render_h / hwpunit_to_px(sa.original_height as i32, self.dpi)
                } else {
                    1.0
                };

                let cx = render_x + hwpunit_to_px(arc.center.x, self.dpi) * sx;
                let cy = render_y + hwpunit_to_px(arc.center.y, self.dpi) * sy;
                let ax1 = render_x + hwpunit_to_px(arc.axis1.x, self.dpi) * sx;
                let ay1 = render_y + hwpunit_to_px(arc.axis1.y, self.dpi) * sy;
                let ax2 = render_x + hwpunit_to_px(arc.axis2.x, self.dpi) * sx;
                let ay2 = render_y + hwpunit_to_px(arc.axis2.y, self.dpi) * sy;

                // center→axis 벡터
                let dx1 = ax1 - cx;
                let dy1 = ay1 - cy;
                let dx2 = ax2 - cx;
                let dy2 = ay2 - cy;

                // 타원 반지름을 axis 좌표 기반으로 계산
                // axis1/axis2가 정확히 축 위에 있으면 각각의 축 반지름 사용
                let (ell_rx, ell_ry) = {
                    let r1 = (dx1 * dx1 + dy1 * dy1).sqrt();
                    let r2 = (dx2 * dx2 + dy2 * dy2).sqrt();
                    if r1 > 0.1 && r2 > 0.1 {
                        // axis1, axis2가 직교축 위에 있다면 rx, ry 분리 가능
                        let a1 = dy1.atan2(dx1);
                        let a2 = dy2.atan2(dx2);
                        let a1_abs = a1.abs();
                        let a2_abs = a2.abs();
                        // axis1이 y축 근처(90° 또는 -90°)이고 axis2가 x축 근처(0° 또는 180°)
                        if (a1_abs - std::f64::consts::FRAC_PI_2).abs() < 0.3 && a2_abs < 0.3 {
                            (r2, r1) // axis2→rx, axis1→ry
                        } else if a1_abs < 0.3 && (a2_abs - std::f64::consts::FRAC_PI_2).abs() < 0.3
                        {
                            (r1, r2) // axis1→rx, axis2→ry
                        } else {
                            (r1.max(r2), r1.min(r2))
                        }
                    } else {
                        (render_w / 2.0, render_h / 2.0)
                    }
                };

                // 각도 계산 (SVG 좌표계: Y-down)
                let angle1 = dy1.atan2(dx1);
                let angle2 = dy2.atan2(dx2);

                // axis1→axis2 방향: 반시계 방향(SVG 좌표) = sweep=0
                // 각도 차이로 large_arc 결정
                let mut sweep_angle = angle1 - angle2;
                if sweep_angle < 0.0 {
                    sweep_angle += 2.0 * std::f64::consts::PI;
                }
                let large_arc = sweep_angle > std::f64::consts::PI;

                let mut commands = Vec::new();
                commands.push(PathCommand::MoveTo(ax1, ay1));
                commands.push(PathCommand::ArcTo(
                    ell_rx, ell_ry, 0.0, large_arc, false, ax2, ay2,
                ));

                match arc.arc_type {
                    1 => {
                        // 부채꼴 (Pie/CircularSector): 호 → 중심 → 시작점 → 닫기
                        commands.push(PathCommand::LineTo(cx, cy));
                        commands.push(PathCommand::ClosePath);
                    }
                    2 => {
                        // 활 (Bow/Chord): 호 끝점 → 시작점 직선 → 닫기
                        commands.push(PathCommand::ClosePath);
                    }
                    _ => {
                        // 호 (Arc): 열린 곡선 (닫지 않음)
                    }
                }

                let node_id = tree.next_id();
                let mut path_node = PathNode::new(commands, style, gradient);
                path_node.section_index = Some(section_index);
                path_node.para_index = Some(para_index);
                path_node.control_index = Some(control_index);
                path_node.transform = transform;
                path_node.cell_index = cell_index;
                path_node.cell_para_index = cell_para_index;
                path_node.outer_table_control_index = outer_table_control_index;
                let node = RenderNode::new(
                    node_id,
                    RenderNodeType::Path(path_node),
                    BoundingBox::new(render_x, render_y, render_w, render_h),
                );
                parent.children.push(node);
            }
            ShapeObject::Polygon(poly) => {
                let (style, gradient) = drawing_to_shape_style(&poly.drawing, self.dpi);
                // 꼭짓점 좌표를 PathCommand로 변환 (원본→렌더 스케일링 적용)
                let sa = &poly.drawing.shape_attr;
                // 저장 행렬은 원본 꼭짓점의 최종 변환이다. 독립 도형도 묶음
                // 자식과 같이 한 번만 적용하며 current 크기·회전을 다시 합치지 않는다.
                let source_affine = !matrix_positioned
                    && (sa.has_saved_affine_geometry() || poly.affine_edit_reference.is_some());
                let sx = if sa.original_width > 0 {
                    render_w / hwpunit_to_px(sa.original_width as i32, self.dpi)
                } else {
                    1.0
                };
                let sy = if sa.original_height > 0 {
                    render_h / hwpunit_to_px(sa.original_height as i32, self.dpi)
                } else {
                    1.0
                };
                let (point_x, point_y, sx, sy) = group_point_frame(
                    sa,
                    matrix_positioned,
                    (render_x, render_y),
                    (render_w, render_h),
                    (sx, sy),
                );
                let mut commands = Vec::new();
                let mut path_bounds = (
                    f64::INFINITY,
                    f64::INFINITY,
                    f64::NEG_INFINITY,
                    f64::NEG_INFINITY,
                );
                for (i, pt) in poly.points.iter().enumerate() {
                    let (px, py) = if source_affine {
                        let x = f64::from(pt.x);
                        let y = f64::from(pt.y);
                        let unit = self.dpi / crate::renderer::HWPUNIT_PER_INCH;
                        (
                            base_x + (sa.render_sx * x + sa.render_b * y + sa.render_tx) * unit,
                            base_y + (sa.render_c * x + sa.render_sy * y + sa.render_ty) * unit,
                        )
                    } else {
                        (
                            point_x + hwpunit_to_px(pt.x, self.dpi) * sx,
                            point_y + hwpunit_to_px(pt.y, self.dpi) * sy,
                        )
                    };
                    path_bounds.0 = path_bounds.0.min(px);
                    path_bounds.1 = path_bounds.1.min(py);
                    path_bounds.2 = path_bounds.2.max(px);
                    path_bounds.3 = path_bounds.3.max(py);
                    if i == 0 {
                        commands.push(PathCommand::MoveTo(px, py));
                    } else {
                        commands.push(PathCommand::LineTo(px, py));
                    }
                }
                // 첫 점과 끝 점이 같으면 닫힌 다각형, 다르면 열린 폴리라인
                if poly.points.len() >= 3 {
                    let first = &poly.points[0];
                    let last = &poly.points[poly.points.len() - 1];
                    if first.x == last.x && first.y == last.y {
                        commands.push(PathCommand::ClosePath);
                    }
                }
                // 변환된 꼭짓점과 hit-test 상자는 같은 최종 경계를 소비한다.
                let (paint_x, paint_y, paint_w, paint_h) =
                    if source_affine && !poly.points.is_empty() {
                        (
                            path_bounds.0,
                            path_bounds.1,
                            path_bounds.2 - path_bounds.0,
                            path_bounds.3 - path_bounds.1,
                        )
                    } else {
                        (render_x, render_y, render_w, render_h)
                    };
                let node_id = tree.next_id();
                let mut path_node = PathNode::new(commands, style, gradient);
                path_stroke_arrows::publish(&mut path_node, &poly.drawing);
                path_node.section_index = Some(section_index);
                path_node.para_index = Some(para_index);
                path_node.control_index = Some(control_index);
                path_node.transform = if source_affine {
                    ShapeTransform::default()
                } else {
                    transform
                };
                path_node.cell_index = cell_index;
                path_node.cell_para_index = cell_para_index;
                path_node.outer_table_control_index = outer_table_control_index;
                let mut node = RenderNode::new(
                    node_id,
                    RenderNodeType::Path(path_node),
                    BoundingBox::new(paint_x, paint_y, paint_w, paint_h),
                );
                self.add_image_fill_node(
                    tree,
                    &mut node,
                    &poly.drawing,
                    paint_x,
                    paint_y,
                    paint_w,
                    paint_h,
                    bin_data_content,
                );
                let empty_map = std::collections::HashMap::new();
                self.layout_textbox_content(
                    tree,
                    &mut node,
                    &poly.drawing,
                    base_x,
                    base_y,
                    w,
                    h,
                    section_index,
                    para_index,
                    control_index,
                    styles,
                    bin_data_content,
                    &empty_map,
                    parent_cell_path,
                    shape.common().treat_as_char,
                    matrix_positioned,
                    textbox_vpos_origin_hu(shape.common(), matrix_positioned),
                );
                parent.children.push(node);
            }
            ShapeObject::Curve(curve) => {
                let (style, gradient) = drawing_to_shape_style(&curve.drawing, self.dpi);
                let sa = &curve.drawing.shape_attr;
                let sx = if sa.original_width > 0 {
                    render_w / hwpunit_to_px(sa.original_width as i32, self.dpi)
                } else {
                    1.0
                };
                let sy = if sa.original_height > 0 {
                    render_h / hwpunit_to_px(sa.original_height as i32, self.dpi)
                } else {
                    1.0
                };
                let (point_x, point_y, sx, sy) = group_point_frame(
                    sa,
                    matrix_positioned,
                    (render_x, render_y),
                    (render_w, render_h),
                    (sx, sy),
                );
                let commands = self.curve_to_path_commands_scaled(curve, point_x, point_y, sx, sy);
                let node_id = tree.next_id();
                let mut path_node = PathNode::new(commands, style, gradient);
                path_stroke_arrows::publish(&mut path_node, &curve.drawing);
                path_node.section_index = Some(section_index);
                path_node.para_index = Some(para_index);
                path_node.control_index = Some(control_index);
                path_node.transform = transform;
                path_node.cell_index = cell_index;
                path_node.cell_para_index = cell_para_index;
                path_node.outer_table_control_index = outer_table_control_index;
                let mut node = RenderNode::new(
                    node_id,
                    RenderNodeType::Path(path_node),
                    BoundingBox::new(render_x, render_y, render_w, render_h),
                );
                self.add_image_fill_node(
                    tree,
                    &mut node,
                    &curve.drawing,
                    render_x,
                    render_y,
                    render_w,
                    render_h,
                    bin_data_content,
                );
                let empty_map = std::collections::HashMap::new();
                self.layout_textbox_content(
                    tree,
                    &mut node,
                    &curve.drawing,
                    base_x,
                    base_y,
                    w,
                    h,
                    section_index,
                    para_index,
                    control_index,
                    styles,
                    bin_data_content,
                    &empty_map,
                    parent_cell_path,
                    shape.common().treat_as_char,
                    matrix_positioned,
                    textbox_vpos_origin_hu(shape.common(), matrix_positioned),
                );
                parent.children.push(node);
            }
            ShapeObject::Group(group) => {
                // 묶음 개체: Group 컨테이너 노드로 감싸서 hittest 시 하나의 개체로 선택되도록 함
                let group_id = tree.next_id();
                let group_origin = inherited_group_origin.unwrap_or({
                    if group.shape_attr.group_level == 0 {
                        (base_x, base_y)
                    } else {
                        (0.0, 0.0)
                    }
                });
                let mut group_node = RenderNode::new(
                    group_id,
                    RenderNodeType::Group(GroupNode {
                        paint_transform: None,
                        section_index: Some(section_index),
                        para_index: Some(para_index),
                        control_index: Some(control_index),
                    }),
                    BoundingBox::new(base_x, base_y, w, h),
                );
                let mut textbox_offset = 0;
                for child in &group.children {
                    let first_child = group_node.children.len();
                    let sa = child.shape_attr();
                    let has_rotation = sa.render_b.abs() > 1e-6 || sa.render_c.abs() > 1e-6;

                    if has_rotation {
                        self.layout_group_child_affine(
                            tree,
                            &mut group_node,
                            child,
                            group_origin.0,
                            group_origin.1,
                            sa,
                            section_index,
                            para_index,
                            control_index,
                            styles,
                            bin_data_content,
                            parent_cell_path,
                        );
                    } else {
                        // render_tx/ty와 render_sx/sy에는 top-level group 로컬 좌표계
                        // 안에서 그룹 스케일/이동/flip이 합성되어 있다. top-level group
                        // anchor만 더하고, nested group bbox는 다시 더하지 않는다. 음수
                        // scale이면 tx는 오른쪽/아래쪽 모서리일 수 있으므로 두 변환
                        // 모서리의 min/max로 실제 bbox를 만든다.
                        let x0 = sa.render_tx;
                        let y0 = sa.render_ty;
                        let x1 = sa.render_tx + sa.original_width as f64 * sa.render_sx;
                        let y1 = sa.render_ty + sa.original_height as f64 * sa.render_sy;
                        let child_x = group_origin.0 + hwpunit_to_px(x0.min(x1) as i32, self.dpi);
                        let child_y = group_origin.1 + hwpunit_to_px(y0.min(y1) as i32, self.dpi);
                        let child_w = hwpunit_to_px((x1 - x0).abs() as i32, self.dpi);
                        let child_h = hwpunit_to_px((y1 - y0).abs() as i32, self.dpi);
                        let empty_map = std::collections::HashMap::new();
                        self.layout_shape_object_with_group_origin(
                            tree,
                            &mut group_node,
                            child,
                            child_x,
                            child_y,
                            child_w,
                            child_h,
                            section_index,
                            para_index,
                            control_index,
                            styles,
                            bin_data_content,
                            &empty_map,
                            parent_cell_path,
                            table_cell_ref, // [Task #1138] 그룹 자식 — 부모와 같은 셀 컨텍스트
                            true,
                            Some(group_origin),
                        );
                    }
                    if textbox_offset > 0 {
                        for rendered in &mut group_node.children[first_child..] {
                            offset_group_textbox_sources(
                                rendered,
                                parent_cell_path.len(),
                                textbox_offset,
                            );
                        }
                    }
                    textbox_offset += child.textbox_shape_count();
                }
                parent.children.push(group_node);
            }
            ShapeObject::Picture(pic) => {
                // 그룹 내 그림: common이 비어있으므로 w, h(shape_attr 기반)를 직접 사용
                let bin_data_id = pic.image_attr.bin_data_id;
                let image_data = find_bin_data_bytes(bin_data_content, bin_data_id);
                // [#5568] 그림 자르기(crop)를 본문 경로와 동일하게 싣는다. 묶음은
                // 원본 하나를 imgClip 띠로 나눠 쓰는 문서가 있어(같은 bin_data 를
                // 자식마다 다른 영역으로), 빠뜨리면 원본 전체가 대상 상자에
                // 압착된다(비율 파괴). 렌더러의 crop 분기는 이 두 필드만 소비한다.
                let crop = pic.render_crop_rect();
                let original_size_hu = pic.crop_reference_size();
                let img_id = tree.next_id();
                let img_node = RenderNode::new(
                    img_id,
                    RenderNodeType::Image(ImageNode {
                        transform,
                        crop,
                        original_size_hu,
                        soft_edge_radius_hu: pic.effects.soft_edge_radius,
                        effect: pic.image_attr.effect,
                        brightness: pic.image_attr.brightness,
                        contrast: pic.image_attr.contrast,
                        opacity: pic.image_attr.opacity(),
                        text_wrap: Some(pic.common.text_wrap),
                        external_path: pic.image_attr.external_path.clone(),
                        ..ImageNode::new(bin_data_id, image_data)
                    }),
                    BoundingBox::new(render_x, render_y, render_w, render_h),
                );
                self.append_picture_image_node(tree, parent, pic, img_node);
            }
            ShapeObject::Chart(chart) => {
                // Task #195: 차트 placeholder (점선 테두리 + "차트" 라벨)
                let _chart = chart;
                let node_id = tree.next_id();
                let node = RenderNode::new(
                    node_id,
                    RenderNodeType::Placeholder(
                        crate::renderer::render_tree::PlaceholderNode::new(
                            0xFFE8F0FE,
                            0xFF4A90E2,
                            "차트 (Chart)".to_string(),
                        ),
                    ),
                    BoundingBox::new(render_x, render_y, render_w, render_h),
                );
                parent.children.push(node);
            }
            ShapeObject::Ole(ole) => {
                // Task #195 단계 8: BinData에서 OOXML 차트 시도 → 성공 시 네이티브 SVG 렌더
                // [#4694] 표 셀은 parent_cell_path 가 아니라 table_cell_ref 로 온다(#1138).
                // ole 노드의 컨테이너 문맥 방출용으로 한 경로에 합친다 — 상위 경로 뒤에 셀 항목.
                let ole_container_path: Vec<CellPathEntry> = {
                    let mut p = parent_cell_path.to_vec();
                    if let Some((cell_idx, cell_para_idx, outer_ctrl)) = table_cell_ref {
                        p.push(CellPathEntry {
                            control_index: outer_ctrl,
                            cell_index: cell_idx,
                            cell_para_index: cell_para_idx,
                            text_direction: 0,
                        });
                    }
                    p
                };
                let mut rendered = false;
                // [#5582] legacy 차트 `Contents` 파싱 실패는 최종 판정이 아니라 폴백
                // 사유다 — 라벨만 기억하고 EMF/WMF/네이티브 이미지/hmapsi 폴백을
                // 계속 시도한다. 전부 실패했을 때만 이 라벨로 자리표시를 그린다.
                let mut chart_error_label: Option<String> = None;
                // [#2550] 상한 로드 1회 — 이하 분기가 같은 바이트를 공유한다 (기존 3중
                // 해제 제거 겸). 상한 초과는 아래 placeholder 폴백으로 접힌다.
                if let Some((content, ole_bytes)) =
                    find_bin_data(bin_data_content, ole.bin_data_id as u16).and_then(|content| {
                        content
                            .data
                            .load_limited(crate::model::bin_data::MAX_BIN_DATA_BYTES)
                            .map(|bytes| (content, bytes))
                    })
                {
                    // HWPX에서 주입된 OOXML 차트 XML 직접 경로 (CFB 컨테이너 없음)
                    if content.extension == "ooxml_chart" {
                        if let Some(mut chart) = crate::ooxml_chart::OoxmlChart::parse(&ole_bytes) {
                            if let Some(fallback) = ole.chart_switch_fallback.as_ref() {
                                if let Some(fallback_bytes) =
                                    find_bin_data(bin_data_content, fallback.bin_data_id as u16)
                                        .and_then(|item| {
                                            item.data.load_limited(
                                                crate::model::bin_data::MAX_BIN_DATA_BYTES,
                                            )
                                        })
                                {
                                    if let Some(container) =
                                        crate::parser::ole_container::parse_ole_container(
                                            &fallback_bytes,
                                        )
                                    {
                                        // 두 OOXML 사본이 다른 입력은 미리보기 색을 빌리지 않는다.
                                        if container.ooxml_chart.as_deref()
                                            == Some(ole_bytes.as_slice())
                                        {
                                            if let (Some(contents), Some(preview)) = (
                                                container.raw_contents.as_deref(),
                                                container.preview_emf.as_deref(),
                                            ) {
                                                crate::ole_chart::apply_preview_palette(
                                                    &mut chart, contents, preview, render_w,
                                                    render_h,
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                            let svg_fragment = crate::ole_chart::render_ooxml_chart(
                                &chart,
                                [render_x, render_y, render_w, render_h],
                            );
                            push_ole_raw_svg_render_node(
                                tree,
                                parent,
                                BoundingBox::new(render_x, render_y, render_w, render_h),
                                svg_fragment,
                                section_index,
                                para_index,
                                control_index,
                                &ole_container_path,
                            );
                            rendered = true;
                        }
                    }
                    if !rendered {
                        if let Some(container) =
                            crate::parser::ole_container::parse_ole_container(&ole_bytes)
                        {
                            if let Some(ooxml_bytes) = container.ooxml_chart.as_ref() {
                                if let Some(mut chart) =
                                    crate::ooxml_chart::OoxmlChart::parse(ooxml_bytes)
                                {
                                    if let (Some(contents), Some(preview)) = (
                                        container.raw_contents.as_deref(),
                                        container.preview_emf.as_deref(),
                                    ) {
                                        crate::ole_chart::apply_preview_palette(
                                            &mut chart, contents, preview, render_w, render_h,
                                        );
                                    }
                                    let svg_fragment = crate::ole_chart::render_ooxml_chart(
                                        &chart,
                                        [render_x, render_y, render_w, render_h],
                                    );
                                    push_ole_raw_svg_render_node(
                                        tree,
                                        parent,
                                        BoundingBox::new(render_x, render_y, render_w, render_h),
                                        svg_fragment,
                                        section_index,
                                        para_index,
                                        control_index,
                                        &ole_container_path,
                                    );
                                    rendered = true;
                                }
                            }

                            // #1251: 레거시 HWP 차트의 Contents 스트림을 읽는다.
                            if !rendered {
                                if let Some(raw_contents) = container.raw_contents.as_ref() {
                                    match crate::ole_chart::parse_ole_chart_contents(raw_contents) {
                                        Ok(ole_chart) => {
                                            let svg_fragment =
                                                crate::ole_chart::render_ole_chart_svg_fragment_with_contents(
                                                    &ole_chart,
                                                    raw_contents,
                                                    [render_x, render_y, render_w, render_h],
                                                    ole.bin_data_id,
                                                );
                                            push_ole_raw_svg_render_node(
                                                tree,
                                                parent,
                                                BoundingBox::new(
                                                    render_x, render_y, render_w, render_h,
                                                ),
                                                svg_fragment,
                                                section_index,
                                                para_index,
                                                control_index,
                                                &ole_container_path,
                                            );
                                            rendered = true;
                                        }
                                        Err(error) => {
                                            // [#5582] 종전에는 여기서 자리표시를 그리고
                                            // 끝냈다 — `Contents` 를 가진 차트 아닌
                                            // 일반 OLE 가 갖고 있는 EMF/WMF 미리보기에
                                            // 도달하지 못해 개체가 화면에서 사라졌다
                                            // (36494613 실측: 개체 2개 자리표시 →
                                            // EMF 렌더 복원). 폴백 사유로 강등한다.
                                            chart_error_label = Some(ole_chart_fallback_label(
                                                error.stable_message(),
                                                ole.bin_data_id,
                                            ));
                                        }
                                    }
                                }
                            }

                            // Task #195 단계 14: OOXML 차트 부재 시 EMF 네이티브 SVG 폴백
                            if !rendered {
                                if let Some(emf_bytes) = container.preview_emf.as_ref() {
                                    let render_rect = (
                                        render_x as f32,
                                        render_y as f32,
                                        render_w as f32,
                                        render_h as f32,
                                    );
                                    if let Ok(svg_fragment) =
                                        crate::emf::convert_to_svg(emf_bytes, render_rect)
                                    {
                                        push_ole_raw_svg_render_node(
                                            tree,
                                            parent,
                                            BoundingBox::new(
                                                render_x, render_y, render_w, render_h,
                                            ),
                                            svg_fragment,
                                            section_index,
                                            para_index,
                                            control_index,
                                            &ole_container_path,
                                        );
                                        if let Some(node) = parent.children.last_mut() {
                                            if let RenderNodeType::RawSvg(raw) = &mut node.node_type
                                            {
                                                raw.emf_source =
                                                    Some(crate::emf::EmfReplaySource {
                                                        data: std::sync::Arc::from(
                                                            emf_bytes.as_slice(),
                                                        ),
                                                        render_rect,
                                                    });
                                            }
                                        }
                                        rendered = true;
                                    }
                                }
                            }

                            // [#3363] EMF 부재 시 WMF 프레젠테이션 폴백 — HWP3 내장
                            // OLE(글맵시 등)의 OlePres000 은 표준 WMF 다. 기존 WMF
                            // 그림 경로와 동일하게 SVG 로 변환해 data URI 로 배치한다.
                            if !rendered {
                                if let Some(wmf_bytes) = container.preview_wmf.as_ref() {
                                    if let Some(svg_bytes) =
                                        crate::renderer::svg::convert_wmf_to_svg(wmf_bytes)
                                    {
                                        use base64::Engine;
                                        let b64 = base64::engine::general_purpose::STANDARD
                                            .encode(&svg_bytes);
                                        let href = format!("data:image/svg+xml;base64,{}", b64);
                                        // OLE의 목적 extent는 WMF 창을 가로·세로 독립 환산한다.
                                        let svg_fragment = format!(
                                            "<image x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" preserveAspectRatio=\"none\" xlink:href=\"{}\" href=\"{}\"/>",
                                            render_x, render_y, render_w, render_h, href, href
                                        );
                                        push_ole_raw_svg_render_node(
                                            tree,
                                            parent,
                                            BoundingBox::new(
                                                render_x, render_y, render_w, render_h,
                                            ),
                                            svg_fragment,
                                            section_index,
                                            para_index,
                                            control_index,
                                            &ole_container_path,
                                        );
                                        rendered = true;
                                    }
                                }
                            }

                            // 네이티브 임베딩 이미지(BMP/PNG/JPEG/GIF) 폴백
                            if !rendered {
                                if let Some((kind, bytes)) = container.native_image.as_ref() {
                                    use base64::Engine;
                                    // BMP → PNG 재인코딩 (SVG <image>는 data:image/bmp 미지원)
                                    let (render_bytes, render_mime): (
                                        std::borrow::Cow<[u8]>,
                                        &str,
                                    ) = if kind.mime() == "image/bmp" {
                                        match crate::renderer::svg::bmp_bytes_to_png_bytes(bytes) {
                                            Some(png) => {
                                                (std::borrow::Cow::Owned(png), "image/png")
                                            }
                                            None => (
                                                std::borrow::Cow::Borrowed(bytes.as_slice()),
                                                kind.mime(),
                                            ),
                                        }
                                    } else {
                                        (std::borrow::Cow::Borrowed(bytes.as_slice()), kind.mime())
                                    };
                                    let b64 = base64::engine::general_purpose::STANDARD
                                        .encode(&*render_bytes);
                                    let href = format!("data:{};base64,{}", render_mime, b64);
                                    let svg_fragment = format!(
                                    "<image x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" preserveAspectRatio=\"xMidYMid meet\" xlink:href=\"{}\" href=\"{}\"/>",
                                    render_x, render_y, render_w, render_h, href, href
                                );
                                    push_ole_raw_svg_render_node(
                                        tree,
                                        parent,
                                        BoundingBox::new(render_x, render_y, render_w, render_h),
                                        svg_fragment,
                                        section_index,
                                        para_index,
                                        control_index,
                                        &ole_container_path,
                                    );
                                    rendered = true;
                                }
                            }

                            // [#5725] 미리보기 없는 한글 수식 OLE — `Contents` 봉투의
                            // 수식 스크립트를 기존 수식 렌더러(Control::Equation 경로와
                            // 동일)로 그린다. 코퍼스의 수식 OLE `OlePres000` 은 전부
                            // 28바이트 스텁이라 미리보기 폴백으로는 그릴 것이 없다 —
                            // 스크립트가 유일한 출처다 (10k 실측 8문서/39개체).
                            if !rendered {
                                if let Some(script) = container.raw_contents.as_deref().and_then(
                                    crate::parser::ole_container::parse_equation_contents_script,
                                ) {
                                    let tokens =
                                        super::super::equation::document_script::tokenize(&script);
                                    let ast =
                                        super::super::equation::parser::EqParser::for_document(
                                            tokens,
                                        )
                                        .parse();
                                    // 글자 크기는 개체 크기에 맞춘다 — 기준 10px 레이아웃의
                                    // 높이 비로 역산. (SVG/Skia 는 수식을 bbox 폭에만 맞춰
                                    // 가로 스케일하므로 세로는 여기서 맞아야 한다.)
                                    let base_layout =
                                        super::super::equation::layout::EqLayout::new(10.0)
                                            .layout(&ast);
                                    let font_size_px = if base_layout.height > 0.0 && render_h > 0.0
                                    {
                                        (10.0 * render_h / base_layout.height).clamp(2.0, 400.0)
                                    } else {
                                        10.0
                                    };
                                    let layout_box =
                                        super::super::equation::layout::EqLayout::new(font_size_px)
                                            .layout(&ast);
                                    let color_str =
                                        super::super::equation::svg_render::eq_color_to_svg(0);
                                    let svg_content =
                                        super::super::equation::svg_render::render_equation_svg(
                                            &layout_box,
                                            &color_str,
                                            font_size_px,
                                        );
                                    let eq_node = RenderNode::new(
                                        tree.next_id(),
                                        RenderNodeType::Equation(EquationNode {
                                            svg_content,
                                            layout_box,
                                            color_str,
                                            color: 0,
                                            script,
                                            font_size: font_size_px,
                                            section_index: Some(section_index),
                                            para_index: Some(para_index),
                                            control_index: Some(control_index),
                                            cell_index: table_cell_ref.map(|(c, _, _)| c),
                                            cell_para_index: table_cell_ref.map(|(_, p, _)| p),
                                            note_ref: None,
                                        }),
                                        BoundingBox::new(render_x, render_y, render_w, render_h),
                                    );
                                    parent.children.push(eq_node);
                                    rendered = true;
                                }
                            }

                            // [#5724] 미리보기 없는 그림(메타파일/비트맵) OLE —
                            // `CONTENTS` 가 곧 그림이다 (CompObj UserType=`그림 (메타
                            // 파일)`, ProgID=StaticMetafile 실측). 미리보기가 있으면 위
                            // EMF/WMF 폴백이 이미 소비했으므로, 이 갈래는 미리보기가
                            // 아예 없는 잔여만 구제한다 (10k 실측 WMF 8문서/11개체 +
                            // BMP 1문서/2개체). 기존 WMF 재생기가 placeable 헤더까지
                            // 자체 처리한다.
                            if !rendered {
                                if let Some(raw) = container.raw_contents.as_deref() {
                                    if crate::parser::ole_container::raw_contents_is_wmf(raw) {
                                        if let Some(svg_bytes) =
                                            crate::renderer::svg::convert_wmf_to_svg(raw)
                                        {
                                            use base64::Engine;
                                            let b64 = base64::engine::general_purpose::STANDARD
                                                .encode(&svg_bytes);
                                            let href = format!("data:image/svg+xml;base64,{}", b64);
                                            // OLE의 목적 extent는 WMF 창을 가로·세로 독립 환산한다.
                                            let svg_fragment = format!(
                                                "<image x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" preserveAspectRatio=\"none\" xlink:href=\"{}\" href=\"{}\"/>",
                                                render_x, render_y, render_w, render_h, href, href
                                            );
                                            push_ole_raw_svg_render_node(
                                                tree,
                                                parent,
                                                BoundingBox::new(
                                                    render_x, render_y, render_w, render_h,
                                                ),
                                                svg_fragment,
                                                section_index,
                                                para_index,
                                                control_index,
                                                &ole_container_path,
                                            );
                                            rendered = true;
                                        }
                                    } else if let Some(contents_emf) =
                                        crate::parser::ole_container::contents_emf_payload(raw)
                                    {
                                        let render_rect = (
                                            render_x as f32,
                                            render_y as f32,
                                            render_w as f32,
                                            render_h as f32,
                                        );
                                        if let Ok(svg_fragment) =
                                            crate::emf::convert_to_svg(contents_emf, render_rect)
                                        {
                                            push_ole_raw_svg_render_node(
                                                tree,
                                                parent,
                                                BoundingBox::new(
                                                    render_x, render_y, render_w, render_h,
                                                ),
                                                svg_fragment,
                                                section_index,
                                                para_index,
                                                control_index,
                                                &ole_container_path,
                                            );
                                            if let Some(node) = parent.children.last_mut() {
                                                if let RenderNodeType::RawSvg(raw) =
                                                    &mut node.node_type
                                                {
                                                    raw.emf_source =
                                                        Some(crate::emf::EmfReplaySource {
                                                            data: std::sync::Arc::from(
                                                                contents_emf,
                                                            ),
                                                            render_rect,
                                                        });
                                                }
                                            }
                                            rendered = true;
                                        }
                                    } else if let Some((kind, bytes)) =
                                        crate::parser::ole_container::detect_native_image(raw)
                                    {
                                        use base64::Engine;
                                        // BMP → PNG 재인코딩 (SVG <image>는 data:image/bmp 미지원)
                                        let (render_bytes, render_mime): (
                                            std::borrow::Cow<[u8]>,
                                            &str,
                                        ) = if kind.mime() == "image/bmp" {
                                            match crate::renderer::svg::bmp_bytes_to_png_bytes(
                                                &bytes,
                                            ) {
                                                Some(png) => {
                                                    (std::borrow::Cow::Owned(png), "image/png")
                                                }
                                                None => (
                                                    std::borrow::Cow::Borrowed(bytes.as_slice()),
                                                    kind.mime(),
                                                ),
                                            }
                                        } else {
                                            (
                                                std::borrow::Cow::Borrowed(bytes.as_slice()),
                                                kind.mime(),
                                            )
                                        };
                                        let b64 = base64::engine::general_purpose::STANDARD
                                            .encode(&*render_bytes);
                                        let href = format!("data:{};base64,{}", render_mime, b64);
                                        let svg_fragment = format!(
                                            "<image x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" preserveAspectRatio=\"xMidYMid meet\" xlink:href=\"{}\" href=\"{}\"/>",
                                            render_x, render_y, render_w, render_h, href, href
                                        );
                                        push_ole_raw_svg_render_node(
                                            tree,
                                            parent,
                                            BoundingBox::new(
                                                render_x, render_y, render_w, render_h,
                                            ),
                                            svg_fragment,
                                            section_index,
                                            para_index,
                                            control_index,
                                            &ole_container_path,
                                        );
                                        rendered = true;
                                    }
                                }
                            }
                        }
                        if !rendered
                            && self.push_hwpx_hmapsi_preview_clip_node(
                                tree,
                                parent,
                                BoundingBox::new(render_x, render_y, render_w, render_h),
                                &ole_bytes,
                                section_index,
                                para_index,
                                control_index,
                                &ole_container_path,
                            )
                        {
                            rendered = true;
                        }
                    } // !rendered (CFB path)
                }

                if !rendered {
                    // [#5582] 차트 `Contents` 파싱이 실패했고 다른 미리보기 폴백도
                    // 전부 실패한 경우엔 그 사유 라벨(종전 색)을 쓴다.
                    //
                    // [#5882] 사유 라벨 없는 회색 자리표시("OLE 개체 (BinData #N)")는
                    // 문서에 없던 이물이다 — 그릴 내용이 원본에 없는 OLE(빈 CFB 등)에 대해
                    // 한글은 빈 자리로 둔다. 진단이 필요할 때만 RHWP_DIAG_OLE_PLACEHOLDER
                    // 로 렌더 트리에 넣는다.
                    let draw_placeholder = chart_error_label.is_some()
                        || std::env::var_os("RHWP_DIAG_OLE_PLACEHOLDER").is_some();
                    if draw_placeholder {
                        let (bg, fg, label) = match chart_error_label {
                            Some(label) => (0xFFFFF4E5, 0xFFB45F06, label),
                            None => (
                                0xFFF0F0F0,
                                0xFF707070,
                                format!("OLE 개체 (BinData #{})", ole.bin_data_id),
                            ),
                        };
                        push_ole_placeholder_render_node(
                            tree,
                            parent,
                            BoundingBox::new(render_x, render_y, render_w, render_h),
                            bg,
                            fg,
                            label,
                            section_index,
                            para_index,
                            control_index,
                            &ole_container_path,
                        );
                    }
                }
            }
        }
    }

    /// 도형의 이미지 채우기를 자식 이미지 노드로 추가한다.
    pub(crate) fn add_image_fill_node(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        drawing: &crate::model::shape::DrawingObjAttr,
        base_x: f64,
        base_y: f64,
        w: f64,
        h: f64,
        bin_data_content: &[BinDataContent],
    ) {
        use crate::model::style::FillType;
        if drawing.fill.fill_type == FillType::Image {
            if let Some(ref img_fill) = drawing.fill.image {
                let bin_data_id = img_fill.bin_data_id;
                let image_data = find_bin_data_bytes(bin_data_content, bin_data_id);
                // [#8575] 배치 모드(가운데로·왼쪽 아래로 등)의 그림 크기는 그림 자체의
                // 픽셀 크기(1px = 1/96in, 그림의 DPI 정보는 쓰지 않음)를 축마다 도형
                // 상자로 줄인 값이다. 도형의 원래 크기·배율과는 무관하다 — 한/글 2020
                // Print 로 확인(`samples/issue8575/shape_image_fill.hwpx` 사례 A~F).
                // 바둑판·크기에 맞추어 등 나머지 모드는 종전 값을 유지한다.
                let placement_size = is_placement_fill_mode(img_fill.fill_mode)
                    .then(|| {
                        image_data
                            .as_deref()
                            .and_then(crate::renderer::svg::parse_image_dimensions)
                    })
                    .flatten()
                    .filter(|(nw, nh)| *nw > 0 && *nh > 0)
                    .map(|(nw, nh)| {
                        let scale = self.dpi / 96.0;
                        ((nw as f64 * scale).min(w), (nh as f64 * scale).min(h))
                    });
                // 이미지 원본 크기: shape_attr의 original_width/height (HWPUNIT)
                let original_size = placement_size.or_else(|| {
                    let ow = drawing.shape_attr.original_width;
                    let oh = drawing.shape_attr.original_height;
                    if ow > 0 && oh > 0 {
                        Some((
                            hwpunit_to_px(ow as i32, self.dpi),
                            hwpunit_to_px(oh as i32, self.dpi),
                        ))
                    } else {
                        None
                    }
                });

                let img_id = tree.next_id();
                // [#6895] `ImageNode` 는 화면 순서를, `ImageFill` 은 이진 순서를 담는다.
                // HWPX 파서가 `hc:img` 를 정규화하게 되었으므로(그 전에는 이 축만 안 했다)
                // 여기서 되돌린다. HWP5·HWP3 도형 채움은 종전부터 이진 순서였고 이 자리가
                // 맞바꾸지 않아 색조가 반대로 그려지고 있었다.
                let (img_bright, img_contrast) = img_fill.display_brightness_contrast();
                let img_node = RenderNode::new(
                    img_id,
                    RenderNodeType::Image(ImageNode {
                        fill_mode: Some(img_fill.fill_mode),
                        original_size,
                        brightness: img_bright,
                        contrast: img_contrast,
                        effect: match img_fill.effect {
                            1 => crate::model::image::ImageEffect::GrayScale,
                            2 => crate::model::image::ImageEffect::BlackWhite,
                            3 => crate::model::image::ImageEffect::Pattern8x8,
                            _ => crate::model::image::ImageEffect::RealPic,
                        },
                        ..ImageNode::new(bin_data_id, image_data)
                    }),
                    BoundingBox::new(base_x, base_y, w, h),
                );
                parent.children.push(img_node);
            }
        }
    }

    fn max_descendant_bottom(node: &RenderNode) -> Option<f64> {
        node.children.iter().fold(None, |acc, child| {
            let child_bottom = child.bbox.y + child.bbox.height;
            let descendant_bottom = Self::max_descendant_bottom(child).unwrap_or(child_bottom);
            Some(acc.map_or(descendant_bottom, |current: f64| {
                current.max(descendant_bottom)
            }))
        })
    }

    fn min_descendant_top(node: &RenderNode) -> Option<f64> {
        node.children.iter().fold(None, |acc, child| {
            let descendant_top = Self::min_descendant_top(child).unwrap_or(child.bbox.y);
            Some(acc.map_or(descendant_top, |current: f64| current.min(descendant_top)))
        })
    }

    /// [#6174·#8153] 편집용 내용 영역과 실제 Print clip을 구분한다.
    ///
    /// 편집용 bbox는 원래 표시 영역과 겹치는 줄의 잉크만 포함한다.
    /// 영역 밖 후속 줄은 새로 수용하지 않는다. Print는 독립 도형 경계를
    /// 별도 소비하며 명시적인 원본 paint clip을 덮어쓰지 않는다.
    fn settle_textbox_clip(textbox_node: &mut RenderNode, shape_bounds: BoundingBox) {
        if textbox_node.paint_clip.is_none() {
            textbox_node.print_clip_bbox = Some(shape_bounds);
        }
        let clip_top = textbox_node.bbox.y;
        let clip_bottom = clip_top + textbox_node.bbox.height;
        let mut new_top = clip_top;
        let mut new_bottom = clip_bottom;
        for child in &textbox_node.children {
            // 원래 표시 영역과 겹치는 줄의 잉크만 확장에 참여한다.
            // 확장된 아래끝으로 다음 줄을 연쇄 수용하지 않는다.
            if matches!(child.node_type, RenderNodeType::TextLine(_))
                && (child.bbox.y >= clip_bottom || child.bbox.y + child.bbox.height <= clip_top)
            {
                continue;
            }
            new_top = new_top.min(Self::min_descendant_top(child).unwrap_or(child.bbox.y));
            new_bottom = new_bottom.max(
                Self::max_descendant_bottom(child).unwrap_or(child.bbox.y + child.bbox.height),
            );
        }
        textbox_node.bbox.y = new_top;
        textbox_node.bbox.height = new_bottom - new_top;
    }

    /// 비인라인 글상자: 절대배치 자식 도형(하단 장식 등)이 박스 세로를 넘으면
    /// 한글은 박스를 내용 높이에 맞춰 늘린다(재현 문서 B 글상자 실측 —
    /// 원본 박스가 선언보다 34px 큼). 텍스트 줄 초과는 대상이 아니다(연결
    /// 글상자 오버플로 관행 보존).
    fn expand_textbox_to_object_children(
        shape_node: &mut RenderNode,
        textbox_node: &mut RenderNode,
        bottom_padding: f64,
    ) {
        let object_bottom = textbox_node
            .children
            .iter()
            .filter(|c| !matches!(c.node_type, RenderNodeType::TextLine(_)))
            .map(|c| {
                let own = c.bbox.y + c.bbox.height;
                Self::max_descendant_bottom(c).map_or(own, |d| d.max(own))
            })
            .fold(f64::NEG_INFINITY, f64::max);
        if !object_bottom.is_finite() {
            return;
        }
        let textbox_bottom = textbox_node.bbox.y + textbox_node.bbox.height;
        if object_bottom > textbox_bottom {
            textbox_node.bbox.height = object_bottom - textbox_node.bbox.y;
        }
        let shape_bottom = shape_node.bbox.y + shape_node.bbox.height;
        let required_shape_bottom = object_bottom + bottom_padding;
        if required_shape_bottom > shape_bottom {
            shape_node.bbox.height = required_shape_bottom - shape_node.bbox.y;
        }
    }

    fn expand_inline_textbox_to_content(
        shape_node: &mut RenderNode,
        textbox_node: &mut RenderNode,
        bottom_padding: f64,
    ) {
        let Some(content_bottom) = Self::max_descendant_bottom(textbox_node) else {
            return;
        };

        let textbox_bottom = textbox_node.bbox.y + textbox_node.bbox.height;
        if content_bottom > textbox_bottom {
            textbox_node.bbox.height = content_bottom - textbox_node.bbox.y;
        }

        let shape_bottom = shape_node.bbox.y + shape_node.bbox.height;
        let required_shape_bottom = content_bottom + bottom_padding;
        if required_shape_bottom > shape_bottom {
            shape_node.bbox.height = required_shape_bottom - shape_node.bbox.y;
        }
    }

    /// 도형 내 TextBox 콘텐츠를 레이아웃한다.
    /// parent_cell_path: 상위 글상자/표의 경로 (최상위이면 빈 슬라이스)
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn layout_textbox_content(
        &self,
        tree: &mut PageLayoutContext,
        shape_node: &mut RenderNode,
        drawing: &crate::model::shape::DrawingObjAttr,
        base_x: f64,
        base_y: f64,
        w: f64,
        h: f64,
        section_index: usize,
        para_index: usize,
        control_index: usize,
        styles: &ResolvedStyleSet,
        bin_data_content: &[BinDataContent],
        overflow_map: &std::collections::HashMap<(usize, usize), Vec<Paragraph>>,
        parent_cell_path: &[CellPathEntry],
        parent_treat_as_char: bool,
        matrix_positioned: bool,
        textbox_vpos_origin_hu: Option<i32>,
    ) {
        let text_box = match &drawing.text_box {
            Some(tb) => tb,
            None => return,
        };

        let mut textbox_path = parent_cell_path.to_vec();
        textbox_path.push(CellPathEntry {
            control_index,
            cell_index: 0,
            cell_para_index: 0,
            text_direction: 0,
        });
        shape_node.textbox_source = Some((
            section_index,
            CellContext {
                parent_para_index: para_index,
                path: textbox_path,
                in_textbox: true,
            },
        ));

        let margin_left = hwpunit_to_px(text_box.margin_left as i32, self.dpi);
        let margin_right = hwpunit_to_px(text_box.margin_right as i32, self.dpi);
        let margin_top = hwpunit_to_px(text_box.margin_top as i32, self.dpi);
        let margin_bottom = hwpunit_to_px(text_box.margin_bottom as i32, self.dpi);

        let inner_area = LayoutRect {
            x: base_x + margin_left,
            y: base_y + margin_top,
            width: (w - margin_left - margin_right).max(0.0),
            height: (h - margin_top - margin_bottom).max(0.0),
        };
        let mut textbox_node = RenderNode::new(
            tree.next_id(),
            RenderNodeType::TextBox,
            BoundingBox::new(
                inner_area.x,
                inner_area.y,
                inner_area.width,
                inner_area.height,
            ),
        );

        if let Some(paths) = &text_box.paint_clip {
            let scale = self.dpi / 7200.0;
            textbox_node.paint_clip = Some(
                paths
                    .iter()
                    .map(|p| p.map(|x, y| (base_x + x * scale, base_y + y * scale)))
                    .collect(),
            );
        }

        // [Task #874 #3 / #930] shortcut.hwp 1 페이지 우측하단 자동번호 "1" 시각 정합:
        // 도형이 원본 (sa.original_*) 대비 확대된 마스터 페이지 글상자는 한컴이 내부
        // 글꼴을 축소 렌더링한다. base_size 가 25400 (254 pt) 인 자동번호 글상자가 현재
        // 좌표계에서 그대로 339 px 로 그려지면 본문 우측 단축키 행과 겹친다.
        //
        // [#930] 발동 조건을 두 축 모두 1.5× 초과 (= min_ratio > 1.5, 등방 확대) 로
        // 좁힌다. table-in-tbox.hwp 2 페이지처럼 한 축만 강하게 늘어난 이방 확��
        // 글상자 (sx≈1.07, sy≈8.2) 는 내부 문단이 이미 current 박스 기준으로 조판된
        // 일반 본문이므로 축소하면 안 된다 (글꼴이 1/8 로 깨짐).
        //
        // [#930] 축소 계수는 2.0 / max_ratio. #874 의 1.0 / max_ratio 는 한컴 2022
        // PDF 측정 대비 자동번호를 약 2× 과축소했다 (글리프 93 px vs PDF 187 px).
        // 단일 샘플 (shortcut.hwp 자동번호) 기반 경험적 보정이므로, 다른 등방 확대
        // 글상자 샘플이 확보되면 재검증한다.
        let sa = &drawing.shape_attr;
        let local_styles_scaled: Option<ResolvedStyleSet> = {
            let positive_current_ratio = |current: u32, original: u32| -> f64 {
                let signed_current = current as i32;
                if original > 0 && signed_current > 0 {
                    signed_current as f64 / original as f64
                } else {
                    1.0
                }
            };
            let sw_ratio = positive_current_ratio(sa.current_width, sa.original_width);
            let sh_ratio = positive_current_ratio(sa.current_height, sa.original_height);
            let max_ratio = sw_ratio.max(sh_ratio);
            let min_ratio = sw_ratio.min(sh_ratio);
            // [Task #928] 인라인 도형 (treat_as_char=true) 은 폰트 자동 축소 적용 안 함.
            // exam_kor 5p 다이어그램의 사각형 [A 단계] 가 original=(2925, 975) HU →
            // current=(6518, 1983) HU 로 2.2배 확대된 채 IR 인코딩되어 있으나 한컴은
            // 폰트를 11.5pt 그대로 유지한다. 본 ratio 축소 (#874 #3) 가 잘못 발동하여
            // 폰트가 6.88px 로 축소되던 회귀를 차단. shortcut.hwp 마스터 페이지
            // 글상자는 tac=false 라 ratio 적용 유지.
            //
            // [PR #1276] HWPX 바탕쪽 하단 글상자처럼 current size 가 음수 HWPUNIT 을
            // u32 로 보존한 값이면(예: curSz height 4294965455 = -1841) 확대율로
            // 사용하지 않는다. 이를 양수로 해석하면 sh_ratio 가 수백만 배가 되어
            // 내부 글꼴이 0px 에 가깝게 붕괴한다.
            if min_ratio > 1.5 && !parent_treat_as_char {
                let inv = (2.0 / max_ratio).min(1.0);
                let mut local = styles.clone();
                for cs in local.char_styles.iter_mut() {
                    cs.font_size *= inv;
                    cs.letter_spacing *= inv;
                    for ls in cs.letter_spacings.iter_mut() {
                        *ls *= inv;
                    }
                }
                Some(local)
            } else {
                None
            }
        };
        let styles: &ResolvedStyleSet = local_styles_scaled.as_ref().unwrap_or(styles);

        // 세로쓰기 판정: 글상자 list_attr bit 0~2 = text_direction
        // (0=가로, 1=영문 눕힘, 2=영문 세움)
        // 주의: 테이블 셀은 bit 16~18이지만 글상자 LIST_HEADER는 bit 0~2
        let text_direction = (text_box.list_attr & 0x07) as u8;
        let reflows_matrix_lines = should_reflow_matrix_textbox_lines(
            matrix_positioned,
            drawing,
            text_box,
            text_direction,
            inner_area.width,
            inner_area.height,
            self.dpi,
        );
        // [#9076] 안내문을 넣고 나눈 개체 줄도 같은 사전 단계에서 이 글상자 폭으로 다시 나눈다.
        let reflows_hidden_guide_rows = text_direction == 0
            && inner_area.width > 0.0
            && text_box
                .paragraphs
                .iter()
                .any(hidden_guide_object_rows_need_reflow);
        let reflowed_textbox_paragraphs = if reflows_matrix_lines || reflows_hidden_guide_rows {
            let mut paragraphs = text_box.paragraphs.clone();
            for index in 0..paragraphs.len() {
                let matrix_lines =
                    reflows_matrix_lines && matrix_textbox_lines_need_reflow(&paragraphs[index]);
                let hidden_guide_rows = reflows_hidden_guide_rows
                    && hidden_guide_object_rows_need_reflow(&paragraphs[index]);
                if !matrix_lines && !hidden_guide_rows {
                    continue;
                }
                let previous_end =
                    crate::renderer::composer::paragraph_flow_end(&paragraphs[index]);
                if matrix_lines {
                    reflow_matrix_textbox_para(
                        &mut paragraphs[index],
                        inner_area.width,
                        styles,
                        self.dpi,
                    );
                } else {
                    textbox_reflow::in_frame(
                        &mut paragraphs[index],
                        inner_area.width,
                        styles,
                        self.dpi,
                    );
                }
                // 줄 수가 바뀌면 뒤 문단도 새 흐름 끝에서 이어진다. 저장 쪽/글상자
                // 리셋은 공통 vpos 재계산기가 보존하며 이전 줄의 끝과 구분한다.
                if crate::renderer::composer::paragraph_flow_end(&paragraphs[index]) != previous_end
                {
                    crate::renderer::composer::recalculate_section_vpos(
                        &mut paragraphs,
                        index,
                        None,
                        previous_end,
                        styles,
                        self.dpi,
                        false,
                    );
                }
            }
            Some(paragraphs)
        } else {
            None
        };
        let textbox_paragraphs = reflowed_textbox_paragraphs
            .as_deref()
            .unwrap_or(&text_box.paragraphs);

        // [#5721] page-기준 vpos 재기저화(origin 빼기)는 저장 vpos 스트림 **전체**가
        // page 좌표일 때만 유효하다. box 좌표 스트림(첫 문단 vpos 가 origin 미만)
        // 에서 줄 단위로 발동하면, origin 을 우연히 넘는 뒤쪽 문단만 재기저화되어
        // 순서가 꺾인다 — 2568129 글상자 실측: 제목 표 문단 vpos 228.6px(17145HU) 가
        // origin(~199px) 을 넘어 29.4px 로 내려앉아 앞의 발신처 표(110.3px) **위**에
        // 그려졌다. 첫 유효 vpos 가 origin 이상인 스트림에만 origin 을 유지한다.
        let textbox_vpos_origin_hu = textbox_vpos_origin_hu.filter(|origin| {
            textbox_paragraphs
                .iter()
                .find_map(|p| p.line_segs.first())
                .map(|seg| seg.vertical_pos >= *origin)
                .unwrap_or(false)
        });

        // 빈 텍스트박스에 오버플로우 문단이 매핑되어 있는지 확인 (가로/세로 공통)
        let key = (para_index, control_index);
        if let Some(overflow_paras) = overflow_map.get(&key) {
            if text_direction != 0 {
                // 세로쓰기 오버플로우 수신: 오버플로우 문단을 세로 레이아웃으로 렌더링
                self.layout_vertical_textbox_text_with_paras(
                    tree,
                    &mut textbox_node,
                    overflow_paras,
                    text_box,
                    styles,
                    &inner_area,
                    text_direction,
                    section_index,
                    para_index,
                    control_index,
                    parent_cell_path,
                );
            } else {
                // 이 텍스트박스는 연결된 텍스트박스의 타겟: 오버플로우 문단 렌더링
                let composed_paras: Vec<_> = overflow_paras
                    .iter()
                    .map(|p| crate::renderer::composer::compose_paragraph_in_context(p, styles))
                    .collect();
                let mut para_y = inner_area.y;
                for (tb_para_idx, composed) in composed_paras.iter().enumerate() {
                    let para = &overflow_paras[tb_para_idx];
                    if let Some(first_ls) = para.line_segs.first() {
                        let vpos_y = inner_area.y
                            + textbox_vpos_px(
                                first_ls.vertical_pos,
                                textbox_vpos_origin_hu,
                                self.dpi,
                            );
                        para_y = vpos_y.max(para_y);
                    }
                    let para_col_area = LayoutRect {
                        y: para_y,
                        ..inner_area
                    };
                    let cell_ctx = CellContext {
                        in_textbox: true,
                        parent_para_index: para_index,
                        path: {
                            let mut p = parent_cell_path.to_vec();
                            p.push(CellPathEntry {
                                control_index,
                                cell_index: 0,
                                cell_para_index: tb_para_idx,
                                text_direction: 0,
                            });
                            p
                        },
                    };
                    let is_last_para = tb_para_idx + 1 == composed_paras.len();
                    para_y = self.layout_composed_paragraph(
                        tree,
                        &mut textbox_node,
                        composed,
                        styles,
                        &para_col_area,
                        para_y,
                        0,
                        composed.lines.len(),
                        section_index,
                        tb_para_idx,
                        Some(cell_ctx),
                        true,
                        is_last_para,
                        0.0,
                        None,
                        Some(para),
                        None,
                        None, // 도형 컨텍스트 — wrap zone 무관
                    );
                }
            }
            if !textbox_node.children.is_empty() {
                if parent_treat_as_char {
                    Self::expand_inline_textbox_to_content(
                        shape_node,
                        &mut textbox_node,
                        margin_bottom,
                    );
                } else {
                    Self::expand_textbox_to_object_children(
                        shape_node,
                        &mut textbox_node,
                        margin_bottom,
                    );
                    Self::settle_textbox_clip(&mut textbox_node, shape_node.bbox);
                }
                shape_node.children.push(textbox_node);
            }
            return;
        }

        // 오버플로우 감지 (가로/세로 공통): 텍스트박스 내 문단의 line_segs에서
        // vpos가 리셋(이전 문단보다 감소)되고 sw가 변경되면
        // 해당 문단은 다른 텍스트박스(연결된 글상자)에 속함
        let first_sw = textbox_paragraphs
            .first()
            .and_then(|p| p.line_segs.first())
            .map(|ls| ls.segment_width)
            .unwrap_or(0);
        let mut max_vpos_end: i32 = 0;
        let mut overflow_start_idx: Option<usize> = None;
        for (pi, para) in textbox_paragraphs.iter().enumerate() {
            if let Some(first_ls) = para.line_segs.first() {
                let sw = first_ls.segment_width;
                let vpos = first_ls.vertical_pos;
                // sw가 변경되고 vpos가 이전 최대치보다 작으면 오버플로우
                if pi > 0 && sw != first_sw && vpos < max_vpos_end {
                    overflow_start_idx = Some(pi);
                    break;
                }
                // 이 문단의 마지막 line_seg의 끝 위치 추적
                if let Some(last_ls) = para.line_segs.last() {
                    let end = last_ls.vertical_pos.saturating_add(last_ls.line_height);
                    if end > max_vpos_end {
                        max_vpos_end = end;
                    }
                }
            }
        }

        // 현재 텍스트박스에 속하는 문단만 사용
        let para_count = overflow_start_idx.unwrap_or(textbox_paragraphs.len());

        // 세로쓰기: 오버플로우 감지 후 세로 레이아웃으로 분기
        if text_direction != 0 {
            self.layout_vertical_textbox_text_with_paras(
                tree,
                &mut textbox_node,
                &textbox_paragraphs[..para_count],
                text_box,
                styles,
                &inner_area,
                text_direction,
                section_index,
                para_index,
                control_index,
                parent_cell_path,
            );
            if !textbox_node.children.is_empty() {
                if parent_treat_as_char {
                    Self::expand_inline_textbox_to_content(
                        shape_node,
                        &mut textbox_node,
                        margin_bottom,
                    );
                } else {
                    Self::expand_textbox_to_object_children(
                        shape_node,
                        &mut textbox_node,
                        margin_bottom,
                    );
                    Self::settle_textbox_clip(&mut textbox_node, shape_node.bbox);
                }
                shape_node.children.push(textbox_node);
            }
            return;
        }

        let mut composed_paras: Vec<_> = textbox_paragraphs[..para_count]
            .iter()
            .map(|para| {
                let composed =
                    crate::renderer::composer::compose_paragraph_in_context(para, styles);
                if !para.line_segs.is_empty() {
                    return composed;
                }

                // [#4968 R4C-4] 저장 LINE_SEG가 없는 가로 글상자는 본문·표 셀과
                // 같은 fresh paragraph measurement를 사용한다. 종전에는 여기서
                // compose_paragraph의 45자 fallback을 그대로 렌더해 exact kerning
                // registry가 있어도 K0/K1 줄 경계가 항상 같았다. 저장 조판은 위에서
                // 그대로 반환해 기존 feature-detection 계약을 건드리지 않는다.
                let para_style = styles.para_styles.get(composed.para_style_id as usize);
                let margin_left = para_style.map(|style| style.margin_left).unwrap_or(0.0);
                let margin_right = para_style.map(|style| style.margin_right).unwrap_or(0.0);
                let inner_width = (inner_area.width - margin_left - margin_right).max(0.0);
                if inner_width <= 0.0 {
                    return composed;
                }
                let paragraph_box = crate::renderer::composer::ParagraphBox::body_for_style(
                    inner_area.width,
                    para_style,
                    self.dpi,
                );
                crate::renderer::composer::recompose_stored_lines_in_frame(
                    &composed,
                    para,
                    paragraph_box,
                    inner_width,
                    styles,
                    self.dpi,
                    self.profile.get().stored_geometry_policy(),
                    crate::renderer::composer::StoredRowMissPolicy::Reflow,
                    &[],
                )
                .unwrap_or(composed)
            })
            .collect();

        // AutoNumber(Page) 치환: 글상자 안의 쪽번호 필드를 현재 페이지 번호로 변환
        let current_pn = self.current_page_number.get();
        if current_pn > 0 {
            for (pi, para) in textbox_paragraphs[..para_count].iter().enumerate() {
                if para.controls.iter().any(|c| {
                    matches!(c, crate::model::control::Control::AutoNumber(an)
                        if an.number_type == crate::model::control::AutoNumberType::Page)
                }) {
                    if let Some(comp) = composed_paras.get_mut(pi) {
                        self.substitute_page_auto_numbers_in_composed(para, comp, current_pn);
                    }
                }
            }
        }

        // AutoNumber(TotalPage) 치환: 글상자 안의 총쪽수 필드를 문서 전체 쪽수로 변환
        let total_pages = self.total_pages.get();
        if total_pages > 0 {
            for (pi, para) in textbox_paragraphs[..para_count].iter().enumerate() {
                if para.controls.iter().any(|c| {
                    matches!(c, crate::model::control::Control::AutoNumber(an)
                        if an.number_type == crate::model::control::AutoNumberType::TotalPage)
                }) {
                    if let Some(comp) = composed_paras.get_mut(pi) {
                        self.substitute_total_page_auto_numbers_in_composed(
                            para,
                            comp,
                            total_pages,
                        );
                    }
                }
            }
        }

        // 저장 줄이 없는 글상자는 세로 정렬에 쓸 줄 끝을 저장 좌표로 알 수 없다. 이때는
        // 문단을 위쪽 정렬로 실제 배치한 결과의 끝으로 정렬량을 정하고, 배치한 노드를
        // 그만큼 옮긴다. 측정이 앞 간격·줄 간격 규칙을 따로 흉내 내지 않는다.
        let align_by_laid_out_flow = matches!(
            text_box.vertical_align,
            crate::model::table::VerticalAlign::Center | crate::model::table::VerticalAlign::Bottom
        ) && textbox_paragraphs[..para_count]
            .iter()
            .all(|p| p.line_segs.is_empty());

        // 세로 정렬: 전체 콘텐츠 높이를 계산하여 center/bottom 오프셋 적용
        let mut content_height_for_align = 0.0f64;
        let mut vert_offset = {
            use crate::model::table::VerticalAlign;
            match text_box.vertical_align {
                VerticalAlign::Center | VerticalAlign::Bottom => {
                    // 전체 콘텐츠 높이 = line_seg 끝 위치와 글상자 내부 non-TAC 개체 높이의 최대값.
                    //
                    // HWPX hy-002처럼 글상자 문단이 빈 line_seg + non-TAC 그림 하나로 구성되면
                    // line_seg 높이만으로 CENTER 오프셋을 계산할 수 없다. 그렇게 하면 그림이 실제
                    // 콘텐츠 높이에서 빠지고, 아래 picture container가 오프셋 이후 남은 높이로
                    // 줄어들어 한컴보다 과도하게 축소된다.
                    let mut total_content_height = textbox_paragraphs[..para_count]
                        .iter()
                        .flat_map(|p| p.line_segs.last())
                        .map(|ls| {
                            textbox_vpos_px(ls.vertical_pos, textbox_vpos_origin_hu, self.dpi)
                                + hwpunit_to_px(ls.line_height, self.dpi)
                        })
                        .last()
                        .unwrap_or(0.0);

                    for (para_idx, para) in textbox_paragraphs[..para_count].iter().enumerate() {
                        let para_vpos = para
                            .line_segs
                            .first()
                            .map(|ls| {
                                normalize_textbox_vpos_hu(ls.vertical_pos, textbox_vpos_origin_hu)
                            })
                            .unwrap_or(0);
                        for ctrl in &para.controls {
                            let common = match ctrl {
                                Control::Picture(pic) if !pic.common.treat_as_char => {
                                    Some(&pic.common)
                                }
                                Control::Shape(shape) if !shape.as_ref().common().treat_as_char => {
                                    Some(shape.as_ref().common())
                                }
                                _ => None,
                            };

                            if let Some(common) = common {
                                let top = para_vpos.saturating_add(common.vertical_offset as i32);
                                let bottom = top.saturating_add(common.height as i32);
                                total_content_height =
                                    total_content_height.max(hwpunit_to_px(bottom, self.dpi));
                            }
                            // 저장 줄 경로는 저장 표 프레임을 쓴다. 저장 줄 없는 제한 표는
                            // 실제 행 하한과 두 바깥 여백을 포함하며 프레임 확장과 같은 값을 쓴다.
                            if let Control::Table(table) = ctrl {
                                let bottom = if align_by_laid_out_flow {
                                    ShapeObject::restricted_textbox_table_bottom_hu(table)
                                } else {
                                    textbox_stored_table_bottom_hu(table)
                                };
                                if let Some(bottom) = bottom {
                                    // 띠가 앵커 줄을 민 자리차지 표는 앞 문단 끝이 문단 위끝이다.
                                    let lift = if table.common.text_wrap == TextWrap::TopAndBottom {
                                        textbox_stored_anchor_lift_hu(
                                            &textbox_paragraphs[..para_count],
                                            para_idx,
                                        )
                                    } else {
                                        0
                                    };
                                    total_content_height = total_content_height.max(hwpunit_to_px(
                                        para_vpos.saturating_sub(lift).saturating_add(bottom),
                                        self.dpi,
                                    ));
                                }
                            }
                        }
                        // [#5820 축2] 저장 lineseg 가 없는 문단(기계생성 로고 줄)은
                        // TAC 인라인 개체 높이가 곧 그 줄의 콘텐츠 높이다 — 제외하면
                        // 콘텐츠 높이 0 으로 계산돼 CENTER 오프셋이 반칸(+21.2px)
                        // 과대해지고 로고가 글상자 아래로 흘러넘친다(156560092:
                        // 한글 로고 B 상자-상대 top +2.4 vs rhwp +21.2). lineseg 가
                        // 있으면 그 lh 가 이미 줄을 계상하므로 이중 가산하지 않는다.
                        if para.line_segs.is_empty() {
                            let tac_max: i32 = para
                                .controls
                                .iter()
                                .filter_map(|ctrl| match ctrl {
                                    Control::Picture(pic) if pic.common.treat_as_char => {
                                        Some(pic.common.height as i32)
                                    }
                                    Control::Shape(shape)
                                        if shape.as_ref().common().treat_as_char =>
                                    {
                                        Some(shape.as_ref().common().height as i32)
                                    }
                                    Control::Equation(eq) if eq.common.treat_as_char => {
                                        Some(crate::renderer::equation::flow_height_hwp(eq) as i32)
                                    }
                                    _ => None,
                                })
                                .max()
                                .unwrap_or(0);
                            if tac_max > 0 {
                                let bottom = para_vpos.saturating_add(tac_max);
                                total_content_height =
                                    total_content_height.max(hwpunit_to_px(bottom, self.dpi));
                            }
                        }
                    }

                    content_height_for_align = total_content_height;
                    if align_by_laid_out_flow {
                        0.0
                    } else {
                        let free_space = (inner_area.height - total_content_height).max(0.0);
                        match text_box.vertical_align {
                            VerticalAlign::Center => free_space / 2.0,
                            VerticalAlign::Bottom => free_space,
                            _ => 0.0,
                        }
                    }
                }
                _ => 0.0,
            }
        };

        let flow_first_child = textbox_node.children.len();
        let flow_first_border_range = self.para_border_ranges.borrow().len();
        let mut paragraph_origins = Vec::with_capacity(composed_paras.len());
        let mut para_y = inner_area.y + vert_offset;
        // [PK-40987] 빈 앵커 문단의 자리차지 표 띠가 차지한 흐름의 가장 아래끝(글상자 글 영역 기준).
        let mut topbottom_band_bottom = 0.0f64;
        for (tb_para_idx, composed) in composed_paras.iter().enumerate() {
            // vpos 기반 수직 위치: 원본 HWP 파일에서는 vertical_pos가 누적 절대값,
            // 편집 후 reflow된 문단은 vertical_pos=0이므로 incremental para_y와 비교하여
            // 더 큰 값 사용 (원본 호환 + 편집 후 정상 배치 모두 지원)
            let para = &textbox_paragraphs[tb_para_idx];
            if let Some(first_ls) = para.line_segs.first() {
                let vpos_y = inner_area.y
                    + vert_offset
                    + textbox_vpos_px(first_ls.vertical_pos, textbox_vpos_origin_hu, self.dpi);
                para_y = vpos_y.max(para_y);
            }
            paragraph_origins.push(para_y);
            // [#6651] 글자처럼 개체 폭 합을 첫 줄 글자 오프셋(`first_line_x_offset`)으로
            // 넘기지 않는다. 그 오프셋은 "개체를 문단 시작에 놓고 글자를 뒤에" 두던 옛
            // 모델의 것이고, 지금은 `layout_composed_paragraph` 의 `run_tacs` 분기가 개체의
            // 글자 위치에서 `tac_w` 를 전진시키며 아래 인라인 개체 렌더러가 개체를 그 자리에
            // 놓는다. 오프셋을 겹쳐 주면 글자만 개체 폭만큼 두 번 밀린다 — table-in-tbox
            // 2쪽 "␣[그림]␣서비스 기간" 의 '서' 가 134.3 (한/글 116.8, 그림 17.5).
            let para_col_area = LayoutRect {
                y: para_y,
                ..inner_area
            };
            let cell_ctx = CellContext {
                in_textbox: true,
                parent_para_index: para_index,
                path: {
                    let mut p = parent_cell_path.to_vec();
                    p.push(CellPathEntry {
                        control_index,
                        cell_index: 0,
                        cell_para_index: tb_para_idx,
                        text_direction: 0,
                    });
                    p
                },
            };
            let is_last_para = tb_para_idx + 1 == composed_paras.len();
            let para_first_child = textbox_node.children.len();
            para_y = self.layout_composed_paragraph(
                tree,
                &mut textbox_node,
                composed,
                styles,
                &para_col_area,
                para_y,
                0,
                composed.lines.len(),
                section_index,
                tb_para_idx,
                Some(cell_ctx),
                true,
                is_last_para,
                0.0,
                None,
                Some(para),
                None,
                None, // 도형 컨텍스트 — wrap zone 무관
            );
            // [PK-40987] 빈 앵커 문단의 자리차지 표는 흐름을 차지한다. 다음 문단은 표 띠 아래에서
            // 시작하고 앵커 문단의 빈 줄은 띠에 흡수된다(띠가 줄보다 짧으면 줄을 지킨다).
            if let Some((band_top, band)) = textbox_topbottom_table_band_extent_px(para, self.dpi) {
                let para_start = paragraph_origins[tb_para_idx];
                let anchor_has_text = !para
                    .text
                    .chars()
                    .all(|c| c.is_whitespace() || c == '\u{FFFC}');
                if anchor_has_text {
                    // 글 있는 앵커: 띠에 걸리는 첫 줄부터 이 문단의 뒤 줄을 띠 아래로 민다.
                    let (top, bottom) = (para_start + band_top, para_start + band);
                    let mut shift = 0.0f64;
                    for node in &mut textbox_node.children[para_first_child..] {
                        if shift == 0.0
                            && matches!(node.node_type, RenderNodeType::TextLine(_))
                            && node.bbox.y < bottom
                            && node.bbox.y + node.bbox.height > top
                        {
                            shift = bottom - node.bbox.y;
                        }
                        if shift > 0.0 {
                            Self::translate_subtree_y(node, shift);
                        }
                    }
                    para_y += shift;
                }
                para_y = para_y.max(para_start + band);
                topbottom_band_bottom = topbottom_band_bottom.max(para_start + band - inner_area.y);
            }
        }

        if align_by_laid_out_flow {
            let flow_bottom = textbox_node.children[flow_first_child..]
                .iter()
                .map(|node| node.bbox.y + node.bbox.height - inner_area.y)
                .fold(topbottom_band_bottom, f64::max);
            let free_space =
                (inner_area.height - content_height_for_align.max(flow_bottom)).max(0.0);
            vert_offset = match text_box.vertical_align {
                crate::model::table::VerticalAlign::Center => free_space / 2.0,
                _ => free_space,
            };
            if vert_offset > 0.0 {
                for origin in &mut paragraph_origins {
                    *origin += vert_offset;
                }
                for node in &mut textbox_node.children[flow_first_child..] {
                    Self::translate_subtree_y(node, vert_offset);
                }
                for range in &mut self.para_border_ranges.borrow_mut()[flow_first_border_range..] {
                    range.2 += vert_offset;
                    range.4 += vert_offset;
                    for band in &mut range.10 {
                        band.top += vert_offset;
                        band.bottom += vert_offset;
                        if let Some((_, origin_y)) = band.anchor.as_mut() {
                            *origin_y += vert_offset;
                        }
                    }
                }
                let parent_path: Vec<(usize, usize, usize)> = parent_cell_path
                    .iter()
                    .map(|e| (e.control_index, e.cell_index, e.cell_para_index))
                    .collect();
                tree.translate_inline_shape_positions_y(
                    |(sec, para, _, path)| {
                        *sec == section_index
                            && *para == para_index
                            && path.len() == parent_path.len() + 1
                            && path.starts_with(&parent_path)
                            && path
                                .last()
                                .is_some_and(|&(ci, cell, _)| ci == control_index && cell == 0)
                    },
                    vert_offset,
                );
            }
        }

        // 텍스트 박스 내 인라인 도형 컨트롤 렌더링
        // treat_as_char 도형은 텍스트 흐름 내 문단 시작 위치에 배치
        // 오버플로우된 문단은 제외 (다른 텍스트박스에서 처리)

        let mut inline_y = inner_area.y + vert_offset; // 텍스트 영역 시작 위치
        for (pi, para) in textbox_paragraphs[..para_count].iter().enumerate() {
            // 글과 개체가 같은 실제 문단 배치 결과를 소비한다. 떠 있는 개체의
            // paint 끝을 다음 문단 원점으로 사용하면 글 흐름과 소유가 갈라진다.
            let para_start_y = paragraph_origins[pi];

            // 문단 정렬 조회
            let para_alignment = if pi < composed_paras.len() {
                let para_style_id = composed_paras[pi].para_style_id as usize;
                styles
                    .para_styles
                    .get(para_style_id)
                    .map(|s| s.alignment)
                    .unwrap_or(Alignment::Left)
            } else {
                Alignment::Left
            };

            // [#6465] 인라인 개체가 놓인 **그 줄**을 쓴다 — 첫 줄이 아니다.
            //
            // 저장 사다리가 문단을 두 줄로 적고 개체를 둘째 줄에 배정한 형상
            // (156677575 13쪽: `tp=0`/`tp=9`, 개체 둘 다 text pos 9 = 둘째 줄 시작)
            // 에서 첫 줄로 재면 ① 정렬 기준 폭이 첫 줄 공백 9자만큼 부풀고
            // ② 개체 앞 전진이 그 9자를 또 더하고 ③ y 가 첫 줄 것이 된다.
            // 방출 경로(`emit_line_runs`)는 이미 둘째 줄에 싣고 있었다.
            let inline_line_idx: usize = composed_paras
                .get(pi)
                .and_then(|comp| {
                    let first_tac = comp.tac_controls.iter().map(|(pos, _, _)| *pos).min()?;
                    comp.lines
                        .iter()
                        .enumerate()
                        .rev()
                        .find(|(_, line)| line.char_start <= first_tac)
                        .map(|(idx, _)| idx)
                })
                .unwrap_or(0);
            // 개체가 놓인 줄의 y — 저장 사다리의 그 줄 `vertical_pos` 를 따른다.
            let mut inline_obj_y = if inline_line_idx > 0 {
                para.line_segs
                    .get(inline_line_idx)
                    .map(|seg| {
                        inner_area.y
                            + vert_offset
                            + textbox_vpos_px(seg.vertical_pos, textbox_vpos_origin_hu, self.dpi)
                    })
                    .unwrap_or(para_start_y)
            } else {
                para_start_y
            };

            // 문단 시작 위치로 inline_y 갱신 (이전 문단보다 앞으로 가지 않도록)
            inline_y = inline_y.max(para_start_y);

            // 인라인(treat_as_char) 컨트롤의 총 너비를 먼저 계산하여 정렬에 사용
            let mut total_inline_width = 0.0f64;
            let mut max_inline_height = 0.0f64;
            for ctrl in &para.controls {
                match ctrl {
                    Control::Shape(shape) => {
                        let child_common = shape.as_ref().common();
                        if child_common.treat_as_char {
                            total_inline_width +=
                                hwpunit_to_px(child_common.width as i32, self.dpi);
                            max_inline_height = max_inline_height
                                .max(hwpunit_to_px(child_common.height as i32, self.dpi));
                        }
                    }
                    Control::Picture(pic) => {
                        if pic.common.treat_as_char {
                            total_inline_width += hwpunit_to_px(pic.common.width as i32, self.dpi);
                            max_inline_height = max_inline_height
                                .max(hwpunit_to_px(pic.common.height as i32, self.dpi));
                        }
                    }
                    Control::Equation(eq) => {
                        total_inline_width += hwpunit_to_px(
                            crate::renderer::equation::inline_box::horizontal_metrics(eq)
                                .occupied_width_hwp(),
                            self.dpi,
                        );
                        max_inline_height = max_inline_height.max(hwpunit_to_px(
                            crate::renderer::equation::flow_height_hwp(eq) as i32,
                            self.dpi,
                        ));
                    }
                    Control::Table(table) if table.common.treat_as_char => {
                        total_inline_width += hwpunit_to_px(table.flow_width_hu() as i32, self.dpi)
                            + hwpunit_to_px(table.outer_margin_left as i32, self.dpi)
                            + hwpunit_to_px(table.outer_margin_right as i32, self.dpi);
                    }
                    _ => {}
                }
            }

            // 인라인 컨트롤의 시작 x 위치 (정렬 기반)
            // 이미지+텍스트 전체 폭을 기준으로 정렬 (함께 센터링)
            let first_line_text_width: f64 =
                if total_inline_width > 0.0 && pi < composed_paras.len() {
                    if let Some(first_line) = composed_paras[pi].lines.get(inline_line_idx) {
                        let tab_width = styles
                            .para_styles
                            .get(composed_paras[pi].para_style_id as usize)
                            .map(|s| styles.default_tab_width(s.default_tab_width))
                            .unwrap_or(0.0);
                        first_line
                            .runs
                            .iter()
                            .map(|run| {
                                let mut ts = run.text_style(styles);
                                ts.default_tab_width = tab_width;
                                estimate_text_width(&run.text, &ts)
                            })
                            .sum()
                    } else {
                        0.0
                    }
                } else {
                    0.0
                };
            // [#5820 축3] 한글은 오른쪽 정렬 폭에서 말미 공백을 제외한다 — 글상자
            // [로고A][로고B][공백5] RIGHT 문단에서 포함하면 로고가 말미 공백 폭
            // (32.7px)만큼 좌측 이탈한다(156560092 실측: 한글 로고 B 우변 여백
            // 4.1px vs rhwp 36.8). paragraph_layout 의 셀-밖 Right 제외 규칙과
            // 같은 계약이다.
            //
            // [Issue #6173] 말미 판정은 **마지막 인라인 개체 뒤**부터다 —
            // `[로고A][공백4][로고B][공백2]` 는 공백 6칸 run 하나로 합성되므로
            // run 만 보고 뒤에서 세면 로고 사이 4칸(26.7px)까지 걷어내 로고가
            // 그만큼 우측으로 밀리고 마지막 로고가 글상자 밖으로 잘린다.
            // paragraph_layout 의 셀-밖 Right 경로와 **같은 헬퍼**를 쓴다.
            let trailing_ws_width: f64 =
                if para_alignment == Alignment::Right && pi < composed_paras.len() {
                    let comp = &composed_paras[pi];
                    comp.lines
                        .get(inline_line_idx)
                        .map(|line| {
                            let line_end = line.char_start
                                + line
                                    .runs
                                    .iter()
                                    .map(|r| r.text.chars().count())
                                    .sum::<usize>();
                            let last_obj = comp
                                .tac_controls
                                .iter()
                                .map(|(pos, _, _)| *pos)
                                .filter(|pos| *pos >= line.char_start && *pos <= line_end)
                                .max();
                            trailing_space_width_after_last_inline_object(
                                line,
                                last_obj,
                                styles,
                                false,
                                estimate_text_width,
                            )
                        })
                        .unwrap_or(0.0)
                } else {
                    0.0
                };
            let total_line_width = total_inline_width + first_line_text_width - trailing_ws_width;
            let mut inline_x = match para_alignment {
                Alignment::Center | Alignment::Distribute => {
                    inner_area.x + (inner_area.width - total_line_width).max(0.0) / 2.0
                }
                Alignment::Right => inner_area.x + (inner_area.width - total_line_width).max(0.0),
                _ => inner_area.x,
            };

            let space_advance_override = if pi < composed_paras.len() {
                textbox_tac_space_advance_override(
                    para,
                    &composed_paras[pi],
                    total_inline_width,
                    para_alignment,
                    self.dpi,
                )
            } else {
                None
            };

            let control_text_positions = para.control_text_positions();
            // [#6465] 개체 앞 전진은 **그 개체가 놓인 줄의 시작**부터 잰다. 0 부터 재면
            // 앞 줄의 글자 폭까지 더해 개체가 그만큼 우측으로 밀린다.
            let mut text_cursor = composed_paras
                .get(pi)
                .and_then(|comp| comp.lines.get(inline_line_idx))
                .map(|line| line.char_start)
                .unwrap_or(0);

            // 개체가 여러 줄에 나뉘면 개체마다 **자기 줄**의 정렬 시작·글자 전진 원점·y 를 쓴다.
            // 위 기준 줄 하나(#6465)로 모두 재면 줄바꿈된 개체가 첫 줄 오른쪽으로 이어 붙어
            // 글상자 밖으로 나간다. 줄 y 는 저장 사다리가 있으면 그 줄의 vpos, 없으면 조판한
            // 줄 높이·줄 간격의 누적이다(본문 글줄이 쓰는 것과 같은 값).
            let tac_line_plan = composed_paras.get(pi).and_then(|comp| {
                let tac_width = |ctrl: &Control| -> Option<(f64, f64)> {
                    match ctrl {
                        Control::Shape(shape) if shape.as_ref().common().treat_as_char => {
                            let c = shape.as_ref().common();
                            Some((
                                hwpunit_to_px(c.width as i32, self.dpi),
                                hwpunit_to_px(c.height as i32, self.dpi),
                            ))
                        }
                        Control::Picture(pic) if pic.common.treat_as_char => Some((
                            hwpunit_to_px(pic.common.width as i32, self.dpi),
                            hwpunit_to_px(pic.common.height as i32, self.dpi),
                        )),
                        Control::Equation(eq) => Some((
                            hwpunit_to_px(
                                crate::renderer::equation::flow_width_hwp(eq) as i32,
                                self.dpi,
                            ),
                            hwpunit_to_px(
                                crate::renderer::equation::flow_height_hwp(eq) as i32,
                                self.dpi,
                            ),
                        )),
                        Control::Table(table) if table.common.treat_as_char => Some((
                            hwpunit_to_px(table.flow_width_hu() as i32, self.dpi)
                                + hwpunit_to_px(table.outer_margin_left as i32, self.dpi)
                                + hwpunit_to_px(table.outer_margin_right as i32, self.dpi),
                            0.0,
                        )),
                        _ => None,
                    }
                };
                // 개체의 줄은 표 셀 배치와 같은 공통 결과로 정한다. 저장 줄과 현재 프레임의 줄은
                // 원시 제어 슬롯(PARA_TEXT) 경계로 소속을 정한다. 글자 번호로 투영하면 글자 없는
                // 문단의 줄 시작이 모두 0 으로 겹쳐, 뒤 줄 개체가 첫 줄 끝에 이어 붙는다(#9021).
                // 공통 결과가 없는 문단(인라인이 아닌 컨트롤이 섞인 합성 줄)은 글자 번호로 판정한다.
                let owner_lines = comp
                    .control_line_indices(para)
                    .filter(|lines| lines.iter().all(|line| *line < comp.lines.len()));
                let line_of = |ci: usize| -> Option<usize> {
                    if let Some(lines) = owner_lines.as_ref() {
                        return lines.get(ci).copied();
                    }
                    let pos = control_text_positions.get(ci).copied()?;
                    Some(
                        comp.lines
                            .iter()
                            .enumerate()
                            .rev()
                            .find(|(_, line)| line.char_start <= pos)
                            .map(|(idx, _)| idx)
                            .unwrap_or(0),
                    )
                };
                let ctrl_line: Vec<Option<usize>> = para
                    .controls
                    .iter()
                    .enumerate()
                    .map(|(ci, ctrl)| {
                        tac_width(ctrl)?;
                        line_of(ci)
                    })
                    .collect();
                let lines_used: std::collections::BTreeSet<usize> =
                    ctrl_line.iter().flatten().copied().collect();
                if lines_used.len() < 2 {
                    return None;
                }
                let tab_width = styles
                    .para_styles
                    .get(comp.para_style_id as usize)
                    .map(|s| styles.default_tab_width(s.default_tab_width))
                    .unwrap_or(0.0);
                let mut start_x = Vec::with_capacity(comp.lines.len());
                let mut line_y = Vec::with_capacity(comp.lines.len());
                let mut line_h = Vec::with_capacity(comp.lines.len());
                let mut cursor_y = para_start_y;
                for (li, line) in comp.lines.iter().enumerate() {
                    let (mut w, mut h) = (0.0f64, 0.0f64);
                    for (ci, ctrl) in para.controls.iter().enumerate() {
                        if ctrl_line[ci] == Some(li) {
                            if let Some((cw, ch)) = tac_width(ctrl) {
                                w += cw;
                                h = h.max(ch);
                            }
                        }
                    }
                    let text_w: f64 = line
                        .runs
                        .iter()
                        .map(|run| {
                            let mut ts = run.text_style(styles);
                            ts.default_tab_width = tab_width;
                            estimate_text_width(&run.text, &ts)
                        })
                        .sum();
                    // 본문과 같은 소유 줄·말미 공백 계약을 쓴다. 마지막 개체 앞의
                    // 공백은 개체 사이 내용이므로 가운데·오른쪽 정렬 폭에 남긴다.
                    let last_inline_object_pos = ctrl_line
                        .iter()
                        .enumerate()
                        .filter(|(_, owner)| **owner == Some(li))
                        .filter_map(|(ci, _)| control_text_positions.get(ci).copied())
                        .max();
                    let center_excludes_trailing_ws = center_alignment_excludes_trailing_space(
                        para_alignment,
                        line,
                        last_inline_object_pos,
                        li + 1 == comp.lines.len(),
                        !crate::renderer::para_has_no_stored_line_segs(para),
                    );
                    let trailing_ws_width =
                        if para_alignment == Alignment::Right || center_excludes_trailing_ws {
                            trailing_space_width_after_last_inline_object(
                                line,
                                last_inline_object_pos,
                                styles,
                                center_excludes_trailing_ws,
                                estimate_text_width,
                            )
                        } else {
                            0.0
                        };
                    let total = w + text_w - trailing_ws_width;
                    start_x.push(match para_alignment {
                        Alignment::Center | Alignment::Distribute => {
                            inner_area.x + (inner_area.width - total).max(0.0) / 2.0
                        }
                        Alignment::Right => inner_area.x + (inner_area.width - total).max(0.0),
                        _ => inner_area.x,
                    });
                    let y = para
                        .line_segs
                        .get(li)
                        .map(|seg| {
                            inner_area.y
                                + vert_offset
                                + textbox_vpos_px(
                                    seg.vertical_pos,
                                    textbox_vpos_origin_hu,
                                    self.dpi,
                                )
                        })
                        .unwrap_or(cursor_y);
                    line_y.push(y);
                    line_h.push(h);
                    cursor_y = y + hwpunit_to_px(line.line_height + line.line_spacing, self.dpi);
                }
                Some((ctrl_line, start_x, line_y, line_h))
            });
            let mut plan_line: Option<usize> = None;

            for (ctrl_idx_in_para, ctrl) in para.controls.iter().enumerate() {
                if let Some((ctrl_line, start_x, line_y, line_h)) = tac_line_plan.as_ref() {
                    if let Some(line) = ctrl_line.get(ctrl_idx_in_para).copied().flatten() {
                        if plan_line != Some(line) {
                            plan_line = Some(line);
                            inline_x = start_x[line];
                            text_cursor = composed_paras[pi].lines[line].char_start;
                            inline_obj_y = line_y[line];
                            max_inline_height = line_h[line];
                        }
                    }
                }
                let ctrl_text_pos = control_text_positions
                    .get(ctrl_idx_in_para)
                    .copied()
                    .unwrap_or(text_cursor);
                let mut advance_to_control = |inline_x: &mut f64| {
                    if ctrl_text_pos > text_cursor && pi < composed_paras.len() {
                        *inline_x += measure_composed_text_range_width(
                            &composed_paras[pi],
                            styles,
                            text_cursor,
                            ctrl_text_pos,
                            space_advance_override,
                        );
                        text_cursor = ctrl_text_pos;
                    }
                };

                match ctrl {
                    Control::Shape(shape) => {
                        let child_common = shape.as_ref().common();

                        let child_w = hwpunit_to_px(child_common.width as i32, self.dpi);
                        let child_h = hwpunit_to_px(child_common.height as i32, self.dpi);

                        let (child_x, child_y) = if child_common.treat_as_char {
                            // 인라인 도형: 텍스트 내 삽입 위치까지의 advance를 반영하여 배치
                            advance_to_control(&mut inline_x);
                            let x = inline_x;
                            inline_x += child_w;
                            (x, inline_obj_y)
                        } else {
                            // 절대 위치 도형 — 세로 기준이 Para(앵커 문단)이면 글상자
                            // 상단이 아니라 앵커 문단의 시작 y 에서 오프셋을 적용한다.
                            let anchor_y = if matches!(
                                child_common.vert_rel_to,
                                crate::model::shape::VertRelTo::Para
                            ) {
                                para_start_y
                            } else {
                                base_y
                            };
                            // 문단/단 기준은 글상자 테두리가 아니라 안 여백을
                            // 제외한 텍스트 프레임에서 시작한다. 밴드 계산과
                            // 실제 개체가 같은 가로 원점을 소비한다.
                            let anchor_x = if matches!(
                                child_common.horz_rel_to,
                                crate::model::shape::HorzRelTo::Para
                                    | crate::model::shape::HorzRelTo::Column
                            ) {
                                inner_area.x
                            } else {
                                base_x
                            };
                            (
                                anchor_x
                                    + hwpunit_to_px(
                                        child_common.horizontal_offset as i32,
                                        self.dpi,
                                    ),
                                anchor_y
                                    + hwpunit_to_px(child_common.vertical_offset as i32, self.dpi),
                            )
                        };

                        // 중첩 도형: 현재 글상자의 경로 엔트리를 추가하여 자식에 전달
                        let mut nested_parent_path = parent_cell_path.to_vec();
                        nested_parent_path.push(CellPathEntry {
                            control_index,
                            cell_index: 0,
                            cell_para_index: pi,
                            text_direction: 0,
                        });
                        let empty_map = std::collections::HashMap::new();
                        self.layout_shape_object(
                            tree,
                            &mut textbox_node,
                            shape.as_ref(),
                            child_x,
                            child_y,
                            child_w,
                            child_h,
                            section_index,
                            para_index,
                            ctrl_idx_in_para,
                            styles,
                            bin_data_content,
                            &empty_map,
                            &nested_parent_path,
                            None, // [Task #1138] TODO: layout_textbox_content 에 cell ctx propagate (별도 후속)
                            false,
                        );
                    }
                    Control::Picture(pic) => {
                        // [Task #1171] 글상자 내부 picture — cellPath sentinel(cell_index=0)을
                        // 빌드해 ImageNode.cell_context 로 전달. text-run(1963행)/표 경로와 동일 패턴.
                        // 식별자: (바깥 Shape control_index, cell_index=0, 글상자 문단 pi). innerControlIdx 는
                        // layout_picture 의 control_index 인자(= ctrl_idx_in_para)로 별도 전달된다.
                        let pic_cell_ctx = CellContext {
                            in_textbox: true,
                            parent_para_index: para_index,
                            path: {
                                let mut p = parent_cell_path.to_vec();
                                p.push(CellPathEntry {
                                    control_index,
                                    cell_index: 0,
                                    cell_para_index: pi,
                                    text_direction: 0,
                                });
                                p
                            },
                        };
                        if pic.common.treat_as_char {
                            // 인라인 이미지: 텍스트 내 삽입 위치까지의 advance를 반영하여 배치
                            advance_to_control(&mut inline_x);
                            let pic_w = hwpunit_to_px(pic.common.width as i32, self.dpi);
                            let pic_h = hwpunit_to_px(pic.common.height as i32, self.dpi);
                            // [Task #477] 도형 컨테이너 폭 초과 시 비율 유지 클램프
                            let clamped_w = pic_w.min(inner_area.width);
                            let clamped_h = if pic_w > 0.0 {
                                pic_h * (clamped_w / pic_w)
                            } else {
                                pic_h
                            };
                            // A saved object line owns its baseline, which need
                            // not be the bottom of the object box. Preserve the
                            // baseline proportion for each inline picture when
                            // the complete saved line matches this object row.
                            // Without an authoritative row, keep the existing
                            // composed bottom alignment (#5820).
                            let baseline_fraction = para
                                .line_segs
                                .get(inline_line_idx)
                                .filter(|line| {
                                    !para.stored_text_partition_is_dirty()
                                        && !para.cell_format_vpos_dirty
                                        && line.tag
                                            & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                                            == 0
                                        && line.line_height > 0
                                        && line.baseline_distance >= 0
                                        && line.baseline_distance <= line.line_height
                                        && (max_inline_height
                                            - hwpunit_to_px(line.line_height, self.dpi))
                                            .abs()
                                            <= self.dpi / 7200.0
                                })
                                .map(|line| {
                                    f64::from(line.baseline_distance)
                                        / f64::from(line.line_height)
                                })
                                .unwrap_or(1.0);
                            let pic_container = LayoutRect {
                                x: inline_x,
                                // [#6465] 개체가 뒤 줄에 배정됐으면 그 줄의 y 를 쓴다.
                                y: inline_obj_y
                                    + (max_inline_height - clamped_h).max(0.0) * baseline_fraction,
                                width: clamped_w,
                                height: clamped_h,
                            };
                            // [Task #1151 v4] 글상자 내부 picture (inline) — section/para/control
                            // 전달하여 findPictureAtClick 의 secIdx undefined skip 차단.
                            self.layout_picture(
                                tree,
                                &mut textbox_node,
                                pic,
                                &pic_container,
                                bin_data_content,
                                Alignment::Left,
                                Some(section_index),
                                Some(para_index),
                                Some(ctrl_idx_in_para),
                                Some(&pic_cell_ctx),
                                styles,
                            );
                            inline_x += clamped_w;
                        } else {
                            // 절대 위치 이미지
                            let pic_container = LayoutRect {
                                x: inner_area.x,
                                y: inline_y,
                                width: inner_area.width,
                                height: (inner_area.height - (inline_y - inner_area.y)).max(0.0),
                            };
                            // [Task #1151 v4] 글상자 내부 picture (absolute) — section/para/control 전달.
                            self.layout_picture(
                                tree,
                                &mut textbox_node,
                                pic,
                                &pic_container,
                                bin_data_content,
                                para_alignment,
                                Some(section_index),
                                Some(para_index),
                                Some(ctrl_idx_in_para),
                                Some(&pic_cell_ctx),
                                styles,
                            );
                            let pic_h = hwpunit_to_px(pic.common.height as i32, self.dpi);
                            max_inline_height = max_inline_height.max(pic_h);
                        }
                    }
                    Control::Equation(eq) => {
                        // 글상자 내 수식: 항상 글자처럼 인라인 배치
                        let eq_w = hwpunit_to_px(
                            crate::renderer::equation::inline_box::horizontal_metrics(eq)
                                .occupied_width_hwp(),
                            self.dpi,
                        );
                        let eq_h = hwpunit_to_px(
                            crate::renderer::equation::flow_height_hwp(eq) as i32,
                            self.dpi,
                        );
                        // [Task #962] 글상자 내부 paragraph 의 inline equation 은
                        // paragraph_layout 가 layout_composed_paragraph 경로에서 정확한
                        // gap 위치 (text 사이) 에 emit 한다. 본 두번째 loop 는
                        // paragraph_layout 미지원 이전의 legacy fallback. paragraph_layout
                        // 가 이미 inline_shape_position 으로 등록한 경우 중복 emit 차단.
                        // (시험지 page 2 문14 <보기> textbox 의 6개 inline 수식이
                        //  paragraph_layout + 본 분기 양쪽에서 각각 emit → 중복).
                        let equiv_cell_ctx = CellContext {
                            in_textbox: true,
                            parent_para_index: para_index,
                            path: {
                                let mut p = parent_cell_path.to_vec();
                                p.push(CellPathEntry {
                                    control_index,
                                    cell_index: 0,
                                    cell_para_index: pi,
                                    text_direction: 0,
                                });
                                p
                            },
                        };
                        if tree
                            .get_inline_shape_position(
                                section_index,
                                pi,
                                ctrl_idx_in_para,
                                Some(&equiv_cell_ctx),
                            )
                            .is_some()
                        {
                            // paragraph_layout 가 이미 emit — inline_x 만 advance
                            inline_x += eq_w;
                        } else {
                            let (eq_x, eq_y) = {
                                let x = inline_x;
                                inline_x += eq_w;
                                (x, inline_obj_y)
                            };

                            let font_size_px = hwpunit_to_px(eq.font_size as i32, self.dpi);
                            let super::super::equation::PaintParts {
                                layout_box,
                                color_str,
                                svg_content,
                            } = super::super::equation::paint_parts(eq, self.dpi);

                            let eq_node = RenderNode::new(
                                tree.next_id(),
                                RenderNodeType::Equation(EquationNode {
                                    svg_content,
                                    layout_box,
                                    color_str,
                                    color: eq.color,
                                    script: eq.script.clone(),
                                    font_size: font_size_px,
                                    section_index: Some(section_index),
                                    para_index: Some(para_index),
                                    control_index: Some(ctrl_idx_in_para),
                                    cell_index: None,
                                    cell_para_index: None,
                                    note_ref: None,
                                }),
                                BoundingBox::new(
                                    crate::renderer::equation::inline_box::horizontal_metrics(eq)
                                        .content_origin_x(eq_x, self.dpi),
                                    eq_y,
                                    hwpunit_to_px(
                                        crate::renderer::equation::inline_box::horizontal_metrics(
                                            eq,
                                        )
                                        .content_width_hwp,
                                        self.dpi,
                                    ),
                                    eq_h,
                                ),
                            );
                            textbox_node.children.push(eq_node);
                        }
                    }
                    Control::Table(table) => {
                        // TextBox 내 인라인 표 렌더링
                        // 현재 글상자의 경로 + 이 문단의 표 컨트롤 인덱스를 전달
                        let mut table_enclosing_path = parent_cell_path.to_vec();
                        table_enclosing_path.push(CellPathEntry {
                            control_index,
                            cell_index: 0,
                            cell_para_index: pi,
                            text_direction: 0,
                        });
                        // 호스트 문단의 정렬 속성
                        let host_align = styles
                            .para_styles
                            .get(para.para_shape_id as usize)
                            .map(|ps| ps.alignment)
                            .unwrap_or(Alignment::Left);
                        // 글상자 안에서 글앞으로/글뒤로 떠 있는 표는 자기 가로·세로 오프셋 자리에 놓는다.
                        // 글상자 안의 단·문단 기준은 글상자 글 영역이다.
                        // [PK-40987] 빈 앵커 문단의 자리차지 표도 자기 오프셋 자리에 놓는다(흐름 전진은
                        // 문단 단계가 같은 띠로 이미 반영했다).
                        let floating_offset = textbox_floating_table_offset_px(
                            &table.common,
                            table.outer_margin_left,
                            table.outer_margin_top,
                            align_by_laid_out_flow,
                            self.dpi,
                        )
                        .or_else(|| {
                            textbox_topbottom_table_band_px(para, table, self.dpi)
                                .map(|(dx, dy, _)| (dx, dy))
                        })
                        .or_else(|| {
                            textbox_stored_topbottom_table_offset_px(
                                para,
                                table,
                                textbox_stored_anchor_lift_hu(
                                    &textbox_paragraphs[..para_count],
                                    pi,
                                ),
                                self.dpi,
                            )
                        });
                        let table_ctx = CellContext {
                            in_textbox: true,
                            parent_para_index: para_index,
                            path: table_enclosing_path.clone(),
                        };
                        let inline_origin = table
                            .common
                            .treat_as_char
                            .then(|| {
                                tree.get_inline_shape_position(
                                    section_index,
                                    pi,
                                    ctrl_idx_in_para,
                                    Some(&table_ctx),
                                )
                            })
                            .flatten();
                        let table_inline_x = if table.common.treat_as_char {
                            advance_to_control(&mut inline_x);
                            let x =
                                inline_x + hwpunit_to_px(table.outer_margin_left as i32, self.dpi);
                            inline_x += hwpunit_to_px(table.flow_width_hu() as i32, self.dpi)
                                + hwpunit_to_px(table.outer_margin_left as i32, self.dpi)
                                + hwpunit_to_px(table.outer_margin_right as i32, self.dpi);
                            Some(inline_origin.map_or(x, |(x, _)| x))
                        } else {
                            floating_offset.map(|(dx, _)| inner_area.x + dx)
                        };
                        let dy = floating_offset.map_or(0.0, |(_, dy)| dy);
                        let fallback_y = if table.common.treat_as_char {
                            // 같은 저장 줄에 글자처럼 취급 표가 둘 이상이면 표 셀·글줄 경로와 같은
                            // 공유 기준선에 앉힌다. 줄 높이가 바깥 상자와 같은 표가 줄 소유자이고
                            // 나머지는 자기 높이의 85% 를 그 기준선 위에 둔다(#7049·#7150). 모두 줄
                            // 상단에 붙이면 낮은 표가 높이 차만큼 위로 뜬다(#9021).
                            let owner_line = |ci: usize| {
                                tac_line_plan
                                    .as_ref()
                                    .and_then(|(ctrl_line, ..)| {
                                        ctrl_line.get(ci).copied().flatten()
                                    })
                                    .unwrap_or(inline_line_idx)
                            };
                            let table_line = owner_line(ctrl_idx_in_para);
                            let line_tables = || {
                                para.controls
                                    .iter()
                                    .enumerate()
                                    .filter_map(|(ci, ctrl)| match ctrl {
                                        Control::Table(other)
                                            if other.common.treat_as_char
                                                && owner_line(ci) == table_line =>
                                        {
                                            Some(other.as_ref())
                                        }
                                        _ => None,
                                    })
                            };
                            para.line_segs
                                .get(table_line)
                                .filter(|line| {
                                    !para.stored_text_partition_is_dirty()
                                        && !para.cell_format_vpos_dirty
                                        && line.tag
                                            & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                                            == 0
                                        && line.line_height > 0
                                        && line_tables().count() >= 2
                                })
                                .and_then(|line| {
                                    super::stored_tac_frame::line_table_owner(
                                        line_tables(),
                                        hwpunit_to_px(line.line_height, self.dpi),
                                        styles,
                                        self.dpi,
                                    )
                                })
                                .map_or(
                                    inline_obj_y
                                        + hwpunit_to_px(table.outer_margin_top as i32, self.dpi),
                                    |(owner_h, owner_om_top)| {
                                        super::stored_tac_frame::companion_table_top(
                                            inline_obj_y,
                                            owner_h,
                                            owner_om_top,
                                            hwpunit_to_px(table.common.height as i32, self.dpi),
                                        )
                                    },
                                )
                        } else {
                            // 자유 배치 표는 글자의 가운데/아래 정렬 전 문단 원점을 유지한다.
                            let free_table = align_by_laid_out_flow
                                && !table.common.flow_with_text
                                && floating_offset.is_some()
                                && matches!(
                                    table.common.text_wrap,
                                    TextWrap::InFrontOfText | TextWrap::BehindText
                                );
                            para_start_y + dy - if free_table { vert_offset } else { 0.0 }
                        };
                        let table_y = inline_origin.map_or(fallback_y, |(_, y)| y);
                        let table_bottom = self.layout_embedded_table(
                            tree,
                            &mut textbox_node,
                            table,
                            styles,
                            &inner_area,
                            table_y,
                            Some((
                                section_index,
                                para_index,
                                &table_enclosing_path,
                                ctrl_idx_in_para,
                            )),
                            bin_data_content,
                            host_align,
                            table_inline_x,
                        );
                        if table.common.treat_as_char
                            || !matches!(
                                table.common.text_wrap,
                                TextWrap::InFrontOfText | TextWrap::BehindText
                            )
                        {
                            inline_y = table_bottom;
                        }
                    }
                    _ => {}
                }
            }
            // 인라인 컨트롤의 최대 높이만큼 y 전진
            if max_inline_height > 0.0 {
                inline_y += max_inline_height;
            }
        }
        if !textbox_node.children.is_empty() {
            if parent_treat_as_char {
                Self::expand_inline_textbox_to_content(
                    shape_node,
                    &mut textbox_node,
                    margin_bottom,
                );
            } else {
                Self::expand_textbox_to_object_children(
                    shape_node,
                    &mut textbox_node,
                    margin_bottom,
                );
                Self::settle_textbox_clip(&mut textbox_node, shape_node.bbox);
            }
            shape_node.children.push(textbox_node);
        }
    }

    /// 글상자 세로쓰기 레이아웃
    ///
    /// 텍스트 방향: 위→아래, 열(column)은 오른쪽→왼쪽
    /// text_direction: 1=영문 눕힘(회전), 2=영문 세움(직립)
    /// 정렬 매핑: Top→오른쪽(첫 열), Center→중앙, Bottom→왼쪽
    #[allow(clippy::too_many_arguments)]
    fn layout_vertical_textbox_text_with_paras(
        &self,
        tree: &mut PageLayoutContext,
        shape_node: &mut RenderNode,
        paragraphs: &[Paragraph],
        text_box: &crate::model::shape::TextBox,
        styles: &ResolvedStyleSet,
        inner_area: &LayoutRect,
        text_direction: u8,
        section_index: usize,
        para_index: usize,
        control_index: usize,
        parent_cell_path: &[CellPathEntry],
    ) {
        use super::super::composer::compose_paragraph;

        // 1. line_seg 기반으로 composed lines를 열(column)로 변환
        struct CharInfo {
            ch: char,
            style: TextStyle,
            char_style_id: u32,
            para_style_id: u16,
            cell_para_index: usize,
            char_offset: usize,
            is_para_end: bool,
        }

        struct ColumnInfo {
            start_idx: usize,
            end_idx: usize,
            col_width: f64, // line_height + line_spacing (px), 마지막 칼럼은 line_height만
            col_spacing: f64, // 항상 0 (line_spacing이 col_width에 흡수됨)
            total_height: f64,
            alignment: Alignment,
            absorbed_spacing: f64, // 흡수된 line_spacing (px) — 마지막 칼럼 후처리용
        }

        let composed_paras: Vec<_> = paragraphs
            .iter()
            .map(|p| crate::renderer::composer::compose_paragraph_in_context(p, styles))
            .collect();

        let get_alignment = |para_style_id: u16| -> Alignment {
            styles
                .para_styles
                .get(para_style_id as usize)
                .map(|s| s.alignment)
                .unwrap_or(Alignment::Left)
        };

        let mut chars: Vec<CharInfo> = Vec::new();
        let mut columns: Vec<ColumnInfo> = Vec::new();

        for (cp_idx, composed) in composed_paras.iter().enumerate() {
            let para = &paragraphs[cp_idx];
            let alignment = get_alignment(composed.para_style_id);

            if composed.lines.is_empty() {
                // 빈 문단: 빈 열 추가
                // 칼럼 너비 = line_height + line_spacing (전체 피치를 칼럼에 흡수)
                let ls = para.line_segs.first();
                let spacing = ls
                    .map(|l| hwpunit_to_px(l.line_spacing, self.dpi))
                    .unwrap_or(0.0);
                columns.push(ColumnInfo {
                    start_idx: chars.len(),
                    end_idx: chars.len(),
                    col_width: ls
                        .map(|l| {
                            hwpunit_to_px(l.line_height.saturating_add(l.line_spacing), self.dpi)
                        })
                        .unwrap_or(13.0),
                    col_spacing: 0.0,
                    total_height: 0.0,
                    alignment,
                    absorbed_spacing: spacing,
                });
                continue;
            }

            let mut char_offset = 0usize;
            for (line_idx, line) in composed.lines.iter().enumerate() {
                let ls = para.line_segs.get(line_idx);
                // 칼럼 너비 = line_height + line_spacing (전체 피치 흡수)
                let col_width = ls
                    .map(|l| hwpunit_to_px(l.line_height.saturating_add(l.line_spacing), self.dpi))
                    .unwrap_or(13.0);
                let col_spacing = 0.0;
                let absorbed_spacing = ls
                    .map(|l| hwpunit_to_px(l.line_spacing, self.dpi))
                    .unwrap_or(0.0);

                let col_start = chars.len();
                let mut col_height = 0.0;

                for run in &line.runs {
                    let text_style = run.text_style(styles);
                    for ch in run.text.chars() {
                        if ch == '\n' || ch == '\r' {
                            char_offset += 1;
                            continue;
                        }
                        let is_rotate = is_vertical_rotate_char(ch);
                        let needs_rotation = is_rotate || (text_direction == 1 && !is_cjk_char(ch));
                        // 세로쓰기에서 구두점/기호만 반칸 advance (영문/숫자는 캐릭터 높이)
                        let half_advance =
                            needs_rotation || (!is_cjk_char(ch) && !ch.is_ascii_alphanumeric());
                        let advance = if half_advance {
                            text_style.font_size * 0.5
                        } else {
                            text_style.font_size
                        };
                        chars.push(CharInfo {
                            ch,
                            style: text_style.clone(),
                            char_style_id: run.char_style_id,
                            para_style_id: composed.para_style_id,
                            cell_para_index: cp_idx,
                            char_offset,
                            is_para_end: false,
                        });
                        col_height += advance;
                        char_offset += 1;
                    }
                }

                if line_idx == composed.lines.len() - 1 {
                    if let Some(last) = chars.last_mut() {
                        if last.cell_para_index == cp_idx {
                            last.is_para_end = true;
                        }
                    }
                }

                columns.push(ColumnInfo {
                    start_idx: col_start,
                    end_idx: chars.len(),
                    col_width,
                    col_spacing,
                    total_height: col_height,
                    alignment,
                    absorbed_spacing,
                });
            }
        }

        if chars.is_empty() && columns.iter().all(|c| c.start_idx == c.end_idx) {
            return;
        }

        // 마지막 칼럼은 뒤에 간격이 불필요하므로 흡수된 line_spacing분 제거
        if let Some(last_col) = columns.last_mut() {
            last_col.col_width -= last_col.absorbed_spacing;
        }

        // 2. 열 배치 x좌표 계산 (오른쪽→왼쪽)
        let total_cols_width: f64 = if columns.is_empty() {
            0.0
        } else {
            columns.iter().map(|c| c.col_width).sum::<f64>()
                + columns[..columns.len() - 1]
                    .iter()
                    .map(|c| c.col_spacing)
                    .sum::<f64>()
        };

        use crate::model::table::VerticalAlign;
        // 열이 셀보다 넓으면 첫 열이 오른쪽 가장자리에서 시작하도록 클램핑
        let right_aligned = inner_area.x + inner_area.width - total_cols_width;
        let cols_x_start = match text_box.vertical_align {
            VerticalAlign::Top => right_aligned,
            VerticalAlign::Center => {
                let centered = inner_area.x + (inner_area.width - total_cols_width) / 2.0;
                centered.min(right_aligned)
            }
            VerticalAlign::Bottom => inner_area.x.min(right_aligned),
        };

        // 3. 각 글자를 TextLine + TextRun 노드로 생성
        let mut col_x = cols_x_start + total_cols_width;

        for col in &columns {
            col_x -= col.col_width;

            let free_space = (inner_area.height - col.total_height).max(0.0);
            let y_start = inner_area.y
                + match col.alignment {
                    Alignment::Center | Alignment::Distribute => free_space / 2.0,
                    Alignment::Right => free_space,
                    _ => 0.0,
                };
            let mut char_y = y_start;
            let col_bottom = inner_area.y + inner_area.height;

            for i in col.start_idx..col.end_idx {
                let ci = &chars[i];
                let is_rotate = is_vertical_rotate_char(ci.ch);
                let needs_rotation = is_rotate || (text_direction == 1 && !is_cjk_char(ci.ch));
                // 세로쓰기에서 구두점/기호만 반칸 advance (영문/숫자는 캐릭터 높이)
                let half_advance =
                    needs_rotation || (!is_cjk_char(ci.ch) && !ci.ch.is_ascii_alphanumeric());
                let advance = if half_advance {
                    ci.style.font_size * 0.5
                } else {
                    ci.style.font_size
                };

                // 열 높이 초과 시 렌더링 중단
                if char_y + advance > col_bottom + 0.5 {
                    break;
                }

                let char_width = if is_cjk_char(ci.ch) || is_rotate {
                    ci.style.font_size
                } else if needs_rotation {
                    ci.style.font_size
                } else {
                    ci.style.font_size * 0.5
                };

                let char_x = col_x + (col.col_width - char_width) / 2.0;
                // 기호 대체: 세로 형태 Unicode가 있으면 대체 문자를 사용 (회전 불필요)
                let (render_ch, rotation) = if needs_rotation {
                    if let Some(sub) = vertical_substitute_char(ci.ch) {
                        (sub, 0.0)
                    } else {
                        (ci.ch, 90.0)
                    }
                } else {
                    (ci.ch, 0.0)
                };

                let cell_ctx = CellContext {
                    in_textbox: true,
                    parent_para_index: para_index,
                    path: {
                        let mut p = parent_cell_path.to_vec();
                        p.push(CellPathEntry {
                            control_index,
                            cell_index: 0,
                            cell_para_index: ci.cell_para_index,
                            text_direction,
                        });
                        p
                    },
                };

                let line_id = tree.next_id();
                let mut line_node = RenderNode::new(
                    line_id,
                    RenderNodeType::TextLine(TextLineNode::new(advance, advance * 0.85)),
                    BoundingBox::new(char_x, char_y, char_width, advance),
                );

                let run_id = tree.next_id();
                let run_node = RenderNode::new(
                    run_id,
                    RenderNodeType::TextRun(TextRunNode {
                        text: render_ch.to_string(),
                        style: ci.style.clone(),
                        char_shape_id: Some(ci.char_style_id),
                        para_shape_id: Some(ci.para_style_id),
                        section_index: Some(section_index),
                        para_index: Some(ci.cell_para_index),
                        char_start: Some(ci.char_offset),
                        cell_context: Some(cell_ctx),
                        is_para_end: ci.is_para_end,
                        is_line_break_end: false,
                        rotation,
                        is_vertical: true,
                        char_overlap: None,
                        border_fill_id: styles
                            .char_styles
                            .get(ci.char_style_id as usize)
                            .map(|cs| cs.border_fill_id)
                            .unwrap_or(0),
                        baseline: advance * 0.85,
                        field_marker: FieldMarkerType::None,
                        layout_positions: None,
                        display_text: None,
                    }),
                    BoundingBox::new(char_x, char_y, char_width, advance),
                );

                line_node.children.push(run_node);
                shape_node.children.push(line_node);

                char_y += advance;
            }

            col_x -= col.col_spacing;
        }
    }

    pub(crate) fn curve_to_path_commands_scaled(
        &self,
        curve: &crate::model::shape::CurveShape,
        base_x: f64,
        base_y: f64,
        sx: f64,
        sy: f64,
    ) -> Vec<PathCommand> {
        curve_geometry::commands(curve, |x, y| {
            (
                base_x + x * self.dpi / 7200.0 * sx,
                base_y + y * self.dpi / 7200.0 * sy,
            )
        })
    }

    /// TopAndBottom 모드 글상자들의 앵커 문단별 예약 높이 계산
    /// 각 (앵커 문단 인덱스, 글상자 하단 y) 쌍을 반환
    /// 앵커 문단 이전 문단은 글상자 위에, 앵커 문단부터는 글상자 아래에 배치됨
    pub(crate) fn calculate_shape_reserved_heights(
        &self,
        paragraphs: &[Paragraph],
        items: &[PageItem],
        col_area: &LayoutRect,
        body_area: &LayoutRect,
    ) -> Vec<(usize, f64)> {
        use crate::model::shape::TextWrap;

        let mut result: Vec<(usize, f64)> = Vec::new();

        for item in items {
            let (para_index, control_index) = match item {
                PageItem::Shape {
                    para_index,
                    control_index,
                } => (para_index, control_index),
                PageItem::Table {
                    para_index,
                    control_index,
                } => (para_index, control_index),
                _ => continue,
            };
            {
                let para = match paragraphs.get(*para_index) {
                    Some(p) => p,
                    None => continue,
                };
                let ctrl = match para.controls.get(*control_index) {
                    Some(c) => c,
                    None => continue,
                };
                let common = match ctrl {
                    Control::Shape(s) => s.common(),
                    Control::Table(t) if !t.common.treat_as_char => &t.common,
                    Control::Picture(p) if !p.common.treat_as_char => &p.common,
                    _ => continue,
                };

                if col_area.width < body_area.width {
                    if let Some(bottom) = crate::renderer::float_placement::stored_square_top_band(
                        para, ctrl, body_area, self.dpi,
                    ) {
                        result.push((*para_index, bottom));
                        continue;
                    }
                }
                if !matches!(common.text_wrap, TextWrap::TopAndBottom) {
                    continue;
                }

                // 글자처럼 취급(인라인)은 LineSeg가 이미 높이를 포함하므로 예약 불필요
                if common.treat_as_char {
                    continue;
                }

                // vert=Para: 문단 상대 위치 표/도형은 shape_reserved 제외
                // 이 개체들은 앵커 문단의 y_offset에 따라 배치되므로
                // 미리 공간을 예약하면 y_offset이 이중으로 밀려남
                if matches!(common.vert_rel_to, crate::model::shape::VertRelTo::Para) {
                    continue;
                }

                // [#7696] 쪽·종이 기준 자리차지 그림·도형은 앵커 문단에서 점프하는 예약이 아니라
                // 세로 밴드로 계상한다 — 밴드 안에서 시작하는 문단만 밴드 아래로 간다
                // (`ObjectPlacementFrame::page_anchored_topbottom_band`, 조판과 같은 계산).
                if matches!(ctrl, Control::Picture(_) | Control::Shape(_)) {
                    continue;
                }

                // 수평 겹침 확인
                if !self.check_horizontal_overlap(common, col_area, body_area) {
                    continue;
                }

                // 하단 y 좌표 계산
                // Table: common.height는 실제 렌더링 높이(셀 콘텐츠 포함)보다 작을 수 있음
                // 셀 내 LINE_SEG 기반 실제 높이를 사용하여 보정
                let effective_common = if let Control::Table(t) = ctrl {
                    let measured_h = crate::renderer::float_placement::table_reserved_height_hu(t);
                    if measured_h > common.height {
                        let mut c = common.clone();
                        c.height = measured_h;
                        Some(c)
                    } else {
                        None
                    }
                } else {
                    None
                };
                let effective_ref = effective_common.as_ref().unwrap_or(common);
                let (bottom_y, shape_y) = if let Control::Table(table) = ctrl {
                    let (ref_y, ref_h) = match common.vert_rel_to {
                        VertRelTo::Page => (body_area.y, body_area.height),
                        VertRelTo::Paper => (0.0, self.current_page_height.get()),
                        VertRelTo::Para => unreachable!("문단 기준 표는 위에서 제외됨"),
                    };
                    let (top, bottom) =
                        crate::renderer::float_placement::absolute_table_vertical_geometry(
                            table,
                            ref_y,
                            ref_h,
                            hwpunit_to_px(effective_ref.height as i32, self.dpi),
                            self.dpi,
                        );
                    (bottom, top)
                } else {
                    self.calc_shape_bottom_y(ctrl, effective_ref, col_area, body_area)
                };

                // 본문 시작 근처만 고려 (페이지 하단 개체는 제외)
                let threshold_y = col_area.y + col_area.height / 3.0;
                if shape_y > threshold_y {
                    continue;
                }

                // 같은 앵커 문단에 여러 글상자가 있으면 최대 하단 y 사용
                if let Some(existing) = result.iter_mut().find(|(pi, _)| *pi == *para_index) {
                    if bottom_y > existing.1 {
                        existing.1 = bottom_y;
                    }
                } else {
                    result.push((*para_index, bottom_y));
                }
            }
        }

        result
    }

    /// [#6266] 양식 개체의 좌상단 좌표 — `calc_shape_bottom_y` 와
    /// `check_horizontal_overlap` 이 쓰는 것과 같은 기준·정렬 산식이다.
    fn form_object_origin(
        &self,
        common: &CommonObjAttr,
        col_area: &LayoutRect,
        body_area: &LayoutRect,
        paper_area: &LayoutRect,
        para_y: f64,
    ) -> (f64, f64) {
        let w = hwpunit_to_px(common.width as i32, self.dpi);
        let h = hwpunit_to_px(common.height as i32, self.dpi);
        let h_offset = hwpunit_to_px(common.horizontal_offset as i32, self.dpi);
        let v_offset = hwpunit_to_px(common.vertical_offset as i32, self.dpi);
        // 가장자리 정렬은 바깥 여백만큼 안쪽으로 들어간다. 2955289 실측:
        // margin.bottom=4252HU(42.5pt) 이고 한글이 이 개체를 용지 하단에서
        // 정확히 그만큼 위(788.5pt)에 둔다.
        let m_left = hwpunit_to_px(i32::from(common.margin.left), self.dpi);
        let m_right = hwpunit_to_px(i32::from(common.margin.right), self.dpi);
        let m_top = hwpunit_to_px(i32::from(common.margin.top), self.dpi);
        let m_bottom = hwpunit_to_px(i32::from(common.margin.bottom), self.dpi);

        let (ref_x, ref_w) = match common.horz_rel_to {
            HorzRelTo::Paper => (paper_area.x, paper_area.width),
            HorzRelTo::Page => (body_area.x, body_area.width),
            _ => (col_area.x, col_area.width),
        };
        let x = match common.horz_align {
            HorzAlign::Left | HorzAlign::Inside => ref_x + m_left + h_offset,
            HorzAlign::Center => ref_x + (ref_w - w) / 2.0 + h_offset,
            HorzAlign::Right | HorzAlign::Outside => ref_x + ref_w - m_right - w - h_offset,
        };

        let (ref_y, ref_h) = match common.vert_rel_to {
            VertRelTo::Paper => (paper_area.y, paper_area.height),
            VertRelTo::Page => (body_area.y, body_area.height),
            VertRelTo::Para => (para_y, (col_area.y + col_area.height - para_y).max(0.0)),
        };
        let y = match common.vert_align {
            VertAlign::Top | VertAlign::Inside => ref_y + m_top + v_offset,
            VertAlign::Center => ref_y + (ref_h - h) / 2.0 + v_offset,
            VertAlign::Bottom | VertAlign::Outside => ref_y + ref_h - m_bottom - h - v_offset,
        };
        (x, y)
    }

    /// TopAndBottom 개체의 하단 y 좌표와 상단 y 좌표를 계산 (pub(crate) — Task #901 Stage 8 flow-around)
    pub(crate) fn calc_shape_bottom_y(
        &self,
        control: &Control,
        common: &CommonObjAttr,
        col_area: &LayoutRect,
        body_area: &LayoutRect,
    ) -> (f64, f64) {
        use crate::model::shape::{VertAlign, VertRelTo};
        let v_offset = hwpunit_to_px(common.vertical_offset as i32, self.dpi);
        let shape_h = hwpunit_to_px(common.height as i32, self.dpi);
        let (ref_y, ref_h) = match common.vert_rel_to {
            VertRelTo::Paper => (0.0_f64, body_area.y + body_area.height + body_area.y),
            VertRelTo::Page => (body_area.y, body_area.height),
            VertRelTo::Para => (col_area.y, col_area.height),
        };
        let margin_top = if matches!(control, Control::Shape(_)) {
            hwpunit_to_px(
                crate::renderer::float_placement::topbottom_shape_top_margin_hu(common),
                self.dpi,
            )
        } else {
            0.0
        };
        let shape_y = margin_top
            + match common.vert_align {
                VertAlign::Top | VertAlign::Inside => ref_y + v_offset,
                VertAlign::Center => ref_y + (ref_h - shape_h) / 2.0 + v_offset,
                VertAlign::Bottom | VertAlign::Outside => ref_y + ref_h - shape_h - v_offset,
            };
        // 캡션의 간격과 실제 글줄 상자를 포함한 프레임 뒤에 본문 여백을 둔다.
        let frame_h = if let Control::Shape(shape) = control {
            captioned_shape_height_px(shape_h, &shape_caption_for_layout(shape), self.dpi)
        } else {
            shape_h
        };
        let margin_bottom = hwpunit_to_px(common.margin.bottom as i32, self.dpi);
        (shape_y + frame_h + margin_bottom, shape_y)
    }

    /// 다단 레이아웃에서 body_area 전체에 걸치는 TopAndBottom 개체의 예약 높이 계산
    /// 모든 단의 items를 순회하여 body_area 너비와 동일하거나 큰 개체만 반환
    /// [#7282] 쪽의 모든 단 항목에서, 가로 범위가 둘 이상의 단에 걸치는 비-TAC
    /// 자리차지(TopAndBottom) 개체의 틀 높이(높이 + 바깥 위·아래 여백, HU)를 모은다.
    /// 앵커 단을 가리지 않는다 — 한/글은 이 틀이 지나는 모든 단의 줄을 틀 아래로 밀어
    /// LINE_SEG.vertical_pos 에 저장한다. 문단 배치는 줄 사이 저장 점프가 이 높이와
    /// 같을 때만 그 저장 위치를 쓴다.
    pub(crate) fn collect_page_spanning_float_frames(
        &self,
        paragraphs: &[Paragraph],
        page_content: &super::super::pagination::PageContent,
        layout: &super::super::page_layout::PageLayoutInfo,
        styles: &ResolvedStyleSet,
    ) -> PageSpanningFloatFrames {
        let mut frames = PageSpanningFloatFrames::default();
        for col_content in &page_content.column_contents {
            let zone_layout = col_content.zone_layout.as_ref().unwrap_or(layout);
            if zone_layout.column_areas.len() < 2 {
                continue;
            }
            let col_idx = col_content.column_index as usize;
            let Some(col_area) = zone_layout.column_areas.get(col_idx) else {
                continue;
            };
            for item in &col_content.items {
                let (para_index, control_index) = match item {
                    PageItem::Shape {
                        para_index,
                        control_index,
                    }
                    | PageItem::Table {
                        para_index,
                        control_index,
                    } => (*para_index, *control_index),
                    _ => continue,
                };
                let Some(ctrl) = paragraphs
                    .get(para_index)
                    .and_then(|p| p.controls.get(control_index))
                else {
                    continue;
                };
                let (common, margin_top, margin_bottom) = match ctrl {
                    Control::Table(t) => (
                        &t.common,
                        i32::from(t.outer_margin_top),
                        i32::from(t.outer_margin_bottom),
                    ),
                    Control::Picture(p) => (
                        &p.common,
                        i32::from(p.common.margin.top),
                        i32::from(p.common.margin.bottom),
                    ),
                    Control::Shape(s) => (
                        s.common(),
                        i32::from(s.common().margin.top),
                        i32::from(s.common().margin.bottom),
                    ),
                    _ => continue,
                };
                if common.treat_as_char {
                    continue;
                }
                if let Control::Picture(picture) = ctrl {
                    if matches!(common.vert_rel_to, VertRelTo::Paper | VertRelTo::Page) {
                        let paper = LayoutRect {
                            x: 0.0,
                            y: 0.0,
                            width: layout.page_width,
                            height: layout.page_height,
                        };
                        let placement = crate::renderer::float_placement::ObjectPlacementFrame {
                            container: col_area,
                            column: col_area,
                            body: &zone_layout.body_area,
                            paper: &paper,
                            paragraph_y: col_area.y,
                            alignment: Alignment::Left,
                            dpi: self.dpi,
                        };
                        if let Some(exclusion) = placement.picture_exclusion(
                            picture,
                            &paragraphs[para_index],
                            control_index,
                            styles,
                        ) {
                            let spanned = zone_layout
                                .column_areas
                                .iter()
                                .filter(|area| {
                                    let left = px_to_hwpunit(area.x, self.dpi);
                                    let right = px_to_hwpunit(area.x + area.width, self.dpi);
                                    exclusion.horizontal.start < right
                                        && left < exclusion.horizontal.end
                                })
                                .count();
                            if spanned > 1 && !frames.square_exclusions.contains(&exclusion) {
                                frames.square_exclusions.push(exclusion);
                            }
                        }
                    }
                }
                if common.text_wrap != TextWrap::TopAndBottom {
                    continue;
                }
                let width_px = hwpunit_to_px(common.width as i32, self.dpi);
                let ctx = crate::renderer::float_placement::FloatPlacementContext::new(*col_area)
                    .with_body_area(zone_layout.body_area)
                    .with_paper_width(layout.page_width);
                let (left, right) = crate::renderer::float_placement::horizontal_range(
                    common, width_px, ctx, self.dpi,
                );
                let spanned = zone_layout
                    .column_areas
                    .iter()
                    .filter(|area| right > area.x + 0.5 && left < area.x + area.width - 0.5)
                    .count();
                if spanned < 2 {
                    continue;
                }
                let frame = (common.height as i32)
                    .saturating_add(margin_top)
                    .saturating_add(margin_bottom);
                if frame > 0 && !frames.topbottom_heights.contains(&frame) {
                    frames.topbottom_heights.push(frame);
                }
            }
        }
        frames
    }

    pub(crate) fn calculate_body_wide_shape_reserved(
        &self,
        paragraphs: &[Paragraph],
        column_contents: &[super::super::pagination::ColumnContent],
        body_area: &LayoutRect,
    ) -> Vec<(usize, f64)> {
        use crate::model::shape::TextWrap;

        let mut result: Vec<(usize, f64)> = Vec::new();

        for col_content in column_contents {
            for item in &col_content.items {
                let (para_index, control_index) = match item {
                    super::super::pagination::PageItem::Shape {
                        para_index,
                        control_index,
                    } => (para_index, control_index),
                    super::super::pagination::PageItem::Table {
                        para_index,
                        control_index,
                    } => (para_index, control_index),
                    _ => continue,
                };
                let para = match paragraphs.get(*para_index) {
                    Some(p) => p,
                    None => continue,
                };
                let ctrl = match para.controls.get(*control_index) {
                    Some(c) => c,
                    None => continue,
                };
                let common = match ctrl {
                    Control::Shape(s) => s.common(),
                    Control::Table(t) if !t.common.treat_as_char => &t.common,
                    Control::Picture(p) if !p.common.treat_as_char => &p.common,
                    _ => continue,
                };
                if let Some(bottom) = crate::renderer::float_placement::stored_square_top_band(
                    para, ctrl, body_area, self.dpi,
                ) {
                    result.push((*para_index, bottom));
                    continue;
                }
                if !matches!(common.text_wrap, TextWrap::TopAndBottom) || common.treat_as_char {
                    continue;
                }
                // body_area 너비의 80% 이상 차지하는 개체만 (2단에 걸치는 개체)
                let shape_w = hwpunit_to_px(common.width as i32, self.dpi);
                if shape_w < body_area.width * 0.8 {
                    continue;
                }
                let (bottom_y, shape_y) = if let Control::Table(table) = ctrl {
                    if matches!(common.vert_rel_to, VertRelTo::Page | VertRelTo::Paper) {
                        let (ref_y, ref_h) = if common.vert_rel_to == VertRelTo::Page {
                            (body_area.y, body_area.height)
                        } else {
                            (0.0, self.current_page_height.get())
                        };
                        let (top, bottom) =
                            crate::renderer::float_placement::absolute_table_vertical_geometry(
                                table,
                                ref_y,
                                ref_h,
                                hwpunit_to_px(common.height as i32, self.dpi),
                                self.dpi,
                            );
                        (bottom, top)
                    } else {
                        self.calc_shape_bottom_y(ctrl, common, body_area, body_area)
                    }
                } else {
                    self.calc_shape_bottom_y(ctrl, common, body_area, body_area)
                };
                // 머리말에만 있는 용지 기준 개체는 모든 단의 본문을 밀지 않는다.
                // 위 여백·캡션을 반영한 최종 프레임 끝으로 판정한다.
                if common.vert_rel_to == VertRelTo::Paper && bottom_y <= body_area.y {
                    continue;
                }
                let threshold_y = body_area.y + body_area.height / 3.0;
                if shape_y > threshold_y {
                    continue;
                }
                if let Some(existing) = result.iter_mut().find(|(pi, _)| *pi == *para_index) {
                    if bottom_y > existing.1 {
                        existing.1 = bottom_y;
                    }
                } else {
                    result.push((*para_index, bottom_y));
                }
            }
        }

        result
    }

    /// 개체가 단 영역과 수평으로 겹치는지 확인
    fn check_horizontal_overlap(
        &self,
        common: &CommonObjAttr,
        col_area: &LayoutRect,
        body_area: &LayoutRect,
    ) -> bool {
        use crate::model::shape::{HorzAlign, HorzRelTo};
        let h_offset = hwpunit_to_px(common.horizontal_offset as i32, self.dpi);
        let shape_w = hwpunit_to_px(common.width as i32, self.dpi);
        let (ref_x, ref_w) = match common.horz_rel_to {
            HorzRelTo::Paper => (0.0_f64, body_area.x + body_area.width + body_area.x),
            HorzRelTo::Page => (body_area.x, body_area.width),
            HorzRelTo::Column => (col_area.x, col_area.width),
            _ => (col_area.x, col_area.width),
        };
        let shape_x = match common.horz_align {
            HorzAlign::Left | HorzAlign::Inside => ref_x + h_offset,
            HorzAlign::Center => ref_x + (ref_w - shape_w) / 2.0 + h_offset,
            HorzAlign::Right | HorzAlign::Outside => ref_x + ref_w - shape_w - h_offset,
        };
        let shape_right = shape_x + shape_w;
        let col_right = col_area.x + col_area.width;
        shape_right >= col_area.x && shape_x <= col_right
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::paragraph::{CharShapeRef, LineSeg};
    use crate::renderer::style_resolver::{ResolvedCharStyle, ResolvedParaStyle};

    fn line_seg(text_start: u32, vertical_pos: i32) -> LineSeg {
        LineSeg {
            text_start,
            vertical_pos,
            line_height: 2000,
            text_height: 2000,
            baseline_distance: 1700,
            line_spacing: 1200,
            segment_width: 16856,
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            ..Default::default()
        }
    }

    #[test]
    fn matrix_textbox_para_reflows_imported_lines_when_frame_width_changed() {
        let mut para = Paragraph {
            char_count: 2,
            text: "AB".to_string(),
            char_offsets: vec![0, 1],
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
            line_segs: vec![line_seg(0, 0), line_seg(1, 3200)],
            ..Default::default()
        };
        let mut styles = ResolvedStyleSet::default();
        styles.char_styles.push(ResolvedCharStyle {
            font_family: "Arial".to_string(),
            font_families: vec!["Arial".to_string(); 7],
            font_size: 20.0,
            ..Default::default()
        });
        styles.para_styles.push(ResolvedParaStyle::default());

        reflow_matrix_textbox_para(&mut para, 80.0, &styles, 96.0);

        assert_eq!(para.line_segs.len(), 1);
        assert_eq!(para.line_segs[0].text_start, 0);
        assert_eq!(para.line_segs[0].segment_width, px_to_hwpunit(80.0, 96.0));
    }
}