ftui-text 0.4.0

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

//! Text shaping backend and deterministic shaped-run cache.
//!
//! This module provides the interface and caching layer for text shaping —
//! the process of converting a sequence of Unicode codepoints into positioned
//! glyphs. Shaping handles script-specific reordering, ligature substitution,
//! and glyph positioning (kerning, mark attachment).
//!
//! # Architecture
//!
//! ```text
//! TextRun (from script_segmentation)
//!//!//! ┌───────────────┐
//! │ ShapingCache   │──cache hit──▶ ShapedRun (cached)
//! │ (LRU + gen)    │
//! └───────┬───────┘
//!         │ cache miss
//!//! ┌───────────────┐
//! │ TextShaper     │  trait (NoopShaper | RustybuzzShaper)
//! └───────┬───────┘
//!//!//!     ShapedRun
//! ```
//!
//! # Key schema
//!
//! The [`ShapingKey`] captures all parameters that affect shaping output:
//! text content (hashed), script, direction, style, font identity, font size,
//! and OpenType features. Two runs producing the same `ShapingKey` are
//! guaranteed to produce identical `ShapedRun` output.
//!
//! # Invalidation
//!
//! The cache uses generation-based invalidation. When fonts change (DPR
//! change, zoom, font swap), the generation is bumped and stale entries are
//! lazily evicted on access. This avoids expensive bulk-clear operations.
//!
//! # Example
//!
//! ```
//! use ftui_text::shaping::{
//!     NoopShaper, ShapingCache, FontId, FontFeatures,
//! };
//! use ftui_text::script_segmentation::{Script, RunDirection};
//!
//! let shaper = NoopShaper;
//! let mut cache = ShapingCache::new(shaper, 1024);
//!
//! let result = cache.shape(
//!     "Hello",
//!     Script::Latin,
//!     RunDirection::Ltr,
//!     FontId(0),
//!     256 * 12, // 12pt in 1/256th units
//!     &FontFeatures::default(),
//! );
//! assert!(!result.glyphs.is_empty());
//! ```

use crate::script_segmentation::{RunDirection, Script};
use lru::LruCache;
use rustc_hash::FxHasher;
use smallvec::SmallVec;
use std::hash::{Hash, Hasher};
use std::num::NonZeroUsize;

// ---------------------------------------------------------------------------
// Font identity types
// ---------------------------------------------------------------------------

/// Opaque identifier for a font face within the application.
///
/// The mapping from `FontId` to actual font data is managed by the caller.
/// The shaping layer treats this as an opaque discriminant for cache keying.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FontId(pub u32);

/// A single OpenType feature tag + value.
///
/// Tags are 4-byte ASCII identifiers (e.g., `b"liga"`, `b"kern"`, `b"smcp"`).
/// Value 0 disables the feature, 1 enables it, higher values select alternates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FontFeature {
    /// OpenType tag (4 ASCII bytes, e.g., `*b"liga"`).
    pub tag: [u8; 4],
    /// Feature value (0 = off, 1 = on, >1 = alternate selection).
    pub value: u32,
}

impl FontFeature {
    /// Create a new feature from a tag and value.
    #[inline]
    pub const fn new(tag: [u8; 4], value: u32) -> Self {
        Self { tag, value }
    }

    /// Create an enabled feature from a tag.
    #[inline]
    pub const fn enabled(tag: [u8; 4]) -> Self {
        Self { tag, value: 1 }
    }

    /// Create a disabled feature from a tag.
    #[inline]
    pub const fn disabled(tag: [u8; 4]) -> Self {
        Self { tag, value: 0 }
    }
}

/// A set of OpenType features requested for shaping.
///
/// Stack-allocated for the common case of ≤4 features.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct FontFeatures {
    features: SmallVec<[FontFeature; 4]>,
}

impl FontFeatures {
    /// Create an empty feature set.
    #[inline]
    pub fn new() -> Self {
        Self {
            features: SmallVec::new(),
        }
    }

    /// Add a feature to the set.
    #[inline]
    pub fn push(&mut self, feature: FontFeature) {
        self.features.push(feature);
    }

    /// Create from a slice of features.
    pub fn from_slice(features: &[FontFeature]) -> Self {
        Self {
            features: SmallVec::from_slice(features),
        }
    }

    /// Number of features.
    #[inline]
    pub fn len(&self) -> usize {
        self.features.len()
    }

    /// Whether the feature set is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.features.is_empty()
    }

    /// Iterate over features.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &FontFeature> {
        self.features.iter()
    }

    /// Return the value for a feature tag if present.
    #[inline]
    pub fn feature_value(&self, tag: [u8; 4]) -> Option<u32> {
        self.features.iter().find(|f| f.tag == tag).map(|f| f.value)
    }

    /// Insert or update a feature value by tag.
    pub fn set_feature_value(&mut self, tag: [u8; 4], value: u32) {
        if let Some(existing) = self.features.iter_mut().find(|f| f.tag == tag) {
            existing.value = value;
        } else {
            self.features.push(FontFeature::new(tag, value));
        }
        self.canonicalize();
    }

    /// Toggle standard ligature features (`liga`, `clig`).
    ///
    /// This explicit toggle is used by capability-gated fallback code so
    /// ligature behavior stays deterministic across runtimes.
    pub fn set_standard_ligatures(&mut self, enabled: bool) {
        let value = u32::from(enabled);
        self.set_feature_value(*b"liga", value);
        self.set_feature_value(*b"clig", value);
    }

    /// Return explicit standard-ligature state if configured.
    ///
    /// - `Some(true)`: all explicitly configured standard ligatures are on.
    /// - `Some(false)`: at least one explicit standard-ligature feature is off.
    /// - `None`: no explicit standard-ligature feature was configured.
    #[must_use]
    pub fn standard_ligatures_enabled(&self) -> Option<bool> {
        let mut saw_explicit = false;
        let mut enabled = true;
        for tag in [*b"liga", *b"clig"] {
            if let Some(value) = self.feature_value(tag) {
                saw_explicit = true;
                enabled &= value != 0;
            }
        }
        saw_explicit.then_some(enabled)
    }

    /// Sort features by tag for deterministic hashing.
    pub fn canonicalize(&mut self) {
        self.features.sort_by_key(|f| f.tag);
    }
}

// ---------------------------------------------------------------------------
// Shaped output types
// ---------------------------------------------------------------------------

/// A single positioned glyph from the shaping engine.
///
/// All metric values are in font design units. The caller converts to pixels
/// using the font's units-per-em and the desired point size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShapedGlyph {
    /// Glyph ID from the font (0 = `.notdef`).
    pub glyph_id: u32,
    /// Byte offset of the start of this glyph's cluster in the source text.
    ///
    /// Multiple glyphs can share the same cluster (ligatures produce one glyph
    /// for multiple characters; complex scripts may produce multiple glyphs
    /// for one character).
    pub cluster: u32,
    /// Horizontal advance in font design units.
    pub x_advance: i32,
    /// Vertical advance in font design units.
    pub y_advance: i32,
    /// Horizontal offset from the nominal position.
    pub x_offset: i32,
    /// Vertical offset from the nominal position.
    pub y_offset: i32,
}

/// The result of shaping a text run.
///
/// Contains the positioned glyphs and aggregate metrics needed for layout.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShapedRun {
    /// Positioned glyphs in visual order.
    pub glyphs: Vec<ShapedGlyph>,
    /// Total horizontal advance of all glyphs (sum of x_advance).
    pub total_advance: i32,
}

impl ShapedRun {
    /// Number of glyphs in the run.
    #[inline]
    pub fn len(&self) -> usize {
        self.glyphs.len()
    }

    /// Whether the run contains no glyphs.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.glyphs.is_empty()
    }
}

// ---------------------------------------------------------------------------
// ShapingKey — deterministic cache key
// ---------------------------------------------------------------------------

/// Deterministic cache key for shaped glyph output.
///
/// Captures all parameters that affect shaping results. Two identical keys
/// are guaranteed to produce identical `ShapedRun` output, enabling safe
/// caching.
///
/// # Key components
///
/// | Field          | Purpose                                        |
/// |----------------|------------------------------------------------|
/// | `text_hash`    | FxHash of the text content                     |
/// | `text_len`     | Byte length (collision avoidance)               |
/// | `script`       | Unicode script (affects glyph selection)        |
/// | `direction`    | LTR/RTL (affects reordering + positioning)     |
/// | `style_id`     | Style discriminant (bold/italic affect glyphs) |
/// | `font_id`      | Font face identity                             |
/// | `size_256ths`  | Font size in 1/256th point units               |
/// | `features`     | Active OpenType features                       |
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShapingKey {
    /// FxHash of the text content.
    pub text_hash: u64,
    /// Byte length of the text (for collision avoidance with the hash).
    pub text_len: u32,
    /// Unicode script.
    pub script: Script,
    /// Text direction.
    pub direction: RunDirection,
    /// Style discriminant.
    pub style_id: u64,
    /// Font face identity.
    pub font_id: FontId,
    /// Font size in 1/256th of a point (sub-pixel precision matching ftui-render).
    pub size_256ths: u32,
    /// Active OpenType features (canonicalized for determinism).
    pub features: FontFeatures,
}

impl ShapingKey {
    /// Build a key from shaping parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        text: &str,
        script: Script,
        direction: RunDirection,
        style_id: u64,
        font_id: FontId,
        size_256ths: u32,
        features: &FontFeatures,
    ) -> Self {
        let mut hasher = FxHasher::default();
        text.hash(&mut hasher);
        let text_hash = hasher.finish();

        Self {
            text_hash,
            text_len: text.len() as u32,
            script,
            direction,
            style_id,
            font_id,
            size_256ths,
            features: features.clone(),
        }
    }
}

// ---------------------------------------------------------------------------
// TextShaper trait
// ---------------------------------------------------------------------------

/// Abstract text shaping backend.
///
/// Implementations convert a Unicode text string into positioned glyphs
/// according to the rules of the specified script, direction, and font
/// features.
///
/// The trait is object-safe to allow dynamic dispatch between backends
/// (e.g., terminal noop vs. web rustybuzz).
pub trait TextShaper {
    /// Shape a text run into positioned glyphs.
    ///
    /// # Parameters
    ///
    /// * `text` — The text to shape (UTF-8, from a single `TextRun`).
    /// * `script` — The resolved Unicode script.
    /// * `direction` — LTR or RTL text direction.
    /// * `features` — OpenType features to apply.
    ///
    /// # Returns
    ///
    /// A `ShapedRun` containing positioned glyphs in visual order.
    fn shape(
        &self,
        text: &str,
        script: Script,
        direction: RunDirection,
        features: &FontFeatures,
    ) -> ShapedRun;
}

// ---------------------------------------------------------------------------
// NoopShaper — terminal / monospace backend
// ---------------------------------------------------------------------------

/// Identity shaper for monospace terminal rendering.
///
/// Maps each grapheme cluster to a single glyph with uniform advance.
/// This is the correct shaping backend for fixed-width terminal output
/// where each cell is one column wide (or two for CJK/wide characters).
///
/// The glyph ID is set to the first codepoint of each grapheme, and
/// the advance is the grapheme's display width in terminal cells.
pub struct NoopShaper;

impl TextShaper for NoopShaper {
    fn shape(
        &self,
        text: &str,
        _script: Script,
        _direction: RunDirection,
        _features: &FontFeatures,
    ) -> ShapedRun {
        use unicode_segmentation::UnicodeSegmentation;

        let mut glyphs = Vec::new();
        let mut total_advance = 0i32;

        for (byte_offset, grapheme) in text.grapheme_indices(true) {
            let first_char = grapheme.chars().next().unwrap_or('\0');
            let width = crate::grapheme_width(grapheme) as i32;

            glyphs.push(ShapedGlyph {
                glyph_id: first_char as u32,
                cluster: byte_offset as u32,
                x_advance: width,
                y_advance: 0,
                x_offset: 0,
                y_offset: 0,
            });

            total_advance += width;
        }

        ShapedRun {
            glyphs,
            total_advance,
        }
    }
}

// ---------------------------------------------------------------------------
// ShapingCache — LRU cache with generation-based invalidation
// ---------------------------------------------------------------------------

/// Statistics for the shaping cache.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ShapingCacheStats {
    /// Number of cache hits.
    pub hits: u64,
    /// Number of cache misses (triggered shaping).
    pub misses: u64,
    /// Number of stale entries evicted due to generation mismatch.
    pub stale_evictions: u64,
    /// Current number of entries in the cache.
    pub size: usize,
    /// Maximum capacity of the cache.
    pub capacity: usize,
    /// Current invalidation generation.
    pub generation: u64,
}

impl ShapingCacheStats {
    /// Hit rate as a fraction (0.0 to 1.0).
    #[must_use]
    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            self.hits as f64 / total as f64
        }
    }
}

/// Cached entry with its generation stamp.
#[derive(Debug, Clone)]
struct CachedEntry {
    run: ShapedRun,
    generation: u64,
}

/// LRU cache for shaped text runs with generation-based invalidation.
///
/// # Invalidation policy
///
/// The cache tracks a monotonically increasing generation counter. Each
/// cached entry is stamped with the generation at insertion time. When
/// global state changes (font swap, DPR change, zoom), the caller bumps
/// the generation via [`invalidate`](Self::invalidate). Entries from older
/// generations are treated as misses on access and lazily replaced.
///
/// This avoids expensive bulk-clear operations while ensuring correctness.
///
/// # Thread safety
///
/// The cache is not `Sync`. For multi-threaded use, wrap in a `Mutex` or
/// use per-thread instances (matching the `thread_local_cache` feature
/// pattern from `WidthCache`).
pub struct ShapingCache<S: TextShaper> {
    shaper: S,
    cache: LruCache<ShapingKey, CachedEntry>,
    generation: u64,
    stats: ShapingCacheStats,
}

impl<S: TextShaper> ShapingCache<S> {
    /// Create a new shaping cache with the given backend and capacity.
    pub fn new(shaper: S, capacity: usize) -> Self {
        let cap = NonZeroUsize::new(capacity.max(1)).expect("capacity must be > 0");
        Self {
            shaper,
            cache: LruCache::new(cap),
            generation: 0,
            stats: ShapingCacheStats {
                capacity,
                ..Default::default()
            },
        }
    }

    /// Shape a text run, returning a cached result if available.
    ///
    /// The full shaping key is constructed from the provided parameters.
    /// If a cache entry exists with the current generation, it is returned
    /// directly. Otherwise, the shaper is invoked and the result is cached.
    pub fn shape(
        &mut self,
        text: &str,
        script: Script,
        direction: RunDirection,
        font_id: FontId,
        size_256ths: u32,
        features: &FontFeatures,
    ) -> ShapedRun {
        self.shape_with_style(text, script, direction, 0, font_id, size_256ths, features)
    }

    /// Shape with an explicit style discriminant.
    #[allow(clippy::too_many_arguments)]
    pub fn shape_with_style(
        &mut self,
        text: &str,
        script: Script,
        direction: RunDirection,
        style_id: u64,
        font_id: FontId,
        size_256ths: u32,
        features: &FontFeatures,
    ) -> ShapedRun {
        let key = ShapingKey::new(
            text,
            script,
            direction,
            style_id,
            font_id,
            size_256ths,
            features,
        );

        // Check cache.
        if let Some(entry) = self.cache.get(&key) {
            if entry.generation == self.generation {
                self.stats.hits += 1;
                return entry.run.clone();
            }
            // Stale entry — will be replaced below.
            self.stats.stale_evictions += 1;
        }

        // Cache miss — invoke shaper.
        self.stats.misses += 1;
        let run = self.shaper.shape(text, script, direction, features);

        self.cache.put(
            key,
            CachedEntry {
                run: run.clone(),
                generation: self.generation,
            },
        );

        self.stats.size = self.cache.len();
        run
    }

    /// Bump the generation counter, invalidating all cached entries.
    ///
    /// Stale entries are not removed eagerly — they are lazily evicted
    /// on next access. This makes invalidation O(1).
    ///
    /// Call this when:
    /// - The font set changes (font swap, fallback resolution).
    /// - Display DPR changes (affects pixel grid rounding).
    /// - Zoom level changes.
    pub fn invalidate(&mut self) {
        self.generation += 1;
        self.stats.generation = self.generation;
    }

    /// Clear all cached entries and reset stats.
    pub fn clear(&mut self) {
        self.cache.clear();
        self.generation += 1;
        self.stats = ShapingCacheStats {
            capacity: self.stats.capacity,
            generation: self.generation,
            ..Default::default()
        };
    }

    /// Current cache statistics.
    #[inline]
    pub fn stats(&self) -> ShapingCacheStats {
        ShapingCacheStats {
            size: self.cache.len(),
            ..self.stats
        }
    }

    /// Current generation counter.
    #[inline]
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Access the underlying shaper.
    #[inline]
    pub fn shaper(&self) -> &S {
        &self.shaper
    }

    /// Resize the cache capacity.
    ///
    /// If the new capacity is smaller than the current size, excess
    /// entries are evicted in LRU order.
    pub fn resize(&mut self, new_capacity: usize) {
        let cap = NonZeroUsize::new(new_capacity.max(1)).expect("capacity must be > 0");
        self.cache.resize(cap);
        self.stats.capacity = new_capacity;
        self.stats.size = self.cache.len();
    }
}

// ---------------------------------------------------------------------------
// RustybuzzShaper — real shaping backend (feature-gated)
// ---------------------------------------------------------------------------

#[cfg(feature = "shaping")]
mod rustybuzz_backend {
    use super::*;

    /// HarfBuzz-compatible shaper using the rustybuzz pure-Rust engine.
    ///
    /// Wraps a `rustybuzz::Face` and provides the `TextShaper` interface.
    /// The face data must outlive the shaper (typically held in an `Arc`).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let font_data: &[u8] = include_bytes!("path/to/font.ttf");
    /// let face = rustybuzz::Face::from_slice(font_data, 0).unwrap();
    /// let shaper = RustybuzzShaper::new(face);
    /// ```
    pub struct RustybuzzShaper {
        face: rustybuzz::Face<'static>,
    }

    impl RustybuzzShaper {
        /// Create a shaper from a rustybuzz face.
        ///
        /// The face must have `'static` lifetime — typically achieved by
        /// loading font data into a leaked `Box<[u8]>` or `Arc` with a
        /// transmuted lifetime (handled by the font loading layer).
        pub fn new(face: rustybuzz::Face<'static>) -> Self {
            Self { face }
        }

        /// Convert our Script enum to a rustybuzz script constant.
        fn to_rb_script(script: Script) -> rustybuzz::Script {
            use rustybuzz::script;
            match script {
                Script::Latin => script::LATIN,
                Script::Greek => script::GREEK,
                Script::Cyrillic => script::CYRILLIC,
                Script::Armenian => script::ARMENIAN,
                Script::Hebrew => script::HEBREW,
                Script::Arabic => script::ARABIC,
                Script::Syriac => script::SYRIAC,
                Script::Thaana => script::THAANA,
                Script::Devanagari => script::DEVANAGARI,
                Script::Bengali => script::BENGALI,
                Script::Gurmukhi => script::GURMUKHI,
                Script::Gujarati => script::GUJARATI,
                Script::Oriya => script::ORIYA,
                Script::Tamil => script::TAMIL,
                Script::Telugu => script::TELUGU,
                Script::Kannada => script::KANNADA,
                Script::Malayalam => script::MALAYALAM,
                Script::Sinhala => script::SINHALA,
                Script::Thai => script::THAI,
                Script::Lao => script::LAO,
                Script::Tibetan => script::TIBETAN,
                Script::Myanmar => script::MYANMAR,
                Script::Georgian => script::GEORGIAN,
                Script::Hangul => script::HANGUL,
                Script::Ethiopic => script::ETHIOPIC,
                Script::Han => script::HAN,
                Script::Hiragana => script::HIRAGANA,
                Script::Katakana => script::KATAKANA,
                Script::Bopomofo => script::BOPOMOFO,
                Script::Common | Script::Inherited | Script::Unknown => script::COMMON,
            }
        }

        /// Convert our RunDirection to rustybuzz::Direction.
        fn to_rb_direction(direction: RunDirection) -> rustybuzz::Direction {
            match direction {
                RunDirection::Ltr => rustybuzz::Direction::LeftToRight,
                RunDirection::Rtl => rustybuzz::Direction::RightToLeft,
            }
        }

        /// Convert our FontFeature to rustybuzz::Feature.
        fn to_rb_feature(feature: &FontFeature) -> rustybuzz::Feature {
            let tag = rustybuzz::ttf_parser::Tag::from_bytes(&feature.tag);
            rustybuzz::Feature::new(tag, feature.value, ..)
        }
    }

    impl TextShaper for RustybuzzShaper {
        fn shape(
            &self,
            text: &str,
            script: Script,
            direction: RunDirection,
            features: &FontFeatures,
        ) -> ShapedRun {
            let mut buffer = rustybuzz::UnicodeBuffer::new();
            buffer.push_str(text);
            buffer.set_script(Self::to_rb_script(script));
            buffer.set_direction(Self::to_rb_direction(direction));

            let rb_features: Vec<rustybuzz::Feature> =
                features.iter().map(Self::to_rb_feature).collect();

            let output = rustybuzz::shape(&self.face, &rb_features, buffer);

            let infos = output.glyph_infos();
            let positions = output.glyph_positions();

            let mut glyphs = Vec::with_capacity(infos.len());
            let mut total_advance = 0i32;

            for (info, pos) in infos.iter().zip(positions.iter()) {
                glyphs.push(ShapedGlyph {
                    glyph_id: info.glyph_id,
                    cluster: info.cluster,
                    x_advance: pos.x_advance,
                    y_advance: pos.y_advance,
                    x_offset: pos.x_offset,
                    y_offset: pos.y_offset,
                });
                total_advance += pos.x_advance;
            }

            ShapedRun {
                glyphs,
                total_advance,
            }
        }
    }
}

#[cfg(feature = "shaping")]
pub use rustybuzz_backend::RustybuzzShaper;

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::script_segmentation::{RunDirection, Script};

    // -----------------------------------------------------------------------
    // FontFeature / FontFeatures tests
    // -----------------------------------------------------------------------

    #[test]
    fn font_feature_new() {
        let f = FontFeature::new(*b"liga", 1);
        assert_eq!(f.tag, *b"liga");
        assert_eq!(f.value, 1);
    }

    #[test]
    fn font_feature_enabled_disabled() {
        let on = FontFeature::enabled(*b"kern");
        assert_eq!(on.value, 1);

        let off = FontFeature::disabled(*b"kern");
        assert_eq!(off.value, 0);
    }

    #[test]
    fn font_features_push_and_iter() {
        let mut ff = FontFeatures::new();
        assert!(ff.is_empty());

        ff.push(FontFeature::enabled(*b"liga"));
        ff.push(FontFeature::enabled(*b"kern"));
        assert_eq!(ff.len(), 2);

        let tags: Vec<[u8; 4]> = ff.iter().map(|f| f.tag).collect();
        assert_eq!(tags, vec![*b"liga", *b"kern"]);
    }

    #[test]
    fn font_features_canonicalize() {
        let mut ff = FontFeatures::from_slice(&[
            FontFeature::enabled(*b"kern"),
            FontFeature::enabled(*b"aalt"),
            FontFeature::enabled(*b"liga"),
        ]);
        ff.canonicalize();
        let tags: Vec<[u8; 4]> = ff.iter().map(|f| f.tag).collect();
        assert_eq!(tags, vec![*b"aalt", *b"kern", *b"liga"]);
    }

    #[test]
    fn font_features_default_is_empty() {
        let ff = FontFeatures::default();
        assert!(ff.is_empty());
    }

    #[test]
    fn font_features_set_feature_value_upserts() {
        let mut ff = FontFeatures::new();
        ff.set_feature_value(*b"liga", 1);
        ff.set_feature_value(*b"liga", 0);
        ff.set_feature_value(*b"kern", 1);

        assert_eq!(ff.feature_value(*b"liga"), Some(0));
        assert_eq!(ff.feature_value(*b"kern"), Some(1));
        assert_eq!(ff.len(), 2, "upsert should not duplicate existing tags");
    }

    #[test]
    fn font_features_standard_ligatures_toggle() {
        let mut ff = FontFeatures::new();
        assert_eq!(ff.standard_ligatures_enabled(), None);

        ff.set_standard_ligatures(true);
        assert_eq!(ff.feature_value(*b"liga"), Some(1));
        assert_eq!(ff.feature_value(*b"clig"), Some(1));
        assert_eq!(ff.standard_ligatures_enabled(), Some(true));

        ff.set_standard_ligatures(false);
        assert_eq!(ff.feature_value(*b"liga"), Some(0));
        assert_eq!(ff.feature_value(*b"clig"), Some(0));
        assert_eq!(ff.standard_ligatures_enabled(), Some(false));
    }

    // -----------------------------------------------------------------------
    // ShapedRun tests
    // -----------------------------------------------------------------------

    #[test]
    fn shaped_run_len_and_empty() {
        let empty = ShapedRun {
            glyphs: vec![],
            total_advance: 0,
        };
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);

        let non_empty = ShapedRun {
            glyphs: vec![ShapedGlyph {
                glyph_id: 65,
                cluster: 0,
                x_advance: 600,
                y_advance: 0,
                x_offset: 0,
                y_offset: 0,
            }],
            total_advance: 600,
        };
        assert!(!non_empty.is_empty());
        assert_eq!(non_empty.len(), 1);
    }

    // -----------------------------------------------------------------------
    // ShapingKey tests
    // -----------------------------------------------------------------------

    #[test]
    fn shaping_key_same_input_same_key() {
        let ff = FontFeatures::default();
        let k1 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        let k2 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        assert_eq!(k1, k2);
    }

    #[test]
    fn shaping_key_differs_by_text() {
        let ff = FontFeatures::default();
        let k1 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        let k2 = ShapingKey::new(
            "World",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        assert_ne!(k1, k2);
    }

    #[test]
    fn shaping_key_differs_by_font() {
        let ff = FontFeatures::default();
        let k1 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        let k2 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(1),
            3072,
            &ff,
        );
        assert_ne!(k1, k2);
    }

    #[test]
    fn shaping_key_differs_by_size() {
        let ff = FontFeatures::default();
        let k1 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        let k2 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            4096,
            &ff,
        );
        assert_ne!(k1, k2);
    }

    #[test]
    fn shaping_key_generation_is_not_part_of_key() {
        let ff = FontFeatures::default();
        let k1 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        let k2 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        assert_eq!(k1, k2);
    }

    #[test]
    fn shaping_key_differs_by_features() {
        let mut ff1 = FontFeatures::default();
        ff1.push(FontFeature::enabled(*b"liga"));

        let ff2 = FontFeatures::default();

        let k1 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff1,
        );
        let k2 = ShapingKey::new(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff2,
        );
        assert_ne!(k1, k2);
    }

    #[test]
    fn shaping_key_hashable() {
        use std::collections::HashSet;
        let ff = FontFeatures::default();
        let key = ShapingKey::new(
            "test",
            Script::Latin,
            RunDirection::Ltr,
            0,
            FontId(0),
            3072,
            &ff,
        );
        let mut set = HashSet::new();
        set.insert(key.clone());
        assert!(set.contains(&key));
    }

    // -----------------------------------------------------------------------
    // NoopShaper tests
    // -----------------------------------------------------------------------

    #[test]
    fn noop_shaper_ascii() {
        let shaper = NoopShaper;
        let ff = FontFeatures::default();
        let run = shaper.shape("Hello", Script::Latin, RunDirection::Ltr, &ff);

        assert_eq!(run.len(), 5);
        assert_eq!(run.total_advance, 5); // 5 ASCII chars × 1 cell each

        // Each glyph should have the codepoint as glyph_id.
        assert_eq!(run.glyphs[0].glyph_id, b'H' as u32);
        assert_eq!(run.glyphs[1].glyph_id, b'e' as u32);
        assert_eq!(run.glyphs[4].glyph_id, b'o' as u32);

        // Clusters should be byte offsets.
        assert_eq!(run.glyphs[0].cluster, 0);
        assert_eq!(run.glyphs[1].cluster, 1);
        assert_eq!(run.glyphs[4].cluster, 4);
    }

    #[test]
    fn noop_shaper_empty() {
        let shaper = NoopShaper;
        let ff = FontFeatures::default();
        let run = shaper.shape("", Script::Latin, RunDirection::Ltr, &ff);
        assert!(run.is_empty());
        assert_eq!(run.total_advance, 0);
    }

    #[test]
    fn noop_shaper_wide_chars() {
        let shaper = NoopShaper;
        let ff = FontFeatures::default();
        // CJK characters are 2 cells wide
        let run = shaper.shape("\u{4E16}\u{754C}", Script::Han, RunDirection::Ltr, &ff);

        assert_eq!(run.len(), 2);
        assert_eq!(run.total_advance, 4); // 2 chars × 2 cells each
        assert_eq!(run.glyphs[0].x_advance, 2);
        assert_eq!(run.glyphs[1].x_advance, 2);
    }

    #[test]
    fn noop_shaper_combining_marks() {
        let shaper = NoopShaper;
        let ff = FontFeatures::default();
        // "é" as e + combining acute: single grapheme cluster
        let run = shaper.shape("e\u{0301}", Script::Latin, RunDirection::Ltr, &ff);

        // Should produce 1 glyph (one grapheme cluster).
        assert_eq!(run.len(), 1);
        assert_eq!(run.total_advance, 1);
        assert_eq!(run.glyphs[0].glyph_id, b'e' as u32);
        assert_eq!(run.glyphs[0].cluster, 0);
    }

    #[test]
    fn noop_shaper_ignores_direction_and_features() {
        let shaper = NoopShaper;
        let mut ff = FontFeatures::new();
        ff.push(FontFeature::enabled(*b"liga"));

        let ltr = shaper.shape("ABC", Script::Latin, RunDirection::Ltr, &ff);
        let rtl = shaper.shape("ABC", Script::Latin, RunDirection::Rtl, &ff);

        // NoopShaper produces identical output regardless of direction.
        assert_eq!(ltr, rtl);
    }

    // -----------------------------------------------------------------------
    // ShapingCache tests
    // -----------------------------------------------------------------------

    #[test]
    fn cache_hit_on_second_call() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        let r1 = cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );
        let r2 = cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );

        assert_eq!(r1, r2);
        assert_eq!(cache.stats().hits, 1);
        assert_eq!(cache.stats().misses, 1);
    }

    #[test]
    fn cache_miss_on_different_text() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );
        cache.shape(
            "World",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );

        assert_eq!(cache.stats().hits, 0);
        assert_eq!(cache.stats().misses, 2);
    }

    #[test]
    fn cache_miss_on_different_font() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );
        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(1),
            3072,
            &ff,
        );

        assert_eq!(cache.stats().misses, 2);
    }

    #[test]
    fn cache_miss_on_different_size() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );
        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            4096,
            &ff,
        );

        assert_eq!(cache.stats().misses, 2);
    }

    #[test]
    fn cache_miss_on_ligature_feature_toggle() {
        let mut cache = ShapingCache::new(NoopShaper, 64);

        let mut ligatures_on = FontFeatures::default();
        ligatures_on.set_standard_ligatures(true);

        let mut ligatures_off = FontFeatures::default();
        ligatures_off.set_standard_ligatures(false);

        cache.shape(
            "office affine",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ligatures_on,
        );
        cache.shape(
            "office affine",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ligatures_off,
        );

        assert_eq!(
            cache.stats().misses,
            2,
            "ligature mode changes must produce distinct cache keys"
        );
    }

    #[test]
    fn cache_hit_with_canonicalized_ligature_feature_order() {
        let mut cache = ShapingCache::new(NoopShaper, 64);

        let mut ff_a = FontFeatures::new();
        ff_a.push(FontFeature::new(*b"clig", 1));
        ff_a.push(FontFeature::new(*b"liga", 1));
        ff_a.canonicalize();

        let mut ff_b = FontFeatures::new();
        ff_b.push(FontFeature::new(*b"liga", 1));
        ff_b.push(FontFeature::new(*b"clig", 1));
        ff_b.canonicalize();

        cache.shape(
            "offline profile",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff_a,
        );
        cache.shape(
            "offline profile",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff_b,
        );

        assert_eq!(
            cache.stats().hits,
            1,
            "equivalent ligature features must hit the same key after canonicalization"
        );
    }

    #[test]
    fn cache_invalidation_bumps_generation() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        assert_eq!(cache.generation(), 0);

        cache.invalidate();
        assert_eq!(cache.generation(), 1);

        cache.invalidate();
        assert_eq!(cache.generation(), 2);
    }

    #[test]
    fn cache_stale_entries_are_reshared() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        // Cache a result at generation 0.
        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );
        assert_eq!(cache.stats().misses, 1);
        assert_eq!(cache.stats().hits, 0);

        // Invalidate (bump to generation 1).
        cache.invalidate();

        // Same text — should be a miss because generation changed.
        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );
        assert_eq!(cache.stats().misses, 2);
        assert_eq!(cache.stats().stale_evictions, 1);
    }

    #[test]
    fn cache_invalidation_recomputes_ligature_entries_after_font_change() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let mut ligatures_on = FontFeatures::default();
        ligatures_on.set_standard_ligatures(true);

        // Cache baseline entry.
        cache.shape(
            "office affine",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ligatures_on,
        );
        assert_eq!(cache.stats().misses, 1);
        assert_eq!(cache.stats().hits, 0);

        // Same request hits.
        cache.shape(
            "office affine",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ligatures_on,
        );
        assert_eq!(cache.stats().hits, 1);

        // Simulate font reload/zoom/DPR transition.
        cache.invalidate();

        // Same request must miss due to generation bump.
        cache.shape(
            "office affine",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ligatures_on,
        );
        let stats = cache.stats();
        assert_eq!(stats.misses, 2);
        assert_eq!(stats.stale_evictions, 1);
        assert_eq!(stats.generation, 1);
    }

    #[test]
    fn cache_clear_resets_everything() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        cache.shape(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );
        cache.shape(
            "World",
            Script::Latin,
            RunDirection::Ltr,
            FontId(0),
            3072,
            &ff,
        );

        cache.clear();

        let stats = cache.stats();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.size, 0);
        assert!(cache.generation() > 0);
    }

    #[test]
    fn cache_resize_evicts_lru() {
        let mut cache = ShapingCache::new(NoopShaper, 4);
        let ff = FontFeatures::default();

        // Fill cache with 4 entries.
        for i in 0..4u8 {
            let text = format!("text{i}");
            cache.shape(
                &text,
                Script::Latin,
                RunDirection::Ltr,
                FontId(0),
                3072,
                &ff,
            );
        }
        assert_eq!(cache.stats().size, 4);

        // Shrink to 2 — should evict 2 LRU entries.
        cache.resize(2);
        assert!(cache.stats().size <= 2);
    }

    #[test]
    fn cache_with_style_id() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        let r1 = cache.shape_with_style(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            1,
            FontId(0),
            3072,
            &ff,
        );
        let r2 = cache.shape_with_style(
            "Hello",
            Script::Latin,
            RunDirection::Ltr,
            2,
            FontId(0),
            3072,
            &ff,
        );

        // Same text but different style — both are misses.
        assert_eq!(cache.stats().misses, 2);
        // Results are the same (NoopShaper ignores style) but they're cached separately.
        assert_eq!(r1, r2);
    }

    #[test]
    fn cache_stats_hit_rate() {
        let stats = ShapingCacheStats {
            hits: 75,
            misses: 25,
            ..Default::default()
        };
        let rate = stats.hit_rate();
        assert!((rate - 0.75).abs() < f64::EPSILON);

        let empty = ShapingCacheStats::default();
        assert_eq!(empty.hit_rate(), 0.0);
    }

    #[test]
    fn cache_shaper_accessible() {
        let cache = ShapingCache::new(NoopShaper, 64);
        let _shaper: &NoopShaper = cache.shaper();
    }

    // -----------------------------------------------------------------------
    // Integration: script_segmentation → shaping
    // -----------------------------------------------------------------------

    #[test]
    fn shape_partitioned_runs() {
        use crate::script_segmentation::partition_text_runs;

        let text = "Hello\u{4E16}\u{754C}World";
        let runs = partition_text_runs(text, None, None);

        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();

        let mut total_advance = 0;
        for run in &runs {
            let shaped = cache.shape(
                run.text(text),
                run.script,
                run.direction,
                FontId(0),
                3072,
                &ff,
            );
            total_advance += shaped.total_advance;
        }

        // Hello (5) + 世界 (4) + World (5) = 14 cells
        assert_eq!(total_advance, 14);
    }

    #[test]
    fn shape_empty_run() {
        let mut cache = ShapingCache::new(NoopShaper, 64);
        let ff = FontFeatures::default();
        let run = cache.shape("", Script::Latin, RunDirection::Ltr, FontId(0), 3072, &ff);
        assert!(run.is_empty());
    }
}