rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
//! 스타일 해소 (Style Resolution)
//!
//! DocInfo 참조 테이블을 렌더링에서 바로 사용할 수 있는
//! 해소된 스타일 목록(ResolvedStyleSet)으로 변환한다.

use super::{hwpunit_to_px, GradientFillInfo, PatternFillInfo, TabStop};
use crate::model::document::{DocInfo, Document};
use crate::model::image::ImageEffect;
use crate::model::style::{
    Alignment, BorderFill, BorderLine, Bullet, CenterLine, CharShape, DiagonalLine, FillType,
    HeadType, ImageFillMode, LineSpacingType, Numbering, ParaShape, TabDef, UnderlineType,
};
use crate::model::ColorRef;
use crate::renderer::font_rule_layout_name_projection::{
    find_font_rule_layout_name, GeneratedFontRuleProjection,
};

/// HWP 언어 카테고리 수 (한국어, 영어, 한자, 일본어, 기타, 기호, 사용자)
pub const LANG_COUNT: usize = 7;

mod ascii_punctuation;
mod document_font_chain;
mod missing_fonts;
mod original_font_slots;
pub(crate) use missing_fonts::{missing_char_table, missing_latin_default};
mod page_number;
mod resolved;
pub(crate) use crate::storage;
pub use resolved::{
    ResolvedBorderStyle, ResolvedCharStyle, ResolvedImageFill, ResolvedParaStyle, ResolvedStyleSet,
};

/// DocInfo 참조 테이블을 해소된 스타일 목록으로 변환한다.
pub fn resolve_styles(doc_info: &DocInfo, dpi: f64) -> ResolvedStyleSet {
    resolve_styles_with_variant(doc_info, dpi, false)
}

/// Resolve styles with the document's format-specific style normalization.
/// Layout provenance itself remains owned by `LayoutCompatibilityProfile` and
/// is passed separately to consumers that need it.
pub(crate) fn resolve_styles_for_document(document: &Document, dpi: f64) -> ResolvedStyleSet {
    match try_resolve_styles_for_document(document, dpi, &storage::Unbounded) {
        Ok(styles) => styles,
        Err(never) => match never {},
    }
}

/// 문서의 호환 대상이 MS 워드인가. HWP5 는 `HWPTAG_COMPATIBLE_DOCUMENT` 의 대상 프로그램 값
/// (0 = 한/글 현재, 1 = 한/글 2007, 2 = MS 워드), HWPX 는 `hh:compatibleDocument` 의
/// `targetProgram` 이다.
fn doc_targets_ms_word(doc_info: &crate::model::document::DocInfo) -> bool {
    let hwp5_word = doc_info.extra_records.iter().any(|record| {
        record.tag_id == crate::parser::tags::HWPTAG_COMPATIBLE_DOCUMENT
            && record.data.get(..4).is_some_and(|bytes| {
                u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) == 2
            })
    });
    let hwpx_word = doc_info
        .hwpx_head_tail
        .as_deref()
        .is_some_and(|tail| tail.contains(r#"targetProgram="MS_WORD""#));
    hwp5_word || hwpx_word
}

pub(crate) fn try_resolve_styles_for_document<S: storage::Storage>(
    document: &Document,
    dpi: f64,
    storage: &S,
) -> Result<ResolvedStyleSet, S::Error> {
    let profile = document.layout_profile();
    let lookup = missing_fonts::try_lookup_context(document, storage)?;
    let mut styles = try_resolve_styles_with_variant(&lookup, dpi, profile.hwp3_layout(), storage)?;
    styles.source_hwp3_native = profile.hwp3_native_layout();
    styles.word_compat_target = doc_targets_ms_word(&document.doc_info);
    if document.provenance.format == crate::model::provenance::SourceFormat::Hwp5
        && !document.provenance.hwpx_lineage
    {
        // HWP5 FACE_NAME의 속성 하위 비트는 공식 표 20에서 글꼴 유형으로
        // 정의하지 않는다. HWPX의 명시 type과 달리 이 값만으로 실제 TTF를
        // 확정해 같은 family의 HFT 공급 순서를 덮어쓰지 않는다. HWPX에서
        // rhwp가 변환한 문서는 명시적 type을 이 비트에 저장하므로 보존한다.
        for style in &mut styles.char_styles {
            style.font_families_source_ttf.fill(false);
            style.font_families_print_text_device_frame.fill(false);
        }
    }
    if missing_fonts::missing_char_table(document) {
        styles.page_number_char_style_id = Some(0);
        styles.page_number_font_is_hft = false;
    }
    if document.provenance.format == crate::model::provenance::SourceFormat::Hwp5 {
        styles.char_overlap_size_bounds = Some((-8, 2));
    }
    super::legacy_font_advances::select_native_programs(document, &mut styles);
    original_font_slots::refresh(&lookup, &mut styles, storage)?;
    // [#7051] 계보 신호가 없는 저장본의 HFT ASCII 반각 판정은 로드 시 한 번 내려 출처에 둔다.
    styles.hft_ascii_halfwidth |= document.provenance.hft_ascii_halfwidth_witnessed;
    if profile.hwpx_stored_layout() {
        // 같은 14pt 한양신명조라도 일반 본문과 표 안의 공백 조판은 다르다.
        // 검증 HWPX의 일반 본문은 반각, 표 안은 기존 저장 메트릭을 쓴다.
        // 같은 글자 모양이 양쪽에 쓰이면 전역 스타일 보정으로 구분할 수
        // 없으므로 원래 측정을 유지한다.
        let mut body_space_styles = std::collections::HashSet::new();
        let mut table_space_styles = std::collections::HashSet::new();
        for section in &document.sections {
            for para in &section.paragraphs {
                if !para
                    .controls
                    .iter()
                    .any(|control| matches!(control, crate::model::control::Control::Table(_)))
                {
                    collect_paragraph_space_styles(para, &mut body_space_styles);
                }
                for control in &para.controls {
                    if let crate::model::control::Control::Table(table) = control {
                        collect_table_space_styles(table, &mut table_space_styles);
                    }
                }
            }
        }
        for (id, style) in styles.char_styles.iter_mut().enumerate() {
            if body_space_styles.contains(&(id as u32))
                && !table_space_styles.contains(&(id as u32))
                && style.font_size >= 56.0 / 3.0 - 0.01
                && style.font_family.split(',').next() == Some("한양신명조")
                && style.font_space_em.is_none()
            {
                style.font_space_em = Some(0.5);
            }
        }
    }
    Ok(styles)
}

fn collect_paragraph_space_styles(
    para: &crate::model::paragraph::Paragraph,
    ids: &mut std::collections::HashSet<u32>,
) {
    for (index, ch) in para.text.chars().enumerate() {
        if ch == ' ' {
            if let Some(id) = para.char_shape_id_at(index) {
                ids.insert(id);
            }
        }
    }
}

fn collect_table_space_styles(
    table: &crate::model::table::Table,
    ids: &mut std::collections::HashSet<u32>,
) {
    for cell in &table.cells {
        for para in &cell.paragraphs {
            collect_paragraph_space_styles(para, ids);
            for control in &para.controls {
                if let crate::model::control::Control::Table(nested) = control {
                    collect_table_space_styles(nested, ids);
                }
            }
        }
    }
}

/// The environment selects the same final face for measurement and every painter.
pub(crate) fn resolve_styles_with_environment(
    document: &Document,
    dpi: f64,
    environment: Option<&super::font_environment::FontEnvironment>,
    profile: crate::model::provenance::LayoutCompatibilityProfile,
) -> ResolvedStyleSet {
    let mut styles = resolve_styles_for_document(document, dpi);
    styles.inferred_ttf_requires_selection =
        environment.is_some_and(|env| env.explicitly_replaces_source_metrics());
    styles.script_metrics = super::script_metrics::ScriptMetricsContract::for_profile(profile);
    // 독립 동일 입력의 2020은 HCRDotum을 강제하고, 2024는 원 face/대체 face의
    // 자모 전진을 유지한다. 세대는 기존 명시적 출력 profile에서만 받는다.
    styles.isolated_jamo_font = (!profile.hangul2024_layout()
        && document.provenance.format != crate::model::provenance::SourceFormat::Pdf)
        .then_some(crate::renderer::IsolatedJamoFont::HcrDotum);
    if !missing_fonts::missing_char_table(document) {
        (
            styles.page_number_char_style_id,
            styles.page_number_font_is_hft,
        ) = page_number::resolve(&document.doc_info, profile.hangul2024_layout());
    }
    if environment.is_some() {
        let lookup = missing_fonts::lookup_context(document);
        let font_requests = super::font_environment::FontEnvironment::document_requests_with_slots(
            &document.doc_info,
        );
        // 원본 전진 보존 시 표시용 치환을 원본 TTF 프로그램으로 승격하지 않는다.
        // 원본의 별칭과 명시적으로 선택한 TrueType 프로그램은 자연 전진을 소유한다.
        let display_only_fonts: std::collections::HashSet<_> = environment
            .map(|env| {
                font_requests
                    .iter()
                    .filter_map(|(lang, id, request)| {
                        if !env.preserves_source_metrics_for(&request.source) {
                            return None;
                        }
                        let target = env.replacement_for(&request.source, *lang, *id)?;
                        let original = request
                            .primary
                            .iter()
                            .any(|name| name.trim().eq_ignore_ascii_case(target.trim()));
                        (!original && !env.selects_true_type(target)).then_some((*lang, *id))
                    })
                    .collect()
            })
            .unwrap_or_default();
        // 문서에 저장된 대체 글꼴은 실제 선택한 HFT 프로그램의 문장부호 계약을
        // 소유한다. 미지정 글꼴에 임의로 공급한 표시용 웹폰트와 구분한다.
        let selected_source_programs: std::collections::HashSet<_> = environment
            .map(|env| {
                font_requests
                    .iter()
                    .filter_map(|(lang, id, request)| {
                        let query = env.selected_program_query_for(&request.source, *lang, *id)?;
                        request
                            .primary
                            .iter()
                            .chain(request.substitute.iter())
                            .any(|name| name == query)
                            .then_some((*lang, *id))
                    })
                    .collect()
            })
            .unwrap_or_default();
        let selected_primary_programs: std::collections::HashMap<_, _> = environment
            .map(|env| {
                font_requests
                    .iter()
                    .filter_map(|(lang, id, request)| {
                        let query = env.selected_program_query_for(&request.source, *lang, *id)?;
                        request
                            .primary
                            .iter()
                            .any(|name| name == query)
                            .then_some(())?;
                        Some((
                            (*lang, *id),
                            env.selected_program_identity_for(&request.source, *lang, *id)?,
                        ))
                    })
                    .collect()
            })
            .unwrap_or_default();
        let mut display_only_slots = std::collections::HashSet::new();
        for (style_id, (style, shape)) in styles
            .char_styles
            .iter_mut()
            .zip(&document.doc_info.char_shapes)
            .enumerate()
        {
            let mut latin_program_changed = false;
            for lang in 0..LANG_COUNT {
                style.font_families_primary_program[lang] = selected_primary_programs
                    .get(&(lang, shape.font_ids[lang]))
                    .copied();
                if style.source_ttf_for_lang(lang)
                    && display_only_fonts.contains(&(lang, shape.font_ids[lang]))
                {
                    display_only_slots.insert((style_id as u32, lang));
                }
                let decision = lookup_font_name_in_environment(
                    &lookup,
                    lang,
                    shape.font_ids[lang],
                    environment,
                );
                if decision.environment_profile_id.is_some() {
                    let source_metric_face = style.font_families_metric_face[lang]
                        .as_deref()
                        .unwrap_or_else(|| primary_font_name(&style.font_families[lang]))
                        .to_owned();
                    style.font_families[lang] = decision.css_family_chain.join(",");
                    style.font_families_glyph_fallback_advance_explicit[lang] = decision.embedded
                        != Some(true)
                        && environment.is_some_and(|env| {
                            decision
                                .normalized_face
                                .as_deref()
                                .and_then(|face| {
                                    decision.requested_face.as_deref().and_then(|source| {
                                        env.glyph_fallbacks_for_slot(
                                            source,
                                            face,
                                            lang,
                                            shape.font_ids[lang],
                                        )
                                    })
                                })
                                .is_some()
                        });
                    if display_only_fonts.contains(&(lang, shape.font_ids[lang]))
                        && !selected_source_programs.contains(&(lang, shape.font_ids[lang]))
                    {
                        // 표시용 치환은 원본 TTF/HFT의 폭 표와 추정 규칙을 바꾸지 않는다.
                        // family를 먼저 바꾸면 숫자·영문 슬롯까지 대체 face의 반각
                        // 추정으로 떨어지므로, 치환 전 실제 측정 face와 신뢰·프레임을
                        // 함께 보존한다. 명시적으로 선택한 프로그램은 아래에서 처리한다.
                        style.font_families_metric_face[lang] = Some(source_metric_face);
                        continue;
                    }
                    // 명시적 프로그램 선택과 독립적으로 검증한 글리프 표가 모두 있어야
                    // TrueType 폭을 사용한다. 선언만으로 임의 face의 표를 신뢰하지 않는다.
                    // 실제 face 조회 이름과 환경의 논리 family를 구분한다. 프로그램
                    // 메타데이터는 family에 묶고 paint는 선택한 face를 먼저 조회한다.
                    let target = decision
                        .normalized_face
                        .as_deref()
                        .unwrap_or_else(|| primary_font_name(&style.font_families[lang]));
                    let original = lookup_font_name_decision(&lookup, lang, shape.font_ids[lang]);
                    let preserve_source_metrics = environment.is_some_and(|env| {
                        original.requested_face.as_deref().map_or_else(
                            || env.preserves_source_metrics(),
                            |source| env.preserves_source_metrics_for(source),
                        )
                    });
                    // 같은 이름의 실제 주 TrueType 프로그램은 표시용 대체가 아니다.
                    // 검증된 폭과 실제 선택을 확인한 경우 그 프로그램이 전진을 소유한다.
                    // 원 HFT 프로그램 출처가 있거나 치환 경계를 건넌 대체 face는 보존한다.
                    let source_font = document
                        .doc_info
                        .font_faces
                        .get(lang)
                        .and_then(|faces| faces.get(shape.font_ids[lang] as usize));
                    // 같은 원본 프로그램의 존재 확인·family 별칭은 HFT 종이 프레임을
                    // 버리는 요청이 아니다. 초기 미설치 fallback에서 잃은 프레임도 복원한다.
                    // 대체 프로그램 조회·내장 face·자연 전진 선택은 이 인증에 포함하지 않는다.
                    if preserve_source_metrics
                        && original.alt_type == Some(2)
                        && original.embedded != Some(true)
                        && source_font.is_some_and(|face| face.native_program.is_none())
                        && style.font_families_primary_program[lang].is_some()
                    {
                        style.font_families_hft_print_frame[lang] = true;
                    }
                    // 실제 원본 TTF를 조회해 인증한 family 별칭은 기존 폭 신뢰를
                    // 잃지 않는다. 대체 쿼리·HFT·다른 메트릭의 선택은 포함하지 않는다.
                    let verified_source_alias = original.substitution_boundary.is_none()
                        && original.alt_type == Some(1)
                        && style.font_families_metric_trusted[lang]
                        && original.requested_face.as_deref().is_some_and(|source| {
                            environment.is_some_and(|env| {
                                env.selected_program_query_for(source, lang, shape.font_ids[lang])
                                    == Some(source)
                            }) && primary_font_name(&style.font_families[lang]) == source
                                && original_font_slots::keeps_source_metric_table(
                                    source,
                                    &source_metric_face,
                                    target,
                                    style.bold,
                                    style.italic,
                                )
                        });
                    let primary_true_type_program = environment
                        .is_some_and(|env| env.selects_true_type(target))
                        && original.substitution_boundary.is_none()
                        && (original.normalized_face.as_deref() == Some(target)
                            || verified_source_alias)
                        && source_font.is_some_and(|face| face.native_program.is_none())
                        && (metric_widths_verified_face(target)
                            || verified_source_alias
                            || matches!(target, "휴먼명조" | "HumanMyeongJo"));
                    // 원문 유형 선언이나 자동 대체만으로 text device 좌표를
                    // 부여하지 않는다. 실제 원 primary를 선택한 세션만 같은
                    // 자격을 사용하며 원문의 source_ttf는 변경하지 않는다.
                    if preserve_source_metrics
                        && original.embedded != Some(true)
                        && primary_true_type_program
                    {
                        style.font_families_print_text_device_frame[lang] = true;
                    }
                    // 자동 표시용 선택은 저장된 원본 HFT 메트릭의 변경이 아니다.
                    let keep_source_metrics = !primary_true_type_program
                        && preserve_source_metrics
                        && (original.alt_type == Some(2)
                            || style.font_families_source_hft[lang])
                        && original.embedded != Some(true)
                        && original.requested_face.as_deref().is_some_and(|face| {
                            crate::renderer::font_metrics_data::legacy_hft_metric_face(face).is_some()
                                || has_own_metric_table(&face, style.bold, style.italic)
                                || crate::renderer::font_metrics_data::has_declared_original_glyph_metrics(face)
                        });
                    if keep_source_metrics
                        && source_font.is_none_or(|face| face.native_program.is_none())
                    {
                        style.font_families_metric_face[lang] = original
                            .requested_face
                            .as_deref()
                            .and_then(|face| {
                                crate::renderer::font_metrics_data::legacy_hft_metric_face(face)
                                    .or_else(|| {
                                        has_own_metric_table(&face, style.bold, style.italic)
                                            .then_some(face)
                                    })
                            })
                            .map(str::to_owned);
                    }
                    let explicit_true_type = !keep_source_metrics
                        && environment.is_some_and(|env| env.selects_true_type(target));
                    let explicit_replacement = environment.is_some_and(|env| {
                        decision
                            .requested_face
                            .as_deref()
                            .is_some_and(|face| env.replacement(face).is_some())
                    });
                    // 기존 명시 공급의 윤곽은 전진 칸에 눌러 그리지 않는다(#8188).
                    // 생략된 설정의 기존 전진/leader와 명시 자연 전진은 별도로 선택한다.
                    style.font_families_preserve_glyph_ink[lang] =
                        (explicit_true_type || explicit_replacement) && !preserve_source_metrics;
                    style.font_families_natural_program_metrics[lang] = style
                        .font_families_preserve_glyph_ink[lang]
                        && environment.is_some_and(|env| {
                            original
                                .requested_face
                                .as_deref()
                                .is_some_and(|source| env.selects_natural_program_for(source))
                        });
                    // 프로그램·메트릭을 직접 선택한 자연 잉크에 이전 슬롯의
                    // HFT 종이 프레임을 상속하지 않는다. 원본 메트릭을 유지하는
                    // 자동 표시용 공급은 기존 인쇄 프레임을 그대로 소비한다.
                    if style.font_families_preserve_glyph_ink[lang] {
                        style.font_families_hft_print_frame[lang] = false;
                        style.font_families_print_text_device_frame[lang] = false;
                    }
                    // 결측 글리프 체인만 추가한 세션은 원 face의 TTF/HFT 신뢰를 바꾸지 않는다.
                    if !keep_source_metrics && (explicit_true_type || explicit_replacement) {
                        latin_program_changed |= lang == 1;
                        style.font_families_metric_trusted[lang] = explicit_true_type
                            && (metric_widths_verified_face(target)
                                || verified_source_alias
                                || matches!(target, "휴먼명조" | "HumanMyeongJo"));
                    }
                    if explicit_true_type {
                        style.font_families_hft_hangul[lang] = false;
                        style.font_families_hft_fullwidth_dot[lang] = false;
                        style.font_families_metric_face[lang] = None;
                        // 같은 주 프로그램의 가용성 인증은 저장 HFT의 물리 Print
                        // 종이 프레임을 바꾸는 요청이 아니다. 전진 프로그램과
                        // source가 소유한 paint 프레임을 별개로 보존한다.
                        if !primary_true_type_program || !preserve_source_metrics {
                            style.font_families_hft_print_frame[lang] = false;
                        }
                        style.font_families_original_glyph_metric_face[lang] = None;
                    } else if explicit_replacement {
                        // TTF로 기록한 옛 face도 호출자가 원 HFT 프로그램을
                        // 공급하면 그 프로그램의 폭을 사용한다. 독립 2020 Print의
                        // TTF 선언 한양신명조도 U+2024를 같은 Type3 전각으로 그린다.
                        // 원본 선언(source_hft)은 바꾸지 않는다.
                        if let Some(metric) =
                            super::font_metrics_data::legacy_hft_metric_face(target)
                        {
                            style.font_families_metric_face[lang] = Some(metric.to_owned());
                            style.font_families_hft_fullwidth_dot[lang] = true;
                        }
                    }
                }
            }
            style.font_family = style.font_families[0].clone();
            if latin_program_changed {
                style.font_space_em = resolved_space_advance_em(
                    shape.use_font_space,
                    &style.font_families,
                    &style.font_families_original_glyph_metric_face,
                    style.bold,
                    style.italic,
                );
            }
        }
        styles.display_only_otf_slots = std::sync::Arc::new(display_only_slots);
    }
    match original_font_slots::refresh(&document.doc_info, &mut styles, &storage::Unbounded) {
        Ok(()) => (),
        Err(never) => match never {},
    }
    match refresh_source_program_projection_slots_with_storage(
        &document.doc_info,
        &mut styles,
        &storage::Unbounded,
    ) {
        Ok(()) => (),
        Err(never) => match never {},
    }
    // 쪽번호도 명시적으로 공급한 원 HFT 폭 표를 소비한다. TTF로 적힌
    // 한양신명조를 원 프로그램으로 선택했는데 원 선언만 보면, 폭은 HFT로
    // 재면서 기준선은 TTF의 1/3em 여유를 적용해 위로 이동한다.
    if let Some(style) = styles
        .page_number_char_style_id
        .and_then(|id| styles.char_styles.get(id))
    {
        styles.page_number_font_is_hft |= style
            .metric_face_for_lang(1)
            .is_some_and(super::font_metrics_data::is_legacy_hft_metric_face);
    }
    styles
}

/// [Task #1001] HWP3 → HWP5 변환본 인지하여 ParaShape spacing/margin 추가 보정.
/// 변환본의 ParaShape 단위는 일반 HWP5 의 2배 (HwpUnitChar / HWPUNIT 의 2배 스케일)
/// 이므로 추가 1/2 보정 적용. 호출자가 Document::is_hwp3_variant 를 전달.
pub fn resolve_styles_with_variant(
    doc_info: &DocInfo,
    dpi: f64,
    is_hwp3_variant: bool,
) -> ResolvedStyleSet {
    match try_resolve_styles_with_variant(doc_info, dpi, is_hwp3_variant, &storage::Unbounded) {
        Ok(styles) => styles,
        Err(never) => match never {},
    }
}

fn try_resolve_styles_with_variant<S: storage::Storage>(
    doc_info: &DocInfo,
    dpi: f64,
    is_hwp3_variant: bool,
    storage: &S,
) -> Result<ResolvedStyleSet, S::Error> {
    let mut char_styles = storage.vec(doc_info.char_shapes.len())?;
    for shape in &doc_info.char_shapes {
        char_styles.push(try_resolve_single_char_style(
            shape, doc_info, dpi, storage,
        )?);
    }
    let mut para_styles = storage.vec(doc_info.para_shapes.len())?;
    let char_unit_hu = para_margin_char_unit_hu(doc_info);
    for shape in &doc_info.para_shapes {
        para_styles.push(try_resolve_single_para_style(
            shape,
            &doc_info.tab_defs,
            dpi,
            is_hwp3_variant,
            char_unit_hu,
            storage,
        )?);
    }
    let mut border_styles = storage.vec(doc_info.border_fills.len())?;
    for fill in &doc_info.border_fills {
        border_styles.push(try_resolve_single_border_style(fill, dpi, storage)?);
    }
    let numberings = storage.clone_record(&doc_info.numberings)?;
    let bullets = storage.clone_record(&doc_info.bullets)?;
    storage.bytes(
        2 * std::mem::size_of::<usize>()
            + std::mem::size_of::<super::native_pua_fonts::NativePuaFonts>(),
    )?;
    let (page_number_char_style_id, page_number_font_is_hft) =
        page_number::resolve(doc_info, false);

    let mut styles = ResolvedStyleSet {
        source_hwp3_native: false,
        word_compat_target: false,
        source_program_projection_slots: Default::default(),
        script_metrics: Default::default(),
        native_pua_fonts: Default::default(),
        display_only_otf_slots: Default::default(),
        inferred_ttf_requires_selection: false,
        unsubstituted_font_slots: Default::default(),
        char_overlap_size_bounds: None,
        source_char_shapes: {
            storage.bytes(
                2 * std::mem::size_of::<usize>()
                    + std::mem::size_of_val(doc_info.char_shapes.as_slice()),
            )?;
            storage
                .try_collect(doc_info.char_shapes.iter().map(|source| {
                    if let Some(raw) = &source.raw_data {
                        storage.bytes(raw.len())?;
                    }
                    let mut shape = storage.clone_record(source)?;
                    shape.raw_data = None;
                    Ok(shape)
                }))?
                .into()
        },
        section_tab_width_bits: {
            storage.bytes(2 * std::mem::size_of::<usize>() + std::mem::size_of::<u64>())?;
            Default::default()
        },
        resolved_dpi: Some(dpi),
        isolated_jamo_font: None,
        page_number_char_style_id,
        page_number_font_is_hft,
        style_char_shapes: storage.try_collect(
            doc_info
                .styles
                .iter()
                .map(|style| Ok(u32::from(style.char_shape_id))),
        )?,
        char_styles,
        para_styles,
        border_styles,
        numberings,
        bullets,
        hwp3_variant: is_hwp3_variant,
        hft_ascii_halfwidth: is_hwp3_variant,
        kerning_measurement_context: None,
        horizontal_shaping_context: None,
        supplemental_metrics: None,
    };
    original_font_slots::refresh(doc_info, &mut styles, storage)?;
    refresh_source_program_projection_slots_with_storage(doc_info, &mut styles, storage)?;
    Ok(styles)
}

/// 한/글이 저장 줄을 그대로 쓰는 변경 추적 설정 비트 (#8639 실측).
const TRACK_CHANGE_KEEPS_STORED_ROWS: u32 = 0x08;

/// 대체 선언과 실제 선택을 구분한다. HFT의 원본 전진, 내장 프로그램,
/// 실제 대체 face 및 폭을 추정하는 face를 원본 TTF의 캐시 갱신 근거로 쓰지 않는다.
fn refresh_source_program_projection_slots_with_storage<S: storage::Storage>(
    doc_info: &DocInfo,
    styles: &mut ResolvedStyleSet,
    storage: &S,
) -> Result<(), S::Error> {
    styles.source_program_projection_slots = Default::default();
    // [#8639] 한/글은 변경 추적 설정(`HWPTAG_TRACKCHANGE` · `<hh:trackchageConfig flags>`)에
    // 0x08 이 있으면 가로 상자가 같은 저장 줄을 그대로 쓰고, 없을 때만 현재 글꼴로 다시
    // 조판한다. 한/글 2020·2024 Print 실측: 86712(flags 0)는 표·문단만 남겨도 재조판하고
    // flags 를 8 로 바꾸면 저장 줄을 유지한다. 반대로 정책연구과제심의신청서(flags 56)는
    // 저장 줄을 유지하고 flags 를 0 으로 바꾸면 원본 KoPub 으로 재조판한다(16·32 는 무관).
    // 저장 줄이 유지되는 문서에서 원본 프로그램으로 다시 짜면 한/글과 어긋난다.
    if doc_info.track_change_flags() & TRACK_CHANGE_KEEPS_STORED_ROWS != 0 {
        return Ok(());
    }
    let dpi = styles.resolved_dpi.unwrap_or(96.0);
    let mut fallback_char_styles = None;
    let mut build_fallback = || -> Result<Vec<ResolvedCharStyle>, S::Error> {
        let mut fallback_info = storage.clone_doc_info(doc_info)?;
        for fonts in &mut fallback_info.font_faces {
            for font in fonts {
                if let Some(substitute) = font.subst_font.take() {
                    if substitute.font_type == 1 && !substitute.face.trim().is_empty() {
                        font.name = substitute.face;
                    }
                }
            }
        }
        storage.try_collect(
            fallback_info
                .char_shapes
                .iter()
                .map(|cs| try_resolve_single_char_style(cs, &fallback_info, dpi, storage)),
        )
    };
    for (shape_id, shape) in doc_info.char_shapes.iter().enumerate() {
        let Some(style) = styles.char_styles.get(shape_id) else {
            continue;
        };
        for language in 0..LANG_COUNT {
            let Some(font) = doc_info
                .font_faces
                .get(language)
                .and_then(|fonts| fonts.get(shape.font_ids[language] as usize))
            else {
                continue;
            };
            let primary = primary_font_name(style.font_family_for_lang(language));
            if font.alt_type != 1
                || font.is_embedded
                || font.native_program.is_some()
                // 같은 SFNT의 name 6 조회 이름으로 바뀐 것은 다른 원본을
                // 선택한 것이 아니다. 굵기별 설치 별칭의 동일성만 허용한다.
                || (primary != font.name.trim()
                    && !super::installed_font_program_aliases(font.name.trim()).contains(&primary))
                || !font.subst_font.as_ref().is_some_and(|substitute| {
                    substitute.font_type == 1
                        && !substitute.face.trim().is_empty()
                        && substitute.face.trim() != primary
                })
                || style.metric_face_for_lang(language).is_some()
                || style
                    .original_glyph_metric_face_for_lang(language)
                    .is_some()
            {
                continue;
            }
            // 원본 프로그램의 전진폭이 검증된 경우에만 저장 줄을 다시 구성한다.
            if style.font_metric_trusted_for_lang(language)
                || super::layout::verified_source_projection_face(primary, style.bold, style.italic)
            {
                if fallback_char_styles.is_none() {
                    fallback_char_styles = Some(build_fallback()?);
                }
                if let Some(fallback) = fallback_char_styles
                    .as_ref()
                    .and_then(|values| values.get(shape_id))
                {
                    let copied = crate::storage::try_clone(fallback, storage)?;
                    storage.insert_map(
                        std::sync::Arc::make_mut(&mut styles.source_program_projection_slots),
                        (shape_id as u32, language),
                        copied,
                    )?;
                }
            }
        }
    }
    Ok(())
}

/// [#7391] 이 face 이름으로 **자기 자신의** 메트릭 표를 찾을 수 있는지.
///
/// 별칭(`layout-metric` 평면)을 타고 남의 표를 빌려 오는 경우는 거짓이다 — 그건
/// 치환 대상의 표와 다를 바 없어서 되돌릴 근거가 못 된다.
/// [#7702] rhwp 의 폭 표가 한/글 **HFT 글리프**를 잰 값인 face.
///
/// 전체 HFT 표는 HFT 선언에서 사용한다. type1에서도 독립 Print가 확인한 원본
/// 글리프는 개별 폭 경로로 보존하며, 그 증거를 전체 ASCII 표의 승격으로 넓히지 않는다.
///
/// ```text
///   HCI Poppy  alt_type=2  k-water-rfp 등 50여 문서   정본 `·` = Type3 0.38 em
///              alt_type=1  76076·80168 HWP (대체 Palatino Linotype)   정본 `·` = Palatino 0.25 em
///              alt_type=1  80168 구판 HWPX (대체 TTF 없음)   정본 Type3 `·` = 0.384 em
/// ```
fn hft_program_metric_face(face: &&str) -> bool {
    *face == "HCI Poppy"
}

fn has_own_metric_table(face: &&str, bold: bool, italic: bool) -> bool {
    if *face == "HCI Tulip" {
        return true;
    }
    crate::renderer::font_metrics_data::find_metric_decision(face, bold, italic).is_some_and(
        |decision| {
            decision.alias_rule_id.is_none()
                && decision.metric.bold == bold
                && decision.metric.italic == italic
        },
    )
}

/// [#7092] 한/글이 선언 face 대신 **문서가 적은 대체 TTF** 로 그리는 경우, 그 대체 글꼴.
///
/// 한양 계열 이름(`한양중고딕`·`한양신명조`)을 TTF 로 선언한 문서는 같은 이름의 TTF 가 없어
/// 한/글이 대체 글꼴 자리를 본다. 대체가 **TTF `HY중고딕`·`HY신명조`** 면 그 TrueType 으로
/// 그리고(정본 PDF 의 `H2gtrM`·`H2mjsM` 자원, `·` 1.0em), 대체가 HFT(같은 이름) 이거나
/// 없으면 자기 HFT 글리프로 그린다(Type3 자원, `·` 0.38em). 저장소 정본 전수(한양중고딕
/// 선언 TTF 문서)에서 대체 `HY중고딕` 5문서는 전부 `H2gtrM`, 대체 HFT `한양중고딕`
/// 9개 출력은 전부 Type3 이고 반례가 없다 — 같은 문서를 2020·2024 엔진으로 뽑아도 같다.
///
/// ```text
///   78494 · issue1891_external_bindata_link · 75544 · 80550 · regulatory_impact_nested_table_escape
///       한양중고딕 TTF, 대체 TTF HY중고딕      → 정본 H2gtrM  · 1.000~1.010em (n=61·14·26·5·5)
///   80168(2020·2022·2024 출력) · 86712
///       한양중고딕 TTF, 대체 HFT 한양중고딕     → 정본 Type3   · 0.381~0.386em
/// ```
///
/// 두 형식 모두 `subst_font`(HWP5 `FACE_NAME` 의 대체 글꼴·유형, HWPX `<hh:substFont>`)를
/// 보고, 대체가 HFT·임베드가 아니면서 **대체 face 이름이 글꼴 파일로 검증한 TTF 표**
/// ([`metric_widths_verified_face`])인지로 가른다. 같은 이름의 HFT 대체(`한양중고딕`→
/// `한양중고딕`)와 검증되지 않은 대체(`한컴바탕`)는 여기 걸리지 않아 종전 HFT 실측 표
/// (`font_metrics_overlays`)를 그대로 쓴다. 결과는 측정 face(`font_families_metric_face`)와
/// 신뢰 여부에만 쓰고 표시 체인은 바꾸지 않는다.
fn verified_ttf_substitute(font: &crate::model::style::Font) -> Option<&str> {
    if font.alt_type != 1 {
        return None;
    }
    let substitute = match (&font.subst_font, &font.alt_name) {
        (Some(subst), _) => (subst.font_type != 2 && !subst.is_embedded).then(|| subst.face.trim()),
        (None, Some(alt_name)) => Some(alt_name.trim()),
        (None, None) => None,
    }?;
    (!substitute.is_empty()
        && substitute != font.name.trim()
        && metric_widths_verified_face(substitute))
    .then_some(substitute)
}

/// [#7387] CSS 체인의 첫 face 가 **선언한** 공백 글리프 전진폭(em).
///
/// 공백을 반각으로 눌러 두는 [`measure_char_width_embedded_decision_for_font`] 의
/// `c == ' '` 갈래를 우회해, 글꼴 표에 적힌 U+0020 의 값을 그대로 읽는다.
/// `use_font_space` 가 켜진 run 에서만 쓴다.
///
/// [`measure_char_width_embedded_decision_for_font`]: crate::renderer::layout
pub(crate) fn declared_space_advance_em(
    css_family_chain: &str,
    bold: bool,
    italic: bool,
) -> Option<f64> {
    let primary = css_family_chain
        .split(',')
        .next()?
        .trim()
        .trim_matches('\'')
        .trim_matches('"');
    // KoPub 은 메트릭 DB 가 아니라 전용 표가 폭을 소유한다 — 같은 출처에서 공백을 읽는다.
    if let Some(em) = crate::renderer::layout::kopub_declared_space_em(primary) {
        return Some(em);
    }
    let decision = crate::renderer::font_metrics_data::find_metric_decision(primary, bold, italic)?;
    let em = decision.metric.em_size;
    if em == 0 {
        return None;
    }
    let width = decision.metric.get_width(' ')?;
    if width == 0 {
        return None;
    }
    Some(f64::from(width) / f64::from(em))
}

/// 일반 해소와 명시적 프로그램 변경은 같은 최종 공급자의 공백을 소비한다.
fn resolved_space_advance_em(
    use_font_space: bool,
    families: &[String],
    original_glyph_faces: &[Option<String>],
    bold: bool,
    italic: bool,
) -> Option<f64> {
    use_font_space
        .then(|| {
            original_glyph_faces
                .get(1)
                .and_then(Option::as_deref)
                .and_then(|face| {
                    crate::renderer::font_metrics_data::declared_original_glyph_advance_em(
                        face, bold, italic, ' ',
                    )
                })
                .or_else(|| {
                    families
                        .get(1)
                        .and_then(|chain| declared_space_advance_em(chain, bold, italic))
                })
        })
        .flatten()
}

/// CharShape + FontFace → ResolvedCharStyle 목록
fn resolve_char_styles(doc_info: &DocInfo, dpi: f64) -> Vec<ResolvedCharStyle> {
    doc_info
        .char_shapes
        .iter()
        .map(|cs| resolve_single_char_style(cs, doc_info, dpi))
        .collect()
}

/// 개별 CharShape 해소
fn resolve_single_char_style(cs: &CharShape, doc_info: &DocInfo, dpi: f64) -> ResolvedCharStyle {
    match try_resolve_single_char_style(cs, doc_info, dpi, &storage::Unbounded) {
        Ok(style) => style,
        Err(never) => match never {},
    }
}

pub(crate) fn try_resolve_single_char_style<A: storage::Storage>(
    cs: &CharShape,
    doc_info: &DocInfo,
    dpi: f64,
    storage: &A,
) -> Result<ResolvedCharStyle, A::Error> {
    // base_size는 HWPUNIT 단위
    let font_size = hwpunit_to_px(cs.base_size, dpi);

    // 7개 언어 카테고리별 폰트 이름, 자간, 장평 해소
    let mut font_families = storage.vec(LANG_COUNT)?;
    let mut font_families_metric_trusted = storage.vec(LANG_COUNT)?;
    let mut font_families_glyph_fallback_advance_explicit = storage.vec(LANG_COUNT)?;
    let mut font_families_hft_hangul = storage.vec(LANG_COUNT)?;
    let mut font_families_source_hft = storage.vec(LANG_COUNT)?;
    let mut font_families_source_ttf = storage.vec(LANG_COUNT)?;
    let mut font_families_verified_hft_bold_tracking = storage.vec(LANG_COUNT)?;
    let mut font_families_hft_print_frame = storage.vec(LANG_COUNT)?;
    let mut font_families_print_text_device_frame = storage.vec(LANG_COUNT)?;
    let mut font_families_hft_fullwidth_dot = storage.vec(LANG_COUNT)?;
    let mut font_families_metric_face: Vec<Option<String>> = storage.vec(LANG_COUNT)?;
    let mut font_families_original_glyph_metric_face = storage.vec(LANG_COUNT)?;
    let mut letter_spacings = storage.vec(LANG_COUNT)?;
    let mut ratios = storage.vec(LANG_COUNT)?;
    let mut font_sizes = storage.vec(LANG_COUNT)?;
    let latin_slot_legacy = false;
    let mut latin_declared_hft = false;
    let latin_slot_explicit = false;

    for lang in 0..LANG_COUNT {
        let font_id = cs.font_ids[lang];
        let source_font = doc_info
            .font_faces
            .get(lang)
            .and_then(|faces| faces.get(font_id as usize));
        font_families_source_hft.push(source_font.is_some_and(|face| face.alt_type == 2));
        font_families_source_ttf.push(source_font.is_some_and(|face| face.alt_type == 1));
        font_families_verified_hft_bold_tracking.push(source_font.is_some_and(
            crate::renderer::legacy_font_advances::has_verified_hft_bold_tracking_source,
        ));
        let decision = try_lookup_font_name_decision(doc_info, lang, font_id, storage)?;
        let substituted = decision.substitution_boundary.is_some()
            && decision.normalized_face != decision.requested_face;
        // 대체 후보의 선언과 실제 주 공급자의 선택은 구분한다.
        // 현재 해소 결과가 선택한 TTF만 원본 프로그램의 전진폭을 대체한다.
        let document_true_type_substitute = source_font.is_some_and(|face| {
            face.alt_type == 1
                && face.subst_font.as_ref().is_some_and(|substitute| {
                    let name = substitute.face.trim();
                    substitute.font_type == 1
                        && !name.is_empty()
                        && decision.normalized_face.as_deref()
                            == Some(
                                resolve_font_substitution_decision(
                                    name,
                                    substitute.font_type,
                                    lang,
                                )
                                .map(|(resolved, _, _)| resolved)
                                .unwrap_or(name),
                            )
                })
        });
        if lang == 1 {
            latin_declared_hft = decision.alt_type == Some(2) && !substituted;
        }
        // [#7092] 문서가 적은 대체 TTF 로 한/글이 실제로 그리는 face — 폭 표도 그 글꼴을 쓴다.
        let substitute_ttf = doc_info
            .font_faces
            .get(lang)
            .and_then(|faces| faces.get(font_id as usize))
            .and_then(verified_ttf_substitute);
        font_families_metric_trusted.push(
            substitute_ttf.is_some()
                || (decision.alt_type == Some(1)
                    && !substituted
                    && decision
                        .requested_face
                        .as_deref()
                        .is_some_and(metric_widths_verified_face)),
        );
        font_families_glyph_fallback_advance_explicit.push(false);
        font_families_hft_hangul
            .push(decision.substitution_boundary == Some(FontSubstitutionBoundary::Hft));
        font_families_hft_fullwidth_dot.push(decision.alt_type == Some(2) && !substituted);
        // 원 HFT의 그래픽 프레임과 TTF text device 프레임을 분리한다.
        // 표시 치환은 원문 유형을 바꾸지 않는다. HWP3의 유형 미상 HFT
        // 추론도 보존하며 실제 세션 TTF 선택은 환경 적용 단계에서 해소한다.
        font_families_hft_print_frame
            .push(decision.alt_type == Some(2) && !substituted && decision.embedded != Some(true));
        // 실제 프로그램 선택은 environment 단계에서 확인한다. 명시 TTF
        // 이름도 같은 이름의 CFF·대체 프로그램을 증명하지 않는다.
        font_families_print_text_device_frame.push(false);
        // [#7391] legacy-latin은 선언 face의 기존 표를 사용한다. HFT는
        // 프로그램 자체를 확인한 표만 사용하며 표시용 TTF와 구분한다.
        // HWP3 ASCII 반각 여부는 기존 문서의 저장 줄 증인이 계속 결정한다.
        font_families_metric_face.push(if let Some(face) = substitute_ttf {
            Some(storage.string(face)?)
        } else if decision.alt_type == Some(2)
            && decision.requested_face.as_deref().is_some_and(|face| {
                crate::renderer::font_metrics_data::legacy_hft_metric_face(face).is_some()
            })
        {
            // 표시 이름의 치환 여부와 원본 HFT 프로그램의 폭은 별개다.
            decision
                .requested_face
                .as_deref()
                .and_then(crate::renderer::font_metrics_data::legacy_hft_metric_face)
                .map(|face| storage.string(face))
                .transpose()?
        } else {
            (decision.substitution_boundary == Some(FontSubstitutionBoundary::LegacyLatin))
                .then(|| {
                    decision
                        .requested_face
                        .as_deref()
                        .filter(|face| has_own_metric_table(face, cs.bold, cs.italic))
                        .filter(|face| {
                            // type1에서 확인한 원본 글리프는 아래의 개별 폭 경로가
                            // 소유한다. 전체 HFT 표의 승격은 미측정 ASCII도 바꾼다.
                            decision.alt_type == Some(2) || !hft_program_metric_face(face)
                        })
                })
                .flatten()
                .map(|face| storage.string(face))
                .transpose()?
        });
        // 선택되지 않은 대체 후보가 있는 type1도 원본 HFT 글리프를 쓸 수 있다.
        // 실제 선택한 TTF 대체 프로그램은 자기 전진폭을 소유한다. 전체 HFT 표 선택과
        // 실제 type2의 부분 폭은 보존하고 내장 글꼴·호출자 TTF 환경은 승격하지 않는다.
        font_families_original_glyph_metric_face.push(
            (!document_true_type_substitute
                && decision.embedded != Some(true)
                && (decision.substitution_boundary == Some(FontSubstitutionBoundary::LegacyLatin)
                    || decision.alt_type == Some(2)))
            .then(|| {
                decision
                    .requested_face
                    .as_deref()
                    .filter(|face| {
                        crate::renderer::font_metrics_data::has_declared_original_glyph_metrics(
                            face,
                        )
                    })
                    .map(|face| storage.string(face))
            })
            .flatten()
            .transpose()?,
        );
        font_families.push(storage.join(&decision.css_family_chain, ",")?);

        // 굵기의 추가 전진은 측정에서 별도로 소비한다. 음수 자간과 상쇄되는
        // 사례도 저장 자간을 무시하는 근거가 아니므로 원본 값을 유지한다.
        let spacing_percent = cs.spacings[lang] as f64;

        ratios.push(cs.ratios[lang] as f64 / 100.0);
        // 100%는 저장 줄과 같은 원래 크기를 보존한다. 먼저 곱하고 나누면
        // 반올림 잔차로 글꼴이 저장 줄보다 커져 유효한 0 간격이 재계산된다.
        let relative_size = f64::from(cs.relative_sizes[lang]) / 100.0;
        let lang_font_size = font_size * relative_size;
        // 자간은 그 언어 슬롯이 실제로 그리는 크기(상대 크기 적용 후)의 백분율이다.
        letter_spacings.push(lang_font_size * spacing_percent / 100.0);
        font_sizes.push(lang_font_size);
    }

    // [#7387] 공백은 영문 슬롯(1) 글꼴이 정한다. 원본 프로그램의 폭을 선택한
    // 슬롯은 공백도 그 프로그램의 폭을 소비한다. 표시용 대체 글꼴의 좁은 공백을
    // 섞으면 같은 원본 글꼴의 문자와 들여쓰기 전진폭이 달라진다.
    // 확인하지 못한 원본 공백·명시 TrueType·내장 글꼴은 기존 표시 체인으로 조회한다.
    let font_space_em = resolved_space_advance_em(
        cs.use_font_space,
        &font_families,
        &font_families_original_glyph_metric_face,
        cs.bold,
        cs.italic,
    );

    let ascii_punct_latin_slot = ascii_punctuation::uses_latin_slot(
        &font_families,
        font_families_metric_face[1].as_deref(),
        latin_slot_legacy,
        font_families_hft_hangul[0],
        latin_declared_hft,
        cs.bold,
        cs.italic,
    );
    let primary = |chain: &String| {
        storage.string(
            chain
                .split(',')
                .next()
                .unwrap_or("")
                .trim()
                .trim_matches(|c| c == '\'' || c == '"'),
        )
    };
    let explicit_latin_slot = latin_slot_explicit
        && latin_slot_legacy
        && primary(&font_families[0])? != primary(&font_families[1])?;
    let ascii_punct_latin_slot = ascii_punct_latin_slot || explicit_latin_slot;
    let latin_primary = primary(&font_families[1])?;
    let ascii_punct_latin_slot = ascii_punct_latin_slot
        || (primary(&font_families[0])? != latin_primary
            && (latin_slot_explicit
                || crate::renderer::font_metrics_data::find_metric(
                    &latin_primary,
                    cs.bold,
                    cs.italic,
                )
                .is_some_and(|found| found.metric.hangul.is_none())));

    // 한국어(0번) 값을 기본값으로 사용
    let font_family = storage.string(&font_families[0])?;
    let letter_spacing = letter_spacings[0];
    let ratio = ratios[0];

    Ok(ResolvedCharStyle {
        font_family,
        font_families,
        font_families_metric_trusted,
        font_families_glyph_fallback_advance_explicit,
        font_families_hft_hangul,
        font_families_source_hft,
        font_families_source_ttf,
        font_families_primary_program: vec![None; LANG_COUNT],
        font_families_verified_hft_bold_tracking,
        font_families_hft_print_frame,
        font_families_print_text_device_frame,
        font_families_preserve_glyph_ink: vec![false; LANG_COUNT],
        font_families_natural_program_metrics: vec![false; LANG_COUNT],
        font_families_hft_fullwidth_dot,
        ascii_punct_latin_slot,
        explicit_latin_slot,
        font_families_metric_face,
        font_families_original_glyph_metric_face,
        font_space_em,
        font_size,
        font_sizes,
        font_positions: storage.copy_slice(&cs.char_offsets)?,
        bold: cs.bold,
        italic: cs.italic,
        text_color: cs.text_color,
        underline: cs.underline_type,
        underline_color: cs.underline_color,
        strike_color: cs.strike_color,
        strikethrough: cs.strikethrough,
        letter_spacing,
        letter_spacings,
        ratio,
        ratios,
        border_fill_id: cs.border_fill_id,
        text_paint: cs.text_paint.map(|paint| paint.at_dpi(dpi)),
        outline_type: cs.outline_type,
        shadow_type: cs.shadow_type,
        shadow_color: cs.shadow_color,
        shadow_offset_x: cs.shadow_offset_x,
        shadow_offset_y: cs.shadow_offset_y,
        emboss: cs.emboss,
        engrave: cs.engrave,
        superscript: cs.superscript,
        subscript: cs.subscript,
        emphasis_dot: cs.emphasis_dot,
        underline_shape: cs.underline_shape,
        strike_shape: cs.strike_shape,
        kerning: cs.kerning,
        shade_color: cs.shade_color,
    })
}

impl ResolvedCharStyle {
    /// 기준 크기 0 인 글자 모양을 `font_size`(px) 기준 크기로 다시 해소한 값.
    ///
    /// 한/글 '문단 번호 사용자 정의 모양'의 '본문 글자 크기 따름'은 번호 글자 모양의 기준 크기를 0 으로
    /// 저장하고 번호를 문단 본문 크기로 그린다. 크기에서 나오는 값은 [`try_resolve_single_char_style`]
    /// 와 같은 식으로 다시 계산하고 글꼴·장평·꾸밈은 그대로 둔다.
    pub(crate) fn with_base_size(&self, cs: &CharShape, font_size: f64) -> Self {
        let mut style = self.clone();
        style.font_size = font_size;
        // 상대 크기는 해소 경로와 같은 순서(비율을 먼저 구해 곱함)로 계산해 반올림 잔차를 맞춘다.
        style.font_sizes = (0..LANG_COUNT)
            .map(|lang| font_size * (f64::from(cs.relative_sizes[lang]) / 100.0))
            .collect();
        style.letter_spacings = (0..LANG_COUNT)
            .map(|lang| style.font_sizes[lang] * cs.spacings[lang] as f64 / 100.0)
            .collect();
        style.letter_spacing = style.letter_spacings[0];
        style
    }
}

/// [#7702] 한/글이 앞 글자 언어와 무관하게 **영문 슬롯** 글꼴로 재고 그리는 기호.
///
/// 글꼴 슬롯만 영문일 뿐 영문 낱말을 이루는 글자는 아니다 — 줄 나눔은 이 글자를
/// 종전처럼 구두점으로 다룬다(`composer::line_breaking`).
///
/// [#8136] Latin-1 구두점·기호(U+00A1–00BF)와 아래 따옴표 ‚ ‛ „ ‟ 도 같다. 슬롯마다 다른
/// 설치 글꼴을 준 합성 입력(`samples/lang_slot/gen_lang_slot_probe.py`, 한/글 2024 Print)에서
/// `가X가` 의 X 가 영문 슬롯 Arial 로 그려지고, 영문 슬롯만 Courier New 로 바꾸면 따라 바뀐다.
/// NBSP(U+00A0)와 소프트 하이픈(U+00AD)은 공백·줄 나눔 문자라 언어 중립으로 남긴다.
pub(crate) fn is_latin_slot_symbol(ch: char) -> bool {
    matches!(ch, '\u{00A1}'..='\u{00AC}' | '\u{00AE}'..='\u{00BF}')
        || matches!(
            ch,
            '\u{2018}'
                | '\u{2019}'
                | '\u{201A}'
                | '\u{201B}'
                | '\u{201C}'
                | '\u{201D}'
                | '\u{201E}'
                | '\u{201F}'
        )
}

/// [#8136] 한/글이 앞 글자 언어와 무관하게 **기호 슬롯** 글꼴로 재고 그리는 글자 중, 블록 단위
/// 분류(`detect_lang_category` 의 기호 범위) 밖에 있는 것.
///
/// 합성 입력(`samples/lang_slot/gen_lang_slot_probe.py`, 한/글 2024 Print)에서 기호 슬롯에만 둔
/// 궁서로 그려지거나, 기호 슬롯만 함초롬바탕으로 바꾸면 따라 바뀐 글자다. 어느 슬롯 글꼴에도
/// 글리프가 없어 한/글이 시스템 대체 글꼴로 그린 글자(‐ ‖ ⁰ ₀ 등)는 슬롯을 가를 수 없어 넣지 않았다.
fn is_symbol_slot_char(cp: u32) -> bool {
    matches!(
        cp,
        // 그리스·키릴
        0x0391..=0x03A1 | 0x03A3..=0x03A9 | 0x03B1..=0x03C9 | 0x0401 | 0x0410..=0x044F | 0x0451 |
        // General Punctuation: – — ‗ † ‡ • ‥ … ‰ ′ ″ ‹ › ※ ‼ ‽ ‾ ⁄ ⁇ ⁎ ⁏ ⁓–⁞
        0x2013..=0x2014 | 0x2017 | 0x2020..=0x2022 | 0x2025..=0x2026 | 0x2030 | 0x2032..=0x2033 |
        0x2039..=0x203C | 0x203E | 0x2044 | 0x2047 | 0x204E..=0x204F | 0x2053..=0x205E |
        // 위·아래 첨자 ⁴ ⁿ ₁–₄ ₐ–ₔ
        0x2074 | 0x207F | 0x2081..=0x2084 | 0x2090..=0x2094 |
        // 통화 ₣ ₤ ₧ ₩ €
        0x20A3..=0x20A4 | 0x20A7 | 0x20A9 | 0x20AC |
        // Letterlike ℃ ℅ ℉ ℓ № ℡ ™ Ω Å ℮ ℻–ⅎ
        0x2103 | 0x2105 | 0x2109 | 0x2113 | 0x2116 | 0x2121..=0x2122 | 0x2126 | 0x212B | 0x212E |
        0x213B..=0x214E |
        // Number Forms ⅓ ⅔ ⅛–⅞
        0x2153..=0x2154 | 0x215B..=0x215E |
        // 괄호·원 한글 ㈀–㈜ ㉠–㉻ ㉿, 단위 ㎀–㎄ ㎈–㏊ ㏏ ㏐ ㏓ ㏖ ㏘ ㏛–㏝
        0x3200..=0x321C | 0x3260..=0x327B | 0x327F | 0x3380..=0x3384 | 0x3388..=0x33CA |
        0x33CF..=0x33D0 | 0x33D3 | 0x33D6 | 0x33D8 | 0x33DB..=0x33DD
    )
}

/// Unicode 코드포인트로 HWP 언어 카테고리를 판별한다.
///
/// 반환값: 0=한국어, 1=영어(라틴), 2=한자, 3=일본어, 4=기타, 5=기호, 6=사용자
///
/// 공백/일반 구두점은 언어 중립으로 간주하여 기본값(한국어)을 반환한다.
/// 호출부에서 "이전 문자의 언어를 따르는" 로직을 별도 처리해야 한다.
pub fn detect_lang_category(ch: char) -> usize {
    let cp = ch as u32;
    match cp {
        // [#2070] ㆍ(아래아, U+318D)는 한컴이 USER 스크립트 폰트로 렌더한다.
        // 80168 실문서(user=9='명조', 반각 오라클)와 사다리 v3(user=한양신명조,
        // 전각 실측)를 동시에 만족하는 유일 분류. 호환 자모 블록이지만
        // 한글(0)이 아니라 사용자(6)로 분류해 user 폰트를 태운다.
        0x318D => 6,

        // [#7092] 굽은 따옴표 ‘ ’ “ ” 는 한컴이 **영문(1) 슬롯** 글꼴로 그린다.
        // 저장소 `samples/`↔`pdf/` 정본 233문서에서 한글·영문·기호 슬롯 face 가 서로
        // 다른 출현만 골라 정본 글자의 PDF face 와 대조하면, 영문 슬롯만 일치하는 문서가
        // ‘ 46 · ’ 39 · “ 29 · ” 27 개이고 한글 슬롯만 일치하는 문서는 0 개다(기호 슬롯만
        // 일치 1 개). 같은 General Punctuation 블록이라도 `․`(U+2024)는 기호 슬롯 쪽으로
        // 갈린다. 블록 전체가 아니라 근거가 있는 글자만 옮긴다 — `…`·`–`·`—`·`※`·`•` 등은
        // 합성 입력으로 기호 슬롯을 확인했다(#8136, `is_symbol_slot_char`).
        0x2018 | 0x2019 | 0x201C | 0x201D => 1,

        // 독립 Print의 U+2024/U+2027은 앞 글자의 언어와 무관하게 기호
        // 슬롯을 쓴다. 한글/영문/기호 face를 교차한 한컴2020 출력으로 확인했다.
        // 본문 face의 결측 여부로 소유 슬롯을 추정하지 않는다.
        0x2024 | 0x2027 => 5,

        // 전각 ASCII와 통화 기호도 기호 슬롯을 쓴다. 2020/2024 독립
        // 103자 표본에서 슬롯별 상대 크기를 달리해 같은 선택을 확인했다.
        // 한글 슬롯으로 묶으면 FF5E 물결표 등이 다른 프로그램으로 그려진다.
        0xFF01..=0xFF60 | 0xFFE0..=0xFFE6 => 5,

        // 로마 숫자도 기호 슬롯을 선택한다. 서로 다른 슬롯 크기를 준
        // 독립 41자 표본에서 2020/2024 모두 같은 선택을 확인했다.
        0x2160..=0x2188 => 5,

        // 한국어: Hangul Jamo, Compatibility Jamo, Syllables
        0x1100..=0x11FF | 0x3130..=0x318F | 0xAC00..=0xD7AF |
        // Hangul Jamo Extended-A/B
        0xA960..=0xA97F | 0xD7B0..=0xD7FF => 0,

        // 영어/라틴: Basic Latin letters+digits, Latin Extended
        0x0041..=0x005A | 0x0061..=0x007A | 0x0030..=0x0039 |
        0x00C0..=0x024F |
        // Latin Extended Additional, Extended-B (subset)
        0x1E00..=0x1EFF => 1,

        // [#7702] 가운뎃점 `·` 과 곡선 따옴표 ‘’“” 는 앞 글자가 한글이어도 한/글이 **영문
        // 슬롯** 글꼴로 재고 그린다. 한글 휴먼명조 + 영문 Times New Roman 합성 문단(한/글
        // 2020)에서 `“`·`”` 는 0.444em, `‘`·`’`·`·` 는 0.336em 이고 PDF 글꼴도 Times 다. 영문
        // 슬롯을 휴먼명조로 바꾸면 따옴표가 1.0em 이 된다. 같은 문단의 `…`·`※`·`「` 등은
        // 휴먼명조로 남는다. 도 기호 `°` 도 Times 로 그려진다. 뒤따르는 공백도 Times 로
        // 그려진다(폭은 어느 쪽이든 0.5em).
        _ if is_latin_slot_symbol(ch) => 1,

        // 한자: CJK Unified Ideographs, Extension A
        0x4E00..=0x9FFF | 0x3400..=0x4DBF |
        // CJK Compatibility Ideographs
        0xF900..=0xFAFF |
        // CJK Unified Extension B (서로게이트 쌍이 아닌 범위)
        0x20000..=0x2A6DF => 2,

        // 일본어: Hiragana, Katakana
        0x3040..=0x309F | 0x30A0..=0x30FF |
        // Katakana Phonetic Extensions
        0x31F0..=0x31FF => 3,

        // ―는 치수 화살표의 가로선에도 쓰는 기호다. HWP3 입장권의
        // 한컴 Print는 기호 슬롯 바탕(687/1000 em)으로 출력한다.
        // 한글 슬롯 HFT로 분류하면 1em이 되어 저장 텍스트가 더 길어진다.
        // 기호: 수학 기호, 화살표, 기술 기호, 도형, Dingbats 등
        0x2015 | 0x2190..=0x21FF | 0x2200..=0x22FF | 0x2300..=0x23FF |
        0x2500..=0x257F | 0x2580..=0x259F | 0x25A0..=0x25FF |
        0x2600..=0x26FF | 0x2700..=0x27BF |
        // 원 숫자, 괄호 숫자 등
        0x2460..=0x24FF |
        // CJK 기호/구두점 (한자 구두점이 아닌 기호 영역)
        0x3000..=0x303F => 5,

        // 수학 기호 보충 블록도 한/글은 **기호 슬롯** 글꼴로 재고 그린다. 슬롯마다 다른 설치
        // 글꼴을 준 합성 입력(`samples/lang_slot/gen_lang_slot_probe.py`, 한/글 2020·2024
        // Print)에서 앞뒤가 한글이어도 ⦁(U+2981)·⟨(U+27E8)·⤀(U+2900)·⨀(U+2A00) 등은 기호
        // 슬롯 글꼴(함초롬바탕)로 그려지고, 기호 슬롯 글꼴에 글리프가 없을 때만 대체 글꼴로
        // 간다. 한글 슬롯으로 재면 한글 글꼴에 없는 글자라 반각 대체 폭을 받는다. 기호 슬롯
        // 글꼴의 폭은 확인한 hmtx 표(`font_metric_math_symbol_blocks.rs`)가 보충한다.
        0x27C0..=0x27FF | 0x2900..=0x2BFF => 5,

        _ if is_symbol_slot_char(cp) => 5,

        // 공백/ASCII 구두점/제어문자 → 한국어(기본값)로 반환
        // 호출부에서 "이전 문자의 언어를 따르는" 로직으로 처리
        _ => 0,
    }
}

/// FontFace 테이블에서 폰트 이름 조회 + 폰트 치환 적용
///
/// HWP 문서의 폰트 이름을 웹/SVG에서 렌더링 가능한 폰트로 치환한다.
/// webhwp의 g_SubstFonts 치환 체인을 평탄화(flatten)한 테이블을 사용한다.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FontSubstitutionBoundary {
    LegacyLatin,
    Hft,
    Ttf,
    MissingProgram,
}

impl FontSubstitutionBoundary {
    pub(crate) const fn source_boundary_id(self) -> &'static str {
        match self {
            Self::LegacyLatin => "rust-style-resolution.legacy-latin",
            Self::Hft => "rust-style-resolution.hft",
            Self::Ttf => "rust-style-resolution.ttf",
            Self::MissingProgram => "rust-style-resolution.missing-program",
        }
    }

    pub(crate) fn language_condition(self, source_face: &str) -> &'static str {
        match self {
            Self::LegacyLatin => "1",
            Self::Ttf | Self::MissingProgram => "all",
            Self::Hft
                if find_font_rule_layout_name(self.source_boundary_id(), source_face, 0)
                    .is_some() =>
            {
                "all"
            }
            Self::Hft => "1",
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct FontNameDecision {
    pub(crate) environment_profile_id: Option<String>,
    pub(crate) language_slot: usize,
    pub(crate) font_id: u16,
    pub(crate) requested_face: Option<String>,
    pub(crate) alt_type: Option<u8>,
    pub(crate) embedded: Option<bool>,
    pub(crate) normalized_face: Option<String>,
    pub(crate) requested_subst_font: Option<String>,
    pub(crate) subst_font: Option<String>,
    pub(crate) document_substitute_rule_id: Option<&'static str>,
    pub(crate) css_family_chain: Vec<String>,
    pub(crate) substitution_boundary: Option<FontSubstitutionBoundary>,
    pub(crate) substitution_rule_id: Option<&'static str>,
}

/// [#7092] 메트릭 표에 적힌 폭이 **그 글꼴 자신의 전진폭**임을 글꼴 파일로 확인한 face 인지.
///
/// 문서가 적은 `alt_type`(TTF/HFT)은 *문서의 주장*일 뿐 표의 출처를 말해 주지 않는다.
/// `76076_regulatory_analysis.hwp` 는 `함초롬바탕` 을 `alt_type=1`(TTF)로 선언하지만 메트릭
/// 조회는 별칭 규칙(`rule.rust-metric.1de1fcb9b17d66d599b5`)으로 **다른 글꼴인 `HCR Batang`
/// 표**를 쓴다. 한/글 2024 정본은 그 문서의 `·` 를 0.345em 으로 그린다 — `덮개·울`(한글3+·)
/// 37.8pt 와 `덮개·울을`(한글4+·) 49.1pt 에서 한글 전진폭 11.3pt 를 빼면 3.9pt 다. 선언을
/// 근거로 표를 믿으면 이 글자가 전각이 되어 조각 경계가 한 행 밀린다.
///
/// 그래서 근거는 선언이 아니라 **글꼴 파일 실측**으로 둔다. 별칭이 같은 글꼴의 다른 이름인지
/// (`HY신명조` → `HYSinMyeongJo-Medium`) 다른 글꼴인지(`함초롬바탕` → `HCR Batang`)는 규칙
/// 표만으로 구분되지 않으므로, 확인한 face 만 여기에 적는다.
///
/// - `HY신명조` — `H2MJSM.TTF` 가 `periodcentered`(gid 20313 · 윤곽선 1개)를 1024/1024 로
///   갖고, `#7092` 재현체의 한/글 정본이 0.999em 이다(`·` 31회 전부 이 face).
/// - `HY헤드라인M` — `ttfs/hwp/H2HDRM.TTF` 가 `periodcentered` 를 1024/1024 로 갖고
///   윤곽선 bbox 가 `(439, 297, 586, 435)` 다(결측 글리프가 아니다). 저장소 한컴 정본
///   **25개 문서**에서 이 face 의 `·` 전진폭이 0.89~1.06em 이고 중앙값이 1.000 이다
///   (`k-water-rfp` 5종 · `mel-001` 3종 · `aift-2022` · `pr_6528_issue6181_p5` …).
///   좁은 갈래(0.2~0.4em)는 한 건도 없다.
/// - `HY울릉도M` — `ttfs/hwp/HYWULM.TTF` 가 같은 글리프를 1024/1024 로 갖고, 정본
///   `press_release_split_cell_nested_table-hwpx-2020`(n=8, 0.944~1.000) 과
///   `pr_6528_issue6181_p5_2020`(n=1, 1.000) 이 전각을 말한다.
/// - `휴먼고딕` — `HMKMG.TTF`의 실제 `periodcentered`(gid12190)는 512/512이다.
///   독립 `80250` Print p10의 같은 face도 이웃 원점 사이에 1em을 소비한다.
///   이 목록은 기존 TTF 선언·비치환 조건과 함께 쓰므로 HFT·불명 face는 유지한다.
/// - `HY중고딕` / `HYGothic-Medium` — `H2GTRM.TTF`의 가운데점·작은따옴표는
///   모두 1024/1024이다. 실제 SVG 임베딩과 원 파일의 glyf/hmtx/cmap도 같으며,
///   독립 개인정보 Print 66쪽의 가운데점 29개·작은따옴표 8개가 같은 1em을 확인한다.
///
/// 새 face 를 넣으려면 그 글꼴 파일의 글리프와 한/글 출력 실측을 함께 남긴다.
///
/// - `휴먼명조` — `HMKMM.TTF` 가 `‘’“”` 를 모두 512/512 로 갖는다. 저장소 한컴 정본
///   23문서에서 이 face 의 `‘`·`’` 전진폭 중앙값이 0.988em 이고(n=2,042), 한/글 2020
///   합성 문단(영문 슬롯 휴먼명조 TTF)도 `‘’“”` 를 1.0em 으로 놓는다(#7702). HFT 로
///   선언된 휴먼명조는 `alt_type == 1` 을 만족하지 않으므로 여기서 걸러진다.
/// - `Times New Roman` — `curly_quote_latin_slot` 독립 Print의 CID TrueType 프로그램과
///   공급한 원 프로그램의 `‘’“”` 전진폭·분해 윤곽선이 모두 동일하다. 작은따옴표는
///   682/2048em, 큰따옴표는 909/2048em으로 원래 좁은 글리프다. 이 TTF 선택을 신뢰하지
///   않으면 측정한 원 전진폭은 유지하면서 Canvas/Skia만 다시 절반으로 축소한다.
///
/// 글꼴 파일은 배포하지 않고 프로그램 SHA와 독립 출력 근거만 기록한다.
///
/// - `HY중고딕` — Windows `H2GTRM.TTF`(family `HY중고딕`, PostScript `H2gtrM`)가
///   `periodcentered`(gid 19305, 윤곽선 bbox `(466, 321, 558, 413)`)를 1024/1024 로 갖고
///   `‘’“”` 도 1024 다. 저장소 한컴 정본 **8개 문서**(78494 n=61 · 76076 2020 출력 n=32 ·
///   75544 n=26 · issue1891_external_bindata_link n=14 · 80550 · regulatory_impact_nested_table_escape
///   · 113424 · pr6275)에서 `H2gtrM` 의 `·` 전진폭 중앙값이 1.000em(0.88~1.02, n=145)이다.
///   이 face 는 직접 선언보다 `한양중고딕` 의 **대체 TTF** 로 더 자주 쓰인다
///   ([`verified_ttf_substitute`]).
/// - `HY견고딕` — `H2GTRE.TTF`(bbox `(432, 286, 593, 446)`) 1024/1024, 정본
///   `trade_report_forced_break_object-2024`(n=1, 1.000) · 같은 문서 2020 출력(0.989).
/// - `HY그래픽` — `H2GPRM.TTF`(family `HY그래픽M`, bbox `(460, 316, 564, 421)`) 1024/1024,
///   정본 `press_release_split_cell_nested_table-hwpx-2020`(n=1, 1.000).
///
/// 아직 넣지 않은 것 — `휴먼고딕`(글꼴 파일은 512/512 이고 정본 2문서 n=9 가 1.0em 이지만
/// 저장소에 TTF 로 선언한 짝 표본이 없다).
fn metric_widths_verified_face(face: &str) -> bool {
    matches!(
        face.trim(),
        "HY신명조"
            | "HYSinMyeongJo-Medium"
            | "HY중고딕"
            | "HYGothic-Medium"
            | "HY헤드라인M"
            | "HYHeadLine-Medium"
            | "HY울릉도M"
            | "HYwulM"
            | "HY견고딕"
            | "HYGothic-Extra"
            | "HY그래픽"
            | "HYGraphic-Medium"
            | "휴먼명조"
            | "HumanMyeongJo"
            | "Times New Roman"
            | "휴먼고딕"
    )
}

pub(crate) fn lookup_font_name_decision(
    doc_info: &DocInfo,
    lang_index: usize,
    font_id: u16,
) -> FontNameDecision {
    match try_lookup_font_name_decision(doc_info, lang_index, font_id, &storage::Unbounded) {
        Ok(decision) => decision,
        Err(never) => match never {},
    }
}

fn try_lookup_font_name_decision<A: storage::Storage>(
    doc_info: &DocInfo,
    lang_index: usize,
    font_id: u16,
    storage: &A,
) -> Result<FontNameDecision, A::Error> {
    let mut decision = FontNameDecision {
        environment_profile_id: None,
        language_slot: lang_index,
        font_id,
        requested_face: None,
        alt_type: None,
        embedded: None,
        normalized_face: None,
        requested_subst_font: None,
        subst_font: None,
        document_substitute_rule_id: None,
        css_family_chain: Vec::new(),
        substitution_boundary: None,
        substitution_rule_id: None,
    };
    if lang_index < doc_info.font_faces.len() {
        let lang_fonts = &doc_info.font_faces[lang_index];
        if (font_id as usize) < lang_fonts.len() {
            let font = &lang_fonts[font_id as usize];
            let name = &font.name;
            decision.requested_face = Some(storage.string(name)?);
            decision.alt_type = Some(font.alt_type);
            decision.embedded = Some(font.is_embedded);
            // 폰트 치환: HFT 등 웹 미지원 폰트를 렌더링 가능한 폰트로 완전 대체
            let substitution = resolve_font_substitution_decision(name, font.alt_type, lang_index);
            let resolved = storage.string(substitution.map(|(face, _, _)| face).unwrap_or(name))?;
            decision.normalized_face = Some(storage.string(&resolved)?);
            decision.substitution_boundary = substitution.map(|(_, boundary, _)| boundary);
            decision.substitution_rule_id = substitution.map(|(_, _, rule_id)| rule_id);
            storage.push(&mut decision.css_family_chain, storage.string(&resolved)?)?;
            if let Some(substitute) = font
                .subst_font
                .as_ref()
                .filter(|substitute| !substitute.is_embedded)
                .filter(|substitute| !substitute.face.trim().is_empty())
                .filter(|substitute| substitute.face.trim() != resolved)
            {
                let requested = substitute.face.trim();
                decision.requested_subst_font = Some(storage.string(requested)?);
                // 대체 필드의 이름 해석은 주 글꼴의 별칭과 별도 계약이다.
                // 독립 2020/2024 Print: 영문 HCR 대체 필드는 한컴바탕,
                // 한글 대체 필드와 주 글꼴 HCR은 실제 HCR을 선택한다.
                let rule = (!font.is_embedded && font.alt_type == 1 && substitute.font_type == 1)
                    .then(|| {
                        find_font_rule_layout_name(
                            "rust-style-resolution.document-substitute",
                            requested,
                            lang_index,
                        )
                    })
                    .flatten()
                    .filter(|rule| {
                        rule.conditions.alt_type == Some("1")
                            && rule.conditions.availability
                                == Some("nonembedded-ttf-document-substitute")
                    });
                let face =
                    storage.string(rule.map_or(requested, |rule| rule.target_face_or_policy))?;
                decision.document_substitute_rule_id = rule.map(|rule| rule.rule_id);
                decision.subst_font = Some(storage.string(&face)?);
                if face != resolved {
                    storage.push(&mut decision.css_family_chain, face)?;
                }
            }
            document_font_chain::prefer_declared_single_face(font, &mut decision, storage)?;
        }
    }
    Ok(decision)
}

pub(crate) fn lookup_font_name_in_environment(
    doc_info: &DocInfo,
    lang_index: usize,
    font_id: u16,
    environment: Option<&super::font_environment::FontEnvironment>,
) -> FontNameDecision {
    let mut decision = lookup_font_name_decision(doc_info, lang_index, font_id);
    if decision.embedded != Some(true) {
        if let Some((environment, target)) = environment.and_then(|env| {
            decision
                .requested_face
                .as_deref()
                .and_then(|face| env.replacement_for(face, lang_index, font_id))
                .map(|target| (env, target))
        }) {
            // 같은 주 프로그램의 신원 인증은 준비된 glyph fallback 체인을 바꾸지 않는다.
            let same_primary_family = decision.normalized_face.as_deref() == Some(target);
            if !same_primary_family {
                // 표시용 별칭은 문서의 substFont·검증된 결측 공급자를 교체하는
                // 요청이 아니다. 원본 전진 보존 세션에서는 주 face만 바꾸고
                // 뒤 공급 체인을 유지한다. 자연 프로그램을 직접 선택한 세션은
                // 기존대로 새 주 프로그램에서 시작한다.
                let source_fallbacks = if decision
                    .requested_face
                    .as_deref()
                    .is_some_and(|source| environment.preserves_source_metrics_for(source))
                {
                    decision
                        .css_family_chain
                        .iter()
                        .skip(1)
                        .cloned()
                        .collect::<Vec<_>>()
                } else {
                    Vec::new()
                };
                decision.normalized_face = Some(target.to_string());
                decision.css_family_chain = vec![target.to_string()];
                for face in source_fallbacks {
                    if !decision.css_family_chain.contains(&face) {
                        decision.css_family_chain.push(face);
                    }
                }
            }
            // 공급자가 선택한 face 이름을 family로 합치면 같은 계열의 다른
            // 굵기·너비가 선택될 수 있다. 원본 주소의 실제 조회 이름을 보존하고,
            // family와 글리프 fallback은 뒤에서 기존 계약대로 소비한다.
            if let Some(query) = decision.requested_face.as_deref().and_then(|source| {
                environment.selected_program_query_for(source, lang_index, font_id)
            }) {
                // HFT의 원본 이름은 물리 face 이름이 아닌 조판 별칭일 수 있다.
                // 같은 주 프로그램을 자동 인증할 때 이 별칭을 다시 선두에 넣으면
                // 다른 설치 프로그램이 먼저 선택된다. 명시적 face 선택과 구분한다.
                let preserves_hft_alias = decision.alt_type == Some(2)
                    && decision.requested_face.as_deref() == Some(query)
                    && environment.preserves_source_metrics_for(query);
                if query != target && !preserves_hft_alias {
                    decision.css_family_chain.retain(|face| face != query);
                    decision.css_family_chain.insert(0, query.to_string());
                }
            }
            let canonical_rule = decision.requested_face.as_deref().and_then(|source| {
                environment.canonical_selection_rule_for(source, lang_index, font_id)
            });
            decision.substitution_boundary =
                canonical_rule.map(|_| FontSubstitutionBoundary::MissingProgram);
            decision.substitution_rule_id = canonical_rule;
            decision.environment_profile_id = Some(environment.id().to_string());
        }
    }
    if decision.embedded != Some(true)
        && environment.is_some_and(|env| {
            decision
                .normalized_face
                .as_deref()
                .is_some_and(|face| env.selects_true_type(face))
        })
    {
        decision.environment_profile_id = environment.map(|env| env.id().to_string());
    }
    if decision.embedded != Some(true) {
        if let Some((environment, fallbacks)) = environment.and_then(|env| {
            decision
                .normalized_face
                .as_deref()
                .and_then(|face| {
                    decision.requested_face.as_deref().and_then(|source| {
                        env.glyph_fallbacks_for_slot(source, face, lang_index, font_id)
                    })
                })
                .map(|fallbacks| (env, fallbacks))
        }) {
            // 호출자가 검증한 체인은 일반 OS 폴백보다 먼저 사용한다.
            // 기본 face·원본 substFont를 보존하고 중복만 제거한다.
            let source_fallbacks = decision.css_family_chain.split_off(1);
            for face in fallbacks.iter().chain(&source_fallbacks) {
                if !decision.css_family_chain.contains(face) {
                    decision.css_family_chain.push(face.clone());
                }
            }
            decision.environment_profile_id = Some(environment.id().to_string());
        } else if let Some(primary) = decision.normalized_face.as_deref() {
            // 원본의 substFont와 명시 환경을 먼저 존중한다. 검증된 기본 glyph
            // 공급자는 OS 체인 앞에 붙이되, TTF/HFT·메트릭 신뢰도는 승격하지 않는다.
            for face in super::font_metrics_data::verified_program_glyph_fallback_families(primary)
            {
                if !decision
                    .css_family_chain
                    .iter()
                    .any(|existing| existing == face)
                {
                    decision.css_family_chain.push((*face).to_string());
                }
            }
        }
    }
    decision
}

fn lookup_font_name(doc_info: &DocInfo, lang_index: usize, font_id: u16) -> String {
    lookup_font_name_decision(doc_info, lang_index, font_id)
        .css_family_chain
        .join(",")
}

/// 폰트명에서 원본(첫 번째) 폰트명만 추출 (폴백 제거)
pub fn primary_font_name(font_family: &str) -> &str {
    font_family.split(',').next().unwrap_or(font_family).trim()
}

/// webhwp g_SubstFonts 기반 폰트 치환
///
/// HWP 문서의 원본 폰트 이름 + 타입(TTF/HFT) + 언어 카테고리를 기반으로
/// @font-face에 등록된 최종 폰트로 치환한다.
/// 체인이 이미 평탄화되어 1회 조회로 최종 결과를 반환한다.
pub(crate) fn resolve_font_substitution(
    name: &str,
    alt_type: u8,
    lang_index: usize,
) -> Option<&'static str> {
    resolve_font_substitution_decision(name, alt_type, lang_index).map(|(face, _, _)| face)
}

pub(crate) fn resolve_font_substitution_decision(
    name: &str,
    alt_type: u8,
    lang_index: usize,
) -> Option<(&'static str, FontSubstitutionBoundary, &'static str)> {
    // HWP3 원본/일부 한컴 재저장본은 HCI 영문 폰트를 TTF(type=1) 또는
    // unknown(type=0)으로 싣기도 한다. 한컴은 같은 face를 보여주므로
    // alt_type 차이와 무관하게 legacy 영문 HFT 치환을 우선 적용한다.
    if let Some(rule) =
        resolve_projected_font_rule(FontSubstitutionBoundary::LegacyLatin, name, lang_index)
    {
        return Some((
            rule.target_face_or_policy,
            FontSubstitutionBoundary::LegacyLatin,
            rule.rule_id,
        ));
    }

    // HFT(type=2) 폰트 치환
    if alt_type == 2 {
        if let Some(rule) =
            resolve_projected_font_rule(FontSubstitutionBoundary::Hft, name, lang_index)
        {
            return Some((
                rule.target_face_or_policy,
                FontSubstitutionBoundary::Hft,
                rule.rule_id,
            ));
        }
    }

    // TTF(type=1) 또는 알수없음(type=0) 치환
    resolve_projected_font_rule(FontSubstitutionBoundary::Ttf, name, lang_index).map(|rule| {
        (
            rule.target_face_or_policy,
            FontSubstitutionBoundary::Ttf,
            rule.rule_id,
        )
    })
}

fn resolve_projected_font_rule(
    boundary: FontSubstitutionBoundary,
    name: &str,
    lang_index: usize,
) -> Option<&'static GeneratedFontRuleProjection> {
    find_font_rule_layout_name(boundary.source_boundary_id(), name, lang_index)
}

/// Heavy display 계열 face 여부 판정.
///
/// HY헤드라인M, HY견고딕 등 face 이름 자체가 굵은 display 폰트들은
/// HWP CharShape.bold=false 로 저장되어도 실제로는 시각적 bold 로
/// 렌더된다. 해당 face 가 설치되지 않은 환경에서 Malgun Gothic 등
/// regular weight fallback 으로 떨어지면 PDF(한컴) 출력과 시각 괴리가
/// 발생하므로, 이 리스트에 포함된 face 는 SVG 에서 font-weight="bold"
/// 를 강제해 fallback bold variant 로 근사 렌더한다.
///
/// Task #574: HY견명조 는 한컴 일반 두께 명조 — heavy 가 아님. 제거.
/// HY견명조B (명시 Bold variant) 는 보존.
pub(crate) fn is_heavy_display_face(font_family: &str) -> bool {
    // font_family 는 "HY헤드라인M,'Malgun Gothic',..." 처럼 CSS 체인 형태.
    // 첫 face 만 검사 (HWP 가 지정한 primary face).
    let primary = font_family
        .split(',')
        .next()
        .unwrap_or(font_family)
        .trim()
        .trim_matches('\'')
        .trim_matches('"');
    matches!(
        primary,
        "HY헤드라인M"
            | "HYHeadLine M"
            | "HYHeadLine Medium"
            | "HY견고딕"
            | "한양견고딕"
            | "HYGothic-Extra"
            | "HY견명조B"
            | "HY그래픽"
            | "HY그래픽M"
            | "휴먼엑스포"
    )
}

fn primary_font_face(font_family: &str) -> &str {
    font_family
        .split(',')
        .next()
        .unwrap_or(font_family)
        .trim()
        .trim_matches('\'')
        .trim_matches('"')
}

/// Face name explicitly carries a bold weight.
pub(crate) fn is_bold_weight_face(font_family: &str) -> bool {
    let primary = primary_font_face(font_family);
    let lower = primary.to_lowercase();
    lower.contains("bold") || lower.contains("볼드")
}

/// Face name explicitly carries a light weight.
pub(crate) fn is_light_weight_face(font_family: &str) -> bool {
    let primary = primary_font_face(font_family);
    let lower = primary.to_lowercase();
    !is_bold_weight_face(font_family)
        && (lower.contains("light")
            || lower.contains("extralight")
            || lower.contains("thin")
            || lower.contains("ultralight"))
}

/// 중고딕/태고딕 계열 (CSS font-weight 500) 폰트 판별.
///
/// HWP 에서 중고딕 계열은 Regular(400)과 Bold(700) 사이의 Medium(500) weight.
/// Fallback 폰트 매칭 시 weight 500 힌트를 주어 선명도를 유지한다.
pub(crate) fn is_medium_weight_face(font_family: &str) -> bool {
    let primary = primary_font_face(font_family);
    let lower = primary.to_lowercase();
    lower.contains("중고딕")
        || lower.contains("태고딕")
        || lower.contains("mediumgothic")
        || lower.contains("hymedium")
}

/// ParaShape → ResolvedParaStyle 목록
fn resolve_para_styles(doc_info: &DocInfo, dpi: f64) -> Vec<ResolvedParaStyle> {
    resolve_para_styles_with_variant(doc_info, dpi, false)
}

/// [Task #1001] 변환본 인지 ParaShape 해소
fn resolve_para_styles_with_variant(
    doc_info: &DocInfo,
    dpi: f64,
    is_hwp3_variant: bool,
) -> Vec<ResolvedParaStyle> {
    let char_unit_hu = para_margin_char_unit_hu(doc_info);
    doc_info
        .para_shapes
        .iter()
        .map(|ps| {
            resolve_single_para_style(ps, &doc_info.tab_defs, dpi, is_hwp3_variant, char_unit_hu)
        })
        .collect()
}

/// [#7816] 문단 여백의 «글자» 단위 하나가 몇 HWPUNIT 인가 — 바탕글 스타일 글자 크기의 1/200.
///
/// 한/글 2020 통제 실험(저장 줄 없는 합성 HWPX·그 HWP 저장본)에서 홀수 저장값 `s` 의 양은
/// `(s − 1) / 2` 단위였고, 단위 하나는 바탕글 10pt 에서 5 HU · 20pt 에서 10 HU 였다.
/// 바탕글이 가리키는 글자 모양만 바꾸면 따라 바뀌고, 글자 모양 0 이나 문단 자신의 글자
/// 크기를 바꾸면 그대로였다. 바탕글을 찾지 못하면 10pt(1000) 로 둔다.
fn para_margin_char_unit_hu(doc_info: &DocInfo) -> f64 {
    let base_size = doc_info
        .styles
        .first()
        .and_then(|style| doc_info.char_shapes.get(style.char_shape_id as usize))
        .map(|shape| shape.base_size)
        .filter(|&size| size > 0)
        .unwrap_or(1000);
    base_size as f64 / 200.0
}

/// [#7816] ParaShape 여백·문단 간격 저장값 → HWPUNIT.
///
/// 저장값은 HWPUNIT 의 2배다. 최하위 비트는 단위 표지라, **홀수면 «글자» 단위**다 —
/// 한/글 HWPX 는 그 자리를 HwpUnitChar `case` 에 `unit="CHAR"` · 값 `(s − 1) / 2` 로 적는다
/// (`serializer/hwpx/header.rs` `write_margin_child`, #6875). 한/글은 이 값을 단위 수로 읽어
/// 단위 하나에 [`para_margin_char_unit_hu`] HU 를 준다. 들여쓰기·왼쪽·오른쪽·문단 위·아래
/// 다섯 항목 모두 같다(저장값 1001·2001·4001 → 33.3·66.7·133.3px, 바탕글 10pt).
fn para_margin_hwpunit(stored: i32, char_unit_hu: f64) -> f64 {
    if stored % 2 != 0 {
        ((stored - 1) / 2) as f64 * char_unit_hu
    } else {
        (stored / 2) as f64
    }
}

pub(crate) fn paragraph_margin_hwpunit(raw: i32, doc_info: &DocInfo) -> f64 {
    para_margin_hwpunit(raw, para_margin_char_unit_hu(doc_info))
}

/// 개별 ParaShape 해소
fn resolve_single_para_style(
    ps: &ParaShape,
    tab_defs: &[TabDef],
    dpi: f64,
    is_hwp3_variant: bool,
    char_unit_hu: f64,
) -> ResolvedParaStyle {
    match try_resolve_single_para_style(
        ps,
        tab_defs,
        dpi,
        is_hwp3_variant,
        char_unit_hu,
        &storage::Unbounded,
    ) {
        Ok(style) => style,
        Err(never) => match never {},
    }
}

/// Resolve one normalized paragraph from the original style tables. A compact
/// character-ID projection must still use the document's default character size
/// for CHAR-unit margins. The ordinary resolver consumes the same rule below.
#[cfg(feature = "pdf-import")]
pub(crate) fn try_resolve_paragraph_style<A: storage::Storage>(
    ps: &ParaShape,
    doc_info: &DocInfo,
    dpi: f64,
    storage: &A,
) -> Result<ResolvedParaStyle, A::Error> {
    try_resolve_single_para_style(
        ps,
        &doc_info.tab_defs,
        dpi,
        false,
        para_margin_char_unit_hu(doc_info),
        storage,
    )
}

fn try_resolve_single_para_style<A: storage::Storage>(
    ps: &ParaShape,
    tab_defs: &[TabDef],
    dpi: f64,
    is_hwp3_variant: bool,
    char_unit_hu: f64,
    storage: &A,
) -> Result<ResolvedParaStyle, A::Error> {
    // [#2070] 비-Percent 줄간격(Fixed/SpaceOnly/Minimum)도 여백·문단간격·탭과
    // 동일하게 저장값이 유효 HWPUNIT 의 2배다 — 통제 사다리(#2197)로 확정한
    // 계약과 실문서 이중 실증: 시장구조조사 본문 ps Fixed 3320HU, 한글 PDF
    // 줄 pitch 22.1px = 3320/2 (rhwp 종전 44.3px = 2배 팽창); 편람 한컴 HWPX
    // case FIXED=1560/default=3120 (case=유효, default=저장). HWPX 파서도
    // case×2 적재라 양 포맷 IR 동일 스케일 — 일괄 /2 가 정합.
    let line_spacing = match ps.line_spacing_type {
        LineSpacingType::Percent => ps.line_spacing as f64,
        _ => hwpunit_to_px(ps.line_spacing, dpi) / 2.0,
    };

    // 기본 탭 간격: 한/글 기본값 40pt(4000 HWPUNIT). 문서의 구역 정의 값은
    // 구역 composition·측정·배치의 section_tab_scope가 함께 소비한다.
    let default_tab_width = hwpunit_to_px(4000, dpi);

    // 커스텀 탭 정지 해소: TabDef.tabs[] → px 변환
    // TabItem.position은 ParaShape 여백과 동일하게 2배 스케일로 저장되므로
    // 렌더링 시 2로 나누어야 한다 (hwp2hwpx 변환 코드 및 HWP 대화상자 확인).
    let tab_def = tab_defs.get(ps.tab_def_id as usize);
    let mut tab_stops = storage.vec(tab_def.map_or(0, |definition| definition.tabs.len()))?;
    if let Some(definition) = tab_def {
        for tab in &definition.tabs {
            tab_stops.push(TabStop {
                position: hwpunit_to_px(tab.position as i32, dpi) / 2.0,
                tab_type: tab.tab_type,
                fill_type: tab.fill_type,
            });
        }
    }
    let auto_tab_right = tab_def.map(|td| td.auto_tab_right).unwrap_or(false);

    // ParaShape의 여백 및 문단 간격은 값과 단위 비트를 함께 보존한다.
    // margin_left/right/indent: LineSeg.column_start와 비교하면 column_start = margin_left / 2
    // 하위 비트0은 HWPUNIT(물리 HU), 1은 CHAR(기본 스타일의 반각 em 백분율)다.
    // HwpUnitChar case의 CHAR80/raw161은400HU이며 raw160은80HU다.
    //
    // [Task #1037] HWP5 변환본 의 추가 2배 스케일 (총 4배) 은 parser 단계 (parser/mod.rs)
    // 에서 normalize (halve) 되어 본 단계에서는 normal HWP5 동등 (2배 스케일) — uniform
    // variant_div=2 적용. 종전 variant_div=4 는 raw 값 normalize 전 보정 패턴이었음.
    //
    // [#7816] 홀수 저장값은 «글자» 단위다 — [`para_margin_hwpunit`].
    let _ = is_hwp3_variant;
    let margin_px = |stored: i32| {
        para_margin_hwpunit(stored, char_unit_hu) * dpi / crate::renderer::HWPUNIT_PER_INCH
    };
    Ok(ResolvedParaStyle {
        alignment: ps.alignment,
        vertical_alignment: ((ps.attr1 >> 20) & 0x03) as u8,
        line_spacing,
        line_spacing_type: ps.line_spacing_type,
        margin_left: margin_px(ps.margin_left),
        margin_right: margin_px(ps.margin_right),
        indent: margin_px(ps.indent),
        spacing_before: margin_px(ps.spacing_before),
        spacing_after: margin_px(ps.spacing_after),
        head_type: ps.head_type,
        para_level: ps.para_level,
        numbering_id: ps.numbering_id,
        border_fill_id: ps.border_fill_id,
        border_spacing: [
            hwpunit_to_px(ps.border_spacing[0] as i32, dpi),
            hwpunit_to_px(ps.border_spacing[1] as i32, dpi),
            hwpunit_to_px(ps.border_spacing[2] as i32, dpi),
            hwpunit_to_px(ps.border_spacing[3] as i32, dpi),
        ],
        border_connect: ps.attr1 & (1 << 28) != 0,
        border_ignore_margin: ps.attr1 & (1 << 29) != 0,
        default_tab_width,
        tab_stops,
        auto_tab_left: tab_def.is_some_and(|td| td.auto_tab_left),
        auto_tab_right,
        condense_min_space: ((ps.attr1 >> 9) & 0x7f).min(75) as u8,
        english_break_unit: ((ps.attr1 >> 5) & 0x03) as u8,
        korean_break_unit: ((ps.attr1 >> 7) & 0x01) as u8,
        widow_orphan: (ps.attr1 >> 16) & 1 != 0,
        keep_with_next: (ps.attr1 >> 17) & 1 != 0,
        keep_lines: (ps.attr1 >> 18) & 1 != 0,
        page_break_before: (ps.attr1 >> 19) & 1 != 0,
        line_wrap_squeeze: ps.attr2 & crate::model::style::PARA_ATTR2_LINE_WRAP_MASK == 1,
    })
}

/// BorderFill → ResolvedBorderStyle 목록
fn resolve_border_styles(doc_info: &DocInfo, dpi: f64) -> Vec<ResolvedBorderStyle> {
    doc_info
        .border_fills
        .iter()
        .map(|bf| resolve_single_border_style(bf, dpi))
        .collect()
}

/// 개별 BorderFill 해소
fn resolve_single_border_style(bf: &BorderFill, dpi: f64) -> ResolvedBorderStyle {
    match try_resolve_single_border_style(bf, dpi, &storage::Unbounded) {
        Ok(style) => style,
        Err(never) => match never {},
    }
}

fn try_resolve_single_border_style<S: storage::Storage>(
    bf: &BorderFill,
    dpi: f64,
    storage: &S,
) -> Result<ResolvedBorderStyle, S::Error> {
    let fill_color = match bf.fill.fill_type {
        FillType::Solid => bf.fill.solid.as_ref().and_then(|s| {
            // 무늬(0~5)가 있으면 패턴 채우기 → 단색 fill 아님 (background_color는 패턴 배경)
            // ColorRef 상위 바이트가 0이 아니면 "채우기 없음" (투명)
            // 0xFFFFFFFF = CLR_INVALID/CLR_DEFAULT (Windows COLORREF)
            if s.hatch().is_some() || (s.background_color >> 24) != 0 {
                None
            } else {
                Some(s.background_color)
            }
        }),
        _ => None,
    };

    let pattern = match bf.fill.fill_type {
        FillType::Solid => bf.fill.solid.as_ref().and_then(|s| {
            s.hatch().map(|hatch| PatternFillInfo {
                pattern_type: hatch.pattern_type(),
                tile_size: hwpunit_to_px(576, dpi),
                pattern_color: s.pattern_color,
                background_color: s.background_color,
            })
        }),
        _ => None,
    };

    let gradient = match bf.fill.fill_type {
        FillType::Gradient => {
            if let Some(g) = bf.fill.gradient.as_ref() {
                // 유효성 검사: 색상 2개 미만이거나 비정상적으로 많으면 무효
                if g.colors.len() < 2
                    || g.colors.len() > 64
                    || g.center_x.abs() > 200
                    || g.center_y.abs() > 200
                {
                    None
                } else {
                    let positions: Vec<f64> = if g.positions.is_empty() {
                        let n = g.colors.len();
                        storage.collect((0..n).map(|i| i as f64 / (n.max(2) - 1).max(1) as f64))?
                    } else {
                        storage.collect(g.positions.iter().map(|&p| p as f64 / 100.0))?
                    };
                    // [#6822] `step`(띠 개수)·`step_center`(전이 위치)를 stop 으로 편다.
                    let (colors, positions) = super::try_expand_gradient_steps(
                        &g.colors,
                        &positions,
                        g.blur,
                        g.step_center,
                        storage,
                    )?;
                    storage.bytes(std::mem::size_of::<GradientFillInfo>())?;
                    Some(Box::new(GradientFillInfo {
                        gradient_type: g.gradient_type,
                        angle: g.angle,
                        center_x: g.center_x,
                        center_y: g.center_y,
                        colors,
                        positions,
                    }))
                }
            } else {
                None
            }
        }
        _ => None,
    };

    let image_fill = match bf.fill.fill_type {
        FillType::Image => bf.fill.image.as_ref().map(|img| ResolvedImageFill {
            bin_data_id: img.bin_data_id,
            fill_mode: img.fill_mode,
            brightness: img.brightness,
            contrast: img.contrast,
            effect: image_fill_effect(img.effect),
        }),
        _ => None,
    };

    Ok(ResolvedBorderStyle {
        borders: bf.borders,
        fill_color,
        pattern,
        gradient,
        image_fill,
        diagonal_attr: bf.attr,
        break_cell_separate_line: bf.break_cell_separate_line,
        diagonal: bf.diagonal,
        center_line: if bf.center_line != CenterLine::None {
            bf.center_line
        } else {
            CenterLine::from_hwp_attr(bf.attr)
        },
    })
}

fn image_fill_effect(effect: u8) -> ImageEffect {
    match effect {
        1 => ImageEffect::GrayScale,
        2 => ImageEffect::BlackWhite,
        3 => ImageEffect::Pattern8x8,
        _ => ImageEffect::RealPic,
    }
}

#[cfg(test)]
mod tests;