rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
//! Dormant Q2-D3 lowering from page-local common-shaping decisions.
//!
//! This module deliberately has no product caller before Q2-D4.  It proves
//! that the final `LayerNode::source_node_id` can recover one exact sidecar and
//! losslessly express its glyph geometry with the existing glyph-run schema.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::paint::{
    font_blob_resource_key, resource_digest_hex, BinaryResourceKind, BinaryResourceRef,
    FontBlobKey, FontBlobResource, FontDigest, FontFaceKey, FontFaceResource, FontFallbackPolicyId,
    FontInstanceKey, FontPortability, FontResourceSource, GlyphCluster, GlyphClusterFlag,
    GlyphOutlineFillRule, GlyphOutlinePayloadKind, GlyphRange, GlyphRunDiagnostics,
    GlyphRunOrientation, GlyphRunReplayEligibility, LanguageTag, LayerAffineTransform,
    LayerGlyphOutlinePaint, LayerGlyphOutlinePath, LayerGlyphRunPaint, LayerNode, LayerPoint,
    LayerVector, LocalizedName, OpenTypeFeatureSetting, PaintTextStyle, PaintVariantMeta,
    ResourceArena, ScriptTag, ShapeKey, ShapingEngineId, TextDirection, TextRunPlacement,
    TextSourceRange, TextSourceSpan, TextVariantKind, TextVariantQuality, VariationAxisValue,
    WritingMode, MAX_PORTABLE_FONT_BLOB_BYTES, MAX_PORTABLE_GLYPHS_PER_RUN, RESOURCE_KEY_ALGORITHM,
};
use crate::renderer::render_tree::{BoundingBox, FieldMarkerType, TextRunNode};
use crate::renderer::shaping_publication::{
    HorizontalShapingPageSidecars, HorizontalShapingRunDecision,
    MAX_HORIZONTAL_SHAPING_FONT_BYTES_PER_PAGE as MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE,
    MAX_HORIZONTAL_SHAPING_PREPARED_SOURCES_PER_PAGE as MAX_COMMON_SHAPING_PREPARED_SOURCES_PER_PAGE,
};
use crate::renderer::PathCommand;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HorizontalShapingGlyphLoweringRejectReason {
    MissingSourceNode,
    MissingSidecar,
    RejectedDecision,
    MissingReplaySourceCertificate,
    UnsupportedRunSurface,
    UnsupportedReplayRatio,
    RunRangeMismatch,
    MeasurementIdentityMismatch,
    ReplaySourceIdentityMismatch,
    ReplaySourceFaceInvalid,
    VerticalPositioningAuthorityPending,
    MeasurementGeometryInvalid,
    ReplayProjectionMismatch,
    ClusterMappingInvalid,
    VariableOutlineUnavailable,
    VariableOutlineLimitExceeded,
    VariableOutlineBboxMismatch,
    ResourceLimitExceeded,
}

impl HorizontalShapingGlyphLoweringRejectReason {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::MissingSourceNode => "missingSourceNode",
            Self::MissingSidecar => "missingSidecar",
            Self::RejectedDecision => "rejectedDecision",
            Self::MissingReplaySourceCertificate => "missingReplaySourceCertificate",
            Self::UnsupportedRunSurface => "unsupportedRunSurface",
            Self::UnsupportedReplayRatio => "unsupportedReplayRatio",
            Self::RunRangeMismatch => "runRangeMismatch",
            Self::MeasurementIdentityMismatch => "measurementIdentityMismatch",
            Self::ReplaySourceIdentityMismatch => "replaySourceIdentityMismatch",
            Self::ReplaySourceFaceInvalid => "replaySourceFaceInvalid",
            Self::VerticalPositioningAuthorityPending => "verticalPositioningAuthorityPending",
            Self::MeasurementGeometryInvalid => "measurementGeometryInvalid",
            Self::ReplayProjectionMismatch => "replayProjectionMismatch",
            Self::ClusterMappingInvalid => "clusterMappingInvalid",
            Self::VariableOutlineUnavailable => "variableOutlineUnavailable",
            Self::VariableOutlineLimitExceeded => "variableOutlineLimitExceeded",
            Self::VariableOutlineBboxMismatch => "variableOutlineBboxMismatch",
            Self::ResourceLimitExceeded => "resourceLimitExceeded",
        }
    }
}

/// One page-local lowering attempt. Rejected attempts retain only the source
/// node and a typed reason; raw text, font bytes, and host paths are excluded.
#[derive(Debug, Clone)]
pub(crate) struct HorizontalShapingGlyphLoweringReport {
    pub source_node_id: Option<u32>,
    pub glyph_run: Option<LayerGlyphRunPaint>,
    /// Q3 producer-resolved variable outline candidate. Q3-E4 publishes this
    /// atomically with the request-bound GlyphRun.
    pub glyph_outline: Option<LayerGlyphOutlinePaint>,
    pub variable_outline_proof: Option<HorizontalShapingVariableOutlineProof>,
    pub reject_reason: Option<HorizontalShapingGlyphLoweringRejectReason>,
    /// Successful-attempt work that scans or parses the exact portable font.
    /// D5 uses this internal-only counter to prove that resource preparation is
    /// charged to a unique source rather than to every emitted run. It is not
    /// serialized and does not change renderer selection.
    pub portable_source_work: HorizontalShapingPortableSourceWork,
    /// A successful common run owns the one GlyphRun alternative. D4 must use
    /// this bit to skip the nominal lowerer for the same TextRun fallback.
    pub claims_glyph_run_slot: bool,
    /// Explicit instance replay is publishable only when both portable parts
    /// were produced and can be inserted in one leaf mutation.
    pub atomic_outline_required: bool,
}

impl HorizontalShapingGlyphLoweringReport {
    fn rejected(
        source_node_id: Option<u32>,
        reason: HorizontalShapingGlyphLoweringRejectReason,
    ) -> Self {
        Self {
            source_node_id,
            glyph_run: None,
            glyph_outline: None,
            variable_outline_proof: None,
            reject_reason: Some(reason),
            portable_source_work: HorizontalShapingPortableSourceWork::default(),
            claims_glyph_run_slot: false,
            atomic_outline_required: false,
        }
    }

    fn emitted(
        source_node_id: u32,
        glyph_run: LayerGlyphRunPaint,
        glyph_outline: Option<LayerGlyphOutlinePaint>,
        variable_outline_proof: Option<HorizontalShapingVariableOutlineProof>,
        portable_source_work: HorizontalShapingPortableSourceWork,
        atomic_outline_required: bool,
    ) -> Self {
        Self {
            source_node_id: Some(source_node_id),
            glyph_run: Some(glyph_run),
            glyph_outline,
            variable_outline_proof,
            reject_reason: None,
            portable_source_work,
            claims_glyph_run_slot: true,
            atomic_outline_required,
        }
    }
}

pub(crate) const MAX_HORIZONTAL_SHAPING_OUTLINE_COMMANDS_PER_RUN: usize = 262_144;

#[derive(Debug, Clone)]
pub(crate) struct HorizontalShapingVariableOutlineProof {
    pub settings_sha256: String,
    pub canonical_variations: Vec<VariationAxisValue>,
    pub glyph_count: usize,
    pub command_count: usize,
    pub bbox_mismatch_count: usize,
    pub run_local_bbox: BoundingBox,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct HorizontalShapingPortableSourceWork {
    /// Explicit BLAKE3 passes in the common-shaping lowerer. This excludes the
    /// arena's own fingerprinting pass so the counter has one narrow owner.
    pub explicit_blake3_digest_passes: usize,
    pub face_parse_attempts: usize,
    pub arena_intern_attempts: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct HorizontalShapingPreparedSourceKey {
    registry_generation: u64,
    font_source_sha256: String,
    font_bytes: usize,
    face_index: u32,
}

struct HorizontalShapingPreparedSource {
    source_bytes: Arc<[u8]>,
    number_of_glyphs: u16,
    blob_key: FontBlobKey,
    face_key: FontFaceKey,
    digest: FontDigest,
    data_ref: BinaryResourceRef,
    face_index: u32,
    weight_class: u16,
    width_class: u16,
    italic: bool,
    is_variable: bool,
}

/// Page-local prepared exact-source identities. The cache owns only another
/// `Arc` reference to registry bytes and immutable face metadata; it never
/// serializes bytes or host paths. Limits mirror the existing portable page
/// resource boundary.
pub(crate) struct HorizontalShapingPreparedSourceCache {
    entries: HashMap<HorizontalShapingPreparedSourceKey, Arc<HorizontalShapingPreparedSource>>,
    total_source_bytes: usize,
    max_entries: usize,
    max_source_bytes: usize,
}

impl std::fmt::Debug for HorizontalShapingPreparedSourceCache {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HorizontalShapingPreparedSourceCache")
            .field("entry_count", &self.entries.len())
            .field("total_source_bytes", &self.total_source_bytes)
            .field("max_entries", &self.max_entries)
            .field("max_source_bytes", &self.max_source_bytes)
            .finish()
    }
}

impl Default for HorizontalShapingPreparedSourceCache {
    fn default() -> Self {
        Self::with_limits(
            MAX_COMMON_SHAPING_PREPARED_SOURCES_PER_PAGE,
            MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE,
        )
    }
}

impl HorizontalShapingPreparedSourceCache {
    pub(crate) fn with_limits(max_entries: usize, max_source_bytes: usize) -> Self {
        Self {
            entries: HashMap::new(),
            total_source_bytes: 0,
            max_entries: max_entries.min(MAX_COMMON_SHAPING_PREPARED_SOURCES_PER_PAGE),
            max_source_bytes: max_source_bytes.min(MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE),
        }
    }

    pub(crate) fn entry_count(&self) -> usize {
        self.entries.len()
    }

    pub(crate) fn total_source_bytes(&self) -> usize {
        self.total_source_bytes
    }

    fn prepare(
        &mut self,
        decision: &HorizontalShapingRunDecision,
        portable_source_work: &mut HorizontalShapingPortableSourceWork,
    ) -> Result<Arc<HorizontalShapingPreparedSource>, HorizontalShapingGlyphLoweringRejectReason>
    {
        let measurement = decision
            .measurement()
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
        let certificate = decision
            .replay_source_certificate()
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::MissingReplaySourceCertificate)?;
        let source = &measurement.source_handle;
        if certificate.registry_generation() != measurement.registry_generation
            || certificate.source_handle() != source
            || certificate.units_per_em() != measurement.units_per_em
            || certificate.source_bytes().len() != source.font_bytes
        {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ReplaySourceIdentityMismatch);
        }
        if certificate.source_bytes().len() > MAX_PORTABLE_FONT_BLOB_BYTES {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
        }
        let key = HorizontalShapingPreparedSourceKey {
            registry_generation: measurement.registry_generation,
            font_source_sha256: source.font_source_sha256.clone(),
            font_bytes: source.font_bytes,
            face_index: source.face_index,
        };
        if let Some(prepared) = self.entries.get(&key) {
            if !Arc::ptr_eq(&prepared.source_bytes, certificate.source_bytes_arc())
                || prepared.source_bytes.len() != source.font_bytes
            {
                return Err(
                    HorizontalShapingGlyphLoweringRejectReason::ReplaySourceIdentityMismatch,
                );
            }
            return Ok(Arc::clone(prepared));
        }
        if self.entries.len() >= self.max_entries {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
        }
        let Some(next_total) = self
            .total_source_bytes
            .checked_add(certificate.source_bytes().len())
        else {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
        };
        if next_total > self.max_source_bytes {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
        }

        portable_source_work.face_parse_attempts =
            portable_source_work.face_parse_attempts.saturating_add(1);
        let face = ttf_parser::Face::parse(certificate.source_bytes(), source.face_index)
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ReplaySourceFaceInvalid)?;
        if face.units_per_em() != measurement.units_per_em {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ReplaySourceFaceInvalid);
        }
        portable_source_work.explicit_blake3_digest_passes = portable_source_work
            .explicit_blake3_digest_passes
            .saturating_add(1);
        let digest_value = resource_digest_hex(certificate.source_bytes());
        let resource_key = font_blob_resource_key(source.font_bytes, &digest_value);
        let digest = FontDigest {
            algorithm: RESOURCE_KEY_ALGORITHM.to_string(),
            value: digest_value,
        };
        let data_ref = BinaryResourceRef {
            kind: BinaryResourceKind::FontBlob,
            id: resource_key.clone(),
        };
        let prepared = Arc::new(HorizontalShapingPreparedSource {
            source_bytes: Arc::clone(certificate.source_bytes_arc()),
            number_of_glyphs: face.number_of_glyphs(),
            blob_key: FontBlobKey(resource_key.clone()),
            face_key: FontFaceKey(format!("{resource_key}:face:{}", source.face_index)),
            digest,
            data_ref,
            face_index: source.face_index,
            weight_class: face.weight().to_number(),
            width_class: face.width().to_number(),
            italic: face.is_italic(),
            is_variable: face.is_variable(),
        });
        self.entries.insert(key, Arc::clone(&prepared));
        self.total_source_bytes = next_total;
        Ok(prepared)
    }
}

fn same_f64(left: f64, right: f64) -> bool {
    left.is_finite()
        && right.is_finite()
        && (left - right).abs() <= 1.0e-9 * left.abs().max(right.abs()).max(1.0)
}

fn run_surface_supported(run: &TextRunNode) -> bool {
    let style = &run.style;
    let homogeneous_language = run.text.chars().next().is_some_and(|first| {
        let language_index = crate::renderer::style_resolver::detect_lang_category(first);
        run.text.chars().all(|character| {
            crate::renderer::style_resolver::detect_lang_category(character) == language_index
        })
    });
    !run.text.is_empty()
        && run
            .text
            .chars()
            .take(MAX_PORTABLE_GLYPHS_PER_RUN + 1)
            .count()
            <= MAX_PORTABLE_GLYPHS_PER_RUN
        && run.layout_positions.is_none()
        && run.display_text.is_none()
        && run.char_shape_id.is_some()
        && homogeneous_language
        && !run.is_vertical
        && run.rotation.abs() <= f64::EPSILON
        && run.char_overlap.is_none()
        && run.border_fill_id == 0
        && matches!(run.field_marker, FieldMarkerType::None)
        && !style.bold
        && !style.italic
        && super::font_size::glyph_font_size_is_portable(style.font_size)
        && style.ratio.is_finite()
        && style.ratio > 0.0
        && style.ratio <= 16.0
        && style.letter_spacing.abs() <= f64::EPSILON
        && style.extra_word_spacing.abs() <= f64::EPSILON
        && style.extra_char_spacing.abs() <= f64::EPSILON
        && style.extra_dash_advance.abs() <= f64::EPSILON
        && style.tab_leaders.is_empty()
        && style.inline_tabs.is_empty()
        && {
            let mut paint_style = PaintTextStyle::from(style);
            // Q2 geometry already carries width ratio. Existing GlyphTransform
            // is its explicit replay representation; inspect other effects with
            // an identity ratio so width ratio is not mistaken for an effect.
            paint_style.ratio = 1.0;
            paint_style.is_fill_only_glyph_replay()
        }
}

fn text_run_placement(bbox: BoundingBox, run: &TextRunNode) -> TextRunPlacement {
    let radians = run.rotation.to_radians();
    let (sin, cos) = radians.sin_cos();
    let local_origin_x = -bbox.width / 2.0;
    let local_origin_y = -bbox.height / 2.0 + run.baseline;
    let center_x = bbox.x + bbox.width / 2.0;
    let center_y = bbox.y + bbox.height / 2.0;
    TextRunPlacement {
        run_to_page: LayerAffineTransform {
            a: cos,
            b: sin,
            c: -sin,
            d: cos,
            e: center_x + cos * local_origin_x - sin * local_origin_y,
            f: center_y + sin * local_origin_x + cos * local_origin_y,
        },
        baseline_y: 0.0,
    }
}

fn validate_measurement(
    decision: &HorizontalShapingRunDecision,
    run: &TextRunNode,
    number_of_glyphs: u16,
) -> Result<(), HorizontalShapingGlyphLoweringRejectReason> {
    let measurement = decision
        .measurement()
        .ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
    let identity = &measurement.applied.identity;
    if measurement.source_handle.font_source_sha256 != identity.font_source_sha256
        || measurement.source_handle.font_bytes != identity.font_bytes
        || measurement.source_handle.face_index != identity.face_index
        || identity.direction != "ltr"
        || identity.writing_mode != "horizontal-tb"
        || !matches!(
            (identity.script.as_deref(), identity.language.as_deref()),
            (Some("Hang"), Some("ko")) | (Some("Latn"), Some("en"))
        )
        || identity.features.len() != 1
        || identity.features[0].tag != "kern"
        || identity.features[0].value != u32::from(run.style.kerning)
        || measurement.glyphs_px.len() != measurement.applied.glyphs.len()
        || measurement.glyphs_px.is_empty()
        || measurement.glyphs_px.len() > MAX_PORTABLE_GLYPHS_PER_RUN
        || measurement.clusters.is_empty()
        || measurement.clusters.len() > MAX_PORTABLE_GLYPHS_PER_RUN
    {
        return Err(HorizontalShapingGlyphLoweringRejectReason::MeasurementIdentityMismatch);
    }

    let horizontal_scale =
        run.style.font_size * run.style.ratio / f64::from(measurement.units_per_em);
    let vertical_scale = run.style.font_size / f64::from(measurement.units_per_em);
    let mut pen_x = 0.0;
    for (pixel, design) in measurement
        .glyphs_px
        .iter()
        .zip(measurement.applied.glyphs.iter())
    {
        if pixel.glyph_id == 0
            || pixel.glyph_id >= u32::from(number_of_glyphs)
            || pixel.cluster_utf8 != design.cluster_utf8
            || !same_f64(
                pixel.x,
                pen_x + f64::from(design.x_offset) * horizontal_scale,
            )
            || !same_f64(pixel.y, f64::from(design.y_offset) * vertical_scale)
            || !same_f64(
                pixel.advance_x,
                f64::from(design.x_advance) * horizontal_scale,
            )
            || !same_f64(
                pixel.advance_y,
                f64::from(design.y_advance) * vertical_scale,
            )
        {
            return Err(HorizontalShapingGlyphLoweringRejectReason::MeasurementGeometryInvalid);
        }
        pen_x += pixel.advance_x;
    }
    if !same_f64(pen_x, measurement.total_advance_px) {
        return Err(HorizontalShapingGlyphLoweringRejectReason::MeasurementGeometryInvalid);
    }
    Ok(())
}

fn lower_clusters(
    decision: &HorizontalShapingRunDecision,
    run: &TextRunNode,
) -> Result<Vec<GlyphCluster>, HorizontalShapingGlyphLoweringRejectReason> {
    let measurement = decision
        .measurement()
        .ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
    let mut utf8_offsets = Vec::with_capacity(measurement.code_point_count + 1);
    let mut utf16_offsets = Vec::with_capacity(measurement.code_point_count + 1);
    utf8_offsets.push(0usize);
    utf16_offsets.push(0usize);
    let mut utf8_cursor = 0usize;
    let mut utf16_cursor = 0usize;
    for character in run.text.chars() {
        utf8_cursor = utf8_cursor
            .checked_add(character.len_utf8())
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        utf16_cursor = utf16_cursor
            .checked_add(character.len_utf16())
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        utf8_offsets.push(utf8_cursor);
        utf16_offsets.push(utf16_cursor);
    }

    let mut scalar_cursor = 0usize;
    let mut glyph_cursor = 0usize;
    let mut cluster_advance = 0.0;
    let mut lowered = Vec::with_capacity(measurement.clusters.len());
    for cluster in &measurement.clusters {
        if cluster.scalar_start != scalar_cursor
            || cluster.glyph_start != glyph_cursor
            || cluster.scalar_start >= cluster.scalar_end
            || cluster.glyph_start >= cluster.glyph_end
            || cluster.scalar_end > measurement.code_point_count
            || cluster.glyph_end > measurement.glyphs_px.len()
            || utf8_offsets.get(cluster.scalar_start).copied() != Some(cluster.utf8_start)
            || utf8_offsets.get(cluster.scalar_end).copied() != Some(cluster.utf8_end)
            || !cluster.advance_px.is_finite()
        {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid);
        }
        let utf8_start = u32::try_from(cluster.utf8_start)
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        let utf8_end = u32::try_from(cluster.utf8_end)
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        let utf16_start = u32::try_from(utf16_offsets[cluster.scalar_start])
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        let utf16_end = u32::try_from(utf16_offsets[cluster.scalar_end])
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        let glyph_start = u32::try_from(cluster.glyph_start)
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        let glyph_end = u32::try_from(cluster.glyph_end)
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        let flags = if cluster.scalar_end - cluster.scalar_start
            > cluster.glyph_end - cluster.glyph_start
        {
            vec![GlyphClusterFlag::Ligature]
        } else {
            Vec::new()
        };
        lowered.push(GlyphCluster {
            source_range_utf8: TextSourceRange::new(utf8_start, utf8_end),
            source_range_utf16: Some(TextSourceRange::new(utf16_start, utf16_end)),
            text_range_utf8: Some(TextSourceRange::new(utf8_start, utf8_end)),
            glyph_range: GlyphRange::new(glyph_start, glyph_end),
            flags,
        });
        scalar_cursor = cluster.scalar_end;
        glyph_cursor = cluster.glyph_end;
        cluster_advance += cluster.advance_px;
    }
    if scalar_cursor != measurement.code_point_count
        || glyph_cursor != measurement.glyphs_px.len()
        || !same_f64(cluster_advance, measurement.total_advance_px)
    {
        return Err(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid);
    }
    Ok(lowered)
}

struct HorizontalShapingReplayProjection {
    draw_font_size_px: f64,
    positions: Vec<LayerPoint>,
    advances: Vec<LayerVector>,
    placement: TextRunPlacement,
    max_origin_delta_px: f64,
    max_advance_delta_px: f64,
}

struct VariableOutlineBuilder {
    origin_x: f64,
    origin_y: f64,
    scale: f64,
    command_limit: usize,
    commands: Vec<PathCommand>,
    current: (f64, f64),
    contour_start: (f64, f64),
    overflowed: bool,
}

impl VariableOutlineBuilder {
    fn new(origin_x: f64, origin_y: f64, scale: f64, command_limit: usize) -> Self {
        Self {
            origin_x,
            origin_y,
            scale,
            command_limit,
            commands: Vec::new(),
            current: (0.0, 0.0),
            contour_start: (0.0, 0.0),
            overflowed: false,
        }
    }

    fn point(&self, x: f64, y: f64) -> (f64, f64) {
        (
            self.origin_x + x * self.scale,
            self.origin_y - y * self.scale,
        )
    }

    fn push(&mut self, command: PathCommand) {
        if self.commands.len() >= self.command_limit {
            self.overflowed = true;
            return;
        }
        self.commands.push(command);
    }
}

impl ttf_parser::OutlineBuilder for VariableOutlineBuilder {
    fn move_to(&mut self, x: f32, y: f32) {
        let design = (f64::from(x), f64::from(y));
        let point = self.point(design.0, design.1);
        self.push(PathCommand::MoveTo(point.0, point.1));
        self.current = design;
        self.contour_start = design;
    }

    fn line_to(&mut self, x: f32, y: f32) {
        let design = (f64::from(x), f64::from(y));
        let point = self.point(design.0, design.1);
        self.push(PathCommand::LineTo(point.0, point.1));
        self.current = design;
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        let control = (f64::from(x1), f64::from(y1));
        let end = (f64::from(x), f64::from(y));
        let first = (
            self.current.0 + (control.0 - self.current.0) * (2.0 / 3.0),
            self.current.1 + (control.1 - self.current.1) * (2.0 / 3.0),
        );
        let second = (
            end.0 + (control.0 - end.0) * (2.0 / 3.0),
            end.1 + (control.1 - end.1) * (2.0 / 3.0),
        );
        let first = self.point(first.0, first.1);
        let second = self.point(second.0, second.1);
        let end_point = self.point(end.0, end.1);
        self.push(PathCommand::CurveTo(
            first.0,
            first.1,
            second.0,
            second.1,
            end_point.0,
            end_point.1,
        ));
        self.current = end;
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        let first = self.point(f64::from(x1), f64::from(y1));
        let second = self.point(f64::from(x2), f64::from(y2));
        let end = (f64::from(x), f64::from(y));
        let end_point = self.point(end.0, end.1);
        self.push(PathCommand::CurveTo(
            first.0,
            first.1,
            second.0,
            second.1,
            end_point.0,
            end_point.1,
        ));
        self.current = end;
    }

    fn close(&mut self) {
        self.push(PathCommand::ClosePath);
        self.current = self.contour_start;
    }
}

fn build_variable_outline_shadow(
    decision: &HorizontalShapingRunDecision,
    prepared: &HorizontalShapingPreparedSource,
    projection: &HorizontalShapingReplayProjection,
    clusters: &[GlyphCluster],
    source: &TextSourceSpan,
    run: &TextRunNode,
) -> Result<
    (
        LayerGlyphOutlinePaint,
        HorizontalShapingVariableOutlineProof,
    ),
    HorizontalShapingGlyphLoweringRejectReason,
> {
    let text_source_id = source.id.0;
    let measurement = decision
        .measurement()
        .ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
    let identity = &measurement.applied.identity;
    let canonical_variations = identity
        .variations
        .iter()
        .map(|variation| VariationAxisValue {
            tag: variation.tag.clone(),
            value: f32::from_bits(variation.value_bits),
        })
        .collect::<Vec<_>>();
    let mut face = ttf_parser::Face::parse(&prepared.source_bytes, prepared.face_index)
        .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ReplaySourceFaceInvalid)?;
    for variation in &canonical_variations {
        let tag_bytes: [u8; 4] =
            variation.tag.as_bytes().try_into().map_err(|_| {
                HorizontalShapingGlyphLoweringRejectReason::MeasurementIdentityMismatch
            })?;
        face.set_variation(ttf_parser::Tag::from_bytes(&tag_bytes), variation.value)
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::MeasurementIdentityMismatch)?;
    }
    let scale = projection.draw_font_size_px / f64::from(measurement.units_per_em);
    if !scale.is_finite() || scale <= 0.0 {
        return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
    }

    let mut paths = Vec::with_capacity(measurement.glyphs_px.len());
    let mut command_count = 0usize;
    let mut bbox_mismatch_count = 0usize;
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    let mut max_x = f64::NEG_INFINITY;
    let mut max_y = f64::NEG_INFINITY;
    for (glyph_index, (glyph, position)) in measurement
        .glyphs_px
        .iter()
        .zip(&projection.positions)
        .enumerate()
    {
        let glyph_id = u16::try_from(glyph.glyph_id)
            .map(ttf_parser::GlyphId)
            .map_err(|_| HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable)?;
        let remaining = MAX_HORIZONTAL_SHAPING_OUTLINE_COMMANDS_PER_RUN
            .checked_sub(command_count)
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded)?;
        let mut builder = VariableOutlineBuilder::new(position.x, position.y, scale, remaining);
        let outline_bbox = face
            .outline_glyph(glyph_id, &mut builder)
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable)?;
        if builder.overflowed {
            return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded);
        }
        if face.glyph_bounding_box(glyph_id) != Some(outline_bbox) {
            bbox_mismatch_count = bbox_mismatch_count.saturating_add(1);
        }
        if builder.commands.is_empty() {
            return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable);
        }
        command_count = command_count
            .checked_add(builder.commands.len())
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded)?;
        let local_x_min = position.x + f64::from(outline_bbox.x_min) * scale;
        let local_x_max = position.x + f64::from(outline_bbox.x_max) * scale;
        let local_y_min = position.y - f64::from(outline_bbox.y_max) * scale;
        let local_y_max = position.y - f64::from(outline_bbox.y_min) * scale;
        min_x = min_x.min(local_x_min);
        min_y = min_y.min(local_y_min);
        max_x = max_x.max(local_x_max);
        max_y = max_y.max(local_y_max);
        let glyph_index_u32 = u32::try_from(glyph_index).map_err(|_| {
            HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded
        })?;
        let cluster = clusters
            .iter()
            .find(|cluster| {
                cluster.glyph_range.start <= glyph_index_u32
                    && glyph_index_u32 < cluster.glyph_range.end
            })
            .ok_or(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
        paths.push(LayerGlyphOutlinePath {
            glyph_id: glyph.glyph_id,
            source_range_utf8: cluster.source_range_utf8,
            glyph_range: GlyphRange::new(glyph_index_u32, glyph_index_u32 + 1),
            commands: builder.commands,
            fill_rule: GlyphOutlineFillRule::NonZero,
        });
    }
    if bbox_mismatch_count != 0 {
        return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineBboxMismatch);
    }
    if ![min_x, min_y, max_x, max_y].into_iter().all(f64::is_finite)
        || max_x <= min_x
        || max_y <= min_y
    {
        return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable);
    }

    let equivalence_group = format!("text-{text_source_id}");
    let mut variant = PaintVariantMeta::text_run_default(equivalence_group.clone());
    variant.variant_id = "glyphOutline".to_string();
    variant.variant_kind = TextVariantKind::GlyphOutline;
    variant.is_default_fallback = false;
    variant.requires = vec!["text.glyphOutline.monochromeFill".to_string()];
    variant.quality = Some(TextVariantQuality::Exact);
    variant.anchor_op_id = Some(equivalence_group);
    let mut paint_style = PaintTextStyle::from(&run.style);
    paint_style.font_size = projection.draw_font_size_px;
    paint_style.ratio = 1.0;
    let proof = HorizontalShapingVariableOutlineProof {
        settings_sha256: identity.settings_sha256.clone(),
        canonical_variations,
        glyph_count: paths.len(),
        command_count,
        bbox_mismatch_count,
        run_local_bbox: BoundingBox::new(min_x, min_y, max_x - min_x, max_y - min_y),
    };
    let outline = LayerGlyphOutlinePaint {
        source: source.clone(),
        variant,
        payload_kind: GlyphOutlinePayloadKind::MonochromeFill,
        color_layers: None,
        bitmap_glyph: None,
        svg_glyph: None,
        paint_style,
        placement: projection.placement,
        paths,
        stroke: None,
        diagnostics: GlyphRunDiagnostics {
            quality: TextVariantQuality::Exact,
            replay_eligibility: GlyphRunReplayEligibility::Portable,
            strict_visual_eligible: true,
            max_origin_delta_px: projection.max_origin_delta_px,
            max_advance_delta_px: projection.max_advance_delta_px,
            max_residual_after_adjustment_px: projection
                .max_origin_delta_px
                .max(projection.max_advance_delta_px),
            cluster_mismatch_count: 0,
            missing_glyph_count: 0,
            used_fallback_font_count: 0,
            reason: Some("q3VariableOutlineProjectionV1".to_string()),
        },
    };
    Ok((outline, proof))
}

fn project_replay_geometry(
    decision: &HorizontalShapingRunDecision,
    bbox: BoundingBox,
    run: &TextRunNode,
) -> Result<HorizontalShapingReplayProjection, HorizontalShapingGlyphLoweringRejectReason> {
    let measurement = decision
        .measurement()
        .ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
    let explicit_instance = measurement.instance_request.is_some();
    if (!explicit_instance && !(0.0..0.999).contains(&run.style.ratio))
        || (explicit_instance && !(0.0..=16.0).contains(&run.style.ratio))
    {
        return Err(HorizontalShapingGlyphLoweringRejectReason::UnsupportedReplayRatio);
    }
    if measurement
        .applied
        .glyphs
        .iter()
        .any(|glyph| glyph.y_offset != 0 || glyph.y_advance != 0)
    {
        return Err(
            HorizontalShapingGlyphLoweringRejectReason::VerticalPositioningAuthorityPending,
        );
    }

    let (draw_font_size_px, draw_x_scale) = run.style.ratio_draw_params(run.style.font_size);
    if !super::font_size::glyph_font_size_is_portable(draw_font_size_px)
        || !draw_x_scale.is_finite()
        || draw_x_scale <= 0.0
    {
        return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
    }
    let local_scale = draw_font_size_px / f64::from(measurement.units_per_em);
    if !local_scale.is_finite() || local_scale <= 0.0 {
        return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
    }

    let mut local_pen_x = 0.0;
    let mut positions = Vec::with_capacity(measurement.applied.glyphs.len());
    let mut advances = Vec::with_capacity(measurement.applied.glyphs.len());
    let mut max_origin_delta_px: f64 = 0.0;
    let mut max_advance_delta_px: f64 = 0.0;
    for (design, page) in measurement
        .applied
        .glyphs
        .iter()
        .zip(&measurement.glyphs_px)
    {
        let local_x = local_pen_x + f64::from(design.x_offset) * local_scale;
        let local_advance_x = f64::from(design.x_advance) * local_scale;
        if !local_x.is_finite() || !local_advance_x.is_finite() {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
        }
        let origin_delta = (local_x * draw_x_scale - page.x).abs();
        let advance_delta = (local_advance_x * draw_x_scale - page.advance_x).abs();
        max_origin_delta_px = max_origin_delta_px.max(origin_delta);
        max_advance_delta_px = max_advance_delta_px.max(advance_delta);
        if !same_f64(local_x * draw_x_scale, page.x)
            || !same_f64(local_advance_x * draw_x_scale, page.advance_x)
            || !same_f64(page.y, 0.0)
            || !same_f64(page.advance_y, 0.0)
        {
            return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
        }
        positions.push(LayerPoint { x: local_x, y: 0.0 });
        advances.push(LayerVector {
            dx: local_advance_x,
            dy: 0.0,
        });
        local_pen_x += local_advance_x;
    }
    if !same_f64(local_pen_x * draw_x_scale, measurement.total_advance_px) {
        return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
    }

    let mut placement = text_run_placement(bbox, run);
    placement.run_to_page.a = draw_x_scale;
    Ok(HorizontalShapingReplayProjection {
        draw_font_size_px,
        positions,
        advances,
        placement,
        max_origin_delta_px,
        max_advance_delta_px,
    })
}

fn register_prepared_portable_face(
    prepared: &HorizontalShapingPreparedSource,
    family: &str,
    resources: &mut ResourceArena,
    portable_source_work: &mut HorizontalShapingPortableSourceWork,
) -> FontFaceKey {
    if resources
        .font_blob_bytes_for_ref(&prepared.data_ref)
        .is_none()
    {
        portable_source_work.arena_intern_attempts =
            portable_source_work.arena_intern_attempts.saturating_add(1);
        resources.intern_font_blob_bytes(&prepared.source_bytes);
    }
    if !resources
        .font_resources()
        .blobs
        .iter()
        .any(|blob| blob.id == prepared.blob_key)
    {
        resources.font_resources_mut().blobs.push(FontBlobResource {
            id: prepared.blob_key.clone(),
            digest: Some(prepared.digest.clone()),
            source: FontResourceSource::Embedded,
            data_ref: Some(prepared.data_ref.clone()),
            portability: FontPortability::PortableBlob {
                digest: prepared.digest.clone(),
                data_ref: prepared.data_ref.clone(),
            },
        });
    }
    if !resources
        .font_resources()
        .faces
        .iter()
        .any(|registered| registered.id == prepared.face_key)
    {
        let family_names = vec![LocalizedName {
            locale: None,
            value: family.to_string(),
        }];
        resources.font_resources_mut().faces.push(FontFaceResource {
            id: prepared.face_key.clone(),
            blob_key: prepared.blob_key.clone(),
            face_index: prepared.face_index,
            postscript_name: None,
            family_names,
            style_names: Vec::new(),
            weight_class: Some(prepared.weight_class),
            width_class: Some(prepared.width_class),
            italic: Some(prepared.italic),
        });
    }
    prepared.face_key.clone()
}

/// Lower one exact page-local decision without adding it to a product layer.
/// The original TextRun operation is owned by the caller and is never removed.
pub(crate) fn lower_horizontal_shaping_layer_node_shadow(
    node: &LayerNode,
    bbox: BoundingBox,
    run: &TextRunNode,
    text_source_id: u32,
    sidecars: &HorizontalShapingPageSidecars,
    resources: &mut ResourceArena,
) -> HorizontalShapingGlyphLoweringReport {
    let mut prepared_sources = HorizontalShapingPreparedSourceCache::default();
    lower_horizontal_shaping_layer_node_shadow_with_prepared_sources(
        node,
        bbox,
        run,
        text_source_id,
        sidecars,
        resources,
        &mut prepared_sources,
    )
}

pub(crate) fn lower_horizontal_shaping_layer_node_shadow_with_prepared_sources(
    node: &LayerNode,
    bbox: BoundingBox,
    run: &TextRunNode,
    text_source_id: u32,
    sidecars: &HorizontalShapingPageSidecars,
    resources: &mut ResourceArena,
    prepared_sources: &mut HorizontalShapingPreparedSourceCache,
) -> HorizontalShapingGlyphLoweringReport {
    let source = TextSourceSpan::for_text_run(text_source_id, run);
    lower_horizontal_shaping_source_shadow(
        node.source_node_id,
        bbox,
        run,
        &source,
        sidecars,
        resources,
        prepared_sources,
    )
}

fn lower_horizontal_shaping_source_shadow(
    source_node_id: Option<u32>,
    bbox: BoundingBox,
    run: &TextRunNode,
    source: &TextSourceSpan,
    sidecars: &HorizontalShapingPageSidecars,
    resources: &mut ResourceArena,
    prepared_sources: &mut HorizontalShapingPreparedSourceCache,
) -> HorizontalShapingGlyphLoweringReport {
    let text_source_id = source.id.0;
    let Some(source_node_id) = source_node_id else {
        return HorizontalShapingGlyphLoweringReport::rejected(
            None,
            HorizontalShapingGlyphLoweringRejectReason::MissingSourceNode,
        );
    };
    let Some(decision) = sidecars.get(source_node_id) else {
        return HorizontalShapingGlyphLoweringReport::rejected(
            Some(source_node_id),
            HorizontalShapingGlyphLoweringRejectReason::MissingSidecar,
        );
    };
    if decision.measurement().is_none() {
        return HorizontalShapingGlyphLoweringReport::rejected(
            Some(source_node_id),
            HorizontalShapingGlyphLoweringRejectReason::RejectedDecision,
        );
    }
    if !run_surface_supported(run) {
        return HorizontalShapingGlyphLoweringReport::rejected(
            Some(source_node_id),
            HorizontalShapingGlyphLoweringRejectReason::UnsupportedRunSurface,
        );
    }
    let range = decision.range();
    let scalar_count = run.text.chars().count();
    if range.scalar_end - range.scalar_start != scalar_count
        || range.utf8_end - range.utf8_start != run.text.len()
        || range.utf16_end - range.utf16_start != run.text.encode_utf16().count()
    {
        return HorizontalShapingGlyphLoweringReport::rejected(
            Some(source_node_id),
            HorizontalShapingGlyphLoweringRejectReason::RunRangeMismatch,
        );
    }

    let mut portable_source_work = HorizontalShapingPortableSourceWork::default();
    let prepared = match prepared_sources.prepare(decision, &mut portable_source_work) {
        Ok(prepared) => prepared,
        Err(reason) => {
            return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
        }
    };
    if let Err(reason) = validate_measurement(decision, run, prepared.number_of_glyphs) {
        return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason);
    }
    let projection = match project_replay_geometry(decision, bbox, run) {
        Ok(value) => value,
        Err(reason) => {
            return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
        }
    };
    let clusters = match lower_clusters(decision, run) {
        Ok(value) => value,
        Err(reason) => {
            return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
        }
    };
    let measurement = decision
        .measurement()
        .expect("measurement was validated above");
    let variable_outline = if prepared.is_variable {
        match build_variable_outline_shadow(
            decision,
            &prepared,
            &projection,
            &clusters,
            source,
            run,
        ) {
            Ok(value) => Some(value),
            Err(reason) => {
                return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
            }
        }
    } else {
        None
    };
    if measurement.instance_request.is_some() && variable_outline.is_none() {
        return HorizontalShapingGlyphLoweringReport::rejected(
            Some(source_node_id),
            HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable,
        );
    }
    let glyph_ids = measurement
        .glyphs_px
        .iter()
        .map(|glyph| glyph.glyph_id)
        .collect();
    // All validation precedes resource mutation, so a rejected attempt cannot
    // leave a partial portable-font publication behind.
    if resources
        .font_blob_bytes_for_ref(&prepared.data_ref)
        .is_none()
    {
        let Some(existing_bytes) = resources
            .font_blob_resources()
            .try_fold(0usize, |total, (_, bytes)| total.checked_add(bytes.len()))
        else {
            return HorizontalShapingGlyphLoweringReport::rejected(
                Some(source_node_id),
                HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded,
            );
        };
        if existing_bytes
            .checked_add(prepared.source_bytes.len())
            .is_none_or(|total| total > MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE)
        {
            return HorizontalShapingGlyphLoweringReport::rejected(
                Some(source_node_id),
                HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded,
            );
        }
    }
    let face_key = register_prepared_portable_face(
        &prepared,
        &run.style.font_family,
        resources,
        &mut portable_source_work,
    );
    let equivalence_group = format!("text-{text_source_id}");
    let mut variant = PaintVariantMeta::text_run_default(equivalence_group.clone());
    variant.variant_id = "glyphRun".to_string();
    variant.variant_kind = TextVariantKind::GlyphRun;
    variant.is_default_fallback = false;
    variant.requires = vec!["fontResources".to_string(), "text.glyphRun".to_string()];
    variant.quality = Some(TextVariantQuality::Exact);
    variant.anchor_op_id = Some(equivalence_group);
    let identity = &measurement.applied.identity;
    let variations = identity
        .variations
        .iter()
        .map(|variation| VariationAxisValue {
            tag: variation.tag.clone(),
            value: f32::from_bits(variation.value_bits),
        })
        .collect();
    let features = identity
        .features
        .iter()
        .map(|feature| OpenTypeFeatureSetting {
            tag: feature.tag.clone(),
            enabled: feature.value != 0,
            value: Some(feature.value),
        })
        .collect();
    let mut paint_style = PaintTextStyle::from(&run.style);
    paint_style.font_size = projection.draw_font_size_px;
    paint_style.ratio = 1.0;
    let glyph_run = LayerGlyphRunPaint {
        source: source.clone(),
        variant,
        paint_style,
        shape_key: ShapeKey {
            font_instance: FontInstanceKey {
                face_key,
                size_px: projection.draw_font_size_px,
                variations,
                synthetic_bold: false,
                synthetic_italic: false,
            },
            direction: TextDirection::Ltr,
            writing_mode: WritingMode::HorizontalTb,
            script: identity.script.clone().map(ScriptTag),
            language: identity.language.clone().map(LanguageTag),
            features,
            shaping_engine: ShapingEngineId("rustybuzz-q2-v1".to_string()),
            fallback_policy: FontFallbackPolicyId("none".to_string()),
        },
        placement: projection.placement,
        glyph_ids,
        positions: projection.positions,
        advances: Some(projection.advances),
        clusters,
        direction: TextDirection::Ltr,
        bidi_level: Some(0),
        writing_mode: WritingMode::HorizontalTb,
        orientation: GlyphRunOrientation::Horizontal,
        glyph_transforms: None,
        diagnostics: GlyphRunDiagnostics {
            quality: TextVariantQuality::Exact,
            replay_eligibility: GlyphRunReplayEligibility::Portable,
            strict_visual_eligible: true,
            max_origin_delta_px: projection.max_origin_delta_px,
            max_advance_delta_px: projection.max_advance_delta_px,
            max_residual_after_adjustment_px: projection
                .max_origin_delta_px
                .max(projection.max_advance_delta_px),
            cluster_mismatch_count: 0,
            missing_glyph_count: 0,
            used_fallback_font_count: 0,
            reason: Some(
                if measurement.instance_request.is_some() {
                    "q3ExplicitInstanceGlyphRunProjectionV1"
                } else {
                    "q2CommonShapingCondensedDrawProjectionV1"
                }
                .to_string(),
            ),
        },
    };
    let (glyph_outline, variable_outline_proof) = variable_outline
        .map(|(outline, proof)| (Some(outline), Some(proof)))
        .unwrap_or((None, None));
    HorizontalShapingGlyphLoweringReport::emitted(
        source_node_id,
        glyph_run,
        glyph_outline,
        variable_outline_proof,
        portable_source_work,
        measurement.instance_request.is_some(),
    )
}

/// Page-local common shaping sidecar를 TextRun 순서와 같은 text_source_id로
/// 먼저 내린다. 성공한 source id 집합은 뒤따르는 nominal font lowerer가
/// 중복 GlyphRun 생성을 건너뛰는 유일한 claim이다.
pub(crate) fn lower_horizontal_shaping_page_sidecars(
    root: &mut LayerNode,
    sidecars: &HorizontalShapingPageSidecars,
    resources: &mut ResourceArena,
) -> HashSet<u32> {
    fn lower_node(
        node: &mut LayerNode,
        sidecars: &HorizontalShapingPageSidecars,
        resources: &mut ResourceArena,
        prepared_sources: &mut HorizontalShapingPreparedSourceCache,
        next_text_source_id: &mut u32,
        claimed: &mut HashSet<u32>,
    ) {
        let source_node_id = node.source_node_id;
        match &mut node.kind {
            crate::paint::LayerNodeKind::Group { children, .. } => {
                for child in children {
                    lower_node(
                        child,
                        sidecars,
                        resources,
                        prepared_sources,
                        next_text_source_id,
                        claimed,
                    );
                }
            }
            crate::paint::LayerNodeKind::ClipRect { child, .. }
            | crate::paint::LayerNodeKind::ClipPath { child, .. } => {
                lower_node(
                    child,
                    sidecars,
                    resources,
                    prepared_sources,
                    next_text_source_id,
                    claimed,
                );
            }
            crate::paint::LayerNodeKind::Leaf { ops } => {
                let mut lowered = Vec::with_capacity(ops.len());
                for op in ops.drain(..) {
                    if let crate::paint::PaintOp::TextRun {
                        bbox, run, source, ..
                    } = op
                    {
                        let source = source.unwrap_or_else(|| {
                            crate::paint::TextSourceSpan::for_text_run(*next_text_source_id, &run)
                        });
                        let text_source_id = source.id.0;
                        *next_text_source_id =
                            (*next_text_source_id).max(text_source_id.saturating_add(1));
                        let report = lower_horizontal_shaping_source_shadow(
                            source_node_id,
                            bbox,
                            &run,
                            &source,
                            sidecars,
                            resources,
                            prepared_sources,
                        );
                        lowered.push(crate::paint::PaintOp::TextRun {
                            paint_transform: None,
                            bbox,
                            run,
                            source: Some(source),
                        });
                        if report.claims_glyph_run_slot {
                            if report.atomic_outline_required {
                                if let (Some(glyph_run), Some(glyph_outline)) =
                                    (report.glyph_run, report.glyph_outline)
                                {
                                    lowered.push(crate::paint::PaintOp::GlyphRun {
                                        paint_transform: None,
                                        bbox,
                                        run: Box::new(glyph_run),
                                    });
                                    lowered.push(crate::paint::PaintOp::GlyphOutline {
                                        paint_transform: None,
                                        bbox,
                                        outline: Box::new(glyph_outline),
                                    });
                                    claimed.insert(text_source_id);
                                }
                            } else if let Some(glyph_run) = report.glyph_run {
                                lowered.push(crate::paint::PaintOp::GlyphRun {
                                    paint_transform: None,
                                    bbox,
                                    run: Box::new(glyph_run),
                                });
                                claimed.insert(text_source_id);
                            }
                        }
                    } else {
                        lowered.push(op);
                    }
                }
                *ops = lowered;
            }
        }
    }

    let mut next_text_source_id = 0;
    let mut claimed = HashSet::new();
    let mut prepared_sources = HorizontalShapingPreparedSourceCache::default();
    lower_node(
        root,
        sidecars,
        resources,
        &mut prepared_sources,
        &mut next_text_source_id,
        &mut claimed,
    );
    claimed
}