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
//! Caller-declared font availability for one rendering session, never document IR.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::error::HwpError;

/// 문서가 선언한 글꼴 이름 수는 레코드 번호로 제한되지 않는다. 공개 서식에서 267개까지 관측됐다.
/// 입력 환경 JSON의 크기 상한과 별도로, 프로그램 조회 상한과 같은 값을 쓴다.
const MAX_FONT_SUBSTITUTIONS: usize = 1024;

/// Explicit final face substitutions shared by layout and paint.
///
/// Global keys are exact document font names. Conflicting document declarations
/// retain their language/font-record address. Targets are single faces, not CSS
/// fallback chains. Mappings are applied once, not recursively.
/// This declaration does not prove that the backend has the target font.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FontEnvironment {
    id: String,
    substitutions: BTreeMap<String, String>,
    /// 실제 공급자가 조회한 이름·최종 프로그램 신원. 임의 표시 치환과 구별한다.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    selected_programs: BTreeMap<String, AvailableFontProgram>,
    /// 실제 공급 snapshot에서 조건을 충족한 canonical 선택의 출처다.
    /// 글꼴 설치·바이트 공급의 증명과 구분하며 명시적 환경에는 생략할 수 있다.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    selection_rules: BTreeMap<String, String>,
    /// 호출자가 실제 출력 프로그램을 확인한 TrueType 최종 face.
    /// 설치 증명은 아니며, 생략하면 기존 HFT 호환 메트릭을 유지한다.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    true_type_faces: Vec<String>,
    /// 자동 공급 선택은 표시 프로그램만 보완한다. 검증된 원본 HFT의
    /// 조판 폭까지 대체 프로그램의 폭으로 바꾸는 명시적 요청과 구분한다.
    /// 생략은 기존 메트릭 선언이며, 명시 false만 자연 윤곽의 선택으로 기록한다.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source_metric_policy"
    )]
    preserve_source_metrics: Option<bool>,
    /// 사용자가 자연 프로그램 전진을 명시적으로 선택한 원본만 예외로 둔다.
    /// 다른 원본의 자동 공급·저장 메트릭은 같은 세션에서도 유지한다.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    replace_source_metrics_for: Vec<String>,
    /// 호출자가 공급을 확인한 글리프 폴백. 키는 치환 후의 최종 face이며,
    /// 기본 face가 없는 글자만 이 순서로 측정·출력한다. IR에는 저장하지 않는다.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    glyph_fallbacks: BTreeMap<String, Vec<String>>,
    /// 같은 이름이라도 문서 언어 슬롯이 지정한 보조 글꼴은 다를 수 있다.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    document_glyph_fallbacks: Vec<DocumentGlyphFallback>,
    /// 같은 원본 이름이라도 언어 슬롯/글꼴 레코드가 지정한 프로그램은 다를 수 있다.
    /// 전역 치환으로 합칠 수 없는 선택만 원본 주소와 함께 보존한다.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    document_substitutions: Vec<DocumentFontSubstitution>,
}

/// 선택 신원은 Native의 SFNT+face index 또는 브라우저의 독립 SFNT 자원 해시다.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FontProgramIdentity {
    digest: [u8; 32],
    standalone_resource: bool,
}
crate::storage::clone_copy!(FontProgramIdentity);

impl FontProgramIdentity {
    pub(crate) fn matches(
        &self,
        source_digest: &[u8; 32],
        indexed_digest: &[u8; 32],
        face_index: u32,
    ) -> bool {
        if self.standalone_resource {
            face_index == 0 && &self.digest == source_digest
        } else {
            &self.digest == indexed_digest
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct DocumentGlyphFallback {
    language_slot: usize,
    font_id: u16,
    source: String,
    faces: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct DocumentFontSubstitution {
    language_slot: usize,
    font_id: u16,
    source: String,
    target: String,
    program_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    query: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    selection_rule: Option<String>,
}

/// 실제 프로그램 조회용 이름이다. generic·호환 대체는 설치 별칭에 포함하지 않는다.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentFontSelectionRequest {
    pub source: String,
    pub primary: Vec<String>,
    pub substitute: Vec<String>,
    /// 원본·문서 지정 프로그램이 모두 없을 때만 시도할 공개 프로그램.
    /// 선언 이름을 무조건 정규화하는 alias와 구분한다.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub public_fallback: Vec<String>,
}

/// 출력 호스트가 실제로 로드한 프로그램. 형식 미확인 시 HFT 메트릭을 유지한다.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AvailableFontProgram {
    pub query: String,
    pub family: String,
    pub program_id: String,
    #[serde(default)]
    pub true_type: bool,
    /// 실제 바이트에서 확인한 OpenType CFF 프로그램이다.
    #[serde(default)]
    pub open_type_cff: bool,
    /// TTC의 선택 face를 단독 TTF와 구분한다.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub collection_face: bool,
}

/// 실제 프로그램 공급과 존재 확인은 서로 다른 증거다. 이름만 확인된
/// source는 공개 fallback을 막을 수 있지만 TrueType/메트릭 공급자가 되지 않는다.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct AvailableFontProgramSnapshot {
    programs: Vec<AvailableFontProgram>,
    #[serde(default)]
    public_fallback_blocked_sources: Vec<String>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum AvailableFontProgramInput {
    Snapshot(AvailableFontProgramSnapshot),
    Legacy(Vec<AvailableFontProgram>),
}

fn is_false(value: &bool) -> bool {
    !value
}

/// 같은 프로그램의 이름만 조회한다. 화면용 호환 fallback은 설치 증거가 아니다.
pub(crate) fn program_names(name: &str) -> Vec<String> {
    let mut names: Vec<String> = std::iter::once(name)
        .chain(super::installed_font_program_aliases(name).iter().copied())
        .filter(|name| FontEnvironment::valid_name(name))
        .map(str::to_owned)
        .collect();
    // 확인된 HFT 계열의 # 이름은 원래 이름을 우선 조회한다. 원본 프로그램이
    // 없을 때만 #을 뺀 설치 프로그램도 후보로 제시하며, 존재 확인은 공급자가 한다.
    if let Some(unprefixed) = name.strip_prefix('#') {
        if super::font_rule_layout_name_projection::find_font_rule_layout_name(
            "rust-style-resolution.hft",
            name,
            0,
        )
        .is_some()
            && FontEnvironment::valid_name(unprefixed)
        {
            names.push(unprefixed.to_owned());
        }
    }
    names
}

/// HWP3에는 유형 필드가 없다. 확인된 HFT 이름은 유형 미상이라도 원 프로그램을 조회한다.
fn may_select_hft_program(font: &crate::model::style::Font, language: usize) -> bool {
    font.native_program.is_none()
        && (font.alt_type == 2
            || (font.alt_type == 0
                && super::font_rule_layout_name_projection::find_font_rule_layout_name(
                    "rust-style-resolution.hft",
                    &font.name,
                    language,
                )
                .is_some()))
}

// 생략은 기존 메트릭 계약을 유지한다. 명시 false는 자연 프로그램 선택이며,
// null·문자열·숫자는 기존 bool JSON 계약과 같이 거부한다.
fn deserialize_source_metric_policy<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<bool>, D::Error> {
    bool::deserialize(deserializer).map(Some)
}

impl FontEnvironment {
    pub(crate) fn with_observed_substitutions(
        base: Option<&Self>,
        replacements: BTreeMap<String, String>,
    ) -> Result<Option<Self>, HwpError> {
        if replacements.is_empty() {
            return Ok(None);
        }
        let mut result = base.cloned().unwrap_or(Self {
            id: "observed-host-fonts".to_owned(),
            substitutions: BTreeMap::new(),
            selected_programs: BTreeMap::new(),
            selection_rules: BTreeMap::new(),
            true_type_faces: Vec::new(),
            preserve_source_metrics: None,
            replace_source_metrics_for: Vec::new(),
            document_substitutions: Vec::new(),
            glyph_fallbacks: BTreeMap::new(),
            document_glyph_fallbacks: Vec::new(),
        });
        for (family, target) in replacements {
            if result.has_source_selection(&family) {
                continue;
            }
            result.substitutions.insert(family, target.clone());
            if !result.true_type_faces.contains(&target) {
                result.true_type_faces.push(target);
            }
        }
        result.validate()?;
        Ok(Some(result))
    }

    /// 원본과 문서 지정 내장 프로그램을 같은 이름 집합으로 보존한다.
    pub(crate) fn embedded_program_names(
        doc_info: &crate::model::document::DocInfo,
    ) -> std::collections::BTreeSet<String> {
        let mut names = std::collections::BTreeSet::new();
        for font in doc_info.font_faces.iter().flatten() {
            let substitute = font
                .subst_font
                .as_ref()
                .filter(|substitute| substitute.is_embedded);
            if font.is_embedded || substitute.is_some() {
                names.insert(font.name.clone());
            }
            if let Some(substitute) = substitute {
                names.insert(substitute.face.clone());
            }
        }
        names
    }

    pub(crate) fn valid_name(name: &str) -> bool {
        !name.is_empty()
            && name.trim() == name
            && name.len() <= 256
            && !name.chars().any(|character| {
                character.is_control()
                    || matches!(character, ',' | '\'' | '"' | '\\' | ';' | '{' | '}')
            })
    }

    /// 문서 선언과 프로그램 별칭을 한 번 생산해 Native와 브라우저에 전달한다.
    pub fn document_requests(
        doc_info: &crate::model::document::DocInfo,
    ) -> Vec<DocumentFontSelectionRequest> {
        Self::document_requests_with_slots(doc_info)
            .into_iter()
            .map(|(_, _, request)| request)
            .collect()
    }

    pub(crate) fn document_requests_with_slots(
        doc_info: &crate::model::document::DocInfo,
    ) -> Vec<(usize, u16, DocumentFontSelectionRequest)> {
        let mut requests = Vec::new();
        // 같은 이름에 내장 프로그램이 있으면 전역 CSS 별칭으로 덮어쓰지 않는다.
        let embedded = Self::embedded_program_names(doc_info);
        for (language, fonts) in doc_info.font_faces.iter().enumerate() {
            for (index, font) in fonts.iter().enumerate() {
                if embedded.contains(&font.name) || !Self::valid_name(&font.name) {
                    continue;
                }
                let decision = super::style_resolver::lookup_font_name_decision(
                    doc_info,
                    language,
                    index as u16,
                );
                let Some(primary) = decision.normalized_face.as_deref() else {
                    continue;
                };
                let Ok(font_id) = u16::try_from(index) else {
                    continue;
                };
                // 문서의 TTF/HFT 표시는 설치 프로그램의 형식이 아니다.
                // 호환 대체 이름보다 원래 선언과 실제 설치 별칭을 먼저 조회한다.
                let mut primary_names = program_names(&font.name);
                for name in program_names(primary) {
                    if !primary_names.contains(&name) {
                        primary_names.push(name);
                    }
                }
                requests.push((
                    language,
                    font_id,
                    DocumentFontSelectionRequest {
                        source: font.name.clone(),
                        primary: primary_names,
                        public_fallback:
                            super::font_rule_layout_name_projection::find_font_rule_layout_name(
                                "rust-style-resolution.missing-program",
                                &font.name,
                                language,
                            )
                            .filter(|rule| {
                                rule.conditions.availability
                                    == Some("primary-and-document-substitute-missing")
                            })
                            .map(|rule| program_names(rule.target_face_or_policy))
                            .unwrap_or_default(),
                        substitute: decision
                            .subst_font
                            .as_deref()
                            .map(program_names)
                            .unwrap_or_default(),
                    },
                ));
            }
        }
        requests
    }

    fn from_document_lookup(
        doc_info: &crate::model::document::DocInfo,
        mut lookup: impl FnMut(&str) -> Option<AvailableFontProgram>,
        public_fallback_blocked_sources: &[String],
    ) -> Result<Option<Self>, HwpError> {
        use sha2::{Digest, Sha256};
        // 같은 프로그램을 언어 슬롯마다 다시 읽거나 해시하지 않는다.
        let mut queried = BTreeMap::<String, Option<AvailableFontProgram>>::new();
        let mut resolve = |name: &str| {
            queried
                .entry(name.to_owned())
                .or_insert_with(|| lookup(name))
                .clone()
        };
        let mut candidates =
            BTreeMap::<String, Option<(AvailableFontProgram, Option<&'static str>)>>::new();
        let embedded = Self::embedded_program_names(doc_info);
        let mut slot_candidates = Vec::new();
        for (language_slot, font_id, request) in Self::document_requests_with_slots(doc_info) {
            let original_names = program_names(&request.source);
            // 원 프로그램의 설치 별칭 안에서만 TTF → CFF OpenType 순서를 적용한다.
            // 대체 family의 TTF가 원 family의 OTF를 앞서면 안 된다.
            let primary = original_names
                .iter()
                .filter_map(|name| resolve(name))
                .filter(|program| program.true_type || program.open_type_cff)
                .min_by_key(|program| {
                    if program.true_type {
                        u8::from(program.collection_face)
                    } else {
                        3
                    }
                })
                .or_else(|| request.primary.iter().find_map(|name| resolve(name)));
            let candidate = if let Some(program) = primary {
                // 원본 선언은 HFT지만 실제로 준비된 동일 주 프로그램은 TTF일 수 있다.
                // 존재 확인으로 끝내지 않고 프로그램 신원을 공통 스타일 해소에 전달한다.
                // 치환 family와 원 HFT 프로그램 출처는 이 주 프로그램 인증이 아니다.
                let source = doc_info
                    .font_faces
                    .get(language_slot)
                    .and_then(|faces| faces.get(font_id as usize));
                let is_source_program = original_names.contains(&program.query);
                ((program.true_type || program.open_type_cff)
                    && is_source_program
                    && source
                        .is_some_and(|font| !font.is_embedded && font.native_program.is_none()))
                .then_some((program, None))
            } else {
                request
                    .substitute
                    .iter()
                    .find_map(|name| resolve(name))
                    .filter(|program| !embedded.contains(&program.family))
                    .map(|program| (program, None))
                    .or_else(|| {
                        // local() 이름 존재는 공개 대체를 막는 데만 사용한다.
                        // 프로그램이 실제 공급됐다는 증명으로 바꾸지 않는다.
                        if public_fallback_blocked_sources.contains(&request.source) {
                            return None;
                        }
                        request
                            .public_fallback
                            .iter()
                            .find_map(|name| resolve(name))
                            .filter(|program| !embedded.contains(&program.family))
                            .map(|program| {
                                let rule = super::font_rule_layout_name_projection::find_font_rule_layout_name(
                                    "rust-style-resolution.missing-program", &request.source, 0,
                                ).map(|rule| rule.rule_id);
                                (program, rule)
                            })
                    })
            };
            slot_candidates.push((
                language_slot,
                font_id,
                request.source.clone(),
                candidate.clone(),
            ));
            candidates
                .entry(request.source)
                .and_modify(|previous| {
                    // 한 번 충돌한 선택을 뒤 슬롯에서 되살리지 않는다.
                    match previous.as_mut().zip(candidate.as_ref()) {
                        Some((left, right))
                            if left.0.family == right.0.family
                                && left.0.program_id == right.0.program_id
                                && left.0.query == right.0.query
                                && left.0.true_type == right.0.true_type
                                && left.0.open_type_cff == right.0.open_type_cff =>
                        {
                            // 같은 프로그램이라도 선택 사유가 다른 슬롯은 전역 조건의
                            // 증거가 아니다. 공급 선택은 유지하고 조건 출처만 제외한다.
                            if left.1 != right.1 {
                                left.1 = None;
                            }
                        }
                        _ => *previous = None,
                    }
                })
                .or_insert(candidate);
        }
        let conflicted: std::collections::BTreeSet<_> = candidates
            .iter()
            .filter(|(_, selection)| selection.is_none())
            .map(|(source, _)| source.clone())
            .collect();
        // 다른 프로그램이 같은 최종 family를 주장하면 슬롯 주소만으로 paint를
        // 구분할 수 없다. 그런 모호성은 기존처럼 수용하지 않는다.
        let mut family_programs: BTreeMap<(String, String), Option<(String, bool, bool)>> =
            BTreeMap::new();
        for (_, _, source, candidate) in &slot_candidates {
            if let Some((program, _)) = candidate {
                let identity = (
                    program.program_id.clone(),
                    program.true_type,
                    program.open_type_cff,
                );
                family_programs
                    .entry((source.clone(), program.family.clone()))
                    .and_modify(|previous| {
                        if previous.as_ref() != Some(&identity) {
                            *previous = None;
                        }
                    })
                    .or_insert(Some(identity));
            }
        }
        let mut substitutions = BTreeMap::new();
        let mut selected_programs = BTreeMap::new();
        let mut selection_rules = BTreeMap::new();
        let mut true_type_faces = std::collections::BTreeSet::new();
        let mut digest = Sha256::new();
        digest.update(b"preserve-source-hft-metrics\0");
        for (source, selected) in candidates {
            let Some((selected, rule_id)) = selected else {
                continue;
            };
            if !Self::valid_name(&selected.family) {
                continue;
            }
            for value in [
                &source,
                &selected.family,
                &selected.program_id,
                &selected.query,
            ] {
                digest.update(value.as_bytes());
                digest.update([0]);
            }
            digest.update([u8::from(selected.true_type)]);
            digest.update([u8::from(selected.open_type_cff)]);
            if selected.true_type {
                true_type_faces.insert(selected.family.clone());
            }
            if let Some(rule_id) = rule_id {
                digest.update(rule_id.as_bytes());
                digest.update([0]);
                selection_rules.insert(source.clone(), rule_id.to_owned());
            }
            substitutions.insert(source.clone(), selected.family.clone());
            selected_programs.insert(source, selected);
        }
        let mut document_substitutions = Vec::new();
        for (language_slot, font_id, source, candidate) in slot_candidates {
            let Some((program, rule)) = candidate.filter(|_| conflicted.contains(&source)) else {
                continue;
            };
            if family_programs
                .get(&(source.clone(), program.family.clone()))
                .is_none_or(Option::is_none)
            {
                continue;
            }
            digest.update(b"document-font-slot\0");
            digest.update((language_slot as u64).to_le_bytes());
            digest.update(font_id.to_le_bytes());
            for value in [
                &source,
                &program.family,
                &program.program_id,
                &program.query,
            ] {
                digest.update(value.as_bytes());
                digest.update([0]);
            }
            digest.update([u8::from(program.true_type)]);
            digest.update([u8::from(program.open_type_cff)]);
            if let Some(rule) = rule {
                digest.update(rule.as_bytes());
                digest.update([0]);
            }
            if program.true_type {
                true_type_faces.insert(program.family.clone());
            }
            document_substitutions.push(DocumentFontSubstitution {
                language_slot,
                font_id,
                source,
                target: program.family,
                program_id: program.program_id,
                query: Some(program.query),
                selection_rule: rule.map(str::to_owned),
            });
        }
        if (substitutions.is_empty() && document_substitutions.is_empty())
            || substitutions.len() > MAX_FONT_SUBSTITUTIONS
            || document_substitutions.len() > 256
        {
            return Ok(None);
        }
        let environment = Self {
            id: format!(
                "declared-program-{}",
                digest
                    .finalize()
                    .iter()
                    .map(|byte| format!("{byte:02x}"))
                    .collect::<String>()
            ),
            substitutions,
            selected_programs,
            selection_rules,
            true_type_faces: true_type_faces.into_iter().collect(),
            preserve_source_metrics: Some(true),
            replace_source_metrics_for: Vec::new(),
            glyph_fallbacks: BTreeMap::new(),
            document_glyph_fallbacks: Vec::new(),
            document_substitutions,
        };
        environment.validate()?;
        Ok(Some(environment))
    }

    /// 실제 로드에 성공한 프로그램만 받는다. 존재하지 않는 후보는 넣지 않는다.
    pub fn from_available_programs(
        doc_info: &crate::model::document::DocInfo,
        json: &str,
    ) -> Result<Option<Self>, HwpError> {
        if json.len() > 65_536 {
            return Err(HwpError::RenderError(
                "font program snapshot exceeds 64 KiB".into(),
            ));
        }
        let input: AvailableFontProgramInput = serde_json::from_str(json)
            .map_err(|e| HwpError::RenderError(format!("invalid font program snapshot: {e}")))?;
        let (records, public_fallback_blocked_sources) = match input {
            AvailableFontProgramInput::Snapshot(snapshot) => {
                (snapshot.programs, snapshot.public_fallback_blocked_sources)
            }
            AvailableFontProgramInput::Legacy(records) => (records, Vec::new()),
        };
        if public_fallback_blocked_sources.len() > 1024
            || public_fallback_blocked_sources
                .iter()
                .any(|name| !Self::valid_name(name))
        {
            return Err(HwpError::RenderError(
                "invalid font presence snapshot".into(),
            ));
        }
        if records.len() > 1024
            || records.iter().any(|record| {
                !Self::valid_name(&record.query)
                    || !Self::valid_name(&record.family)
                    || !Self::valid_name(&record.program_id)
            })
        {
            return Err(HwpError::RenderError(
                "invalid font program identity".into(),
            ));
        }
        let mut programs = BTreeMap::new();
        for record in records {
            if let Some(previous) = programs.insert(record.query.clone(), record.clone()) {
                if previous != record {
                    return Err(HwpError::RenderError(
                        "conflicting font program identity".into(),
                    ));
                }
            }
        }
        Self::from_document_lookup(
            doc_info,
            |query| programs.get(query).cloned(),
            &public_fallback_blocked_sources,
        )
    }

    /// Native는 실제 family/PostScript와 프로그램 바이트로 같은 선택을 수행한다.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_native_document_substitutions(
        doc_info: &crate::model::document::DocInfo,
        font_paths: &[std::path::PathBuf],
    ) -> Result<Option<Self>, HwpError> {
        use sha2::{Digest, Sha256};
        // 문서의 TTF/HFT 지정과 관계없이 실제 설치 프로그램 형식을 확인한다.
        // TTF로 기록된 원본 face가 OTF/TTC로 설치된 경우도 같은 조회 경로다.
        let needs_primary_program_identity = doc_info
            .font_faces
            .iter()
            .flatten()
            .any(|font| !font.is_embedded);
        if !needs_primary_program_identity
            && !Self::document_requests(doc_info).iter().any(|request| {
                !request.substitute.is_empty() || !request.public_fallback.is_empty()
            })
        {
            return Ok(None);
        }
        let mut database = usvg::fontdb::Database::new();
        for directory in super::font_paths::search_dirs(font_paths) {
            if directory.is_dir() {
                database.load_fonts_dir(directory);
            } else if directory.is_file() {
                let _ = database.load_font_file(directory);
            }
        }
        super::font_paths::retain_fontdb_family_aliases(&mut database);
        Self::from_document_lookup(
            doc_info,
            |query| {
                let face = database
                    .query(&usvg::fontdb::Query {
                        families: &[usvg::fontdb::Family::Name(query)],
                        ..usvg::fontdb::Query::default()
                    })
                    .and_then(|id| database.face(id))
                    .or_else(|| database.faces().find(|face| face.post_script_name == query))?;
                // 같은 family와 스타일의 설치본은 TTF → CFF OpenType 순서다.
                // PostScript 이름을 직접 지정한 조회는 다른 face로 바꾸지 않는다.
                let face = if face.post_script_name == query
                    && !face.families.iter().any(|(name, _)| name == query)
                {
                    face
                } else {
                    database
                        .faces()
                        .filter(|candidate| {
                            candidate.style == face.style
                                && candidate.weight == face.weight
                                && candidate.stretch == face.stretch
                                && candidate.families.iter().any(|(name, _)| {
                                    face.families.iter().any(|(original, _)| original == name)
                                })
                        })
                        .min_by_key(|candidate| {
                            database
                                .with_face_data(candidate.id, |bytes, index| {
                                    ttf_parser::Face::parse(bytes, index).map_or(2, |face| {
                                        if face.tables().glyf.is_some() {
                                            u8::from(bytes.get(..4) == Some(b"ttcf"))
                                        } else if face.tables().cff.is_some()
                                            || face.tables().cff2.is_some()
                                        {
                                            2
                                        } else {
                                            3
                                        }
                                    })
                                })
                                .unwrap_or(2)
                        })
                        .unwrap_or(face)
                };
                let family = face.families.first()?.0.clone();
                database.with_face_data(face.id, |bytes, index| {
                    let offset = if bytes.get(..4) == Some(b"ttcf") {
                        let record = 12usize.checked_add((index as usize).checked_mul(4)?)?;
                        u32::from_be_bytes(bytes.get(record..record + 4)?.try_into().ok()?) as usize
                    } else {
                        0
                    };
                    let true_type = matches!(
                        bytes.get(offset..offset.checked_add(4)?),
                        Some(b"\0\x01\0\0" | b"true")
                    );
                    let open_type_cff = bytes.get(offset..offset.checked_add(4)?) == Some(b"OTTO");
                    let mut digest = Sha256::new();
                    digest.update(bytes);
                    digest.update(index.to_be_bytes());
                    Some(AvailableFontProgram {
                        query: query.into(),
                        family,
                        true_type,
                        open_type_cff,
                        collection_face: bytes.get(..4) == Some(b"ttcf"),
                        program_id: digest
                            .finalize()
                            .iter()
                            .map(|byte| format!("{byte:02x}"))
                            .collect(),
                    })
                })?
            },
            &[],
        )
    }

    pub fn from_json(json: &str) -> Result<Self, HwpError> {
        if json.len() > 65_536 {
            return Err(HwpError::RenderError(
                "font environment exceeds 64 KiB".into(),
            ));
        }
        let environment: Self = serde_json::from_str(json)
            .map_err(|e| HwpError::RenderError(format!("invalid font environment: {e}")))?;
        environment.validate()?;
        Ok(environment)
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub(crate) fn validate(&self) -> Result<(), HwpError> {
        if !Self::valid_name(&self.id)
            || self.replace_source_metrics_for.len() > 256
            || self
                .replace_source_metrics_for
                .iter()
                .any(|source| !Self::valid_name(source) || !self.has_source_selection(source))
            || self
                .replace_source_metrics_for
                .iter()
                .collect::<std::collections::BTreeSet<_>>()
                .len()
                != self.replace_source_metrics_for.len()
            || self.true_type_faces.len() > 256
            || self
                .true_type_faces
                .iter()
                .any(|face| !Self::valid_name(face))
            || self
                .true_type_faces
                .iter()
                .collect::<std::collections::BTreeSet<_>>()
                .len()
                != self.true_type_faces.len()
            || self.selection_rules.len() > 256
            || self.selection_rules.iter().any(|(source, rule_id)| {
                self.canonical_selection_rule(source) != Some(rule_id.as_str())
            })
            || self.substitutions.len() > MAX_FONT_SUBSTITUTIONS
            || self.selected_programs.len() > 256
            || self.selected_programs.iter().any(|(source, program)| {
                !Self::valid_name(source)
                    || !Self::valid_name(&program.query)
                    || !Self::valid_name(&program.family)
                    || !Self::valid_name(&program.program_id)
            })
            || self.document_substitutions.len() > 256
            || self.document_substitutions.iter().any(|selection| {
                selection.language_slot >= super::style_resolver::LANG_COUNT
                    || !Self::valid_name(&selection.source)
                    || !Self::valid_name(&selection.target)
                    || !Self::valid_name(&selection.program_id)
                    || selection
                        .query
                        .as_deref()
                        .is_some_and(|query| !Self::valid_name(query))
                    || self.substitutions.contains_key(&selection.source)
                    || selection.selection_rule.as_deref().is_some_and(|rule| {
                        Self::canonical_rule(&selection.source, &selection.target, rule).is_none()
                    })
            })
            || self
                .document_substitutions
                .iter()
                .map(|selection| (selection.language_slot, selection.font_id))
                .collect::<std::collections::BTreeSet<_>>()
                .len()
                != self.document_substitutions.len()
            || self.glyph_fallbacks.len() > 256
            || self.document_glyph_fallbacks.len() > 1024
            || self.document_glyph_fallbacks.iter().any(|item| {
                item.language_slot >= super::style_resolver::LANG_COUNT
                    || !Self::valid_name(&item.source)
                    || item.faces.is_empty()
                    || item.faces.len() > 16
                    || item
                        .faces
                        .iter()
                        .any(|face| !Self::valid_name(face) || face == &item.source)
                    || item
                        .faces
                        .iter()
                        .collect::<std::collections::BTreeSet<_>>()
                        .len()
                        != item.faces.len()
            })
            || self
                .document_glyph_fallbacks
                .iter()
                .map(|item| (item.language_slot, item.font_id))
                .collect::<std::collections::BTreeSet<_>>()
                .len()
                != self.document_glyph_fallbacks.len()
            || self.glyph_fallbacks.iter().any(|(from, faces)| {
                !Self::valid_name(from)
                    || faces.is_empty()
                    || faces.len() > 16
                    || faces
                        .iter()
                        .any(|face| !Self::valid_name(face) || face == from)
                    || faces
                        .iter()
                        .collect::<std::collections::BTreeSet<_>>()
                        .len()
                        != faces.len()
            })
            || self
                .substitutions
                .iter()
                .any(|(from, to)| !Self::valid_name(from) || !Self::valid_name(to))
        {
            return Err(HwpError::RenderError(
                "font environment requires a valid id, single-face substitutions, and bounded distinct glyph fallback faces".into(),
            ));
        }
        Ok(())
    }

    /// JSON 전달 뒤에도 canonical 조건·선택 대상과 일치하는 출처만 반환한다.
    pub(crate) fn canonical_selection_rule(&self, source: &str) -> Option<&'static str> {
        let recorded = self.selection_rules.get(source)?;
        let target = self.substitutions.get(source)?;
        Self::canonical_rule(source, target, recorded)
    }

    fn canonical_rule(source: &str, target: &str, recorded: &str) -> Option<&'static str> {
        super::font_rule_layout_name_projection::find_font_rule_layout_name(
            "rust-style-resolution.missing-program",
            source,
            0,
        )
        .filter(|rule| {
            rule.rule_id == recorded
                && rule.target_face_or_policy == target
                && rule.conditions.availability == Some("primary-and-document-substitute-missing")
        })
        .map(|rule| rule.rule_id)
    }

    pub(crate) fn selects_true_type(&self, face: &str) -> bool {
        self.true_type_faces.iter().any(|selected| selected == face)
    }

    pub(crate) fn preserves_source_metrics(&self) -> bool {
        self.preserve_source_metrics.unwrap_or(false)
    }

    pub(crate) fn explicitly_replaces_source_metrics(&self) -> bool {
        self.preserve_source_metrics == Some(false)
    }

    /// 생략된 기존 설정은 자연 프로그램 전진을 선택한 요청이 아니다.
    pub(crate) fn selects_natural_program_for(&self, source: &str) -> bool {
        self.explicitly_replaces_source_metrics()
            || self
                .replace_source_metrics_for
                .iter()
                .any(|selected| selected == source)
    }

    pub(crate) fn preserves_source_metrics_for(&self, source: &str) -> bool {
        self.preserves_source_metrics()
            && !self
                .replace_source_metrics_for
                .iter()
                .any(|selected| selected == source)
    }

    pub(crate) fn replacement(&self, face: &str) -> Option<&str> {
        self.substitutions.get(face).map(String::as_str)
    }

    /// family 단위 관측은 원본 주소별 프로그램 선택을 덮어쓸 수 없다.
    pub(crate) fn has_source_selection(&self, face: &str) -> bool {
        self.substitutions.contains_key(face)
            || self
                .document_substitutions
                .iter()
                .any(|selection| selection.source == face)
    }

    fn document_substitution(
        &self,
        face: &str,
        language_slot: usize,
        font_id: u16,
    ) -> Option<&DocumentFontSubstitution> {
        self.document_substitutions.iter().find(|selection| {
            selection.language_slot == language_slot
                && selection.font_id == font_id
                && selection.source == face
        })
    }

    pub(crate) fn replacement_for(
        &self,
        face: &str,
        language_slot: usize,
        font_id: u16,
    ) -> Option<&str> {
        self.document_substitution(face, language_slot, font_id)
            .map(|selection| selection.target.as_str())
            .or_else(|| self.replacement(face))
    }

    /// 선택 대상이 그대로일 때 실제 조회한 원본·문서 지정 이름을 반환한다.
    pub(crate) fn selected_program_query_for(
        &self,
        source: &str,
        language_slot: usize,
        font_id: u16,
    ) -> Option<&str> {
        if let Some(selection) = self.document_substitution(source, language_slot, font_id) {
            return selection.query.as_deref();
        }
        let selected = self.selected_programs.get(source)?;
        (self.replacement_for(source, language_slot, font_id) == Some(selected.family.as_str()))
            .then_some(selected.query.as_str())
    }

    /// 현재 슬롯에서 유효한 선택의 실제 프로그램 해시다. 임의 표기 ID는 인증하지 않는다.
    pub(crate) fn selected_program_identity_for(
        &self,
        source: &str,
        language_slot: usize,
        font_id: u16,
    ) -> Option<FontProgramIdentity> {
        self.selected_program_query_for(source, language_slot, font_id)?;
        let id = self
            .document_substitution(source, language_slot, font_id)
            .map(|selection| selection.program_id.as_str())
            .or_else(|| {
                self.selected_programs
                    .get(source)
                    .map(|program| program.program_id.as_str())
            })?;
        let (id, standalone_resource) = id
            .strip_prefix("sweep-")
            .map_or((id, false), |digest| (digest, true));
        if id.len() != 64 {
            return None;
        }
        let mut digest = [0; 32];
        for (index, byte) in digest.iter_mut().enumerate() {
            *byte = u8::from_str_radix(id.get(index * 2..index * 2 + 2)?, 16).ok()?;
        }
        Some(FontProgramIdentity {
            digest,
            standalone_resource,
        })
    }

    pub(crate) fn canonical_selection_rule_for(
        &self,
        source: &str,
        language_slot: usize,
        font_id: u16,
    ) -> Option<&'static str> {
        if let Some(selection) = self.document_substitution(source, language_slot, font_id) {
            return Self::canonical_rule(
                source,
                &selection.target,
                selection.selection_rule.as_deref()?,
            );
        }
        self.canonical_selection_rule(source)
    }

    pub(crate) fn glyph_fallbacks(&self, face: &str) -> Option<&[String]> {
        self.glyph_fallbacks.get(face).map(Vec::as_slice)
    }

    pub(crate) fn glyph_fallbacks_for_slot(
        &self,
        source: &str,
        face: &str,
        language_slot: usize,
        font_id: u16,
    ) -> Option<&[String]> {
        self.document_glyph_fallbacks
            .iter()
            .find(|item| {
                item.language_slot == language_slot
                    && item.font_id == font_id
                    && item.source == source
            })
            .map(|item| item.faces.as_slice())
            .or_else(|| self.glyph_fallbacks(face))
    }
}