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
//! 폰트 메트릭 조회 facade.
//!
//! Task #4964 W6에서 historical generated data와 measured/manual overlay를 물리적으로 분리했다.
//! 이 파일은 공통 type, 별칭, lookup/index와 두 data 영역의 기존 순서 합성만 소유한다.

use std::collections::HashMap;
use std::sync::OnceLock;

use crate::renderer::font_rule_layout_metric_projection::find_font_rule_layout_metric;

#[path = "font_metrics_vertical.rs"]
mod vertical;
pub(crate) use vertical::win_descent_em;

#[path = "font_metric_han_santteut.rs"]
mod han_santteut;

#[path = "font_metric_legacy_hft.rs"]
mod legacy_hft;

#[path = "font_metric_hci_poppy.rs"]
mod hci_poppy;

#[path = "font_metric_hci_tulip.rs"]
mod hci_tulip;

#[path = "font_metric_math_alphabet.rs"]
mod math_alphabet;

#[path = "font_metric_math_symbols.rs"]
mod math_symbols;

#[path = "font_metric_cjk_punctuation.rs"]
mod cjk_punctuation;
#[path = "font_metric_supplementary_pictographs.rs"]
mod supplementary_pictographs;

#[path = "font_metric_contextual_scripts.rs"]
mod contextual_scripts;
#[path = "font_metric_math_symbol_blocks.rs"]
mod math_symbol_blocks;

#[path = "font_metric_hangul_jamo.rs"]
mod hangul_jamo;

pub(crate) fn uses_hangul_jamo_overlay(metric: &FontMetric, character: char) -> bool {
    hangul_jamo::width(metric, character).is_some()
}
#[path = "font_metric_symbol_slot_chars.rs"]
mod symbol_slot_chars;

#[path = "font_metric_nimbus_roman.rs"]
mod nimbus_roman;

pub(crate) use legacy_hft::{
    centered_bar_advance_em as original_hft_centered_bar_advance_em,
    is_metric_face as is_legacy_hft_metric_face, metric_face_name as legacy_hft_metric_face,
};

/// 독립 Print와 원본 HFT에서 확인한 전진 표인지 구분한다.
/// 표시용 글꼴 프로그램의 hmtx는 이 표의 원본 정밀도를 대신하지 않는다.
pub(crate) fn is_verified_original_hft_advance(metric: &FontMetric) -> bool {
    hci_poppy::METRICS
        .iter()
        .any(|source| std::ptr::eq(source, metric))
}

#[derive(Debug)]
pub struct HangulMetric {
    pub cho_groups: u8,
    pub jung_groups: u8,
    pub jong_groups: u8,
    pub cho_map: &'static [u8],
    pub jung_map: &'static [u8],
    pub jong_map: &'static [u8],
    pub widths: &'static [u16],
}

#[derive(Debug)]
pub struct FontMetric {
    pub name: &'static str,
    pub bold: bool,
    pub italic: bool,
    pub em_size: u16,
    pub latin_ranges: &'static [LatinRange],
    pub hangul: Option<&'static HangulMetric>,
}

/// Source SFNT hhea descent for the Windows Korean UI families. Like the
/// generated advance tables this is program metadata, independent of an
/// installed rendering substitute. Gulim.ttc faces 0..=3 have upem=1024 and
/// descender=-145; provenance is recorded with the TAC baseline qualification.
/// Other programs retain the caller's existing compatibility fallback.
pub(crate) fn source_descent_em(name: &str, bold: bool, italic: bool) -> Option<f64> {
    let metric = find_metric(name, bold, italic)?.metric;
    match metric.name {
        "Gulim" | "GulimChe" | "Dotum" | "DotumChe" => Some(145.0 / 1024.0),
        _ => None,
    }
}

#[derive(Debug)]
pub struct LatinRange {
    pub start: u32,
    pub end: u32,
    pub widths: &'static [u16],
}

impl FontMetric {
    pub fn get_width(&self, ch: char) -> Option<u16> {
        let code = ch as u32;
        if let Some(width) = hangul_jamo::width(self, ch) {
            return Some(width);
        }
        // 한글 음절 (U+AC00~U+D7A3)
        if code >= 0xAC00 && code <= 0xD7A3 {
            if let Some(h) = self.hangul {
                let idx = code - 0xAC00;
                let cho = (idx / (21 * 28)) as usize;
                let jung = ((idx % (21 * 28)) / 28) as usize;
                let jong = (idx % 28) as usize;
                let gi = h.cho_map[cho] as usize * h.jung_groups as usize * h.jong_groups as usize
                    + h.jung_map[jung] as usize * h.jong_groups as usize
                    + h.jong_map[jong] as usize;
                return h.widths.get(gi).copied();
            }
            return None;
        }
        // Latin 및 기타 범위
        for range in self.latin_ranges {
            if code < range.start || code > range.end {
                continue;
            }
            let idx = (code - range.start) as usize;
            let Some(&w) = range.widths.get(idx) else {
                continue;
            };
            return if w > 0 {
                Some(w)
            } else {
                supplementary_pictographs::width(self, ch)
                    .or_else(|| contextual_scripts::width(self, ch))
            };
        }
        // 기존 범위는 그대로 우선하며, 확인된 프로그램의 누락 구간만 보충한다.
        verified_technical_symbol_width(self, ch)
            .or_else(|| math_symbols::width(self, ch))
            .or_else(|| math_alphabet::width(self, ch))
            .or_else(|| math_symbol_blocks::width(self, ch))
            .or_else(|| supplementary_pictographs::width(self, ch))
            .or_else(|| contextual_scripts::width(self, ch))
            .or_else(|| symbol_slot_chars::width(self, ch))
    }
}

include!("font_metrics_technical_symbols.rs");

/// 실제 프로그램에서 확인한 cmap. DB의 미수집 범위를 glyph 결측으로 취급하지 않는다.
pub(crate) fn verified_metric_has_glyph(metric: &FontMetric, ch: char) -> Option<bool> {
    if nimbus_roman_metric_source(metric).is_some() {
        // These ranges cover the actual program's complete Unicode cmap.
        return Some(metric.get_width(ch).is_some());
    }
    verified_program_has_glyph(metric, ch)
        .or_else(|| math_symbols::has_glyph(metric, ch))
        .or_else(|| math_alphabet::entry(metric, ch).map(|(present, _)| present))
        .or_else(|| cjk_punctuation::primary_has_glyph(metric.name, metric.bold, metric.italic, ch))
        .or_else(|| math_symbol_blocks::entry(metric, ch).map(|(present, _)| present))
        .or_else(|| supplementary_pictographs::entry(metric, ch).map(|(present, _)| present))
        .or_else(|| contextual_scripts::entry(metric, ch).map(|(present, _)| present))
        .or_else(|| symbol_slot_chars::entry(metric, ch).map(|(present, _)| present))
}

/// DB 항목이 없어도 확인한 원 face의 cmap은 독립적으로 조회한다.
pub(crate) fn verified_named_program_has_glyph(
    family: &str,
    bold: bool,
    italic: bool,
    ch: char,
) -> Option<bool> {
    math_alphabet::primary_has_glyph(family, bold, italic, ch)
        .or_else(|| cjk_punctuation::primary_has_glyph(family, bold, italic, ch))
        .or_else(|| supplementary_pictographs::primary_has_glyph(family, bold, italic, ch))
        .or_else(|| contextual_scripts::primary_has_glyph(family, bold, italic, ch))
}

/// 확인한 원 프로그램의 결측 글리프 공급 체인. 기본 face의 폭 계약은 바꾸지 않는다.
pub(crate) fn verified_program_glyph_fallback_families(face: &str) -> &'static [&'static str] {
    // HMKMM.TTF의 cmap에는 U+2024가 없고 HBATANG.TTF에는 있다.
    // 독립 개인정보 Print의 같은 제목도 휴먼명조 사이에서 이 기호만
    // Haansoft Batang으로 출력한다. 이름 별칭은 기존 메트릭 선택기가 해소한다.
    match find_metric(face, false, false).map(|found| found.metric.name) {
        Some("HumanMyeongJo" | "DotumChe" | "HYSinMyeongJo-Medium" | "HYHeadLine-Medium") => {
            &["Haansoft Batang"]
        }
        // Gulim U+2024의 측정도 아래 verified_missing_glyph_supplier가
        // HDOTUM에 맡긴다. 같은 공급자를 실제 paint 후보에도 전달한다.
        // [#8619] Dotum 도 같은 gulim.ttc 의 U+2024 결측이며 독립 Print 는 HDOTUM 으로 그린다.
        Some("Gulim" | "Dotum") => &["Haansoft Dotum"],
        _ => &[],
    }
}

/// 원 프로그램의 결측과 독립 Print의 공급 face를 함께 확인한 기호만 해소한다.
/// 폭 표의 누락만으로 공급자를 추측하지 않으며, HFT 호환 폭과의 경계는 호출자가 지킨다.
pub(crate) fn verified_missing_glyph_supplier(
    metric: &FontMetric,
    ch: char,
) -> Option<&'static str> {
    match (metric.name, metric.em_size, metric.bold, metric.italic, ch) {
        // arial.ttf b2374214…abfd의 cmap에는 두 점이 없다. 명시적 Arial
        // 대조군의 독립 한컴2020 Print는 두 문자 모두 HBATANG으로 출력한다.
        // Arial의 다른 문자나 다른 weight/style의 공급자는 변경하지 않는다.
        ("Arial", 2048, false, false, '\u{2024}' | '\u{2027}') => Some("Haansoft Batang"),
        // gulim.TTC의 DotumChe cmap에는 U+2024가 없다(SHA ed750275…776c).
        // 근린생활시설 표의 독립 Print는 HBATANG의 0.173em 글리프로 출력하며,
        // HBATANG.TTF의 hmtx 178/1024도 같은 자연 전진을 확인한다.
        ("DotumChe", 1024, false, false, '\u{2024}') => Some("Haansoft Batang"),
        // 같은 gulim.TTC의 GulimChe도 이 글리프가 없다. 위임전결규정의
        // 독립2020 Print44·86쪽은 HBATANG178/1024em과 같은 윤곽으로 공급한다.
        // 폭 표에 없는 문자를 고정폭1em으로 추정하지 않는다. 다른 기호는 유지한다.
        ("GulimChe", 1024, false, false, '\u{2024}') => Some("Haansoft Batang"),
        // [#8419] batang.ttc(SHA 51d9a8d4…c9d8)의 Batang cmap에도 U+2024가 없다.
        // 10645 운영지침의 독립 한컴2022 Print는 바탕 사이의 `․`만 Haansoft Batang
        // CID 글꼴로 출력한다. U+2027과 다른 weight/style은 확인하지 않아 바꾸지 않는다.
        ("Batang", 1024, false, false, '\u{2024}') => Some("Haansoft Batang"),
        // 법원 서식 Print의 Haansoft Dotum CID 3과 HDOTUM hmtx의 대응.
        ("Gulim", 1024, false, false, '\u{2024}' | '\u{2027}') => Some("Haansoft Dotum"),
        // [#8619] gulim.ttc(SHA 05a38ff2…ee12)의 Dotum cmap에도 U+2024가 없다.
        // 평가결과서(docs#648)의 독립 한컴2022 Print는 돋움 사이의 `․`만 Haansoft
        // Dotum CID 글꼴의 0.173em으로 출력한다. U+2027과 다른 weight/style은 바꾸지 않는다.
        ("Dotum", 1024, false, false, '\u{2024}') => Some("Haansoft Dotum"),
        // 기호 슬롯을 HY신명조 TTF로 지정한 독립2020 Print의 두 점은
        // HBATANG이다. HFT 한양신명조의 전진은 해당 overlay가 보존한다.
        ("HYSinMyeongJo-Medium", 1024, false, false, '\u{2024}' | '\u{2027}') => {
            Some("Haansoft Batang")
        }
        // H2HDRM의 확인된 U+2024 결측과 독립 한컴2020 Print의 실제 공급자다.
        // 음영/양각의 세 replay 모두 HBATANG을 사용하며 자연 전진은 기존
        // 공급 프로그램의 hmtx를 소비한다. 다른 문자·weight는 추정하지 않는다.
        ("HYHeadLine-Medium", 1024, false, false, '\u{2024}') => Some("Haansoft Batang"),
        _ => None,
    }
}

/// find_metric의 반환값: 메트릭 + 폴백 정보
pub struct MetricMatch {
    pub metric: &'static FontMetric,
    /// Bold 요청했으나 Bold 메트릭이 없어 Regular로 폴백됨
    /// → Faux Bold 폭 보정이 필요한 경우 true
    pub bold_fallback: bool,
}

/// 내장 메트릭 색인이 선택한 기존 3단 폴백 사다리의 단계.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MetricMatchKind {
    Exact,
    BoldOnly,
    NameFirst,
}

impl MetricMatchKind {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Exact => "exact",
            Self::BoldOnly => "boldOnly",
            Self::NameFirst => "nameFirst",
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct MetricSelection {
    metric: &'static FontMetric,
    bold_fallback: bool,
    match_kind: MetricMatchKind,
    entry_index: usize,
}

/// `find_metric`가 숨겨 온 별칭과 선택 단계. 기존 반환값의 관측용 확장이다.
#[derive(Debug, Clone, Copy)]
pub(crate) struct MetricLookupDecision<'a> {
    pub(crate) requested_name: &'a str,
    pub(crate) alias_resolved_name: &'a str,
    pub(crate) alias_rule_id: Option<&'static str>,
    pub(crate) metric: &'static FontMetric,
    pub(crate) bold_fallback: bool,
    pub(crate) match_kind: MetricMatchKind,
    pub(crate) entry_index: usize,
}

/// Canonical font rule projection에서 metric alias와 W2 ruleId를 함께 해소한다.
fn resolve_projected_metric_alias(name: &str) -> (&str, Option<&'static str>) {
    match find_font_rule_layout_metric(name) {
        Some(rule) => (rule.target_face_or_policy, Some(rule.rule_id)),
        // 단축키 원본의 영문 글꼴명은 한국어 family 이름으로 저장되지만,
        // 같은 설치 글꼴의 내장 폭 표는 영문 family 이름으로 수록돼 있다.
        // YNCH05.TTF의 숫자 1은 530/1000em이며 한컴 PDF도 이 폭을 쓴다.
        None if name == "양재난초체M" => ("Yj NANCHO Medium", None),
        None => (name, None),
    }
}

/// PostScript 이름의 굵기 접미사(`-Regular`/`-Medium`/`-Bold`)를 떼어 family 와 Bold 여부를 돌려준다.
fn strip_postscript_weight_suffix(name: &str) -> Option<(&str, bool)> {
    let (family, weight) = name.rsplit_once('-')?;
    match weight {
        "Regular" | "Medium" => Some((family, false)),
        "Bold" => Some((family, true)),
        _ => None,
    }
}

/// (bold, italic) → 색인 슬롯 번호. 조합이 4개뿐이라 이름당 배열로 선계산한다.
fn metric_slot_index(bold: bool, italic: bool) -> usize {
    ((bold as usize) << 1) | (italic as usize)
}

/// 이름별 선계산 색인 — 슬롯 값은 (metric, bold_fallback).
///
/// [#4149] 글자 측정마다 find_metric 이 호출되어 600 엔트리 선형 스캔
/// (문자열 비교 × 최대 3단 폴백)이 캐럿 rect 질의 지연의 주요 원인이었다.
/// 이름이 테이블에 있으면 3단(이름만 매칭)이 항상 성공하므로 슬롯에 Option 이
/// 필요 없고, 조회 실패 = 이름 부재 = 기존 None 과 동일하다.
///
/// 키를 (name, bold, italic) 튜플 대신 이름 단독으로 두는 이유: 튜플 키는
/// &'static str 수명 때문에 임의 사용자 폰트명(&str)으로 borrow 조회가 불가능하다.
static METRIC_INDEX: OnceLock<HashMap<&'static str, [MetricSelection; 4]>> = OnceLock::new();

fn metric_index() -> &'static HashMap<&'static str, [MetricSelection; 4]> {
    METRIC_INDEX.get_or_init(|| {
        // 선형 스캔의 "테이블 첫 매칭 우선" 계약 재현: 테이블 순서대로 순회하며
        // (name, bold, italic) 조합별 첫 엔트리와 이름 첫 등장 엔트리만 기록한다.
        struct FirstSeen {
            exact: [Option<(&'static FontMetric, usize)>; 4],
            first: (&'static FontMetric, usize),
        }
        let mut seen: HashMap<&'static str, FirstSeen> = HashMap::new();
        for (entry_index, m) in FONT_METRICS.iter().enumerate() {
            let entry = seen.entry(m.name).or_insert(FirstSeen {
                exact: [None; 4],
                first: (m, entry_index),
            });
            let idx = metric_slot_index(m.bold, m.italic);
            if entry.exact[idx].is_none() {
                entry.exact[idx] = Some((m, entry_index));
            }
        }
        // 슬롯 선주입 순서 = legacy 폴백 사다리와 동일:
        // 1단 정확 매칭 → 2단 bold 매칭(italic 무시) → 3단 이름만 첫 엔트리.
        seen.into_iter()
            .map(|(name, fs)| {
                let mut slots = [MetricSelection {
                    metric: fs.first.0,
                    bold_fallback: false,
                    match_kind: MetricMatchKind::NameFirst,
                    entry_index: fs.first.1,
                }; 4];
                for bold in [false, true] {
                    for italic in [false, true] {
                        slots[metric_slot_index(bold, italic)] =
                            if let Some((metric, entry_index)) =
                                fs.exact[metric_slot_index(bold, italic)]
                            {
                                MetricSelection {
                                    metric,
                                    bold_fallback: false,
                                    match_kind: MetricMatchKind::Exact,
                                    entry_index,
                                }
                            } else if let Some((metric, entry_index)) =
                                fs.exact[metric_slot_index(bold, false)]
                            {
                                MetricSelection {
                                    metric,
                                    bold_fallback: false,
                                    match_kind: MetricMatchKind::BoldOnly,
                                    entry_index,
                                }
                            } else {
                                // bold 요청이었으면 Faux Bold 보정 표시 (legacy 3단과 동일)
                                MetricSelection {
                                    metric: fs.first.0,
                                    bold_fallback: bold,
                                    match_kind: MetricMatchKind::NameFirst,
                                    entry_index: fs.first.1,
                                }
                            };
                    }
                }
                (name, slots)
            })
            .collect()
    })
}

pub fn find_metric(name: &str, bold: bool, italic: bool) -> Option<MetricMatch> {
    let decision = find_metric_decision(name, bold, italic)?;
    Some(MetricMatch {
        metric: decision.metric,
        bold_fallback: decision.bold_fallback,
    })
}

/// 이름 하나의 별칭·색인 해석. `bold`/`italic` 과 무관하다.
#[derive(Clone, Copy)]
struct MetricNameResolution {
    /// 별칭이 요청 이름과 다르면 그 정적 이름.
    alias: Option<&'static str>,
    alias_rule_id: Option<&'static str>,
    slots: Option<&'static [MetricSelection; 4]>,
}

/// 글자마다 불리므로 최근 이름 몇 개의 해석을 보관한다. 결과는 이름만으로 정해진다.
fn resolve_metric_name(name: &str) -> MetricNameResolution {
    const RECENT: usize = 8;
    thread_local! {
        static RECENT_NAMES: std::cell::RefCell<Vec<(Box<str>, MetricNameResolution)>> =
            const { std::cell::RefCell::new(Vec::new()) };
    }
    RECENT_NAMES.with(|recent| {
        let mut recent = recent.borrow_mut();
        if let Some((_, resolution)) = recent.iter().find(|(cached, _)| **cached == *name) {
            return *resolution;
        }
        let (alias_resolved_name, alias_rule_id) = resolve_projected_metric_alias(name);
        let resolution = MetricNameResolution {
            alias: static_metric_alias(name),
            alias_rule_id,
            slots: metric_index().get(alias_resolved_name),
        };
        if recent.len() >= RECENT {
            recent.remove(0);
        }
        recent.push((name.into(), resolution));
        resolution
    })
}

/// `resolve_projected_metric_alias` 가 요청 이름 대신 돌려주는 정적 별칭.
fn static_metric_alias(name: &str) -> Option<&'static str> {
    match find_font_rule_layout_metric(name) {
        Some(rule) => Some(rule.target_face_or_policy),
        None if name == "양재난초체M" => Some("Yj NANCHO Medium"),
        None => None,
    }
}

pub(crate) fn find_metric_decision<'a>(
    name: &'a str,
    bold: bool,
    italic: bool,
) -> Option<MetricLookupDecision<'a>> {
    let mut resolution = resolve_metric_name(name);
    let mut lookup_name = name;
    let mut bold = bold;
    if resolution.slots.is_none() {
        let (family, suffix_bold) = strip_postscript_weight_suffix(name)?;
        lookup_name = family;
        resolution = resolve_metric_name(family);
        bold |= suffix_bold;
    }
    let alias_resolved_name = resolution.alias.unwrap_or(lookup_name);
    let alias_rule_id = resolution.alias_rule_id;
    let slots = resolution.slots?;
    let selected = slots[metric_slot_index(bold, italic)];
    Some(MetricLookupDecision {
        requested_name: name,
        alias_resolved_name,
        alias_rule_id,
        metric: selected.metric,
        bold_fallback: selected.bold_fallback,
        match_kind: selected.match_kind,
        entry_index: selected.entry_index,
    })
}

/// [#8079] 굵은 글자의 **조판 전진폭**을 줄 같은 family 의 보통(Regular) 표.
///
/// 한/글은 별도 Bold 면이 있는 TrueType 의 굵은 글자를 Bold 면으로 그리지만, 글자 원점은
/// 보통 면의 전진폭으로 잡는다. 한컴 PDF 는 임베드 Bold `/W` 를 그대로 둔 채 TJ 조정으로
/// 다음 글자를 당긴다 — 맑은 고딕 Bold 숫자 `/W` 579/1000 뒤 `29.000` = 보통 1128/2048(0.55em).
/// `pdf/` 한컴 정본 205개 전수(TJ 안 글자의 `/W − 조정`)에서 굵은 맑은 고딕은 보통 폭 쪽이
/// 26,893자, Bold 폭 쪽이 357자다. Arial Bold·Times New Roman Bold 도 Bold 폭 쪽은 0자다.
///
/// 같은 이름·같은 기울임의 보통 항목이 **정확히** 있을 때만 돌려준다. em 이 다르면 같은
/// 격자로 비교할 근거가 없어 None. 글리프 선택·결측 판정은 이 표가 아니라 Bold 항목이 맡는다.
pub(crate) fn regular_advance_metric(bold_metric: &FontMetric) -> Option<&'static FontMetric> {
    if !bold_metric.bold {
        return None;
    }
    let slots = metric_index().get(bold_metric.name)?;
    let regular = slots[metric_slot_index(false, bold_metric.italic)];
    (regular.match_kind == MetricMatchKind::Exact
        && !regular.metric.bold
        && regular.metric.italic == bold_metric.italic
        && regular.metric.em_size == bold_metric.em_size)
        .then_some(regular.metric)
}

/// 원본 프로그램에서 확인한 문자 폭은 표시 대체 글꼴의 완전한 표보다 우선한다.
/// 부분 표의 미측정 문자·확인하지 않은 정체는 기존 색인 선택을 그대로 쓴다.
pub(crate) fn find_metric_decision_for_character<'a>(
    name: &'a str,
    bold: bool,
    italic: bool,
    character: char,
) -> Option<MetricLookupDecision<'a>> {
    let mut decision = find_metric_decision(name, bold, italic)?;
    // 부분 HFT 표에 새로 확인한 일반 glyph를 굵게·기울임의 공급 근거로
    // 상속하지 않는다. 확인하지 않은 서식은 기존 표시 대체 조회가 폭을 소유한다.
    if legacy_hft::is_metric_face(decision.metric.name)
        && legacy_hft::rejects_regular_bar_style(decision.metric.name, bold, italic, character)
    {
        return None;
    }
    if character.is_whitespace() {
        return Some(decision);
    }
    let Some((source_slot, source)) = hci_poppy::METRICS.iter().enumerate().find(|(_, source)| {
        decision.alias_resolved_name == source.name
            && bold == source.bold
            && italic == source.italic
            && source.get_width(character).is_some()
    }) else {
        return Some(decision);
    };
    static SOURCE_INDICES: OnceLock<Vec<Option<usize>>> = OnceLock::new();
    let indices = SOURCE_INDICES.get_or_init(|| {
        hci_poppy::METRICS
            .iter()
            .map(|source| {
                FONT_METRICS
                    .iter()
                    .position(|entry| std::ptr::eq(entry, source))
            })
            .collect()
    });
    if let Some(index) = indices[source_slot] {
        // 각 표가 가진 em을 함께 선택한다. em=1000의 폭을 em=2048 표에
        // 정수 반올림해 섞지 않으며 가운뎃점 등 기존 독립 측정도 보존한다.
        decision.metric = source;
        decision.entry_index = index;
        decision.match_kind = MetricMatchKind::Exact;
        decision.bold_fallback = false;
    }
    Some(decision)
}

/// [#4709] 이 스타일의 글자폭 배치에 실제로 쓰인 내장 메트릭 face 이름.
///
/// `measure_char_width_embedded`(text_measurement.rs)의 해석 순서를 따른다:
/// CSS 체인 첫 face → KoPub 전용 표 → 별칭 해석 → 메트릭 DB. DB 에 없는
/// face(폭이 휴리스틱 추정으로 결정되는 경우)는 None — 주석도 붙이지 않는다.
pub fn layout_metric_face_name(font_family: &str, bold: bool, italic: bool) -> Option<String> {
    let primary = font_family
        .split(',')
        .next()
        .unwrap_or(font_family)
        .trim()
        .trim_matches('\'');
    // KoPub 은 kopub_char_width 전용 표가 find_metric 보다 앞선다 — face 자체가 정체.
    // `measure_char_width_embedded` 의 `KoPubFamily::from_primary` 와 같은 이름 판정
    // (`KoPubWorld` 개정판도 구분하며 각 face의 전진폭은 해당 측정 표가 결정한다).
    let lower = primary.to_lowercase().replace(' ', "");
    if primary.contains("KoPub돋움체")
        || primary.contains("KoPubWorld돋움체")
        || lower.contains("kopubdotum")
        || lower.contains("kopubworlddotum")
        || primary.contains("KoPub바탕체")
        || primary.contains("KoPubWorld바탕체")
        || lower.contains("kopubbatang")
        || lower.contains("kopubworldbatang")
    {
        return Some(primary.to_string());
    }
    find_metric(primary, bold, italic).map(|m| m.metric.name.to_string())
}

/// 기존 선형 스캔 구현 — 색인 등가성 검증 전용으로 보존 (수정 금지).
#[cfg(test)]
fn legacy_find_metric(name: &str, bold: bool, italic: bool) -> Option<MetricMatch> {
    let (name, _) = resolve_projected_metric_alias(name);
    // 정확한 매칭 (name + bold + italic)
    if let Some(m) = FONT_METRICS
        .iter()
        .find(|m| m.name == name && m.bold == bold && m.italic == italic)
    {
        return Some(MetricMatch {
            metric: m,
            bold_fallback: false,
        });
    }
    // bold만 매칭 (italic 무시)
    if let Some(m) = FONT_METRICS
        .iter()
        .find(|m| m.name == name && m.bold == bold && !m.italic)
    {
        return Some(MetricMatch {
            metric: m,
            bold_fallback: false,
        });
    }
    // Regular 폴백 — bold 요청이었으면 bold_fallback 표시
    FONT_METRICS
        .iter()
        .find(|m| m.name == name)
        .map(|m| MetricMatch {
            metric: m,
            bold_fallback: bold,
        })
}

include!("font_metrics_generated.rs");
include!("font_metrics_overlays.rs");
include!("font_metrics_core14.rs");

/// Published AFMs are independent of the historical 600-entry evidence ledger.
pub(crate) fn core14_metric_source(metric: &FontMetric) -> Option<(&'static str, &'static str)> {
    if !CORE14_FONT_METRICS
        .iter()
        .any(|entry| std::ptr::eq(entry, metric))
    {
        return None;
    }
    Some(match (metric.bold, metric.italic) {
        (false, false) => (
            "data/font-metrics/adobe-core14/Helvetica.afm",
            "CORE14_0_RANGES",
        ),
        (true, false) => (
            "data/font-metrics/adobe-core14/Helvetica-Bold.afm",
            "CORE14_1_RANGES",
        ),
        (false, true) => (
            "data/font-metrics/adobe-core14/Helvetica-Oblique.afm",
            "CORE14_2_RANGES",
        ),
        (true, true) => (
            "data/font-metrics/adobe-core14/Helvetica-BoldOblique.afm",
            "CORE14_3_RANGES",
        ),
    })
}

/// Actual SFNT table measurements, separate from the historical rule ledger.
pub(crate) fn nimbus_roman_metric_source(metric: &FontMetric) -> Option<&'static str> {
    if !metric.name.starts_with("Nimbus") {
        return None;
    }
    nimbus_roman::METRICS
        .iter()
        .any(|entry| std::ptr::eq(entry, metric))
        .then_some("data/font-metrics/nimbus-roman/source.json")
}

/// 기존 600-entry 물리 순서를 보존하고 독립 AFM 메트릭을 뒤에 연결한다.
///
/// generated 595개와 measured overlay 5개를 정렬·dedupe하지 않는다.
struct FontMetrics;

static FONT_METRICS: FontMetrics = FontMetrics;

impl FontMetrics {
    fn iter(&self) -> impl Iterator<Item = &'static FontMetric> {
        GENERATED_FONT_METRICS
            .iter()
            .chain(MEASURED_FONT_METRIC_OVERLAYS.iter())
            .chain(CORE14_FONT_METRICS.iter())
            .chain(han_santteut::METRICS.iter())
            .chain(legacy_hft::METRICS.iter())
            .chain(hci_poppy::METRICS.iter())
            .chain(hci_tulip::METRICS.iter())
            .chain(nimbus_roman::METRICS.iter())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sha2::{Digest, Sha256};

    const NOTO_SANS_KR_REGULAR: &[u8] =
        include_bytes!("../../ttfs/opensource/NotoSansKR-Regular.ttf");

    #[test]
    fn issue_4442_noto_sans_kr_ascii_advances_match_tracked_font() {
        let digest = Sha256::digest(NOTO_SANS_KR_REGULAR);
        assert_eq!(
            &digest[..],
            &[
                0x6e, 0x06, 0xa7, 0xfe, 0x5d, 0x69, 0x6c, 0xa7, 0x19, 0x89, 0x4a, 0x23, 0xf3, 0x6b,
                0xb2, 0xb1, 0xbe, 0x8c, 0x81, 0x6a, 0x59, 0x37, 0xcd, 0x4a, 0xd0, 0xf2, 0x3c, 0xa6,
                0x77, 0x80, 0xdd, 0x74,
            ]
        );

        let face = ttf_parser::Face::parse(NOTO_SANS_KR_REGULAR, 0)
            .expect("tracked bundled font must parse");
        let metric = find_metric("Noto Sans KR", false, false).expect("shared regular metric");
        assert_eq!(metric.metric.em_size, face.units_per_em());
        for ch in ' '..='~' {
            let glyph = face.glyph_index(ch).expect("printable ASCII glyph");
            let advance = face
                .glyph_hor_advance(glyph)
                .expect("printable ASCII horizontal advance");
            assert_eq!(
                metric.metric.get_width(ch),
                Some(advance),
                "shared advance for {ch:?}"
            );
        }
    }

    #[test]
    fn hy_gothic_medium_maps_correctly() {
        let m = find_metric("HY중고딕", false, false);
        assert!(m.is_some(), "HY중고딕 매핑 실패");
        assert_eq!(m.unwrap().metric.name, "HYGothic-Medium");
    }

    #[test]
    fn hy_family_all_map() {
        for (korean, expected_english) in &[
            ("HY중고딕", "HYGothic-Medium"),
            ("HY견고딕", "HYGothic-Extra"),
            ("HY헤드라인M", "HYHeadLine-Medium"),
            ("HY견명조", "HYMyeongJo-Extra"),
            ("HY신명조", "HYSinMyeongJo-Medium"),
            ("HY그래픽", "HYGraphic-Medium"),
            ("HY궁서", "HYGungSo-Bold"),
            ("한컴 윤고딕 230", "Haan YGodic 230"),
        ] {
            let m = find_metric(korean, false, false);
            assert!(m.is_some(), "{} 매핑 실패", korean);
            assert_eq!(
                m.unwrap().metric.name,
                *expected_english,
                "{} 이 {} 에 매핑되지 않음",
                korean,
                expected_english
            );
        }
    }

    #[test]
    fn source_han_sans_family_maps_to_pretendard() {
        for name in &[
            "본한글",
            "본한글vf",
            "본한글 Medium",
            "본한글M",
            "본고딕",
            "본고딕vf",
            "Source Han Sans",
            "Source Han Sans K",
            "Source Han Sans KR",
            "SourceHanSans",
            "SourceHanSansKR",
            "SourceHanSansK",
            "Noto Sans CJK KR",
        ] {
            let m = find_metric(name, false, false);
            assert!(m.is_some(), "{} 매핑 실패 (Pretendard 기대)", name);
            assert_eq!(m.unwrap().metric.name, "Pretendard");
        }
    }

    #[test]
    fn source_han_serif_family_maps_to_noto_serif_kr() {
        for name in &[
            "본명조",
            "본명조vf",
            "본명조M",
            "Source Han Serif",
            "Source Han Serif K",
            "Source Han Serif KR",
            "SourceHanSerif",
            "SourceHanSerifKR",
            "SourceHanSerifK",
            "Noto Serif CJK KR",
        ] {
            let m = find_metric(name, false, false);
            assert!(m.is_some(), "{} 매핑 실패 (Noto Serif KR 기대)", name);
            assert_eq!(m.unwrap().metric.name, "Noto Serif KR");
        }
    }

    #[test]
    fn hy_family_bold_fallback() {
        // HY 계열은 DB 에 bold 변형이 없음 (Stage 1 실측 확인).
        // bold=true 요청 시 Regular 폴백 + bold_fallback=true 반환.
        let m = find_metric("HY중고딕", true, false);
        assert!(m.is_some(), "HY중고딕 bold 폴백 실패");
        let mm = m.unwrap();
        assert_eq!(mm.metric.name, "HYGothic-Medium");
        assert!(
            mm.bold_fallback,
            "HY중고딕 bold 요청 시 bold_fallback=true 여야 함"
        );
    }

    #[test]
    fn task885_hy_extra_aliases_resolve() {
        // Task #885 — 한국어 사용명 → DB 단축명 매핑 회귀 테스트.
        // 우변 메트릭이 FONT_METRICS 에 실재해야 하며 (feedback_font_metrics_alias_sync),
        // find_metric 이 Some 반환 + name 일치를 보장한다.
        for (korean, expected_english) in &[
            ("HY수평선B", "HYsupB"),
            ("HY수평선M", "HYsupM"),
            ("HY울릉도B", "HYwulB"),
            ("HY울릉도M", "HYwulM"),
            ("HY태백B", "HYtbrB"),
            ("HY동녘B", "HYdnkB"),
            ("HY동녘M", "HYdnkM"),
            ("HY각헤드라인M", "HYHeadLine-Medium"),
        ] {
            let m = find_metric(korean, false, false);
            assert!(m.is_some(), "{} 별칭 매핑 실패", korean);
            assert_eq!(
                m.unwrap().metric.name,
                *expected_english,
                "{} 이 {} 에 매핑되지 않음",
                korean,
                expected_english
            );
        }
    }

    #[test]
    fn non_korean_font_unchanged() {
        let m = find_metric("함초롬바탕", false, false);
        assert!(m.is_some(), "함초롬바탕 기존 매핑 회귀");
        assert_eq!(m.unwrap().metric.name, "HCR Batang");
    }

    #[test]
    fn index_matches_legacy_linear_scan_exhaustively() {
        // [#4149] O(1) 색인 도입 계약: legacy 선형 스캔(3단 폴백 사다리)과
        // 결과가 100% 동일해야 한다. FONT_METRICS 전체 name + 알려진 alias
        // 전체 + 테이블에 없는 임의 이름 × (bold, italic) 4조합 전수 비교.
        let mut names: Vec<&str> = FONT_METRICS.iter().map(|m| m.name).collect();
        // resolve_metric_alias 좌변 전체 (별칭 추가 시 여기도 갱신).
        names.extend([
            "함초롬돋움",
            "한컴돋움",
            "돋움",
            "함초롬바탕",
            "한컴바탕",
            "바탕",
            "맑은 고딕",
            "나눔고딕",
            "나눔명조",
            "바탕체",
            "굴림",
            "궁서",
            "굴림체",
            "돋움체",
            "궁서체",
            "D2Coding",
            "D2 Coding",
            "고운바탕",
            "Gowun Batang",
            "고운돋움",
            "Gowun Dodum",
            "Pretendard",
            "프리텐다드",
            "HY중고딕",
            "HY견고딕",
            "HY헤드라인M",
            "HY견명조",
            "HY신명조",
            "HY그래픽",
            "HY궁서",
            "한양신명조",
            "한양중고딕",
            "한양견명조",
            "한양견고딕",
            "휴먼명조",
            "신명조",
            "HY수평선B",
            "HY수평선M",
            "HY울릉도B",
            "HY울릉도M",
            "HY태백B",
            "HY동녘B",
            "HY동녘M",
            "HY각헤드라인M",
            "본한글",
            "본한글vf",
            "본한글 Medium",
            "본한글M",
            "본고딕",
            "본고딕vf",
            "Source Han Sans",
            "Source Han Sans K",
            "Source Han Sans KR",
            "SourceHanSans",
            "SourceHanSansKR",
            "SourceHanSansK",
            "Noto Sans CJK KR",
            "본명조",
            "본명조vf",
            "본명조M",
            "Source Han Serif",
            "Source Han Serif K",
            "Source Han Serif KR",
            "SourceHanSerif",
            "SourceHanSerifKR",
            "SourceHanSerifK",
            "Noto Serif CJK KR",
        ]);
        // 테이블에 없는 임의 사용자 폰트명 — 기존과 동일하게 None 이어야 한다.
        names.extend([
            "NoSuchFont-Regular",
            "가상의사용자폰트",
            "Comic Sans MS",
            "",
        ]);

        for name in names {
            for bold in [false, true] {
                for italic in [false, true] {
                    let new = find_metric(name, bold, italic);
                    let old = legacy_find_metric(name, bold, italic);
                    match (new, old) {
                        (None, None) => {}
                        (Some(n), Some(o)) => {
                            assert!(
                                std::ptr::eq(n.metric, o.metric),
                                "metric 불일치: {name:?} bold={bold} italic={italic} \
                                 (new={}/b{}/i{}, old={}/b{}/i{})",
                                n.metric.name,
                                n.metric.bold,
                                n.metric.italic,
                                o.metric.name,
                                o.metric.bold,
                                o.metric.italic,
                            );
                            assert_eq!(
                                n.bold_fallback, o.bold_fallback,
                                "bold_fallback 불일치: {name:?} bold={bold} italic={italic}"
                            );
                        }
                        (n, o) => panic!(
                            "Some/None 불일치: {name:?} bold={bold} italic={italic} \
                             new={} old={}",
                            n.is_some(),
                            o.is_some()
                        ),
                    }
                }
            }
        }
    }
}