rhwp 0.9.0

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
//! 그림/캡션 레이아웃 + 각주 영역 레이아웃

use super::super::composer::{compose_paragraph, ComposedLine, ComposedParagraph};
use super::super::page_layout::LayoutRect;
use super::super::pagination::{FootnoteFragment, FootnoteRef, FootnoteSource};
use super::super::render_tree::*;
use super::super::style_resolver::ResolvedStyleSet;
use super::super::{hwpunit_to_px, AutoNumberCounter, PathCommand, StrokeDash, TextStyle};
use super::border_rendering::border_width_to_px;
use super::text_measurement::{estimate_text_width, resolved_to_text_style};
use super::utils::{
    extract_picture_transform, find_bin_data_bytes, picture_data_is_unusable,
    picture_display_size_hu,
};
use super::{footnote_separator_length_px, LayoutEngine, ParagraphVerticalSpacing};
use crate::model::bin_data::BinDataContent;
use crate::model::control::Control;
use crate::model::footnote::{FootnoteShape, NumberFormat};
use crate::model::paragraph::Paragraph;
use crate::model::shape::{
    Caption, CaptionDirection, CommonObjAttr, HorzAlign, TextWrap, VertAlign, VertRelTo,
};

/// 본문 그림의 표시 끝과 후속 흐름 원점은 서로 다른 소유를 가진다.
pub(crate) struct BodyPicturePlacement {
    pub flow_end: f64,
    pub content_bottom: f64,
}

use crate::model::style::{Alignment, LineSpacingType};

#[derive(Clone, Copy, PartialEq, Eq)]
enum FootnoteParagraphRoute {
    Numbered,
    Plain,
    StoredEmpty,
}

struct FootnoteBlockTableFrame<'a> {
    table: &'a crate::model::table::Table,
    measured: crate::renderer::height_measurer::MeasuredTable,
    top_offset: f64,
    advance: f64,
    /// A saved TAC line includes the table's outer box and owns its spacing.
    trailing_line_spacing: f64,
    /// TAC geometry belongs to the host line, not the object's float offsets.
    line_left_offset: Option<f64>,
}

struct FootnoteParagraphPlacement<'a> {
    route: FootnoteParagraphRoute,
    spacing: ParagraphVerticalSpacing,
    block_table: Option<FootnoteBlockTableFrame<'a>>,
}

fn fragment_line_bounds(fragment: Option<FootnoteFragment>, total_lines: usize) -> (usize, usize) {
    match fragment {
        Some(fragment) => {
            let start = fragment.start_line.min(total_lines);
            let end = fragment.end_line.clamp(start, total_lines);
            (start, end)
        }
        None => (0, total_lines),
    }
}

fn fragment_draws_separator(fragment: Option<FootnoteFragment>) -> bool {
    fragment
        .map(|fragment| fragment.draw_separator)
        .unwrap_or(true)
}

fn fragment_draws_number(fragment: Option<FootnoteFragment>) -> bool {
    fragment
        .map(|fragment| fragment.draw_number)
        .unwrap_or(true)
}

/// [#6034] 저장 LINE_SEG 가 없는 각주 문단은 45자 고정 휴리스틱(compose_lines
/// 폴백) 대신 **각주 영역 폭**으로 재조판해 compose 한다. 한글 6.x 대 저장본은
/// 각주 문단에 LINE_SEG 를 저장하지 않는데, 폴백 폭과 실제 영역 폭의 차가 각주
/// 블록을 부풀려(2912735: rhwp 15줄 vs 한글 9줄) bottom-anchor 인 영역 상단이
/// 본문 마지막 줄 위로 올라가 구분선이 글줄을 관통했다. 편집 경로
/// (footnote_ops)의 reflow 계약과 같은 상자를 쓴다. LINE_SEG 가 있으면 종전
/// 그대로 통과한다.
fn compose_footnote_paragraph(
    para: &Paragraph,
    content_width_px: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> crate::renderer::composer::ComposedParagraph {
    // 저장 줄이 없는 실제 빈 각주 문단도 원본 글자모양의 줄 상자를 소유한다.
    // 본문은 같은 재조판 경로를 쓰는데, 각주만 400HU로 줄이면 앞 각주의
    // 예약 높이와 구분선 원점까지 작아진다. 문단 자체가 없는 입력은 제외한다.
    let has_paragraph_line =
        !para.text.is_empty() || (para.char_count > 0 && para.controls.is_empty());
    if para.line_segs.is_empty() && has_paragraph_line && content_width_px > 0.0 {
        let para_style = styles.para_styles.get(para.para_shape_id as usize);
        let margin_left = para_style.map(|s| s.margin_left).unwrap_or(0.0);
        let margin_right = para_style.map(|s| s.margin_right).unwrap_or(0.0);
        let final_width = (content_width_px - margin_left - margin_right).max(0.0);
        if final_width > 0.0 {
            let mut owned = para.clone();
            crate::renderer::composer::reflow_line_segs(
                &mut owned,
                crate::renderer::composer::ParagraphBox::content_width_px(final_width, dpi),
                styles,
                dpi,
            );
            return crate::renderer::composer::compose_paragraph_in_context(&owned, styles);
        }
    }
    let mut composed = crate::renderer::composer::compose_paragraph_in_context(para, styles);
    // 각주 영역에 실제 등록된 원본 빈 줄도 저장 높이로 측정한다.
    if composed.lines.is_empty()
        && para.text.is_empty()
        && para.controls.is_empty()
        && !para.stored_text_partition_is_dirty()
    {
        if let [line] = para.line_segs.as_slice() {
            if line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                && line.line_height > 0
            {
                composed.lines.push(ComposedLine {
                    runs: Vec::new(),
                    line_height: line.line_height,
                    baseline_distance: line.baseline_distance,
                    segment_width: line.segment_width as i32,
                    column_start: line.column_start,
                    line_spacing: line.line_spacing,
                    has_line_break: false,
                    char_start: 0,
                });
            }
        }
    }
    composed
}

/// 원본 각주 본문의 선두 자동 번호 슬롯과 형식을 보존한다.
fn stored_footnote_number_prefix(para: &Paragraph, number: u16) -> Option<(String, usize)> {
    if para.stored_text_partition_is_dirty()
        || para.line_segs.is_empty()
        || para.line_segs.iter().any(|line| {
            line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
        })
    {
        return None;
    }
    let positions = para.control_text_positions();
    let mut prefix = String::new();
    for (index, control) in para.controls.iter().enumerate() {
        let Control::AutoNumber(auto) = control else {
            return None;
        };
        if auto.number_type != crate::model::control::AutoNumberType::Footnote
            || auto.superscript
            || !crate::renderer::note_marker::supported_format(auto.format)
            || positions.get(index) != Some(&index)
            || para.text.chars().nth(index) != Some(' ')
        {
            return None;
        }
        if auto.prefix_char != '\0' {
            prefix.push(auto.prefix_char);
        }
        prefix.push_str(&crate::renderer::note_marker::number_text(
            number,
            auto.format,
            auto.user_symbol,
        ));
        if auto.suffix_char != '\0' {
            prefix.push(auto.suffix_char);
        }
    }
    Some((prefix, para.controls.len()))
}

/// 각주 번호를 문단 첫 줄에 실은 조합 결과를 만든다.
///
/// 각주 문단은 번호 자리에 autoNum 컨트롤을 두고, 파서는 그 자리를 공백 1자로
/// 남긴다. 머리말·꼬리말 쪽번호(#3216)와 같이 모델 글자는 그대로 두고 `display_text`
/// 만 번호로 바꿔, 글자 인덱스와 줄 나눔을 유지한 채 일반 문단 경로가 내어쓰기·정렬을
/// 적용하게 한다. 자리표시 뒤의 원문 공백이 번호와 본문 사이를 맡으므로 번호 서식의
/// 끝 공백은 뺀다(한/글: `78) CFR`).
///
/// 자리표시가 없는 문단(편집으로 만든 각주 등)은 첫 줄 앞에 번호 run 을 붙이고, 글자
/// 모양은 종전 번호 경로와 같은 문단 첫 글자 모양을 쓴다. 첫 줄을 그리지 않는 조각
/// (`selected_start > 0`)이나 조합 줄이 없는 빈 문단은 `None` 으로 종전 경로에 맡긴다.
fn footnote_composed_with_number(
    para: &Paragraph,
    composed: &ComposedParagraph,
    number_text: &str,
    selected_start: usize,
    base_cs_id: u32,
) -> Option<ComposedParagraph> {
    if selected_start != 0
        || composed
            .lines
            .first()
            .is_none_or(|line| line.runs.is_empty())
    {
        return None;
    }
    let mut numbered = composed.clone();
    let line = numbered.lines.first_mut()?;
    let number_marker = para.controls.iter().find_map(|control| match control {
        Control::AutoNumber(auto)
            if auto.number_type == crate::model::control::AutoNumberType::Footnote =>
        {
            auto.superscript.then_some(auto.assigned_number)
        }
        _ => None,
    });
    let positions = para.control_text_positions();
    let placeholder = para
        .controls
        .iter()
        .enumerate()
        .find_map(|(index, control)| match control {
            Control::AutoNumber(_) => positions.get(index).copied(),
            _ => None,
        });
    let mut run_start = line.char_start;
    let mut target = None;
    if let Some(position) = placeholder {
        for (run_index, run) in line.runs.iter().enumerate() {
            let len = run.text.chars().count();
            if (run_start..run_start + len).contains(&position)
                && run.text.chars().nth(position - run_start) == Some(' ')
            {
                target = Some((run_index, position - run_start));
                break;
            }
            run_start += len;
        }
    }
    match target {
        Some((run_index, local)) => {
            let run = line.runs.remove(run_index);
            let chars: Vec<char> = run.text.chars().collect();
            let mut pieces = Vec::with_capacity(3);
            if local > 0 {
                let mut before = run.clone();
                before.text = chars[..local].iter().collect();
                before.display_text = None;
                before.footnote_marker = None;
                pieces.push(before);
            }
            let mut number = run.clone();
            number.text = " ".to_string();
            number.display_text = Some(number_text.trim_end().to_string());
            number.footnote_marker = number_marker;
            pieces.push(number);
            if local + 1 < chars.len() {
                let mut after = run;
                after.text = chars[local + 1..].iter().collect();
                after.display_text = None;
                after.footnote_marker = None;
                pieces.push(after);
            }
            for (offset, piece) in pieces.into_iter().enumerate() {
                line.runs.insert(run_index + offset, piece);
            }
        }
        None => {
            let mut number = line.runs.first().cloned().unwrap_or_default();
            number.text = number_text.to_string();
            number.char_style_id = base_cs_id;
            number.display_text = None;
            number.footnote_marker = number_marker;
            number.char_overlap = None;
            number.inserted_control_text = true;
            line.runs.insert(0, number);
        }
    }
    Some(numbered)
}

/// 각주 내용 번호 "작게": 일반 문단 경로가 그린 번호 run을 본문 각주 표시와 같은 크기(3/4)·
/// 기준선으로 줄이고, 같은 줄 뒤의 글자 run을 줄어든 폭만큼 당긴다(한/글 12.30 Mac 인쇄).
fn shrink_footnote_number(nodes: &mut [RenderNode], number: &str) {
    for line in nodes
        .iter_mut()
        .filter(|node| matches!(node.node_type, RenderNodeType::TextLine(_)))
    {
        let Some(index) = line.children.iter().position(|child| {
            matches!(&child.node_type, RenderNodeType::TextRun(run)
                if run.display_or_text().trim_end() == number)
        }) else {
            continue;
        };
        let node = &mut line.children[index];
        let RenderNodeType::TextRun(run) = &mut node.node_type else {
            return;
        };
        let base = run.style.font_size;
        let (size, baseline) =
            crate::renderer::script_metrics::ScriptMetricsContract::NoteReference.draw_metrics(
                base,
                run.baseline,
                true,
                false,
                run.style.font_position,
            );
        run.style.font_size = size;
        run.baseline = baseline;
        // 실제 크기·기준선으로 소비했으므로 paint가 첨자를 다시 축소하지 않는다.
        run.style.superscript = false;
        run.style.subscript = false;
        run.style.font_position = None;
        run.layout_positions = None;
        let width = estimate_text_width(run.display_or_text(), &run.style);
        let dx = node.bbox.width - width;
        node.bbox.width = width;
        for next in &mut line.children[index + 1..] {
            if matches!(next.node_type, RenderNodeType::TextRun(_)) {
                next.bbox.x -= dx;
            }
        }
        return;
    }
}

fn footnote_composed_line_count(
    paragraphs: &[Paragraph],
    content_width_px: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> usize {
    paragraphs
        .iter()
        .map(|paragraph| {
            compose_footnote_paragraph(paragraph, content_width_px, styles, dpi)
                .lines
                .len()
                .max(1)
        })
        .sum()
}

/// [#6866] 회전 프레임 그림의 노드 상자 — `pic`(회전 전 비트맵)과 **중심이 같은**
/// `size` 상자를 만든다. `size` 가 `pic` 과 같으면 원래 상자 그대로다.
fn rotated_frame_node_box(
    pic_x: f64,
    pic_y: f64,
    pic_width: f64,
    pic_height: f64,
    size: (f64, f64),
) -> BoundingBox {
    let (width, height) = size;
    let center_x = pic_x + pic_width / 2.0;
    let center_y = pic_y + pic_height / 2.0;
    BoundingBox::new(
        center_x - width / 2.0,
        center_y - height / 2.0,
        width,
        height,
    )
}

impl LayoutEngine {
    /// [Task #825] 머리말/꼬리말 picture 전용 — outer Header/Footer 위치 marker 전달.
    /// `header_footer_ref` 가 `Some` 일 때 ImageNode 에 마커 설정 → rhwp-studio
    /// 머리말/꼬리말 그림 클릭 hit-test + 개체 속성 dialog dispatch 활성화.
    ///
    /// [Task #1151 v4] `cell_ctx` 가 `Some` 일 때 ImageNode 의 cell_index 설정 +
    /// tac=true 인 경우 `inline_shape_positions` 등록. studio findPictureAtClick 가
    /// cellIdx 인식하여 셀 안 picture 의 클릭 hit-test 정상 동작.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn layout_picture_full(
        &self,
        tree: &mut PageLayoutContext,
        parent_node: &mut RenderNode,
        picture: &crate::model::image::Picture,
        container: &LayoutRect,
        bin_data_content: &[BinDataContent],
        alignment: Alignment,
        section_index: Option<usize>,
        para_index: Option<usize>,
        control_index: Option<usize>,
        header_footer_ref: Option<crate::renderer::render_tree::HeaderFooterImageRef>,
        cell_ctx: Option<&crate::renderer::layout::CellContext>,
        // [#6284] 캡션 문단 조판에 필요하다.
        styles: &ResolvedStyleSet,
    ) {
        // 그림 크기 (HWPUNIT → 픽셀)
        // 회전 picture에서 common.width/height는 한컴이 저장한 회전 후 외접 프레임이고
        // current_width/current_height는 실제로 회전시킬 원본 표시 크기다. common 프레임을
        // 다시 회전시키면 다단/셀 경계를 침범하므로, current 이미지를 common 프레임 중앙에 둔다.
        let rotation = picture.shape_attr.rotation_angle.rem_euclid(360);
        let uses_rotated_frame = rotation != 0
            && picture.shape_attr.current_width > 0
            && picture.shape_attr.current_height > 0
            && picture.common.width > 0
            && picture.common.height > 0;
        let (pic_width_hu, pic_height_hu) = if uses_rotated_frame {
            (
                picture.shape_attr.current_width as i32,
                picture.shape_attr.current_height as i32,
            )
        } else {
            picture_display_size_hu(picture)
        };
        let mut pic_width = hwpunit_to_px(pic_width_hu, self.dpi);
        let mut pic_height = hwpunit_to_px(pic_height_hu, self.dpi);
        let mut frame_width = if uses_rotated_frame {
            hwpunit_to_px(picture.common.width as i32, self.dpi)
        } else {
            pic_width
        };
        let mut frame_height = if uses_rotated_frame {
            hwpunit_to_px(picture.common.height as i32, self.dpi)
        } else {
            pic_height
        };

        // 글자처럼 표 셀 그림은 저장 frame으로 그린 뒤 TableCell clip에 맡긴다. 한/글은
        // 셀 안쪽 폭에 맞춰 비율 축소하지 않으며, 넘치는 오른쪽·아래만 셀 경계에서 자른다.
        // 먼저 축소하면 #7333 31쪽 스크린샷과 그 안의 주석 도형이 함께 작아진다. 그 밖의
        // 그림은 기존처럼 컨테이너를 넘지 않도록 비율 유지 축소한다.
        let preserve_inline_cell_frame = picture.common.treat_as_char && cell_ctx.is_some();
        if !preserve_inline_cell_frame {
            // 회전 프레임과 실제 이미지를 같은 비율로 축소해야 중심/회전축이 유지된다.
            if container.width > 0.0 && frame_width > container.width {
                let scale = container.width / frame_width;
                frame_width = container.width;
                frame_height *= scale;
                pic_width *= scale;
                pic_height *= scale;
            }
            if container.height > 0.0 && frame_height > container.height {
                let scale = container.height / frame_height;
                frame_height = container.height;
                frame_width *= scale;
                pic_height *= scale;
                pic_width *= scale;
            }
        }

        // [#6866] **회전 프레임 그림의 노드 상자는 `frame`(= 선언 상자)이다.**
        //
        // 페인터는 `ShapeTransform::effective_image_bbox` 로 90/270° 회전 그림의
        // bbox 가로세로를 **먼저 뒤집은 뒤** 회전을 건다(이중회전 방지, shot 05).
        // 즉 페인터는 노드 상자가 **회전 후** 상자라고 전제한다. 그런데 위에서
        // `pic_*`(= `current_*`, 회전 **전** 비트맵)로 상자를 내면 그 전제가 깨져
        // 뒤집기가 한 번 더 걸린다 — 선언 29.3×53.7 이 53.7×29.3 으로 눕는다
        // (156627451 12쪽 `angle=270`, 같은 문서 `angle=0` 15장은 정상).
        //
        // 두 상자는 중심이 같으므로, 노드에 `frame` 을 실으면 페인터의 뒤집기가
        // 정확히 `pic` 을 만들어 내고 회전이 다시 `frame` 으로 돌려놓는다.
        // 두 상자는 중심이 같으므로 원점도 그 중심에서 되짚는다.
        let node_box_size = if uses_rotated_frame {
            (frame_width, frame_height)
        } else {
            (pic_width, pic_height)
        };

        // [#6284] 캡션 띠 — 그림이 차지하는 블록은 그림 + 캡션이다.
        //
        // 이 계약은 형제 함수 `layout_body_picture` 에 이미 있었는데, 본문 그림을
        // 실제로 그리는 이 경로에는 없었다. 그래서 `side="TOP"` 캡션이 통째로
        // 사라지고 그림이 캡션 띠만큼(≈15.6~20px) 위로 올라왔다
        // (156562502: 캡션 17개 전부 TOP, 그림 9개가 3pt 초과로 어긋남).
        let caption_band_height =
            crate::renderer::composer::caption_height_px(&picture.caption, self.dpi);
        let caption_spacing = picture
            .caption
            .as_ref()
            .map(|c| hwpunit_to_px(c.spacing as i32, self.dpi))
            .unwrap_or(0.0);
        let (caption_top_offset, caption_left_offset, caption_band_width) =
            match picture.caption.as_ref().map(|c| c.direction) {
                Some(CaptionDirection::Top) => (caption_band_height + caption_spacing, 0.0, 0.0),
                Some(CaptionDirection::Left) => {
                    let cw = picture
                        .caption
                        .as_ref()
                        .map(|c| hwpunit_to_px(c.width as i32, self.dpi))
                        .unwrap_or(0.0);
                    (0.0, cw + caption_spacing, cw + caption_spacing)
                }
                Some(CaptionDirection::Right) => {
                    let cw = picture
                        .caption
                        .as_ref()
                        .map(|c| hwpunit_to_px(c.width as i32, self.dpi))
                        .unwrap_or(0.0);
                    (0.0, 0.0, cw + caption_spacing)
                }
                _ => (0.0, 0.0, 0.0),
            };
        // Bottom 캡션은 그림을 밀지 않고 블록 높이만 늘린다.
        let caption_block_extra_height = match picture.caption.as_ref().map(|c| c.direction) {
            Some(CaptionDirection::Top) | Some(CaptionDirection::Bottom) => {
                caption_band_height + caption_spacing
            }
            _ => 0.0,
        };
        let block_width = frame_width + caption_band_width;
        let block_height = frame_height + caption_block_extra_height;

        // 그림 위치: non-TAC 이미지는 common 속성의 offset 적용
        // 머리말/꼬리말에서 vert=Paper는 상단여백(header area) 기준
        let (pic_x, pic_y) = if !picture.common.treat_as_char {
            let h_offset = hwpunit_to_px(picture.common.horizontal_offset as i32, self.dpi);
            let v_offset = hwpunit_to_px(picture.common.vertical_offset as i32, self.dpi);
            let frame_x = match picture.common.horz_align {
                HorzAlign::Left | HorzAlign::Inside => container.x + h_offset,
                HorzAlign::Center => container.x + (container.width - block_width) / 2.0 + h_offset,
                HorzAlign::Right | HorzAlign::Outside => {
                    container.x + container.width - block_width - h_offset
                }
            };
            let frame_y = match picture.common.vert_align {
                VertAlign::Top | VertAlign::Inside => container.y + v_offset,
                VertAlign::Center => {
                    container.y + (container.height - block_height) / 2.0 + v_offset
                }
                VertAlign::Bottom | VertAlign::Outside => {
                    container.y + container.height - block_height - v_offset
                }
            };
            (
                frame_x + caption_left_offset + (frame_width - pic_width) / 2.0,
                frame_y + caption_top_offset + (frame_height - pic_height) / 2.0,
            )
        } else {
            let frame_x = match alignment {
                Alignment::Center | Alignment::Distribute => {
                    container.x + (container.width - block_width).max(0.0) / 2.0
                }
                Alignment::Right => container.x + (container.width - block_width).max(0.0),
                _ => container.x,
            };
            (
                frame_x + caption_left_offset + (frame_width - pic_width) / 2.0,
                container.y + caption_top_offset + (frame_height - pic_height) / 2.0,
            )
        };

        // BinData에서 이미지 데이터 찾기 (bin_data_id는 1-indexed 순번)
        let bin_data_id = picture.image_attr.bin_data_id;
        let image_data = find_bin_data_bytes(bin_data_content, bin_data_id);
        // [Task #2225] 그림 미지정(bin 참조 실패 + 외부 경로 없음): 한컴은 편집기
        // 에서만 점선 테두리+그림-없음 아이콘으로 표시하고 인쇄 등가 출력은
        // 미출력 — 의미 노드(MissingPicture)로 방출해 백엔드별 분기를 일원화.
        if picture_data_is_unusable(image_data.as_deref())
            && picture.image_attr.external_path.is_none()
        {
            let ph_id = tree.next_id();
            parent_node.children.push(RenderNode::new(
                ph_id,
                RenderNodeType::Placeholder(
                    // [Task #2230] 문서 좌표 + 셀 경로 배선 — 편집 뷰 클릭
                    // 선택·그림 지정의 대상 특정에 사용.
                    crate::renderer::render_tree::PlaceholderNode::missing_picture(
                        section_index,
                        para_index,
                        control_index,
                        cell_ctx.cloned(),
                    ),
                ),
                rotated_frame_node_box(pic_x, pic_y, pic_width, pic_height, node_box_size),
            ));
            return;
        }

        // 그림 자르기: crop 좌표를 그대로 저장 (렌더러에서 이미지 px 크기와 비교)
        let crop = picture.render_crop_rect();

        // crop 좌표 기준 범위(imgDim). orgSz는 개체 크기이므로 사용하지 않는다.
        let original_size_hu = picture.crop_reference_size();

        // 이미지 노드 생성
        // [Task #1151 v7 항목 1] cell_ctx 의 3 필드 매핑은 CellContext::last_image_indices()
        // 로 통합 (이전: 각 필드마다 path.last() 호출 반복).
        let (cei, cpi, otci) = cell_ctx
            .map(|c| c.last_image_indices())
            .unwrap_or((None, None, None));
        let img_id = tree.next_id();
        let mut img_node = RenderNode::new(
            img_id,
            RenderNodeType::Image(ImageNode {
                section_index,
                para_index,
                control_index,
                crop,
                original_size_hu,
                effect: picture.image_attr.effect,
                brightness: picture.image_attr.brightness,
                contrast: picture.image_attr.contrast,
                opacity: picture.image_attr.opacity(),
                text_wrap: Some(picture.common.text_wrap),
                transform: crate::renderer::image_geometry::picture_transform(picture),
                external_path: picture.image_attr.external_path.clone(),
                content_inset: crate::renderer::layout::utils::picture_content_inset(picture),
                pre_rotation_ratio: crate::renderer::image_geometry::picture_pre_rotation_ratio(
                    picture,
                ),
                source_rect: crate::renderer::image_geometry::picture_source_rect(picture),
                header_footer_ref: header_footer_ref.clone(),
                cell_index: cei,
                cell_para_index: cpi,
                outer_table_control_index: otci,
                // [Task #1161] 전체 다단계 경로 보존(스칼라는 위 innermost 투영).
                cell_context: cell_ctx.cloned(),
                ..ImageNode::new(bin_data_id, image_data)
            }),
            rotated_frame_node_box(pic_x, pic_y, pic_width, pic_height, node_box_size),
        );
        img_node.source_inline_picture = picture.common.treat_as_char;

        self.append_picture_image_node(tree, parent_node, picture, img_node);

        // [#6284] 캡션 렌더링 — 기하는 위에서 예약한 띠와 같은 산식이다
        // (`layout_body_picture` 의 캡션 방출부와 같은 규칙).
        if let Some(ref caption) = picture.caption {
            use crate::model::shape::CaptionVertAlign;
            let (cap_x, cap_w, cap_y) = match caption.direction {
                CaptionDirection::Top => (
                    pic_x,
                    pic_width,
                    (pic_y - caption_top_offset).max(container.y),
                ),
                CaptionDirection::Bottom => {
                    (pic_x, pic_width, pic_y + pic_height + caption_spacing)
                }
                CaptionDirection::Left | CaptionDirection::Right => {
                    let cw = hwpunit_to_px(caption.width as i32, self.dpi);
                    let cx = if caption.direction == CaptionDirection::Left {
                        pic_x - caption_left_offset
                    } else {
                        pic_x + pic_width + caption_spacing
                    };
                    let cy = match caption.vert_align {
                        CaptionVertAlign::Top => pic_y,
                        CaptionVertAlign::Center => {
                            pic_y + (pic_height - caption_band_height).max(0.0) / 2.0
                        }
                        CaptionVertAlign::Bottom => {
                            pic_y + (pic_height - caption_band_height).max(0.0)
                        }
                    };
                    (cx, cw, cy)
                }
            };
            let caption_cell_ctx = cell_ctx.cloned().or_else(|| {
                para_index.map(|pi| super::CellContext {
                    in_textbox: false,
                    parent_para_index: pi,
                    path: vec![super::CellPathEntry {
                        control_index: control_index.unwrap_or(0),
                        cell_index: 0,
                        cell_para_index: 0,
                        text_direction: 0,
                    }],
                })
            });
            self.layout_caption(
                tree,
                parent_node,
                caption,
                styles,
                container,
                cap_x,
                cap_w,
                cap_y,
                &mut self.auto_counter.borrow_mut(),
                bin_data_content,
                caption_cell_ctx,
                CaptionOwner::new(
                    section_index,
                    para_index,
                    control_index,
                    CaptionControlKind::Image,
                ),
            );
        }

        // [Task #1151 v4] tac=true 셀 안 picture 의 위치를 inline_shape_positions 에 등록 →
        // cursor_rect 의 hit-test 루프가 picture 클릭 인식. 셀 외부 / 본문 picture 는
        // 기존 register path (paragraph_layout) 가 처리하므로 cell_ctx Some + tac=true
        // 인 경우만.
        if picture.common.treat_as_char {
            if let (Some(sec), Some(para_for_layout), Some(ctrl)) =
                (section_index, para_index, control_index)
            {
                tree.set_inline_shape_position(sec, para_for_layout, ctrl, cell_ctx, pic_x, pic_y);
            }
        }

        // 그림과 외곽선은 위 append_picture_image_node에서 한 번 발행했다.
    }

    /// 개체(Picture/Shape)의 절대 좌표 (x, y)를 계산한다.
    /// HWP 스펙에 따른 VertRelTo/HorzRelTo/VertAlign/HorzAlign/treat_as_char 처리를 통합한 단일 함수.
    /// 상대 크기(WidthCriterion/HeightCriterion)를 적용하여 실제 px 크기를 반환한다.
    pub(crate) fn resolve_object_size(
        &self,
        common: &CommonObjAttr,
        col_area: &LayoutRect,
        body_area: &LayoutRect,
        paper_area: &LayoutRect,
    ) -> (f64, f64) {
        use crate::model::shape::SizeCriterion;

        let raw_w = common.width as f64;
        let raw_h = common.height as f64;

        let obj_width = match common.width_criterion {
            SizeCriterion::Absolute => hwpunit_to_px(common.width as i32, self.dpi),
            SizeCriterion::Paper => paper_area.width * raw_w / 10000.0,
            SizeCriterion::Page => body_area.width * raw_w / 10000.0,
            SizeCriterion::Column => col_area.width * raw_w / 10000.0,
            SizeCriterion::Para => col_area.width * raw_w / 10000.0,
        };

        let obj_height = match common.height_criterion {
            SizeCriterion::Absolute => hwpunit_to_px(common.height as i32, self.dpi),
            SizeCriterion::Paper => paper_area.height * raw_h / 10000.0,
            SizeCriterion::Page => body_area.height * raw_h / 10000.0,
            _ => hwpunit_to_px(common.height as i32, self.dpi),
        };

        (obj_width, obj_height)
    }

    pub(crate) fn compute_object_position(
        &self,
        common: &CommonObjAttr,
        obj_width: f64,
        obj_height: f64,
        container: &LayoutRect,
        col_area: &LayoutRect,
        body_area: &LayoutRect,
        paper_area: &LayoutRect,
        para_y: f64,
        alignment: Alignment,
    ) -> (f64, f64) {
        crate::renderer::float_placement::ObjectPlacementFrame {
            container,
            column: col_area,
            body: body_area,
            paper: paper_area,
            paragraph_y: para_y,
            alignment,
            dpi: self.dpi,
        }
        .position(common, obj_width, obj_height)
    }

    /// 본문 그림을 배치하고, 같은 확정 원점에서 표시 하단과 흐름 끝을 반환한다.
    pub(crate) fn layout_body_picture(
        &self,
        tree: &mut PageLayoutContext,
        parent_node: &mut RenderNode,
        picture: &crate::model::image::Picture,
        container: &LayoutRect,
        col_area: &LayoutRect,
        body_area: &LayoutRect,
        paper_area: &LayoutRect,
        bin_data_content: &[BinDataContent],
        styles: &ResolvedStyleSet,
        alignment: Alignment,
        y_offset: f64,
        section_index: usize,
        para_index: usize,
        control_index: usize,
        // [Task #1079] 파일 vpos 가 이미 그림 공간을 반영(그림 para 줄 앞 gap ≥ 그림 높이)하면
        // 그림을 그 gap 안(바닥이 그림 para 줄에 정렬)에 그리고 flow 를 그림 높이만큼 추가
        // 진행하지 않는다. 이중 계상(gap + draw-advance) 방지.
        vpos_accounts_for_height: bool,
    ) -> BodyPicturePlacement {
        // 그림 크기 (HWPUNIT → 픽셀)
        // [Issue #1230] 측면흐름 wrap 은 common(개체 틀) 프레임으로 그린다.
        let (pic_width_hu, pic_height_hu) = super::utils::picture_flow_frame_size_hu(picture);
        let pic_width = hwpunit_to_px(pic_width_hu, self.dpi);
        let pic_height = hwpunit_to_px(pic_height_hu, self.dpi);

        // 캡션 높이 및 간격 계산
        let caption_height = self.calculate_caption_height(&picture.caption, styles);
        let caption_spacing = if let Some(ref caption) = picture.caption {
            hwpunit_to_px(caption.spacing as i32, self.dpi)
        } else {
            0.0
        };

        // #6596의 여백·캡션 상자를 셀과 같은 생산 결과로 소비한다.
        let outer_box = crate::renderer::float_placement::picture_outer_box(
            picture,
            pic_width,
            pic_height,
            caption_height,
            self.dpi,
        );
        let box_width = outer_box.width;
        let box_height = outer_box.height;
        let margin_left = outer_box.margin_left;
        let margin_top = outer_box.margin_top;

        // 통합 좌표 계산 (여백을 포함한 상자 기준)
        let (box_x, base_y) = self.compute_object_position(
            &picture.common,
            box_width,
            box_height,
            container,
            col_area,
            body_area,
            paper_area,
            y_offset,
            alignment,
        );

        // [Issue #2032] restrictInPage(쪽 영역 안으로 제한, HWP5 attr bit 13 = HWPX pos@flowWithText):
        // vert=Para floating 그림의 하단이 쪽 영역을 벗어나면 쪽 영역 안으로 끌어올린다.
        // 미적용 시 앵커+offset 조합으로 좌표가 페이지 캔버스 밖이 되어 그림이 어느
        // 페이지에서도 보이지 않는다 (완전 소실). floating 표 동등 로직
        // (table_layout.rs compute_table_y 의 Para 클램프) 과 동일 시멘틱.
        // 상단(top bleed) 은 한컴도 허용하는 사례가 있어 하단 초과만 교정한다
        // (표의 allow_para_top_bleed 예외와 동일 취지).
        // vpos_accounts_for_height(파일 vpos 가 그림 공간을 이미 반영) 이면 그림은
        // base_y 위쪽 gap 안에 그려지므로 (frame 하단 = base_y) 클램프 비대상.
        let base_y = if !picture.common.treat_as_char
            && picture.common.flow_with_text
            && !vpos_accounts_for_height
            && matches!(picture.common.vert_rel_to, VertRelTo::Para)
        {
            let body_bottom = col_area.y + col_area.height - box_height;
            base_y.min(body_bottom.max(col_area.y))
        } else {
            base_y
        };

        let caption_top_offset = outer_box.caption_top;
        let caption_left_offset = outer_box.caption_left;

        // 잉크 원점 = 상자 원점 + (왼쪽 여백, 위 여백). #3821 이 Column-왼쪽 Square 의
        // 왼쪽 여백에만 좁혀 적용하던 것을 위 실측대로 사방·전 기준으로 편다. wrap
        // exclusion 은 이미 source LINE_SEG 가 상자 기준으로 보유한다.
        let adjusted_pic_x = box_x + margin_left + caption_left_offset;
        // [Task #1079] already_accounted: 상자를 gap 안에 그림(상자 바닥이 base_y=그림 para
        // 줄에 정렬되도록 box_height 만큼 위로). flow 진행은 아래 return 에서 생략.
        let vpos_shift = if vpos_accounts_for_height {
            box_height
        } else {
            0.0
        };
        let content_top = base_y + margin_top - vpos_shift;
        let pic_y = content_top + caption_top_offset;

        // BinData에서 이미지 데이터 찾기 (bin_data_id는 1-indexed 순번)
        let bin_data_id = picture.image_attr.bin_data_id;
        let image_data = find_bin_data_bytes(bin_data_content, bin_data_id);
        // [Task #2225] 그림 미지정 — layout_picture_full 과 동일 분기.
        //
        // 여기서 곧장 되돌아가면(early return) 캡션 배치와 흐름 계산을 통째로 건너뛴다 —
        // 캡션 글자가 사라지고, 반환값도 "후속 y" 가 아니라 "높이" 가 되어 뒤 문단이 그림
        // 위로 올라탄다. 그래서 **노드만 바꿔 끼우고** 나머지 경로는 그대로 태운다.
        let picture_missing = picture_data_is_unusable(image_data.as_deref())
            && picture.image_attr.external_path.is_none();

        // 그림 자르기
        let crop = picture.render_crop_rect();

        let original_size_hu = picture.crop_reference_size();

        // 이미지 노드 생성 (그림 미지정이면 같은 자리·같은 bbox 의 placeholder 노드)
        let img_id = tree.next_id();
        let node_type = if picture_missing {
            RenderNodeType::Placeholder(
                // [Task #2230] 본문 picture — 셀 경로 없음(None).
                crate::renderer::render_tree::PlaceholderNode::missing_picture(
                    Some(section_index),
                    Some(para_index),
                    Some(control_index),
                    None,
                ),
            )
        } else {
            RenderNodeType::Image(ImageNode {
                section_index: Some(section_index),
                para_index: Some(para_index),
                control_index: Some(control_index),
                crop,
                original_size_hu,
                effect: picture.image_attr.effect,
                brightness: picture.image_attr.brightness,
                contrast: picture.image_attr.contrast,
                opacity: picture.image_attr.opacity(),
                text_wrap: Some(picture.common.text_wrap),
                transform: crate::renderer::image_geometry::picture_transform(picture),
                external_path: picture.image_attr.external_path.clone(),
                content_inset: crate::renderer::layout::utils::picture_content_inset(picture),
                pre_rotation_ratio: crate::renderer::image_geometry::picture_pre_rotation_ratio(
                    picture,
                ),
                source_rect: crate::renderer::image_geometry::picture_source_rect(picture),
                ..ImageNode::new(bin_data_id, image_data)
            })
        };
        let img_node = RenderNode::new(
            img_id,
            node_type,
            BoundingBox::new(adjusted_pic_x, pic_y, pic_width, pic_height),
        );

        parent_node.children.push(img_node);
        let mut content_bottom = pic_y + pic_height;

        // 그림 테두리(선) 렌더링
        self.render_picture_border(
            tree,
            parent_node,
            picture,
            img_id,
            adjusted_pic_x,
            pic_y,
            pic_width,
            pic_height,
        );

        // 캡션 렌더링
        if let Some(ref caption) = picture.caption {
            use crate::model::shape::CaptionVertAlign;
            let (cap_x, cap_w, cap_y) = match caption.direction {
                CaptionDirection::Top => (adjusted_pic_x, pic_width, base_y + margin_top),
                CaptionDirection::Bottom => (
                    adjusted_pic_x,
                    pic_width,
                    pic_y + pic_height + caption_spacing,
                ),
                CaptionDirection::Left | CaptionDirection::Right => {
                    let cw = hwpunit_to_px(caption.width as i32, self.dpi);
                    let cx = if caption.direction == CaptionDirection::Left {
                        box_x + margin_left
                    } else {
                        adjusted_pic_x + pic_width + caption_spacing
                    };
                    let cy = match caption.vert_align {
                        CaptionVertAlign::Top => pic_y,
                        CaptionVertAlign::Center => {
                            pic_y + (pic_height - caption_height).max(0.0) / 2.0
                        }
                        CaptionVertAlign::Bottom => pic_y + (pic_height - caption_height).max(0.0),
                    };
                    (cx, cw, cy)
                }
            };

            content_bottom = content_bottom.max(cap_y + caption_height);
            let cell_ctx = super::CellContext {
                in_textbox: false,
                parent_para_index: para_index,
                path: vec![super::CellPathEntry {
                    control_index,
                    cell_index: 0,
                    cell_para_index: 0,
                    text_direction: 0,
                }],
            };
            self.layout_caption(
                tree,
                parent_node,
                caption,
                styles,
                col_area,
                cap_x,
                cap_w,
                cap_y,
                &mut self.auto_counter.borrow_mut(),
                bin_data_content,
                Some(cell_ctx),
                CaptionOwner::new(
                    Some(section_index),
                    Some(para_index),
                    Some(control_index),
                    CaptionControlKind::Image,
                ),
            );
        }

        // y_offset 업데이트: Para 기준 그림만 높이만큼 진행
        // Page/Paper 기준 그림은 플로팅이므로 y_offset 변경 없음
        // Task #347: 글뒤로/글앞으로 그림은 본문 흐름을 점유하지 않으므로 y 미진행.
        // base_y는 vert_offset이 적용된 상자 상단 y이므로, base_y + box_height 가
        // 상자 하단(잉크 + 위·아래 여백) y가 된다. y_offset(앵커 단락 y) 대신 base_y를
        // 기준으로 반환해야 vert_offset이 있는 혼합 단락(텍스트+그림)에서 후속 단락이
        // 그림 위로 겹치지 않는다.
        let flow_end = match (picture.common.vert_rel_to, picture.common.text_wrap) {
            (VertRelTo::Para, TextWrap::BehindText | TextWrap::InFrontOfText) => y_offset,
            // [Task #1079] 파일 vpos 가 그림 공간을 이미 반영하면 그림은 gap 안에 그려졌고
            // 후속 문단은 파일 vpos(그림 para 줄)로 흐르므로 추가 진행 없이 base_y 반환.
            (VertRelTo::Para, _) if vpos_accounts_for_height => base_y,
            (VertRelTo::Para, _) => base_y + box_height,
            (VertRelTo::Page | VertRelTo::Paper, _) => y_offset,
        };
        BodyPicturePlacement {
            flow_end,
            content_bottom,
        }
    }

    /// 캡션의 총 높이를 계산한다.
    ///
    /// 산식은 `composer::caption_height_px`가 단일 정의다(#4320) — height_measurer 의
    /// `measure_caption`도 같은 함수를 호출한다.
    pub(crate) fn calculate_caption_height(
        &self,
        caption: &Option<Caption>,
        styles: &ResolvedStyleSet,
    ) -> f64 {
        super::super::composer::caption_height_px_in_context(caption, Some(styles), self.dpi)
    }

    /// 캡션을 레이아웃한다.
    pub(crate) fn layout_caption(
        &self,
        tree: &mut PageLayoutContext,
        parent_node: &mut RenderNode,
        caption: &Caption,
        styles: &ResolvedStyleSet,
        _col_area: &LayoutRect,
        content_x: f64,
        content_width: f64,
        y_start: f64,
        _auto_counter: &mut AutoNumberCounter,
        bin_data_content: &[BinDataContent],
        cell_ctx: Option<super::CellContext>,
        caption_owner: Option<CaptionOwner>,
    ) {
        if caption.paragraphs.is_empty() {
            return;
        }

        let caption_area = LayoutRect {
            x: content_x,
            y: y_start,
            width: content_width,
            height: 0.0, // 높이는 동적
        };

        let mut para_y = y_start;
        for (pi, para) in caption.paragraphs.iter().enumerate() {
            let first_caption_node = parent_node.children.len();
            let para_y_before_layout = para_y;
            // 먼저 문단을 조합
            let mut composed =
                crate::renderer::composer::compose_paragraph_in_context(para, styles);

            // 자동 번호는 자리표 글자의 표시 문자열로만 바꿔 글자 위치 대응을 지킨다.
            crate::renderer::composer::project_caption_auto_numbers(&mut composed, para);

            // cell_ctx에 cell_para_index 갱신
            let ctx = cell_ctx.as_ref().map(|c| {
                let mut cc = c.clone();
                if let Some(last) = cc.path.last_mut() {
                    last.cell_para_index = pi;
                }
                cc
            });

            para_y = self.layout_composed_paragraph(
                tree,
                parent_node,
                &composed,
                styles,
                &caption_area,
                para_y,
                0,
                composed.lines.len(),
                0,
                0,
                ctx.clone(),
                false,
                false,
                0.0,
                None,
                Some(para),
                Some(bin_data_content),
                None, // 캡션 컨텍스트 — wrap zone 무관
            );

            // Tag only lines emitted by this caption paragraph, not text inside
            // its nested controls or earlier siblings. Wrapped lines share pi.
            for node in &mut parent_node.children[first_caption_node..] {
                if let RenderNodeType::TextLine(line) = &mut node.node_type {
                    line.caption_owner = caption_owner.map(|owner| CaptionOwner {
                        caption_ordinal: pi,
                        ..owner
                    });
                }
            }

            self.layout_caption_topbottom_pictures(
                tree,
                parent_node,
                para,
                &caption_area,
                para_y_before_layout,
                bin_data_content,
                ctx.as_ref(),
                styles,
            );
        }
    }

    fn layout_caption_topbottom_pictures(
        &self,
        tree: &mut PageLayoutContext,
        parent_node: &mut RenderNode,
        para: &Paragraph,
        caption_area: &LayoutRect,
        para_y: f64,
        bin_data_content: &[BinDataContent],
        cell_ctx: Option<&super::CellContext>,
        // [#6284] 캡션 문단 조판에 필요하다.
        styles: &ResolvedStyleSet,
    ) {
        let anchor_y = para
            .line_segs
            .first()
            .filter(|seg| seg.vertical_pos >= 0)
            .map(|seg| caption_area.y + hwpunit_to_px(seg.vertical_pos, self.dpi))
            .unwrap_or(para_y);

        for (ctrl_idx, ctrl) in para.controls.iter().enumerate() {
            let Control::Picture(pic) = ctrl else {
                continue;
            };
            if !matches!(pic.common.text_wrap, TextWrap::TopAndBottom) {
                continue;
            }
            if tree
                .get_inline_shape_position(0, 0, ctrl_idx, cell_ctx)
                .is_some()
            {
                continue;
            }

            let (pic_width_hu, pic_height_hu) = picture_display_size_hu(pic);
            let pic_width = hwpunit_to_px(pic_width_hu, self.dpi);
            let pic_height = hwpunit_to_px(pic_height_hu, self.dpi);
            let placement_area = LayoutRect {
                x: caption_area.x,
                y: anchor_y,
                width: caption_area.width,
                height: pic_height.max(caption_area.height),
            };
            let mut placement_common = pic.common.clone();
            placement_common.treat_as_char = false;
            let (pic_x, pic_y) = self.compute_object_position(
                &placement_common,
                pic_width,
                pic_height,
                &placement_area,
                &placement_area,
                &placement_area,
                &placement_area,
                anchor_y,
                Alignment::Left,
            );
            let pic_area = LayoutRect {
                x: pic_x,
                y: pic_y,
                width: pic_width,
                height: pic_height,
            };
            let mut pic_for_layout = (**pic).clone();
            pic_for_layout.common.treat_as_char = false;
            pic_for_layout.common.horizontal_offset = 0;
            pic_for_layout.common.vertical_offset = 0;
            pic_for_layout.common.horz_align = HorzAlign::Left;
            pic_for_layout.common.vert_align = VertAlign::Top;

            self.layout_picture(
                tree,
                parent_node,
                &pic_for_layout,
                &pic_area,
                bin_data_content,
                Alignment::Left,
                Some(0),
                Some(0),
                Some(ctrl_idx),
                cell_ctx,
                styles,
            );

            if pic.common.treat_as_char {
                tree.set_inline_shape_position(0, 0, ctrl_idx, cell_ctx, pic_x, pic_y);
            }
        }
    }

    /// [#5708] 저장 LINE_SEG 가 없는 각주 문단의 합성 폴백 줄높이(400 HWPUNIT = 5.33px)를
    /// 문단 줄간격 설정으로 보정한다.
    ///
    /// 폴백값을 그대로 쓰면 줄 전진(5.3px)이 글자 크기(9pt = 12px)보다 작아 각주 줄이 서로
    /// 겹쳐 그려진다(00464 1쪽 하단 주석 8줄). 본문·표 경로는 #674 로 같은 보정을 이미
    /// 하고 있고, 각주 경로만 빠져 있었다. `corrected_line_metrics` 는 `raw_lh < max_fs`
    /// 일 때만 개입하므로 저장 LINE_SEG 를 가진 각주는 종전 그대로다(#2112 계약).
    fn footnote_line_metrics(
        &self,
        comp_line: &ComposedLine,
        para_style_id: u16,
        styles: &ResolvedStyleSet,
    ) -> (f64, f64) {
        let raw_lh = hwpunit_to_px(comp_line.line_height, self.dpi);
        let raw_ls = hwpunit_to_px(comp_line.line_spacing, self.dpi);
        let max_fs = comp_line
            .runs
            .iter()
            .map(|run| run.line_box_font_size(styles))
            .fold(0.0f64, f64::max);
        let para_style = styles.para_styles.get(para_style_id as usize);
        let ls_val = para_style.map(|s| s.line_spacing).unwrap_or(160.0);
        let ls_type = para_style
            .map(|s| s.line_spacing_type)
            .unwrap_or(LineSpacingType::Percent);
        crate::renderer::corrected_line_metrics(raw_lh, raw_ls, max_fs, ls_type, ls_val)
    }

    fn footnote_block_table<'a>(
        para: &'a Paragraph,
        selected: &std::ops::Range<usize>,
    ) -> Option<&'a crate::model::table::Table> {
        let [Control::Table(table)] = para.controls.as_slice() else {
            return None;
        };
        if selected.start != 0
            || selected.end == 0
            || para
                .text
                .chars()
                .any(|ch| !ch.is_whitespace() && ch != '\u{fffc}')
            || !matches!(table.common.text_wrap, TextWrap::TopAndBottom)
            || !matches!(table.common.vert_rel_to, VertRelTo::Para)
            || !matches!(table.common.vert_align, VertAlign::Top | VertAlign::Inside)
            || table.caption.is_some()
            || table.row_count == 0
            || table.col_count == 0
        {
            return None;
        }
        if table.common.treat_as_char {
            let seg_width = para.line_segs.first().map_or(0, |line| line.segment_width);
            // Ordinary inline TACs are already painted by the paragraph path.
            // A sole table that owns a saved outer-box line is instead classified
            // as a block by that path. The note must consume the same owned line
            // rather than reserving its height while dropping its table.
            if para.stored_text_partition_is_dirty()
                || !Self::tac_stored_band_is_outer_box(para, table)
                || crate::renderer::height_measurer::is_tac_table_inline_in_para(
                    table, seg_width, para,
                )
            {
                return None;
            }
        }
        Some(table)
    }

    fn footnote_block_table_frame<'a>(
        &self,
        para: &'a Paragraph,
        composed: &ComposedParagraph,
        styles: &ResolvedStyleSet,
        selected: &std::ops::Range<usize>,
        area_width: f64,
    ) -> Option<FootnoteBlockTableFrame<'a>> {
        let table = Self::footnote_block_table(para, selected)?;
        let measurer = crate::renderer::height_measurer::HeightMeasurer::new(self.dpi)
            .with_hwp3_variant(self.profile.get().hwp3_layout())
            .with_stored_geometry_policy(self.profile.get().stored_geometry_policy())
            .with_native_hwp5(self.profile.get().hwp5_stored_pagination_layout())
            .with_hwpx_stored_layout(self.profile.get().hwpx_stored_layout())
            .with_session_edited(self.profile.get().session_edited())
            .with_render_normalization(self.render_normalization_overlay());
        let measured = measurer.measure_table(table, 0, 0, styles);
        // Whole-table paint consumes this same resolved row geometry. The
        // empty host is an anchor, not another text row added below the table.
        let rows = self.resolve_row_heights(
            table,
            table.col_count as usize,
            table.row_count as usize,
            Some(&measured),
            styles,
            table.common.treat_as_char,
        );
        let body_height = rows.iter().sum::<f64>()
            + measured.cell_spacing * (table.row_count as usize + 1) as f64;
        let top_offset = if table.common.treat_as_char {
            // Same stored-band producer as the body TAC path. The verified
            // saved line contains the top/table/bottom outer box.
            self.tac_table_stored_outer_band_top(para, table, body_height, 0.0)?
        } else {
            hwpunit_to_px(table.common.vertical_offset as i32, self.dpi)
                + hwpunit_to_px(table.outer_margin_top as i32, self.dpi)
        };
        let mut advance =
            top_offset + body_height + hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi);
        let (trailing_line_spacing, line_left_offset) = if table.common.treat_as_char {
            let line = composed.lines.first()?;
            let (line_height, line_spacing) =
                self.footnote_line_metrics(line, composed.para_style_id, styles);
            // The line and its table occupy one box. If actual cell demand grows,
            // reserve that demand rather than clipping it into the saved line.
            advance = advance.max(line_height);
            let style = styles.para_styles.get(composed.para_style_id as usize);
            let margin_left = style.map_or(0.0, |style| style.margin_left);
            let right = style.map_or(0.0, |style| style.margin_right);
            let indent = crate::renderer::equation_tac_flow::paragraph_line_indent_for_source(
                style.map_or(0.0, |style| style.indent),
                0,
                Some(para),
                composed.lines.len(),
                true,
                area_width - margin_left - right,
                self.dpi,
            );
            let left = margin_left + indent;
            let outer_left = hwpunit_to_px(table.outer_margin_left as i32, self.dpi);
            let outer_right = hwpunit_to_px(table.outer_margin_right as i32, self.dpi);
            let width = self
                .resolve_column_widths(table, table.col_count as usize)
                .iter()
                .sum::<f64>()
                + measured.cell_spacing * (table.col_count as usize + 1) as f64;
            let slack = (area_width - left - right - width - outer_left - outer_right).max(0.0);
            let aligned = match style.map_or(Alignment::Left, |style| style.alignment) {
                Alignment::Center | Alignment::Distribute => slack / 2.0,
                Alignment::Right => slack,
                _ => 0.0,
            };
            (line_spacing, Some(left + aligned + outer_left))
        } else {
            (0.0, None)
        };
        Some(FootnoteBlockTableFrame {
            table,
            measured,
            top_offset,
            advance,
            trailing_line_spacing,
            line_left_offset,
        })
    }

    #[allow(clippy::too_many_arguments)]
    fn footnote_paragraph_placement<'a>(
        &self,
        para: &'a Paragraph,
        composed: &ComposedParagraph,
        styles: &ResolvedStyleSet,
        fragment: Option<FootnoteFragment>,
        number_drawn: bool,
        selected: std::ops::Range<usize>,
        relative_y: f64,
        area_width: f64,
    ) -> FootnoteParagraphPlacement<'a> {
        let mut block_table = (composed.lines.len() <= 1)
            .then(|| self.footnote_block_table_frame(para, composed, styles, &selected, area_width))
            .flatten();
        let route = if para.text.is_empty()
            && para.controls.is_empty()
            && !fragment_draws_number(fragment)
            && composed.lines.len() == 1
        {
            FootnoteParagraphRoute::StoredEmpty
        } else if fragment_draws_number(fragment) && !number_drawn {
            FootnoteParagraphRoute::Numbered
        } else {
            FootnoteParagraphRoute::Plain
        };
        let mut spacing = ParagraphVerticalSpacing {
            before: 0.0,
            after: 0.0,
        };
        if route == FootnoteParagraphRoute::Plain {
            let style = styles.para_styles.get(composed.para_style_id as usize);
            if selected.start == 0 && relative_y.abs() >= 1.0 {
                spacing.before = crate::renderer::hwp3_variant_flow_spacing_before(
                    style.map_or(0.0, |style| style.spacing_before),
                    self.use_hwp3_origin_flow_spacing_before.get(),
                )
                .max(0.0);
            }
            if selected.end == composed.lines.len().max(1) {
                spacing.after = style.map_or(0.0, |style| style.spacing_after).max(0.0);
            }
        }
        if route == FootnoteParagraphRoute::Numbered {
            if let Some(block) = block_table.as_mut() {
                let number_line_height = composed.lines.first().map_or_else(
                    || hwpunit_to_px(400, self.dpi),
                    |line| {
                        self.footnote_line_metrics(line, composed.para_style_id, styles)
                            .0
                    },
                );
                block.advance = block.advance.max(number_line_height);
            }
        }
        FootnoteParagraphPlacement {
            route,
            spacing,
            block_table,
        }
    }

    /// The saved-note composer retains these source lines without reflow.
    /// Source pagination owns their page cuts; an edited or fallback note uses
    /// the newly composed physical budget instead.
    pub(crate) fn footnote_area_has_stored_lines(
        &self,
        footnotes: &[FootnoteRef],
        paragraphs: &[Paragraph],
        area_width: f64,
    ) -> bool {
        // 저장 줄이 있어도 현재 각주 영역보다 넓은 캐시는 같은 조판을 증언하지 않는다.
        // 생성 각주가 제본 여백을 빼기 전 폭을 저장한 경우 실제 영역을 재조판한다.
        let width_hu = i64::from(crate::renderer::px_to_hwpunit(area_width, self.dpi));
        !footnotes.is_empty()
            && footnotes.iter().all(|note| {
                let paras = get_footnote_paragraphs(note, paragraphs);
                !paras.is_empty()
                    && paras.iter().all(|para| {
                        !para.line_segs.is_empty()
                            && !para.stored_text_partition_is_dirty()
                            && para.line_segs.iter().all(|line| {
                                line.line_height > 0
                                && line.segment_width > 0
                                && i64::from(line.column_start) + i64::from(line.segment_width)
                                    <= width_hu
                                && line.tag
                                    & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                                    == 0
                            })
                    })
            })
    }

    pub(crate) fn estimate_footnote_area_height(
        &self,
        footnotes: &[FootnoteRef],
        paragraphs: &[Paragraph],
        shape: &FootnoteShape,
        styles: &ResolvedStyleSet,
        area_width: f64,
    ) -> f64 {
        self.estimate_footnote_area_height_with_metrics(
            footnotes,
            paragraphs,
            styles,
            area_width,
            hwpunit_to_px(shape.separator_above_margin_hu() as i32, self.dpi)
                + border_width_to_px(shape.separator_line_width).max(0.5)
                + hwpunit_to_px(shape.separator_below_margin_hu() as i32, self.dpi),
            hwpunit_to_px(shape.between_notes_margin_hu() as i32, self.dpi),
        )
    }

    /// 페이지 분할 큐와 최종 배치는 같은 선택 줄 메트릭을 소비한다.
    pub(crate) fn estimate_footnote_area_height_with_metrics(
        &self,
        footnotes: &[FootnoteRef],
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        area_width: f64,
        separator_height: f64,
        between_notes: f64,
    ) -> f64 {
        if footnotes.is_empty() {
            return 0.0;
        }
        let mut total = if footnotes
            .iter()
            .any(|note| fragment_draws_separator(note.fragment))
        {
            separator_height
        } else {
            0.0
        };

        // 실제 `layout_footnote_area`와 같은 줄 높이 산식을 사용한다. 저장 LineSeg의
        // line_height만 더하면 renderer가 누적하는 trailing line_spacing이 빠져 긴
        // 각주가 예약 영역(및 footer)을 넘을 수 있다. 마지막 각주 문단의 마지막 줄은
        // layout 경로에서도 trailing spacing을 붙이지 않는다.
        for (i, fn_ref) in footnotes.iter().enumerate() {
            let fn_paras = get_footnote_paragraphs(fn_ref, paragraphs);
            total += self.footnote_paragraphs_content_height(
                fn_paras,
                styles,
                area_width,
                fn_ref.fragment,
                total,
            );
            // 각주 간 간격
            if i + 1 < footnotes.len() {
                total += between_notes;
            }
        }
        total
    }

    /// Paragraph plans are shared by area sizing, body reservation and paint.
    pub(crate) fn footnote_paragraphs_content_height(
        &self,
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        area_width: f64,
        fragment: Option<FootnoteFragment>,
        origin_y: f64,
    ) -> f64 {
        let (start_line, end_line) = fragment_line_bounds(
            fragment,
            footnote_composed_line_count(paragraphs, area_width, styles, self.dpi),
        );
        let mut total = origin_y;
        let mut flat_line = 0usize;
        let mut number_drawn = false;
        for para in paragraphs {
            let composed = compose_footnote_paragraph(para, area_width, styles, self.dpi);
            let line_count = composed.lines.len().max(1);
            let para_start = flat_line;
            let selected_start = start_line.saturating_sub(para_start).min(line_count);
            let selected_end = end_line.saturating_sub(para_start).min(line_count);
            flat_line += line_count;
            if selected_start >= selected_end {
                continue;
            }
            let placement = self.footnote_paragraph_placement(
                para,
                &composed,
                styles,
                fragment,
                number_drawn,
                selected_start..selected_end,
                total,
                area_width,
            );
            total += placement.spacing.before;
            if let Some(block) = placement.block_table {
                total += block.advance;
                if para_start + selected_end < end_line {
                    total += block.trailing_line_spacing;
                }
            } else if placement.route == FootnoteParagraphRoute::StoredEmpty {
                total += hwpunit_to_px(composed.lines[0].line_height, self.dpi);
            } else if composed.lines.is_empty() {
                total += hwpunit_to_px(400, self.dpi);
            } else {
                for (index, line) in composed.lines[selected_start..selected_end]
                    .iter()
                    .enumerate()
                {
                    let (height, spacing) =
                        self.footnote_line_metrics(line, composed.para_style_id, styles);
                    total += height;
                    if para_start + selected_start + index + 1 < end_line {
                        total += spacing;
                    }
                }
            }
            total += placement.spacing.after;
            number_drawn |= placement.route == FootnoteParagraphRoute::Numbered;
        }
        total - origin_y
    }

    pub(crate) fn footnote_with_block_table_content_height(
        &self,
        footnote: &crate::model::footnote::Footnote,
        styles: &ResolvedStyleSet,
        area_width: f64,
        fragment: Option<FootnoteFragment>,
    ) -> Option<f64> {
        footnote
            .paragraphs
            .iter()
            .any(|para| {
                Self::footnote_block_table(para, &(0..1)).is_some()
                    && compose_footnote_paragraph(para, area_width, styles, self.dpi)
                        .lines
                        .len()
                        <= 1
            })
            .then(|| {
                self.footnote_paragraphs_content_height(
                    &footnote.paragraphs,
                    styles,
                    area_width,
                    fragment,
                    0.0,
                )
            })
    }

    /// 각주 영역 레이아웃 (구분선 + 각주 문단들)
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn layout_footnote_area(
        &self,
        tree: &mut PageLayoutContext,
        fn_node: &mut RenderNode,
        footnotes: &[FootnoteRef],
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        fn_area: &LayoutRect,
        shape: &FootnoteShape,
        source_indices: &[usize],
        bin_data_content: &[BinDataContent],
    ) {
        let mut y = fn_area.y;

        if footnotes
            .iter()
            .any(|footnote| fragment_draws_separator(footnote.fragment))
        {
            // (1) 구분선 위 여백
            y += hwpunit_to_px(shape.separator_above_margin_hu() as i32, self.dpi);

            // (2) 구분선
            let sep_length =
                footnote_separator_length_px(shape.separator_length, fn_area.width, self.dpi);
            let line_width = border_width_to_px(shape.separator_line_width).max(0.5);

            super::note_separator::append(
                tree, fn_node, shape, fn_area.x, y, sep_length, line_width,
            );
            y += line_width;

            // (3) 구분선 아래 여백
            y += hwpunit_to_px(shape.separator_below_margin_hu() as i32, self.dpi);
        }

        // (4) 각 각주 렌더링
        // 각주 TextRun에 마커를 인코딩하여 히트테스트에서 식별 가능하도록 함
        // section_index = footnote_index (footnotes 배열 인덱스)
        // para_index = usize::MAX - 2000 - fn_para_idx (각주 내 문단 인덱스)
        for (frame_index, fn_ref) in footnotes.iter().enumerate() {
            let i = source_indices[frame_index];
            let fn_paras = get_footnote_paragraphs(fn_ref, paragraphs);
            let number_text = format_footnote_number(
                fn_ref.number,
                &shape.number_format,
                shape.prefix_char,
                shape.suffix_char,
                shape.user_char,
            );
            let (fragment_start, fragment_end) = fragment_line_bounds(
                fn_ref.fragment,
                footnote_composed_line_count(fn_paras, fn_area.width, styles, self.dpi),
            );
            let mut flat_line = 0usize;
            let mut number_drawn = false;

            for (p_idx, para) in fn_paras.iter().enumerate() {
                let composed = compose_footnote_paragraph(para, fn_area.width, styles, self.dpi);
                let marker_section = i; // footnote_index
                let marker_para = usize::MAX - 2000 - p_idx; // 각주 내 문단 인덱스
                                                             // 각주 번호 스타일용 기본 char_shape_id (빈/비빈 문단 모두 동일)
                let base_cs_id = para
                    .char_shapes
                    .first()
                    .map(|cs| cs.char_shape_id as u32)
                    .unwrap_or(composed.para_style_id as u32);

                let line_count = composed.lines.len().max(1);
                let para_start = flat_line;
                let para_end = flat_line + line_count;
                let selected_start = fragment_start.saturating_sub(para_start).min(line_count);
                let selected_end = fragment_end.saturating_sub(para_start).min(line_count);
                flat_line = para_end;
                if selected_start >= selected_end {
                    continue;
                }
                let is_last_selected_line = para_start + selected_end == fragment_end;
                let placement = self.footnote_paragraph_placement(
                    para,
                    &composed,
                    styles,
                    fn_ref.fragment,
                    number_drawn,
                    selected_start..selected_end,
                    y - fn_area.y,
                    fn_area.width,
                );
                if let Some(block) = placement.block_table {
                    y += placement.spacing.before;
                    let anchor_y = y;
                    if placement.route == FootnoteParagraphRoute::Numbered {
                        // 번호와 표는 같은 호스트 줄에 속한다. 번호 줄의 높이를
                        // 표 아래에 다시 더하지 않고 공통 advance에 포함한다.
                        let mut number_host = composed.clone();
                        if number_host.lines.is_empty() {
                            // 가상 빈 줄도 번호를 실제 출력한다. 측정과 같은
                            // 기존 400HU fallback 줄이며 표의 내용 줄이 아니다.
                            number_host.lines.push(ComposedLine {
                                runs: Vec::new(),
                                line_height: 400,
                                baseline_distance: 320,
                                segment_width: 0,
                                column_start: 0,
                                line_spacing: 0,
                                has_line_break: false,
                                char_start: 0,
                            });
                        }
                        self.layout_footnote_paragraph_with_number(
                            tree,
                            fn_node,
                            &number_host,
                            para,
                            styles,
                            fn_area,
                            anchor_y,
                            &number_text,
                            fn_ref.number,
                            marker_section,
                            marker_para,
                            base_cs_id,
                            selected_start,
                            selected_end,
                            true,
                            shape.number_code_superscript,
                        );
                        number_drawn = true;
                    }
                    let style = styles.para_styles.get(composed.para_style_id as usize);
                    self.layout_table(
                        tree,
                        fn_node,
                        block.table,
                        marker_section,
                        styles,
                        0,
                        fn_area,
                        anchor_y,
                        bin_data_content,
                        Some(&block.measured),
                        0,
                        Some((marker_para, 0)),
                        style.map_or(Alignment::Left, |style| style.alignment),
                        None,
                        style.map_or(0.0, |style| style.margin_left),
                        style.map_or(0.0, |style| style.margin_right),
                        None,
                        None,
                        Some(anchor_y),
                        None,
                        false,
                        false,
                        0.0,
                        Some((
                            block.line_left_offset.map(|offset| fn_area.x + offset),
                            anchor_y + block.top_offset,
                        )),
                        Self::standalone_table_char_border_fill(Some(para), block.table, styles),
                    );
                    y = anchor_y + block.advance + placement.spacing.after;
                    if !is_last_selected_line {
                        y += block.trailing_line_spacing;
                    }
                    continue;
                }
                if placement.route == FootnoteParagraphRoute::StoredEmpty {
                    y += hwpunit_to_px(composed.lines[0].line_height, self.dpi);
                    continue;
                }

                // 첫 fragment의 첫 선택 줄에만 각주 번호를 싣는다. 번호는 문단의 autoNum
                // 자리표시 위에 얹어 일반 문단 경로로 그린다 — 그래야 번호 문단도 다른 문단과
                // 같은 내어쓰기·정렬을 받는다. 조합 줄이 없는 빈 문단만 종전 전용 경로를 쓴다.
                let draw_number = placement.route == FootnoteParagraphRoute::Numbered;
                number_drawn |= draw_number;
                let stored_prefix = (self.profile.get().hwpx_stored_layout()
                    || self.profile.get().hwp5_stored_pagination_layout())
                .then(|| stored_footnote_number_prefix(para, fn_ref.number))
                .flatten();
                let paragraph_number = stored_prefix
                    .as_ref()
                    .map_or(number_text.as_str(), |(text, _)| text.as_str());
                // 여러 자동 번호 슬롯은 기존 번호 경로가 원본 형식을 보존한다.
                let numbered = (draw_number
                    && stored_prefix.as_ref().is_none_or(|(_, slots)| *slots <= 1))
                .then(|| {
                    footnote_composed_with_number(
                        para,
                        &composed,
                        paragraph_number,
                        selected_start,
                        base_cs_id,
                    )
                })
                .flatten();
                if !draw_number
                    && composed.lines.len() == 1
                    && selected_start == 0
                    && selected_end == line_count
                    && para.controls.iter().any(|control| {
                        matches!(control, Control::Table(table) if table.common.treat_as_char)
                    })
                {
                    // 선택된 TAC 줄의 표는 원본 줄 상자 안의 실제 내용이다.
                    // 일반 인라인 표와 같은 원점·여백·자원을 사용해 빈 글줄만
                    // 남기지 않고 표와 내부 그림까지 해당 각주 조각에 보존한다.
                    let style = styles.para_styles.get(composed.para_style_id as usize);
                    let before = crate::renderer::hwp3_variant_flow_spacing_before(
                        style.map_or(0.0, |style| style.spacing_before),
                        self.use_hwp3_origin_flow_spacing_before.get(),
                    );
                    let after = style.map_or(0.0, |style| style.spacing_after);
                    y = self.layout_inline_table_paragraph(
                        tree,
                        fn_node,
                        para,
                        Some(&composed),
                        styles,
                        fn_area,
                        y + placement.spacing.before - before,
                        marker_section,
                        marker_para,
                        bin_data_content,
                        &[],
                    ).flow_bottom + placement.spacing.after - after;
                    if is_last_selected_line {
                        y -= hwpunit_to_px(composed.lines[0].line_spacing, self.dpi);
                    }
                } else if draw_number && numbered.is_none() {
                    y = self.layout_footnote_paragraph_with_number(
                        tree,
                        fn_node,
                        &composed,
                        para,
                        styles,
                        fn_area,
                        y,
                        &number_text,
                        fn_ref.number,
                        marker_section,
                        marker_para,
                        base_cs_id,
                        selected_start,
                        selected_end,
                        is_last_selected_line,
                            shape.number_code_superscript,
                        );
                } else {
                    let composed = numbered.as_ref().unwrap_or(&composed);
                    let first_new_child = fn_node.children.len();
                    // 각주 줄도 원본 인라인 개체와 문서의 BinData를 소비한다.
                    // 텍스트 줄만 전달하면 높이는 예약하면서 TAC 표·그림을
                    // 출력하지 못한다. 이어받기에도 같은 글줄 소유를 사용한다.
                    let returned_y = self.layout_composed_paragraph_in_frame(
                        tree,
                        fn_node,
                        composed,
                        styles,
                        fn_area,
                        y,
                        selected_start,
                        selected_end,
                        marker_section,
                        marker_para,
                        None,
                        false,
                        false,
                        0.0,
                        None,
                        Some(para),
                        Some(bin_data_content),
                        None, // 각주 컨텍스트 — wrap zone 무관
                        false,
                        false,
                        Some(placement.spacing),
                        None,
                    );
                    if shape.number_code_superscript && numbered.is_some() {
                        shrink_footnote_number(
                            &mut fn_node.children[first_new_child..],
                            paragraph_number.trim_end(),
                        );
                    }
                    if is_last_selected_line {
                        // fragment의 마지막 줄은 trailing line-spacing을 쓰지 않는다.
                        let trail_ls = composed
                            .lines
                            .get(selected_end.saturating_sub(1))
                            .map(|l| hwpunit_to_px(l.line_spacing, self.dpi))
                            .unwrap_or(0.0);
                        y = returned_y - trail_ls;
                    } else {
                        y = returned_y;
                    }
                }
            }

            // 각주 간 간격
            if i + 1 < footnotes.len() {
                y += hwpunit_to_px(shape.between_notes_margin_hu() as i32, self.dpi);
            }
        }
    }

    /// 각주 번호를 앞에 붙여 문단을 레이아웃
    /// marker_section: footnote_index, marker_para: 각주 내 문단 마커 (usize::MAX - 2000 - fn_para_idx)
    /// base_cs_id: 번호 스타일 결정용 기본 char_shape_id (문단의 char_shapes[0])
    pub(crate) fn layout_footnote_paragraph_with_number(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        composed: &ComposedParagraph,
        paragraph: &Paragraph,
        styles: &ResolvedStyleSet,
        area: &LayoutRect,
        y_start: f64,
        number_text: &str,
        note_number: u16,
        marker_section: usize,
        marker_para: usize,
        base_cs_id: u32,
        line_start: usize,
        line_end: usize,
        // fragment의 마지막 선택 줄은 trailing line_spacing을 누적하지 않는다.
        is_last_selected_line: bool,
        // 각주 모양 "각주 내용 번호 속성: 작게"
        small_number: bool,
    ) -> f64 {
        let mut y = y_start;
        let stored_prefix = (self.profile.get().hwpx_stored_layout()
            || self.profile.get().hwp5_stored_pagination_layout())
        .then(|| stored_footnote_number_prefix(paragraph, note_number))
        .flatten();
        let number_text = stored_prefix
            .as_ref()
            .map_or(number_text, |(text, _)| text.as_str());
        // 분할 큐는 빈 각주 문단도 한 줄의 virtual fragment로 센다. 실제 composed
        // 줄은 0개이므로 그 범위를 그대로 slice하면 panic 난다. 기존 비분할 경로처럼
        // 빈 문단 fallback까지 흘려보내 번호/높이 계약을 보존한다.
        let line_start = line_start.min(composed.lines.len());
        let line_end = line_end.min(composed.lines.len()).max(line_start);

        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 indent = para_style.map(|style| style.indent).unwrap_or(0.0);

        for (offset, comp_line) in composed.lines[line_start..line_end].iter().enumerate() {
            // 이어받은 쪽에서도 원본 문단 안의 줄 번호로 들여쓰기를 결정한다.
            let line_indent = crate::renderer::equation_tac_flow::paragraph_line_indent_for_source(
                indent,
                line_start + offset,
                Some(paragraph),
                composed.lines.len(),
                true,
                area.width - margin_left - margin_right,
                self.dpi,
            );
            let line_x = area.x + margin_left + line_indent;
            let line_width = (area.width - margin_left - margin_right - line_indent).max(0.0);
            // LineSeg.line_height는 HWP에서 줄간격이 이미 반영된 값.
            // [#5708] 저장 LINE_SEG 가 없는 문단의 폴백(400 HWPUNIT = 5.33px)은 글자보다
            // 작아 줄이 겹치므로 문단 줄간격 설정으로 보정한다.
            let (line_height, corrected_line_spacing) =
                self.footnote_line_metrics(comp_line, composed.para_style_id, styles);
            let raw_baseline = hwpunit_to_px(comp_line.baseline_distance, self.dpi);
            // 베이스라인도 같은 비율로 따라간다 — 줄 상자만 키우면 글자가 상자 위로 뜬다.
            let baseline = if line_height > 0.0
                && raw_baseline > 0.0
                && hwpunit_to_px(comp_line.line_height, self.dpi) > 0.0
            {
                (raw_baseline * line_height / hwpunit_to_px(comp_line.line_height, self.dpi))
                    .min(line_height)
            } else {
                raw_baseline
            };

            let line_id = tree.next_id();
            let mut line_node = RenderNode::new(
                line_id,
                RenderNodeType::TextLine(TextLineNode::new(line_height, baseline)),
                BoundingBox::new(line_x, y, line_width, line_height),
            );

            let mut x = line_x;

            // 첫 줄에 각주 번호 삽입
            if offset == 0 {
                // 각주 번호 스타일: 문단의 기본 char_shape로 고정 (크기 약간 축소)
                // 빈/비빈 문단 모두 동일한 base_cs_id 사용 → 리렌더링 시 폰트·폭 변동 방지
                let base_style = {
                    let mut ts = resolved_to_text_style(styles, base_cs_id, 0);
                    if small_number {
                        ts.font_size = FootnoteMarkerNode::font_size(ts.font_size);
                    } else if stored_prefix.is_none() {
                        ts.font_size = (ts.font_size * 0.9).max(8.0);
                    }
                    ts
                };
                let number_baseline = if small_number {
                    FootnoteMarkerNode::reference_baseline(
                        resolved_to_text_style(styles, base_cs_id, 0).font_size,
                        baseline,
                    )
                } else {
                    baseline
                };

                let num_width = estimate_text_width(number_text, &base_style);
                let num_id = tree.next_id();
                let num_node = RenderNode::new(
                    num_id,
                    RenderNodeType::TextRun(TextRunNode {
                        text: number_text.to_string(),
                        style: base_style,
                        char_shape_id: None,
                        para_shape_id: None,
                        section_index: Some(marker_section),
                        para_index: Some(marker_para),
                        char_start: None, // 번호 run은 char_start 없음
                        cell_context: None,
                        is_para_end: false,
                        is_line_break_end: false,
                        rotation: 0.0,
                        is_vertical: false,
                        char_overlap: None,
                        border_fill_id: 0,
                        baseline: number_baseline,
                        field_marker: FieldMarkerType::None,
                        layout_positions: None,
                        display_text: None,
                    }),
                    BoundingBox::new(x, y, num_width, line_height),
                );
                line_node.children.push(num_node);
                x += num_width;
            }

            // 원본 TextRun들
            let mut char_offset = comp_line.char_start;
            let mut tab_index = composed
                .lines
                .iter()
                .take(line_start + offset)
                .flat_map(|line| line.runs.iter())
                .flat_map(|run| run.text.chars())
                .filter(|&ch| ch == '\t')
                .count();
            for run in &comp_line.runs {
                let mut text_style = run.text_style(styles);
                let skipped = stored_prefix.as_ref().map_or(0, |(_, count)| {
                    count
                        .saturating_sub(char_offset)
                        .min(run.text.chars().count())
                });
                let text = run.text.chars().skip(skipped).collect::<String>();
                if stored_prefix.is_some() {
                    text_style.inline_tabs = composed
                        .tab_extended
                        .iter()
                        .skip(tab_index)
                        .copied()
                        .collect();
                }
                let width = estimate_text_width(&text, &text_style);
                tab_index += run.text.chars().filter(|&ch| ch == '\t').count();

                let run_id = tree.next_id();
                let run_node = RenderNode::new(
                    run_id,
                    RenderNodeType::TextRun(TextRunNode {
                        text,
                        style: text_style,
                        char_shape_id: None,
                        para_shape_id: None,
                        section_index: Some(marker_section),
                        para_index: Some(marker_para),
                        // 번호 대신 그리지 않은 문자는 원본 문단의 주소에는 남는다.
                        char_start: Some(char_offset + skipped),
                        cell_context: None,
                        is_para_end: false,
                        is_line_break_end: false,
                        rotation: 0.0,
                        is_vertical: false,
                        char_overlap: run.char_overlap.clone(),
                        border_fill_id: 0,
                        baseline,
                        field_marker: FieldMarkerType::None,
                        layout_positions: None,
                        display_text: None,
                    }),
                    BoundingBox::new(x, y, width, line_height),
                );
                line_node.children.push(run_node);
                x += width;
                char_offset += run.text.chars().count();
            }

            parent.children.push(line_node);
            // [Issue #483] trailing line_spacing 추가 — layout_composed_paragraph:2560 과 정합.
            // 단, 각주의 마지막 paragraph 의 마지막 line 에서는 trailing line_spacing 을
            // 누적하지 않는다 — 다음 각주와의 간격은 between-notes 값이 책임하므로
            // 이중 합산을 피하기 위함.
            let is_last_line = offset + 1 >= line_end - line_start;
            if is_last_selected_line && is_last_line {
                y += line_height;
            } else {
                let line_spacing_px = corrected_line_spacing;
                y += line_height + line_spacing_px;
            }
        }

        // 빈 문단 fallback
        if composed.lines.is_empty() {
            let default_height = hwpunit_to_px(400, self.dpi);
            let line_id = tree.next_id();
            let line_node = RenderNode::new(
                line_id,
                RenderNodeType::TextLine(TextLineNode::new(default_height, default_height * 0.8)),
                BoundingBox::new(area.x, y, area.width, default_height),
            );
            parent.children.push(line_node);
            y += default_height;
        }

        y
    }

    /// 문단 내 각주/미주 컨트롤에 대해 윗첨자 참조 번호를 렌더링한다.
    ///
    /// 마지막 TextLine의 마지막 TextRun 우측에 윗첨자 번호를 추가한다.
    pub(crate) fn add_footnote_superscripts(
        &self,
        tree: &mut PageLayoutContext,
        parent: &mut RenderNode,
        para: &Paragraph,
        _styles: &ResolvedStyleSet,
    ) {
        // layout_composed_paragraph에서 이미 인라인 FootnoteMarker를 삽입한 경우 건너뜀
        let has_inline_markers = parent.children.iter().any(|line| {
            line.children
                .iter()
                .any(|n| matches!(n.node_type, RenderNodeType::FootnoteMarker(_)))
        });
        if has_inline_markers {
            return;
        }

        // 각주/미주의 (번호, 텍스트 위치) 수집 — ComposedParagraph에서 미리 계산된 위치 사용
        // 폴백: control_text_positions로 직접 계산
        let ctrl_positions = para.control_text_positions();
        let mut footnotes: Vec<(String, usize)> = Vec::new();
        for (ci, ctrl) in para.controls.iter().enumerate() {
            let marker_text = match ctrl {
                Control::Footnote(note) => Some(
                    super::paragraph_layout::note_marker_text_from_control(Some(ctrl), note.number),
                ),
                Control::Endnote(note) => Some(
                    super::paragraph_layout::note_marker_text_from_control(Some(ctrl), note.number),
                ),
                _ => None,
            };
            if let Some(text) = marker_text {
                let pos = ctrl_positions.get(ci).copied().unwrap_or(usize::MAX);
                footnotes.push((text, pos));
            }
        }

        if footnotes.is_empty() {
            return;
        }

        // 각 각주 위첨자를 렌더링: char_start 기반으로 정확한 TextRun 위치에 삽입
        for (_fn_idx, (number_text, char_pos)) in footnotes.iter().enumerate() {
            let mut target_line_idx: Option<usize> = None;
            let mut insert_x = 0.0;
            let mut line_height = 18.0;
            let mut line_y = 0.0;
            let mut base_font_size = 12.0_f64;
            let mut base_font_family = "sans-serif".to_string();

            // TextRun의 char_start로 각주 위치 찾기
            if *char_pos < usize::MAX {
                'outer: for (li, line_node) in parent.children.iter().enumerate() {
                    if !matches!(line_node.node_type, RenderNodeType::TextLine(_)) {
                        continue;
                    }
                    // 이 줄의 char_start 범위 확인: 첫 run의 char_start ~ 마지막 run의 (char_start + len)
                    let mut line_min_cs = usize::MAX;
                    let mut line_max_end = 0usize;
                    for run_node in &line_node.children {
                        if let RenderNodeType::TextRun(ref run) = run_node.node_type {
                            if let Some(cs) = run.char_start {
                                line_min_cs = line_min_cs.min(cs);
                                line_max_end = line_max_end.max(cs + run.text.chars().count());
                            }
                        }
                    }
                    // 각주 위치가 이 줄에 포함되지 않으면 다음 줄
                    if *char_pos > line_max_end || line_min_cs == usize::MAX {
                        continue;
                    }

                    for run_node in &line_node.children {
                        if let RenderNodeType::TextRun(ref run) = run_node.node_type {
                            if let Some(cs) = run.char_start {
                                let run_len = run.text.chars().count();
                                let run_end = cs + run_len;
                                if *char_pos >= cs && *char_pos <= run_end {
                                    let chars_before = char_pos - cs;
                                    let partial_text: String =
                                        run.text.chars().take(chars_before).collect();
                                    let partial_width =
                                        estimate_text_width(&partial_text, &run.style);
                                    insert_x = run_node.bbox.x + partial_width;
                                    line_height = line_node.bbox.height;
                                    line_y = line_node.bbox.y;
                                    base_font_size = run.style.font_size;
                                    base_font_family = run.style.font_family.clone();
                                    target_line_idx = Some(li);
                                    break 'outer;
                                }
                            }
                        }
                    }
                }
            }

            // 최종 폴백: 마지막 TextLine 끝
            if target_line_idx.is_none() {
                if let Some(li) = parent
                    .children
                    .iter()
                    .rposition(|n| matches!(n.node_type, RenderNodeType::TextLine(_)))
                {
                    let line = &parent.children[li];
                    insert_x = line
                        .children
                        .last()
                        .map(|c| c.bbox.x + c.bbox.width)
                        .unwrap_or(line.bbox.x);
                    line_height = line.bbox.height;
                    line_y = line.bbox.y;
                    if let Some(last_run) = line.children.last() {
                        if let RenderNodeType::TextRun(ref run) = last_run.node_type {
                            base_font_size = run.style.font_size;
                            base_font_family = run.style.font_family.clone();
                        }
                    }
                    target_line_idx = Some(li);
                }
            }

            if let Some(line_idx) = target_line_idx {
                let sup_font_size = (base_font_size * 0.6).max(7.0);
                let sup_y_offset = line_height * 0.35;
                let style = TextStyle {
                    font_size: sup_font_size,
                    font_family: base_font_family,
                    ..Default::default()
                };
                let width = estimate_text_width(&number_text, &style);

                let run_id = tree.next_id();
                let run_node = RenderNode::new(
                    run_id,
                    RenderNodeType::TextRun(TextRunNode {
                        text: number_text.clone(),
                        style,
                        char_shape_id: None,
                        para_shape_id: None,
                        section_index: None,
                        para_index: None,
                        char_start: None,
                        cell_context: None,
                        is_para_end: false,
                        is_line_break_end: false,
                        rotation: 0.0,
                        is_vertical: false,
                        char_overlap: None,
                        border_fill_id: 0,
                        baseline: line_height,
                        field_marker: FieldMarkerType::None,
                        layout_positions: None,
                        display_text: None,
                    }),
                    BoundingBox::new(insert_x, line_y - sup_y_offset, width, line_height),
                );

                let line_mut = &mut parent.children[line_idx];
                line_mut.children.push(run_node);
            }
        }
    }
}

fn get_footnote_paragraphs<'a>(
    fn_ref: &FootnoteRef,
    paragraphs: &'a [Paragraph],
) -> &'a [Paragraph] {
    match &fn_ref.source {
        FootnoteSource::Body {
            para_index,
            control_index,
        } => {
            if let Some(para) = paragraphs.get(*para_index) {
                if let Some(Control::Footnote(footnote)) = para.controls.get(*control_index) {
                    return &footnote.paragraphs;
                }
            }
            &[]
        }
        FootnoteSource::TableCell {
            para_index,
            table_control_index,
            cell_index,
            cell_para_index,
            cell_control_index,
        } => {
            if let Some(para) = paragraphs.get(*para_index) {
                if let Some(Control::Table(table)) = para.controls.get(*table_control_index) {
                    if let Some(cell) = table.cells.get(*cell_index) {
                        if let Some(cp) = cell.paragraphs.get(*cell_para_index) {
                            if let Some(Control::Footnote(footnote)) =
                                cp.controls.get(*cell_control_index)
                            {
                                return &footnote.paragraphs;
                            }
                        }
                    }
                }
            }
            &[]
        }
        FootnoteSource::NestedTableCell {
            para_index,
            table_control_index,
            cell_path,
        } => {
            let Some(Control::Table(table)) = paragraphs
                .get(*para_index)
                .and_then(|para| para.controls.get(*table_control_index))
            else {
                return &[];
            };
            let mut table = table.as_ref();
            for (index, entry) in cell_path.iter().enumerate() {
                let Some(control) = table
                    .cells
                    .get(entry.cell_index)
                    .and_then(|cell| cell.paragraphs.get(entry.cell_para_index))
                    .and_then(|para| para.controls.get(entry.control_index))
                else {
                    return &[];
                };
                if index + 1 == cell_path.len() {
                    return match control {
                        Control::Footnote(note) => &note.paragraphs,
                        _ => &[],
                    };
                }
                let Control::Table(child) = control else {
                    return &[];
                };
                table = child;
            }
            &[]
        }
        FootnoteSource::ShapeTextBox {
            para_index,
            shape_control_index,
            tb_para_index,
            tb_control_index,
        } => {
            if let Some(para) = paragraphs.get(*para_index) {
                if let Some(Control::Shape(shape_obj)) = para.controls.get(*shape_control_index) {
                    if let Some(text_box) = shape_obj.drawing().and_then(|d| d.text_box.as_ref()) {
                        if let Some(tp) = text_box.paragraphs.get(*tb_para_index) {
                            if let Some(Control::Footnote(footnote)) =
                                tp.controls.get(*tb_control_index)
                            {
                                return &footnote.paragraphs;
                            }
                        }
                    }
                }
            }
            &[]
        }
    }
}

/// 각주 번호 포맷 (NumberFormat에 따른 변환)
fn format_footnote_number(
    number: u16,
    format: &NumberFormat,
    prefix: char,
    suffix: char,
    user_symbol: char,
) -> String {
    // 본문 각주 표시와 같은 번호 모양 코드(표 134)로 그린다.
    let code = FootnoteShape::number_format_attr_code(*format) as u8;
    let num_str = crate::renderer::note_marker::number_text(number, code, user_symbol);

    let prefix_str = if prefix != '\0' {
        prefix.to_string()
    } else {
        String::new()
    };
    let suffix_str = if suffix != '\0' {
        suffix.to_string()
    } else {
        ")".to_string()
    };

    format!("{}{}{} ", prefix_str, num_str, suffix_str)
}