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
#![forbid(unsafe_code)]

//! Deterministic fallback path for shaped text rendering.
//!
//! When the shaping engine is unavailable (no font data, feature disabled,
//! or runtime budget exceeded), this module provides a guaranteed fallback
//! that preserves:
//!
//! 1. **Semantic correctness**: all grapheme clusters are rendered.
//! 2. **Interaction stability**: cursor, selection, and copy produce
//!    identical results regardless of whether shaping was used.
//! 3. **Determinism**: the same input always produces the same output.
//!
//! # Fallback strategy
//!
//! The [`ShapingFallback`] struct wraps an optional shaper and transparently
//! degrades when shaping is unavailable or fails:
//!
//! ```text
//!   RustybuzzShaper available → use shaped rendering
//!       ↓ (failure or unavailable)
//!   NoopShaper → terminal/monospace rendering (always succeeds)
//! ```
//!
//! Ligature-sensitive flows are explicitly policy-controlled via
//! [`LigatureMode`]:
//! - `Auto`: preserve caller-provided feature set; if ligatures are unsupported,
//!   force-disable standard ligatures for deterministic canonical output.
//! - `Enabled`: force standard ligatures on when supported.
//! - `Disabled`: force canonical grapheme boundaries.
//!
//! If ligatures are requested but unsupported by [`RuntimeCapability`],
//! fallback returns deterministic canonical grapheme rendering.
//!
//! Both paths produce a [`ShapedLineLayout`] with identical interface,
//! ensuring downstream code (cursor navigation, selection, copy) works
//! without branching on which path was taken.
//!
//! # Example
//!
//! ```
//! use ftui_text::shaping_fallback::{ShapingFallback, FallbackEvent};
//! use ftui_text::shaping::NoopShaper;
//! use ftui_text::script_segmentation::{Script, RunDirection};
//!
//! // Create a fallback that always uses NoopShaper (terminal mode).
//! let fallback = ShapingFallback::terminal();
//! let (layout, event) = fallback.shape_line("Hello!", Script::Latin, RunDirection::Ltr);
//!
//! assert_eq!(layout.total_cells(), 6);
//! assert_eq!(event, FallbackEvent::NoopUsed);
//! ```

use crate::layout_policy::{LayoutTier, RuntimeCapability};
use crate::script_segmentation::{RunDirection, Script};
use crate::shaped_render::ShapedLineLayout;
use crate::shaping::{FontFeatures, NoopShaper, ShapedRun, TextShaper};

// ---------------------------------------------------------------------------
// LigatureMode — explicit ligature policy
// ---------------------------------------------------------------------------

/// Explicit ligature-mode policy for shaping fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum LigatureMode {
    /// Preserve the configured feature set.
    ///
    /// If runtime capability reports ligatures unsupported, standard ligatures
    /// are force-disabled to avoid backend-default variability.
    #[default]
    Auto,
    /// Force standard ligatures on (`liga`, `clig`), if supported.
    Enabled,
    /// Force standard ligatures off with canonical grapheme boundaries.
    Disabled,
}

// ---------------------------------------------------------------------------
// FallbackEvent — what happened during shaping
// ---------------------------------------------------------------------------

/// Diagnostic event describing which path was taken.
///
/// Useful for telemetry, logging, and adaptive quality controllers that
/// may want to track fallback frequency.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FallbackEvent {
    /// Full shaping was used successfully.
    ShapedSuccessfully,
    /// The shaper was invoked but the result was rejected (e.g., empty
    /// output for non-empty input). Fell back to NoopShaper.
    ShapingRejected,
    /// No shaper was available; used NoopShaper directly.
    NoopUsed,
    /// Shaping was skipped because the runtime tier doesn't require it.
    SkippedByPolicy,
}

impl FallbackEvent {
    /// Whether shaping was actually performed.
    #[inline]
    pub const fn was_shaped(&self) -> bool {
        matches!(self, Self::ShapedSuccessfully)
    }

    /// Whether a fallback was triggered.
    #[inline]
    pub const fn is_fallback(&self) -> bool {
        !self.was_shaped()
    }
}

// ---------------------------------------------------------------------------
// FallbackStats — counters for monitoring
// ---------------------------------------------------------------------------

/// Accumulated fallback statistics for monitoring quality degradation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FallbackStats {
    /// Total lines processed.
    pub total_lines: u64,
    /// Lines that used full shaping.
    pub shaped_lines: u64,
    /// Lines that fell back to NoopShaper.
    pub fallback_lines: u64,
    /// Lines where shaping was rejected after attempt.
    pub rejected_lines: u64,
    /// Lines skipped by policy.
    pub skipped_lines: u64,
}

impl FallbackStats {
    /// Record a fallback event.
    pub fn record(&mut self, event: FallbackEvent) {
        self.total_lines += 1;
        match event {
            FallbackEvent::ShapedSuccessfully => self.shaped_lines += 1,
            FallbackEvent::ShapingRejected => {
                self.fallback_lines += 1;
                self.rejected_lines += 1;
            }
            FallbackEvent::NoopUsed => self.fallback_lines += 1,
            FallbackEvent::SkippedByPolicy => self.skipped_lines += 1,
        }
    }

    /// Fraction of lines that used full shaping (0.0-1.0).
    pub fn shaping_rate(&self) -> f64 {
        if self.total_lines == 0 {
            return 0.0;
        }
        self.shaped_lines as f64 / self.total_lines as f64
    }

    /// Fraction of lines that fell back (0.0-1.0).
    pub fn fallback_rate(&self) -> f64 {
        if self.total_lines == 0 {
            return 0.0;
        }
        self.fallback_lines as f64 / self.total_lines as f64
    }
}

// ---------------------------------------------------------------------------
// ShapingFallback
// ---------------------------------------------------------------------------

/// Transparent shaping with guaranteed fallback.
///
/// Wraps an optional primary shaper and a `NoopShaper` fallback. Always
/// produces a valid [`ShapedLineLayout`] regardless of whether the primary
/// shaper is available or succeeds.
///
/// The output layout has identical API surface for both paths, so
/// downstream code (cursor, selection, copy, rendering) does not need
/// to branch on which shaping path was used.
pub struct ShapingFallback<S: TextShaper = NoopShaper> {
    /// Primary shaper (may be NoopShaper for terminal mode).
    primary: Option<S>,
    /// Font features to apply during shaping.
    features: FontFeatures,
    /// Minimum tier required for shaping to be attempted.
    /// Below this tier, NoopShaper is used directly.
    shaping_tier: LayoutTier,
    /// Current runtime capabilities.
    capabilities: RuntimeCapability,
    /// Explicit ligature policy for shaping output.
    ligature_mode: LigatureMode,
    /// Whether to validate shaped output and reject suspicious results.
    validate_output: bool,
}

impl ShapingFallback<NoopShaper> {
    /// Create a terminal-mode fallback (always uses NoopShaper).
    #[must_use]
    pub fn terminal() -> Self {
        Self {
            primary: None,
            features: FontFeatures::default(),
            shaping_tier: LayoutTier::Quality,
            capabilities: RuntimeCapability::TERMINAL,
            ligature_mode: LigatureMode::Disabled,
            validate_output: false,
        }
    }
}

impl<S: TextShaper> ShapingFallback<S> {
    /// Create a fallback with a primary shaper.
    #[must_use]
    pub fn with_shaper(shaper: S, capabilities: RuntimeCapability) -> Self {
        Self {
            primary: Some(shaper),
            features: FontFeatures::default(),
            shaping_tier: LayoutTier::Balanced,
            capabilities,
            ligature_mode: LigatureMode::Auto,
            validate_output: true,
        }
    }

    /// Set the font features used for shaping.
    pub fn set_features(&mut self, features: FontFeatures) {
        self.features = features;
    }

    /// Set the minimum tier for shaping.
    pub fn set_shaping_tier(&mut self, tier: LayoutTier) {
        self.shaping_tier = tier;
    }

    /// Set explicit ligature policy.
    pub fn set_ligature_mode(&mut self, mode: LigatureMode) {
        self.ligature_mode = mode;
    }

    /// Update runtime capabilities (e.g., after font load/unload).
    pub fn set_capabilities(&mut self, caps: RuntimeCapability) {
        self.capabilities = caps;
    }

    /// Enable or disable output validation.
    pub fn set_validate_output(&mut self, validate: bool) {
        self.validate_output = validate;
    }

    /// Shape a line of text with automatic fallback.
    ///
    /// Returns the layout and a diagnostic event describing which path
    /// was taken. The layout is guaranteed to be valid and non-empty
    /// for non-empty input.
    pub fn shape_line(
        &self,
        text: &str,
        script: Script,
        direction: RunDirection,
    ) -> (ShapedLineLayout, FallbackEvent) {
        if text.is_empty() {
            return (ShapedLineLayout::from_text(""), FallbackEvent::NoopUsed);
        }

        // No primary shaper available — use NoopShaper directly.
        let Some(shaper) = &self.primary else {
            return (ShapedLineLayout::from_text(text), FallbackEvent::NoopUsed);
        };

        // Check if the current tier requires shaping.
        let effective_tier = self.capabilities.best_tier();
        if effective_tier < self.shaping_tier {
            return (
                ShapedLineLayout::from_text(text),
                FallbackEvent::SkippedByPolicy,
            );
        }

        let ligature_requested = match self.ligature_mode {
            LigatureMode::Enabled => true,
            LigatureMode::Disabled => false,
            LigatureMode::Auto => self.features.standard_ligatures_enabled().unwrap_or(false),
        };
        if ligature_requested && !self.capabilities.ligature_support {
            tracing::debug!(
                text_len = text.len(),
                mode = ?self.ligature_mode,
                "Ligatures requested but unsupported, using canonical grapheme fallback"
            );
            return (
                ShapedLineLayout::from_text(text),
                FallbackEvent::SkippedByPolicy,
            );
        }

        let mut effective_features = self.features.clone();
        match self.ligature_mode {
            LigatureMode::Enabled => effective_features.set_standard_ligatures(true),
            LigatureMode::Disabled => effective_features.set_standard_ligatures(false),
            LigatureMode::Auto => {
                // Keep AUTO deterministic across runtimes: when ligatures are
                // unsupported, explicitly disable standard ligatures so we do
                // not depend on backend default-feature behavior.
                if !self.capabilities.ligature_support {
                    effective_features.set_standard_ligatures(false);
                }
            }
        }

        // Try shaping with the primary shaper.
        {
            let run = shaper.shape(text, script, direction, &effective_features);

            if self.validate_output
                && let Some(rejection) = validate_shaped_run(text, &run)
            {
                tracing::debug!(
                    text_len = text.len(),
                    glyph_count = run.glyphs.len(),
                    reason = %rejection,
                    "Shaped output rejected, falling back to NoopShaper"
                );
                return (
                    ShapedLineLayout::from_text(text),
                    FallbackEvent::ShapingRejected,
                );
            }

            (
                ShapedLineLayout::from_run(text, &run),
                FallbackEvent::ShapedSuccessfully,
            )
        }
    }

    /// Shape multiple lines with fallback, collecting stats.
    ///
    /// Returns layouts and accumulated statistics.
    pub fn shape_lines(
        &self,
        lines: &[&str],
        script: Script,
        direction: RunDirection,
    ) -> (Vec<ShapedLineLayout>, FallbackStats) {
        let mut layouts = Vec::with_capacity(lines.len());
        let mut stats = FallbackStats::default();

        for text in lines {
            let (layout, event) = self.shape_line(text, script, direction);
            stats.record(event);
            layouts.push(layout);
        }

        (layouts, stats)
    }
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// Validate a shaped run and return a rejection reason if invalid.
///
/// Checks for common shaping failures:
/// - Empty output for non-empty input
/// - Glyph count dramatically exceeding text length (runaway shaping)
/// - All zero advances (broken font/shaper)
fn validate_shaped_run(text: &str, run: &ShapedRun) -> Option<&'static str> {
    if text.is_empty() {
        return None; // Empty input is always valid
    }

    // Rejection: no glyphs produced for non-empty text.
    if run.glyphs.is_empty() {
        return Some("no glyphs produced for non-empty input");
    }

    // Rejection: glyph count > 4x text byte length (runaway).
    // Legitimate cases (complex scripts, ligature decomposition) rarely
    // exceed 2x. 4x gives ample headroom.
    if run.glyphs.len() > text.len() * 4 {
        return Some("glyph count exceeds 4x text byte length");
    }

    // Rejection: all advances are zero (broken font).
    if run.glyphs.iter().all(|g| g.x_advance == 0) {
        return Some("all glyph advances are zero");
    }

    None
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shaping::ShapedGlyph;

    #[derive(Debug, Clone, Copy)]
    struct FeatureAwareLigatureShaper;

    impl TextShaper for FeatureAwareLigatureShaper {
        fn shape(
            &self,
            text: &str,
            _script: Script,
            _direction: RunDirection,
            features: &FontFeatures,
        ) -> ShapedRun {
            // Simulate default-enabled standard ligatures unless explicitly
            // disabled by caller features.
            let ligatures_on = features.feature_value(*b"liga").unwrap_or(1) != 0;
            if ligatures_on && text == "file" {
                return ShapedRun {
                    glyphs: vec![
                        ShapedGlyph {
                            glyph_id: 1,
                            cluster: 0, // "fi" ligature
                            x_advance: 2,
                            y_advance: 0,
                            x_offset: 0,
                            y_offset: 0,
                        },
                        ShapedGlyph {
                            glyph_id: 2,
                            cluster: 2,
                            x_advance: 1,
                            y_advance: 0,
                            x_offset: 0,
                            y_offset: 0,
                        },
                        ShapedGlyph {
                            glyph_id: 3,
                            cluster: 3,
                            x_advance: 1,
                            y_advance: 0,
                            x_offset: 0,
                            y_offset: 0,
                        },
                    ],
                    total_advance: 4,
                };
            }

            let mut glyphs = Vec::new();
            for (byte_offset, ch) in text.char_indices() {
                glyphs.push(ShapedGlyph {
                    glyph_id: ch as u32,
                    cluster: byte_offset as u32,
                    x_advance: 1,
                    y_advance: 0,
                    x_offset: 0,
                    y_offset: 0,
                });
            }
            let total_advance = i32::try_from(glyphs.len()).unwrap_or(i32::MAX);
            ShapedRun {
                glyphs,
                total_advance,
            }
        }
    }

    // -----------------------------------------------------------------------
    // Terminal mode
    // -----------------------------------------------------------------------

    #[test]
    fn terminal_fallback() {
        let fb = ShapingFallback::terminal();
        let (layout, event) = fb.shape_line("Hello", Script::Latin, RunDirection::Ltr);

        assert_eq!(layout.total_cells(), 5);
        assert_eq!(event, FallbackEvent::NoopUsed);
    }

    #[test]
    fn terminal_empty_input() {
        let fb = ShapingFallback::terminal();
        let (layout, event) = fb.shape_line("", Script::Latin, RunDirection::Ltr);

        assert!(layout.is_empty());
        assert_eq!(event, FallbackEvent::NoopUsed);
    }

    #[test]
    fn terminal_wide_chars() {
        let fb = ShapingFallback::terminal();
        let (layout, _) = fb.shape_line("\u{4E16}\u{754C}", Script::Han, RunDirection::Ltr);

        assert_eq!(layout.total_cells(), 4); // 2 CJK chars × 2 cells each
    }

    // -----------------------------------------------------------------------
    // With shaper
    // -----------------------------------------------------------------------

    #[test]
    fn noop_shaper_primary() {
        let fb = ShapingFallback::with_shaper(NoopShaper, RuntimeCapability::TERMINAL);
        let (layout, event) = fb.shape_line("Hello", Script::Latin, RunDirection::Ltr);

        assert_eq!(layout.total_cells(), 5);
        // TERMINAL best_tier is Balanced, shaping_tier is Balanced → tier check passes,
        // NoopShaper shapes successfully.
        assert_eq!(event, FallbackEvent::ShapedSuccessfully);
    }

    #[test]
    fn noop_shaper_with_full_caps() {
        let fb = ShapingFallback::with_shaper(NoopShaper, RuntimeCapability::FULL);
        let (layout, event) = fb.shape_line("Hello", Script::Latin, RunDirection::Ltr);

        assert_eq!(layout.total_cells(), 5);
        assert_eq!(event, FallbackEvent::ShapedSuccessfully);
    }

    // -----------------------------------------------------------------------
    // Validation
    // -----------------------------------------------------------------------

    #[test]
    fn validate_empty_run() {
        let run = ShapedRun {
            glyphs: vec![],
            total_advance: 0,
        };
        assert!(validate_shaped_run("Hello", &run).is_some());
    }

    #[test]
    fn validate_empty_input() {
        let run = ShapedRun {
            glyphs: vec![],
            total_advance: 0,
        };
        assert!(validate_shaped_run("", &run).is_none());
    }

    #[test]
    fn validate_zero_advances() {
        use crate::shaping::ShapedGlyph;

        let run = ShapedRun {
            glyphs: vec![
                ShapedGlyph {
                    glyph_id: 1,
                    cluster: 0,
                    x_advance: 0,
                    y_advance: 0,
                    x_offset: 0,
                    y_offset: 0,
                },
                ShapedGlyph {
                    glyph_id: 2,
                    cluster: 1,
                    x_advance: 0,
                    y_advance: 0,
                    x_offset: 0,
                    y_offset: 0,
                },
            ],
            total_advance: 0,
        };
        assert!(validate_shaped_run("AB", &run).is_some());
    }

    #[test]
    fn validate_valid_run() {
        use crate::shaping::ShapedGlyph;

        let run = ShapedRun {
            glyphs: vec![
                ShapedGlyph {
                    glyph_id: 1,
                    cluster: 0,
                    x_advance: 1,
                    y_advance: 0,
                    x_offset: 0,
                    y_offset: 0,
                },
                ShapedGlyph {
                    glyph_id: 2,
                    cluster: 1,
                    x_advance: 1,
                    y_advance: 0,
                    x_offset: 0,
                    y_offset: 0,
                },
            ],
            total_advance: 2,
        };
        assert!(validate_shaped_run("AB", &run).is_none());
    }

    // -----------------------------------------------------------------------
    // Fallback stats
    // -----------------------------------------------------------------------

    #[test]
    fn stats_tracking() {
        let mut stats = FallbackStats::default();

        stats.record(FallbackEvent::ShapedSuccessfully);
        stats.record(FallbackEvent::ShapedSuccessfully);
        stats.record(FallbackEvent::NoopUsed);
        stats.record(FallbackEvent::ShapingRejected);

        assert_eq!(stats.total_lines, 4);
        assert_eq!(stats.shaped_lines, 2);
        assert_eq!(stats.fallback_lines, 2);
        assert_eq!(stats.rejected_lines, 1);
        assert_eq!(stats.shaping_rate(), 0.5);
        assert_eq!(stats.fallback_rate(), 0.5);
    }

    #[test]
    fn stats_empty() {
        let stats = FallbackStats::default();
        assert_eq!(stats.shaping_rate(), 0.0);
        assert_eq!(stats.fallback_rate(), 0.0);
    }

    // -----------------------------------------------------------------------
    // Batch shaping
    // -----------------------------------------------------------------------

    #[test]
    fn shape_lines_batch() {
        let fb = ShapingFallback::terminal();
        let lines = vec!["Hello", "World", "\u{4E16}\u{754C}"];

        let (layouts, stats) = fb.shape_lines(&lines, Script::Latin, RunDirection::Ltr);

        assert_eq!(layouts.len(), 3);
        assert_eq!(stats.total_lines, 3);
        assert_eq!(stats.fallback_lines, 3);
    }

    // -----------------------------------------------------------------------
    // FallbackEvent predicates
    // -----------------------------------------------------------------------

    #[test]
    fn event_predicates() {
        assert!(FallbackEvent::ShapedSuccessfully.was_shaped());
        assert!(!FallbackEvent::ShapedSuccessfully.is_fallback());

        assert!(!FallbackEvent::NoopUsed.was_shaped());
        assert!(FallbackEvent::NoopUsed.is_fallback());

        assert!(!FallbackEvent::ShapingRejected.was_shaped());
        assert!(FallbackEvent::ShapingRejected.is_fallback());

        assert!(!FallbackEvent::SkippedByPolicy.was_shaped());
        assert!(FallbackEvent::SkippedByPolicy.is_fallback());
    }

    // -----------------------------------------------------------------------
    // Determinism: both paths produce consistent layouts
    // -----------------------------------------------------------------------

    #[test]
    fn shaped_and_unshaped_same_total_cells() {
        let text = "Hello World!";

        // Shaped path (via NoopShaper → shaped successfully with FULL caps).
        let fb_shaped = ShapingFallback::with_shaper(NoopShaper, RuntimeCapability::FULL);
        let (layout_shaped, _) = fb_shaped.shape_line(text, Script::Latin, RunDirection::Ltr);

        // Unshaped path (terminal fallback).
        let fb_unshaped = ShapingFallback::terminal();
        let (layout_unshaped, _) = fb_unshaped.shape_line(text, Script::Latin, RunDirection::Ltr);

        // NoopShaper should produce identical total cell counts.
        assert_eq!(layout_shaped.total_cells(), layout_unshaped.total_cells());
    }

    #[test]
    fn shaped_and_unshaped_identical_interaction() {
        let text = "A\u{4E16}B";

        let fb_shaped = ShapingFallback::with_shaper(NoopShaper, RuntimeCapability::FULL);
        let (layout_s, _) = fb_shaped.shape_line(text, Script::Latin, RunDirection::Ltr);

        let fb_unshaped = ShapingFallback::terminal();
        let (layout_u, _) = fb_unshaped.shape_line(text, Script::Latin, RunDirection::Ltr);

        // Cluster maps should agree on byte↔cell mappings.
        let cm_s = layout_s.cluster_map();
        let cm_u = layout_u.cluster_map();

        for byte in [0, 1, 4] {
            assert_eq!(
                cm_s.byte_to_cell(byte),
                cm_u.byte_to_cell(byte),
                "byte_to_cell mismatch at byte {byte}"
            );
        }

        for cell in 0..layout_s.total_cells() {
            assert_eq!(
                cm_s.cell_to_byte(cell),
                cm_u.cell_to_byte(cell),
                "cell_to_byte mismatch at cell {cell}"
            );
        }
    }

    // -----------------------------------------------------------------------
    // Configuration
    // -----------------------------------------------------------------------

    #[test]
    fn set_features() {
        let mut fb = ShapingFallback::terminal();
        fb.set_features(FontFeatures::default());
        // Just verifies no panic.
        let (layout, _) = fb.shape_line("test", Script::Latin, RunDirection::Ltr);
        assert_eq!(layout.total_cells(), 4);
    }

    #[test]
    fn set_shaping_tier() {
        let mut fb = ShapingFallback::with_shaper(NoopShaper, RuntimeCapability::FULL);
        fb.set_shaping_tier(LayoutTier::Quality);

        // FULL caps support Quality tier, so shaping should still work.
        let (_, event) = fb.shape_line("test", Script::Latin, RunDirection::Ltr);
        assert_eq!(event, FallbackEvent::ShapedSuccessfully);
    }

    #[test]
    fn ligature_mode_enabled_without_capability_falls_back() {
        let mut fb =
            ShapingFallback::with_shaper(FeatureAwareLigatureShaper, RuntimeCapability::TERMINAL);
        fb.set_ligature_mode(LigatureMode::Enabled);

        let (layout, event) = fb.shape_line("file", Script::Latin, RunDirection::Ltr);
        assert_eq!(event, FallbackEvent::SkippedByPolicy);
        assert_eq!(layout.total_cells(), 4);
        assert_eq!(layout.cluster_map().byte_to_cell(1), 1);
    }

    #[test]
    fn ligature_mode_enabled_with_capability_shapes() {
        let mut fb =
            ShapingFallback::with_shaper(FeatureAwareLigatureShaper, RuntimeCapability::FULL);
        fb.set_ligature_mode(LigatureMode::Enabled);

        let (layout, event) = fb.shape_line("file", Script::Latin, RunDirection::Ltr);
        assert_eq!(event, FallbackEvent::ShapedSuccessfully);
        assert_eq!(layout.total_cells(), 4);
        assert_eq!(layout.cluster_map().byte_to_cell(1), 0); // "fi" snapped
        assert_eq!(layout.extract_text("file", 0, 2), "fi");
    }

    #[test]
    fn ligature_mode_disabled_forces_canonical_boundaries() {
        let mut fb =
            ShapingFallback::with_shaper(FeatureAwareLigatureShaper, RuntimeCapability::FULL);
        fb.set_ligature_mode(LigatureMode::Disabled);

        let (layout, event) = fb.shape_line("file", Script::Latin, RunDirection::Ltr);
        assert_eq!(event, FallbackEvent::ShapedSuccessfully);
        assert_eq!(layout.total_cells(), 4);
        assert_eq!(layout.cluster_map().byte_to_cell(1), 1);
    }

    #[test]
    fn auto_mode_honors_explicit_ligature_request_when_unsupported() {
        let mut fb =
            ShapingFallback::with_shaper(FeatureAwareLigatureShaper, RuntimeCapability::TERMINAL);
        let mut features = FontFeatures::default();
        features.set_standard_ligatures(true);
        fb.set_features(features);

        let (layout, event) = fb.shape_line("file", Script::Latin, RunDirection::Ltr);
        assert_eq!(event, FallbackEvent::SkippedByPolicy);
        assert_eq!(layout.cluster_map().byte_to_cell(1), 1);
    }

    #[test]
    fn auto_mode_disables_implicit_ligatures_when_unsupported() {
        let fb =
            ShapingFallback::with_shaper(FeatureAwareLigatureShaper, RuntimeCapability::TERMINAL);

        // No explicit features set. The test shaper defaults `liga` to enabled,
        // so AUTO must inject an explicit disable when ligatures are unsupported.
        let (layout, event) = fb.shape_line("file", Script::Latin, RunDirection::Ltr);
        assert_eq!(event, FallbackEvent::ShapedSuccessfully);
        assert_eq!(layout.cluster_map().byte_to_cell(1), 1);
    }
}