opentui_rust 0.2.1

High-performance terminal UI rendering engine with alpha blending and diffed buffers
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
//! E2E Unicode stress testing (bd-qqf9).
//!
//! This module provides comprehensive tests for Unicode handling edge cases,
//! including wide characters, emoji, combining characters, and stress tests.

#![allow(clippy::uninlined_format_args)] // Clarity over style in test code

mod common;

use common::harness::E2EHarness;
use opentui::buffer::ClipRect;
use opentui::color::Rgba;
use opentui::grapheme_pool::GraphemePool;
use opentui::style::Style;
use opentui::unicode::{display_width, display_width_char, graphemes, reorder_for_display};
use opentui::{EditBuffer, EditorView, OptimizedBuffer};
use opentui_rust as opentui;

// ============================================================================
// Test Helpers
// ============================================================================

/// Verify that rendered text matches expected cell layout.
fn verify_text_render(buffer: &OptimizedBuffer, x: u32, y: u32, text: &str, _style: Style) {
    let mut col = x;
    for grapheme in graphemes(text) {
        let width = u32::try_from(display_width(grapheme)).expect("width fits u32");
        if matches!(width, 0) {
            continue;
        }

        // Check the first cell of the grapheme
        let cell = buffer.get(col, y).expect("cell should exist");
        assert!(
            !cell.is_continuation(),
            "first cell of grapheme '{}' at ({},{}) should not be continuation",
            grapheme,
            col,
            y
        );

        // Check continuation cells for wide characters
        for i in 1..width {
            let cont_cell = buffer
                .get(col + i, y)
                .expect("continuation cell should exist");
            assert!(
                cont_cell.is_continuation(),
                "cell at ({},{}) should be continuation for wide grapheme '{}'",
                col + i,
                y,
                grapheme
            );
        }

        col += width;
    }
}

// ============================================================================
// Wide Characters (CJK)
// ============================================================================

#[test]
fn test_cjk_basic_rendering() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // CJK characters are width 2
    let text = "\u{4E2D}\u{6587}"; // ไธญๆ–‡
    buffer.draw_text(0, 0, text, Style::NONE);

    verify_text_render(&buffer, 0, 0, text, Style::NONE);

    // First character ไธญ
    let cell0 = buffer.get(0, 0).unwrap();
    assert!(!cell0.is_continuation());
    assert_eq!(cell0.display_width(), 2);

    // Second cell is continuation of ไธญ
    let cell1 = buffer.get(1, 0).unwrap();
    assert!(cell1.is_continuation());

    // Second character ๆ–‡ at position 2
    let cell2 = buffer.get(2, 0).unwrap();
    assert!(!cell2.is_continuation());
    assert_eq!(cell2.display_width(), 2);

    // Fourth cell is continuation of ๆ–‡
    let cell3 = buffer.get(3, 0).unwrap();
    assert!(cell3.is_continuation());
}

#[test]
fn test_mixed_ascii_cjk() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Mixed ASCII and CJK
    let text = "Hello\u{4E16}\u{754C}World"; // Helloไธ–็•ŒWorld
    buffer.draw_text(0, 0, text, Style::NONE);

    // Check total display width: 5 (Hello) + 4 (ไธ–็•Œ = 2+2) + 5 (World) = 14
    let total_width: usize = graphemes(text).map(display_width).sum();
    assert_eq!(total_width, 14);

    // Verify positions:
    // H at 0, e at 1, l at 2, l at 3, o at 4
    // ไธ– at 5-6 (width 2), ็•Œ at 7-8 (width 2)
    // W at 9, o at 10, r at 11, l at 12, d at 13

    // Check ASCII before CJK
    for i in 0..5 {
        let cell = buffer.get(i, 0).unwrap();
        assert!(
            !cell.is_continuation(),
            "ASCII char at {} should not be continuation",
            i
        );
    }

    // Check CJK character ไธ–
    let cell5 = buffer.get(5, 0).unwrap();
    assert!(!cell5.is_continuation());
    let cell6 = buffer.get(6, 0).unwrap();
    assert!(cell6.is_continuation());

    // Check CJK character ็•Œ
    let cell7 = buffer.get(7, 0).unwrap();
    assert!(!cell7.is_continuation());
    let cell8 = buffer.get(8, 0).unwrap();
    assert!(cell8.is_continuation());

    // Check ASCII after CJK
    for i in 9..14 {
        let cell = buffer.get(i, 0).unwrap();
        assert!(
            !cell.is_continuation(),
            "ASCII char at {} should not be continuation",
            i
        );
    }
}

#[test]
fn test_cjk_at_line_boundaries() {
    let mut buffer = OptimizedBuffer::new(10, 24);
    buffer.clear(Rgba::BLACK);

    // Push scissor to limit width to 10
    // Try to draw CJK at position 9 (only 1 cell left)
    let text = "\u{4E2D}"; // ไธญ (width 2)
    buffer.draw_text(9, 0, text, Style::NONE);

    // The character should be clipped or wrapped depending on implementation
    // At minimum, it shouldn't panic
}

#[test]
fn test_cjk_in_scissor_region() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Scissor to a 10-cell wide region
    buffer.push_scissor(ClipRect::new(5, 0, 10, 10));

    // Draw CJK text that should be clipped
    let text = "\u{4E2D}\u{6587}\u{5B57}\u{7B26}\u{6D4B}\u{8BD5}"; // ไธญๆ–‡ๅญ—็ฌฆๆต‹่ฏ•
    buffer.draw_text(5, 0, text, Style::NONE);

    buffer.pop_scissor();

    // Only first few characters should be visible within the scissor region
    // (10 cells / 2 width per char = 5 characters max)
}

// ============================================================================
// Emoji
// ============================================================================

#[test]
fn test_basic_emoji_single_codepoint() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Basic emoji (single codepoint, typically width 2)
    let emojis = ["\u{1F600}", "\u{1F601}", "\u{1F602}"]; // ๐Ÿ˜€๐Ÿ˜๐Ÿ˜‚

    for (i, emoji) in emojis.iter().enumerate() {
        let x = u32::try_from(i * 2).expect("emoji offset fits u32");
        buffer.draw_text(x, 0, emoji, Style::NONE);

        // Verify the emoji cell exists and has correct width
        let cell = buffer.get(x, 0).unwrap();
        assert!(
            !cell.is_continuation(),
            "emoji at {} should not be continuation",
            x
        );
    }
}

#[test]
fn test_emoji_with_skin_tone() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    let mut pool = GraphemePool::new();
    buffer.clear(Rgba::BLACK);

    // Emoji with skin tone modifier (single grapheme cluster)
    let emoji = "\u{1F44B}\u{1F3FD}"; // ๐Ÿ‘‹๐Ÿฝ (waving hand + medium skin tone)
    let width = display_width(emoji);

    buffer.draw_text_with_pool(&mut pool, 0, 0, emoji, Style::NONE);

    // The emoji + skin tone should render as a single grapheme
    let cell = buffer.get(0, 0).unwrap();
    assert!(!cell.is_continuation());
    assert_eq!(cell.display_width(), width);
}

#[test]
fn test_emoji_zwj_sequence() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    let mut pool = GraphemePool::new();
    buffer.clear(Rgba::BLACK);

    // Family emoji (ZWJ sequence: man + ZWJ + woman + ZWJ + girl + ZWJ + boy)
    let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}";

    buffer.draw_text_with_pool(&mut pool, 0, 0, family, Style::NONE);

    // The ZWJ sequence should render as a single grapheme cluster
    let grapheme_count: usize = graphemes(family).count();
    assert_eq!(
        grapheme_count, 1,
        "ZWJ family should be single grapheme cluster"
    );

    let cell = buffer.get(0, 0).unwrap();
    assert!(!cell.is_continuation());
}

#[test]
fn test_flag_emoji_regional_indicators() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    let mut pool = GraphemePool::new();
    buffer.clear(Rgba::BLACK);

    // Flag emoji using regional indicator symbols
    let us_flag = "\u{1F1FA}\u{1F1F8}"; // ๐Ÿ‡บ๐Ÿ‡ธ
    let jp_flag = "\u{1F1EF}\u{1F1F5}"; // ๐Ÿ‡ฏ๐Ÿ‡ต
    let gb_flag = "\u{1F1EC}\u{1F1E7}"; // ๐Ÿ‡ฌ๐Ÿ‡ง

    // Each flag should be a single grapheme cluster
    assert_eq!(graphemes(us_flag).count(), 1);
    assert_eq!(graphemes(jp_flag).count(), 1);
    assert_eq!(graphemes(gb_flag).count(), 1);

    buffer.draw_text_with_pool(&mut pool, 0, 0, us_flag, Style::NONE);
    buffer.draw_text_with_pool(&mut pool, 4, 0, jp_flag, Style::NONE);
    buffer.draw_text_with_pool(&mut pool, 8, 0, gb_flag, Style::NONE);

    // Verify rendering
    let cell0 = buffer.get(0, 0).unwrap();
    assert!(!cell0.is_continuation());
}

#[test]
fn test_emoji_in_text_flow() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Emoji mixed with regular text
    let text = "Hello \u{1F600} World \u{1F44D}!"; // Hello ๐Ÿ˜€ World ๐Ÿ‘!
    buffer.draw_text(0, 0, text, Style::NONE);

    // Calculate expected width
    let expected_width: usize = graphemes(text).map(display_width).sum();

    // Verify no panics and reasonable width
    assert!(expected_width > 0);
    assert!(expected_width <= 80);
}

// ============================================================================
// Combining Characters
// ============================================================================

#[test]
fn test_combining_diacriticals_precomposed_vs_decomposed() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Precomposed: รฉ (single codepoint U+00E9)
    let precomposed = "\u{00E9}";
    // Decomposed: e + combining acute accent (U+0065 + U+0301)
    let decomposed = "e\u{0301}";

    buffer.draw_text(0, 0, precomposed, Style::NONE);
    buffer.draw_text(5, 0, decomposed, Style::NONE);

    // Both should display as single grapheme cluster with width 1
    assert_eq!(graphemes(precomposed).count(), 1);
    assert_eq!(graphemes(decomposed).count(), 1);
    assert_eq!(display_width(precomposed), 1);
    assert_eq!(display_width(decomposed), 1);
}

#[test]
fn test_multiple_combining_marks() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    let mut pool = GraphemePool::new();
    buffer.clear(Rgba::BLACK);

    // Base character with multiple combining marks
    // a + acute + circumflex + tilde
    let text = "a\u{0301}\u{0302}\u{0303}";

    buffer.draw_text_with_pool(&mut pool, 0, 0, text, Style::NONE);

    // Should be single grapheme cluster
    assert_eq!(graphemes(text).count(), 1);

    // Width should still be 1 (combining marks don't add width)
    assert_eq!(display_width(text), 1);

    let cell = buffer.get(0, 0).unwrap();
    assert!(!cell.is_continuation());
    assert_eq!(cell.display_width(), 1);
}

#[test]
fn test_combining_marks_at_boundaries() {
    let mut buffer = OptimizedBuffer::new(10, 24);
    buffer.clear(Rgba::BLACK);

    // Draw text near boundary with combining marks
    let text = "test\u{0301}"; // testฬ (t with combining acute at the end)

    buffer.draw_text(5, 0, text, Style::NONE);

    // Should render without panic
    // The 't' with combining mark should still fit
}

// ============================================================================
// Special Cases
// ============================================================================

#[test]
fn test_zero_width_joiner() {
    // ZWJ should have width 0 on its own
    assert_eq!(display_width_char('\u{200D}'), 0);

    // But when part of a ZWJ sequence, it joins graphemes
    let without_zwj = "\u{1F468}\u{1F469}"; // ๐Ÿ‘จ๐Ÿ‘ฉ (separate)
    let with_zwj = "\u{1F468}\u{200D}\u{1F469}"; // ๐Ÿ‘จโ€๐Ÿ‘ฉ (couple)

    assert_eq!(graphemes(without_zwj).count(), 2);
    assert_eq!(graphemes(with_zwj).count(), 1);
}

#[test]
fn test_zero_width_non_joiner() {
    // ZWNJ has width 0
    assert_eq!(display_width_char('\u{200C}'), 0);

    // ZWNJ may or may not cause grapheme breaks depending on implementation
    // The key invariant is that it doesn't add visible width
    let text = "a\u{200C}b";
    let total_width = display_width(text);
    assert_eq!(
        total_width, 2,
        "a+ZWNJ+b should have display width 2 (ZWNJ is invisible)"
    );
}

#[test]
fn test_variation_selectors() {
    // Variation selector 16 (VS16) - emoji presentation
    let text_presentation = "\u{2764}"; // โค (text style heart)
    let emoji_presentation = "\u{2764}\u{FE0F}"; // โค๏ธ (emoji style heart with VS16)

    // Both should be single grapheme clusters
    assert_eq!(graphemes(text_presentation).count(), 1);
    assert_eq!(graphemes(emoji_presentation).count(), 1);

    // Width might differ based on presentation
    // Text style is typically width 1, emoji style is typically width 2
}

#[test]
fn test_tab_characters() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Tab character
    let text = "A\tB";
    buffer.draw_text(0, 0, text, Style::NONE);

    // Tab handling varies - the test verifies no panic occurs
    // Actual tab expansion is implementation-dependent
}

#[test]
fn test_newline_variants() {
    // Newline characters - width behavior is implementation-dependent
    // Our implementation treats them as control characters
    let lf_width = display_width_char('\n');
    let cr_width = display_width_char('\r');

    // At minimum, they shouldn't be wide (width 2)
    assert!(lf_width <= 1, "LF should not be wide");
    assert!(cr_width <= 1, "CR should not be wide");

    // CRLF as a string
    let crlf = "\r\n";
    let crlf_width = display_width(crlf);
    assert!(crlf_width <= 2, "CRLF should not be wide");
}

#[test]
fn test_control_characters() {
    // Control characters should have width 0
    for c in 0..32u8 {
        let ch = c as char;
        assert_eq!(
            display_width_char(ch),
            0,
            "control char U+{:04X} should have width 0",
            c
        );
    }

    // DEL (0x7F) should also have width 0
    assert_eq!(display_width_char('\u{007F}'), 0);
}

// ============================================================================
// Stress Tests
// ============================================================================

#[test]
fn test_many_different_graphemes() {
    let mut buffer = OptimizedBuffer::new(200, 50);
    let mut pool = GraphemePool::new();
    buffer.clear(Rgba::BLACK);

    // Generate many different graphemes
    let mut grapheme_list = Vec::new();

    // ASCII
    for c in 'A'..='Z' {
        grapheme_list.push(c.to_string());
    }
    for c in 'a'..='z' {
        grapheme_list.push(c.to_string());
    }

    // CJK
    for c in '\u{4E00}'..'\u{4E50}' {
        grapheme_list.push(c.to_string());
    }

    // Emoji
    for c in '\u{1F600}'..'\u{1F650}' {
        grapheme_list.push(c.to_string());
    }

    // Greek
    for c in '\u{0391}'..'\u{03C9}' {
        grapheme_list.push(c.to_string());
    }

    // Cyrillic
    for c in '\u{0410}'..'\u{044F}' {
        grapheme_list.push(c.to_string());
    }

    // Hebrew
    for c in '\u{05D0}'..'\u{05EA}' {
        grapheme_list.push(c.to_string());
    }

    // Arabic
    for c in '\u{0621}'..'\u{064A}' {
        grapheme_list.push(c.to_string());
    }

    // Render all graphemes
    let text = grapheme_list.join("");
    let grapheme_count = graphemes(&text).count();

    assert!(
        grapheme_count >= 200,
        "should have at least 200 graphemes, got {}",
        grapheme_count
    );

    // Draw in chunks across multiple rows
    let mut x = 0u32;
    let mut y = 0u32;
    for grapheme in graphemes(&text) {
        let w = u32::try_from(display_width(grapheme)).expect("grapheme width fits in u32");
        if x + w > 200 {
            x = 0;
            y += 1;
            if y >= 50 {
                break;
            }
        }
        buffer.draw_text_with_pool(&mut pool, x, y, grapheme, Style::NONE);
        x += w.max(1); // At least move 1 cell for zero-width
    }
}

#[test]
fn test_very_long_grapheme_cluster() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    let mut pool = GraphemePool::new();
    buffer.clear(Rgba::BLACK);

    // Create a very long grapheme cluster with many combining marks
    // Base character followed by 50 combining marks
    let mut long_grapheme = String::from("e");
    for _ in 0..50 {
        long_grapheme.push('\u{0301}'); // combining acute accent
    }

    // Should be single grapheme cluster
    assert_eq!(graphemes(&long_grapheme).count(), 1);

    // Should have width 1 (combining marks don't add width)
    assert_eq!(display_width(&long_grapheme), 1);

    // Render it
    buffer.draw_text_with_pool(&mut pool, 0, 0, &long_grapheme, Style::NONE);

    // Verify it's stored
    let cell = buffer.get(0, 0).unwrap();
    assert!(!cell.is_continuation());
}

#[test]
fn test_alternating_width_characters() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Alternating ASCII (width 1) and CJK (width 2)
    let text = "A\u{4E2D}B\u{6587}C\u{5B57}D\u{7B26}E";
    // Widths: A=1, ไธญ=2, B=1, ๆ–‡=2, C=1, ๅญ—=2, D=1, ็ฌฆ=2, E=1
    // Total: 1+2+1+2+1+2+1+2+1 = 13

    buffer.draw_text(0, 0, text, Style::NONE);

    let total_width: usize = graphemes(text).map(display_width).sum();
    assert_eq!(total_width, 13);

    // Verify positions
    // A at 0
    // ไธญ at 1-2
    // B at 3
    // ๆ–‡ at 4-5
    // C at 6
    // ๅญ— at 7-8
    // D at 9
    // ็ฌฆ at 10-11
    // E at 12

    let positions = [
        (0, false),  // A
        (1, false),  // ไธญ
        (2, true),   // continuation
        (3, false),  // B
        (4, false),  // ๆ–‡
        (5, true),   // continuation
        (6, false),  // C
        (7, false),  // ๅญ—
        (8, true),   // continuation
        (9, false),  // D
        (10, false), // ็ฌฆ
        (11, true),  // continuation
        (12, false), // E
    ];

    for (pos, should_be_continuation) in positions {
        let cell = buffer.get(pos, 0).unwrap();
        assert_eq!(
            cell.is_continuation(),
            should_be_continuation,
            "position {} should {}be continuation",
            pos,
            if should_be_continuation { "" } else { "not " }
        );
    }
}

#[test]
fn test_full_buffer_with_unicode() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    let mut pool = GraphemePool::new();
    buffer.clear(Rgba::BLACK);

    // Fill entire buffer with mixed Unicode content
    for y in 0..24 {
        let text = match y % 4 {
            0 => "ASCII text with numbers 0123456789 and symbols !@#$%",
            1 => "\u{4E2D}\u{6587}\u{65E5}\u{672C}\u{8A9E}\u{D55C}\u{AE00}",
            2 => "\u{1F600}\u{1F601}\u{1F602}\u{1F603}\u{1F604}\u{1F605}",
            _ => "e\u{0301} a\u{0300} n\u{0303} o\u{0302} u\u{0308}",
        };
        buffer.draw_text_with_pool(&mut pool, 0, y, text, Style::NONE);
    }

    // Verify no panics and buffer is populated
    let (width, height) = buffer.size();
    assert_eq!(width, 80);
    assert_eq!(height, 24);
}

#[test]
fn test_unicode_width_consistency() {
    // Verify that width calculations are consistent between methods

    // Test cases with definite expected widths
    let definite_cases = [
        ("A", 1),
        ("\u{4E2D}", 2),  // ไธญ
        ("\u{1F600}", 2), // ๐Ÿ˜€
        ("e\u{0301}", 1), // รฉ (decomposed)
        ("\u{00E9}", 1),  // รฉ (precomposed)
        ("\u{200D}", 0),  // ZWJ
    ];

    for (grapheme, expected_width) in definite_cases {
        let width = display_width(grapheme);
        assert_eq!(
            width, expected_width,
            "grapheme {:?} should have width {}, got {}",
            grapheme, expected_width, width
        );
    }

    // Control characters - implementation may vary but should be <=1
    let control_cases = ["\t", "\n"];
    for grapheme in control_cases {
        let width = display_width(grapheme);
        assert!(
            width <= 1,
            "control character {:?} should have width <= 1, got {}",
            grapheme,
            width
        );
    }
}

#[test]
fn test_rtl_characters() {
    let mut buffer = OptimizedBuffer::new(80, 24);
    buffer.clear(Rgba::BLACK);

    // Hebrew
    let hebrew = "\u{05E9}\u{05DC}\u{05D5}\u{05DD}"; // ืฉืœื•ื
    buffer.draw_text(0, 0, hebrew, Style::NONE);

    // Arabic
    let arabic = "\u{0645}\u{0631}\u{062D}\u{0628}\u{0627}"; // ู…ุฑุญุจุง
    buffer.draw_text(0, 1, arabic, Style::NONE);

    // Mixed LTR and RTL
    let mixed = "Hello \u{05E9}\u{05DC}\u{05D5}\u{05DD} World";
    buffer.draw_text(0, 2, mixed, Style::NONE);

    // Verify rendering doesn't panic and characters are placed
    // (Actual bidi reordering depends on terminal, not our renderer)
}

#[test]
fn test_e2e_bidi_reorder_and_render() {
    let mut harness = E2EHarness::new("unicode", "bidi_reorder", 20, 2);
    harness
        .log()
        .info("init", "Starting BiDi reorder + render test");

    let logical = "abc ืื‘ื’";
    let visual = reorder_for_display(logical);
    assert_eq!(visual, "abc ื’ื‘ื", "BiDi reorder should flip RTL run");

    let mut buffer = OptimizedBuffer::new(20, 2);
    buffer.clear(Rgba::BLACK);
    buffer.draw_text(0, 0, &visual, Style::NONE);

    for (idx, ch) in visual.chars().enumerate() {
        let idx_u32 = u32::try_from(idx).expect("index fits u32");
        let cell = buffer
            .get(idx_u32, 0)
            .unwrap_or_else(|| unreachable!("No cell at ({}, 0)", idx));
        assert_eq!(
            cell.content.as_char(),
            Some(ch),
            "Visual order char mismatch at index {idx}"
        );
    }

    let mirrored = reorder_for_display("\u{05D0}(ื‘)ื’.");
    assert_eq!(
        mirrored, ".ื’(ื‘)ื",
        "BiDi mirroring should flip parentheses in RTL run"
    );

    harness.finish(true);
    eprintln!("[TEST] PASS: E2E BiDi reorder + render works");
}

#[test]
fn test_e2e_bidi_editor_selection_render() {
    let mut harness = E2EHarness::new("unicode", "bidi_editor_selection", 40, 3);
    harness
        .log()
        .info("init", "Starting BiDi editor selection render test");

    let text = "Hello ืฉืœื•ื World";
    let rtl = "ืฉืœื•ื";
    let byte_start = text.find(rtl).expect("RTL substring should exist");
    let rtl_start = text[..byte_start].chars().count();
    let rtl_end = rtl_start + rtl.chars().count();

    let edit_buffer = EditBuffer::with_text(text);
    let mut view = EditorView::new(edit_buffer);
    let selection_bg = Rgba::from_rgb_u8(60, 60, 120);
    view.set_selection_style(Style::builder().bg(selection_bg).build());
    view.set_selection(rtl_start, rtl_end);

    let mut buffer = OptimizedBuffer::new(40, 3);
    buffer.clear(Rgba::BLACK);
    view.render_to(&mut buffer, 0, 0, 40, 3);

    for (i, ch) in rtl.chars().enumerate() {
        let col = u32::try_from(rtl_start + i).expect("selection index fits u32");
        let cell = buffer
            .get(col, 0)
            .unwrap_or_else(|| unreachable!("No cell at ({col}, 0)"));
        let color_close = |a: Rgba, b: Rgba| {
            const EPS: f32 = 0.01;
            (a.r - b.r).abs() < EPS
                && (a.g - b.g).abs() < EPS
                && (a.b - b.b).abs() < EPS
                && (a.a - b.a).abs() < EPS
        };
        let is_expected_char = cell.content.as_char().is_some_and(|c| c.eq(&ch));
        assert!(
            is_expected_char && color_close(cell.bg, selection_bg),
            "Selected RTL cell should have selection background"
        );
    }

    harness.finish(true);
    eprintln!("[TEST] PASS: E2E BiDi editor selection render works");
}

#[test]
fn test_e2e_grapheme_pool_stress_and_compaction() {
    let mut harness = E2EHarness::new("unicode", "grapheme_pool_stress", 40, 4);
    harness
        .log()
        .info("init", "Starting grapheme pool stress + compaction test");

    let mut pool = GraphemePool::new();
    let mut buffer = OptimizedBuffer::new(40, 4);
    let emoji = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Family ๐ŸŽ‰ Party ๐Ÿš€ Rocket";

    for _ in 0..200 {
        buffer.draw_text_with_pool(&mut pool, 0, 0, emoji, Style::NONE);
        buffer.clear_with_pool(&mut pool, Rgba::BLACK);
    }

    let stats = pool.stats();
    harness
        .log()
        .info("stats", format!("Pool stats after clears: {stats:?}"));
    assert!(
        stats.active_slots <= 2,
        "Pool should not leak active slots after clear: {stats:?}"
    );

    let mut ids = Vec::with_capacity(1200);
    for i in 0..1200 {
        let id = pool.alloc(&format!("g{i}"));
        ids.push(id);
    }

    for (i, id) in ids.iter().enumerate() {
        if !matches!(i % 3, 0) {
            pool.decref(*id);
        }
    }

    assert!(pool.should_compact(), "Pool should recommend compaction");
    let result = pool.compact();
    harness
        .log()
        .info("compact", format!("Compaction result: {result:?}"));
    assert!(
        result.slots_freed > 0,
        "Compaction should free slots: {result:?}"
    );

    harness.finish(true);
    eprintln!("[TEST] PASS: E2E grapheme pool stress + compaction works");
}

#[test]
fn test_private_use_area() {
    // Private Use Area characters (U+E000-U+F8FF)
    // These are often used for custom symbols/icons (e.g., Nerd Fonts)
    let pua_char = '\u{E000}';
    let width = display_width_char(pua_char);

    // PUA width is implementation-dependent, but shouldn't panic
    assert!(width <= 2, "PUA character width should be reasonable");
}

#[test]
fn test_surrogates_and_noncharacters() {
    // These shouldn't appear in valid UTF-8, but verify width function handles them
    // Note: Rust strings can't contain unpaired surrogates (they're invalid UTF-8)

    // Noncharacter: U+FFFE
    let nonchar = '\u{FFFE}';
    let width = display_width_char(nonchar);
    assert!(width <= 2);

    // Replacement character: U+FFFD
    let replacement = '\u{FFFD}';
    let width = display_width_char(replacement);
    assert!(width <= 2);
}