saorsa-tui 0.4.0

Retained-mode, CSS-styled terminal UI framework
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
//! Compositor — resolves overlapping widget layers into a flat cell grid.
//!
//! The compositor collects styled segment output from each widget,
//! finds cut boundaries where widget edges meet, selects the topmost
//! visible widget for each region, and writes the result to a screen buffer.

pub mod chop;
pub mod compose;
pub mod cuts;
pub mod layer;
pub mod zorder;

pub use layer::{CompositorError, CompositorRegion, Layer};

use crate::buffer::ScreenBuffer;
use crate::cell::Cell;
use crate::geometry::{Rect, Size};
use crate::segment::Segment;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

/// The compositor collects widget layers and resolves overlapping regions.
pub struct Compositor {
    layers: Vec<Layer>,
    screen_width: u16,
    screen_height: u16,
}

impl Compositor {
    /// Creates a new compositor with the given screen dimensions.
    pub fn new(width: u16, height: u16) -> Self {
        Self {
            layers: Vec::new(),
            screen_width: width,
            screen_height: height,
        }
    }

    /// Removes all layers from the compositor.
    pub fn clear(&mut self) {
        self.layers.clear();
    }

    /// Adds a layer to the compositor stack.
    pub fn add_layer(&mut self, layer: Layer) {
        self.layers.push(layer);
    }

    /// Convenience method that creates and adds a layer.
    ///
    /// Creates a new layer from the given parameters and adds it to the stack.
    pub fn add_widget(
        &mut self,
        widget_id: u64,
        region: Rect,
        z_index: i32,
        lines: Vec<Vec<Segment>>,
    ) {
        let layer = Layer::new(widget_id, region, z_index, lines);
        self.add_layer(layer);
    }

    /// Returns the number of layers in the compositor.
    pub fn layer_count(&self) -> usize {
        self.layers.len()
    }

    /// Returns the screen size.
    pub fn screen_size(&self) -> Size {
        Size::new(self.screen_width, self.screen_height)
    }

    /// Resizes the compositor screen dimensions.
    ///
    /// Clears all layers since they may no longer be valid for the new size.
    pub fn resize(&mut self, width: u16, height: u16) {
        self.screen_width = width;
        self.screen_height = height;
        self.layers.clear();
    }

    /// Returns a slice of all layers in the compositor.
    pub fn layers(&self) -> &[Layer] {
        &self.layers
    }

    /// Compose all layers and write the result to the screen buffer.
    ///
    /// Processes each row by calling `compose_line` to resolve overlapping
    /// layers, then writes the resulting segments as cells to the buffer.
    pub fn compose(&self, buf: &mut ScreenBuffer) {
        for row in 0..self.screen_height {
            let segments = compose::compose_line(&self.layers, row, self.screen_width);
            self.write_segments_to_buffer(buf, row, &segments);
        }
    }

    /// Write segments to a row of the screen buffer, converting each
    /// segment's graphemes to cells with proper style and width handling.
    fn write_segments_to_buffer(&self, buf: &mut ScreenBuffer, row: u16, segments: &[Segment]) {
        let mut x = 0;

        for segment in segments {
            // Skip control segments (they don't render)
            if segment.is_control {
                continue;
            }

            // Process each grapheme in the segment
            for grapheme in segment.text.graphemes(true) {
                if x >= self.screen_width {
                    return; // Reached end of screen width
                }

                let width = UnicodeWidthStr::width(grapheme);
                let cell = Cell::new(grapheme, segment.style.clone());
                buf.set(x, row, cell);
                x += width as u16;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::Rect;
    use crate::segment::Segment;

    #[test]
    fn new_compositor_empty() {
        let compositor = Compositor::new(80, 24);
        assert!(compositor.layer_count() == 0);
    }

    #[test]
    fn add_layer_increases_count() {
        let mut compositor = Compositor::new(80, 24);
        let region = Rect::new(0, 0, 10, 5);
        let layer = Layer::new(1, region, 0, vec![]);

        compositor.add_layer(layer);
        assert!(compositor.layer_count() == 1);
    }

    #[test]
    fn add_multiple_layers() {
        let mut compositor = Compositor::new(80, 24);
        let region1 = Rect::new(0, 0, 10, 5);
        let region2 = Rect::new(10, 10, 20, 10);
        let region3 = Rect::new(30, 5, 15, 8);

        compositor.add_layer(Layer::new(1, region1, 0, vec![]));
        compositor.add_layer(Layer::new(2, region2, 1, vec![]));
        compositor.add_layer(Layer::new(3, region3, 2, vec![]));

        assert!(compositor.layer_count() == 3);
    }

    #[test]
    fn add_widget_convenience() {
        let mut compositor = Compositor::new(80, 24);
        let region = Rect::new(5, 10, 20, 15);
        let lines = vec![vec![Segment::new("test")]];

        compositor.add_widget(42, region, 5, lines);

        assert!(compositor.layer_count() == 1);
        let layer_slice = compositor.layers();
        assert!(layer_slice.len() == 1);
        let layer = match layer_slice.first() {
            Some(l) => l,
            None => unreachable!(),
        };
        assert!(layer.widget_id == 42);
        assert!(layer.z_index == 5);
        assert!(layer.region == region);
    }

    #[test]
    fn clear_removes_all() {
        let mut compositor = Compositor::new(80, 24);
        let region1 = Rect::new(0, 0, 10, 5);
        let region2 = Rect::new(10, 10, 20, 10);

        compositor.add_layer(Layer::new(1, region1, 0, vec![]));
        compositor.add_layer(Layer::new(2, region2, 1, vec![]));
        assert!(compositor.layer_count() == 2);

        compositor.clear();
        assert!(compositor.layer_count() == 0);
    }

    #[test]
    fn screen_size_accessible() {
        let compositor = Compositor::new(100, 50);
        let size = compositor.screen_size();
        assert!(size.width == 100);
        assert!(size.height == 50);
    }

    #[test]
    fn layers_accessible() {
        let mut compositor = Compositor::new(80, 24);
        let region1 = Rect::new(0, 0, 10, 5);
        let region2 = Rect::new(10, 10, 20, 10);

        compositor.add_layer(Layer::new(1, region1, 0, vec![]));
        compositor.add_layer(Layer::new(2, region2, 1, vec![]));

        let layers = compositor.layers();
        assert!(layers.len() == 2);
        assert!(layers[0].widget_id == 1);
        assert!(layers[1].widget_id == 2);
    }

    #[test]
    fn compose_single_layer_to_buffer() {
        use crate::geometry::Size;

        let mut compositor = Compositor::new(80, 10);
        let region = Rect::new(0, 0, 80, 10);
        let lines = vec![vec![Segment::new("Hello, World!")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(80, 10));
        compositor.compose(&mut buf);

        // Check that the text appears in the buffer
        assert!(buf.get(0, 0).is_some());
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "H");
            }
            None => unreachable!(),
        }

        // Check second character
        match buf.get(1, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "e");
            }
            None => unreachable!(),
        }
    }

    #[test]
    fn compose_overlapping_layers_to_buffer() {
        use crate::geometry::Size;

        let mut compositor = Compositor::new(80, 10);

        // Background layer (z=0)
        let bg_region = Rect::new(0, 0, 80, 10);
        let bg_lines = vec![vec![Segment::new("Background")]];
        compositor.add_layer(Layer::new(1, bg_region, 0, bg_lines));

        // Overlay layer (z=10) at position (5, 0)
        let overlay_region = Rect::new(5, 0, 20, 10);
        let overlay_lines = vec![vec![Segment::new("Overlay")]];
        compositor.add_layer(Layer::new(2, overlay_region, 10, overlay_lines));

        let mut buf = ScreenBuffer::new(Size::new(80, 10));
        compositor.compose(&mut buf);

        // Position 0 should have 'B' from Background
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "B");
            }
            None => unreachable!(),
        }

        // Position 5 should have 'O' from Overlay (topmost)
        match buf.get(5, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "O");
            }
            None => unreachable!(),
        }
    }

    #[test]
    fn compose_correct_cell_styles() {
        use crate::color::{Color, NamedColor};
        use crate::geometry::Size;
        use crate::style::Style;

        let mut compositor = Compositor::new(80, 10);
        let style = Style {
            fg: Some(Color::Named(NamedColor::Red)),
            bold: true,
            ..Default::default()
        };

        let mut seg = Segment::new("Styled");
        seg.style = style.clone();

        let region = Rect::new(0, 0, 20, 10);
        let lines = vec![vec![seg]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(80, 10));
        compositor.compose(&mut buf);

        // Check that the style is preserved
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.style.bold);
                assert!(matches!(cell.style.fg, Some(Color::Named(NamedColor::Red))));
            }
            None => unreachable!(),
        }
    }

    #[test]
    fn compose_empty_compositor_all_blank() {
        use crate::geometry::Size;

        let compositor = Compositor::new(80, 10);
        let mut buf = ScreenBuffer::new(Size::new(80, 10));

        compositor.compose(&mut buf);

        // All cells should be blank (space)
        for y in 0..10 {
            for x in 0..80 {
                match buf.get(x, y) {
                    Some(cell) => {
                        assert!(cell.is_blank());
                    }
                    None => unreachable!(),
                }
            }
        }
    }

    #[test]
    fn compose_wide_characters() {
        use crate::geometry::Size;

        let mut compositor = Compositor::new(80, 10);
        let region = Rect::new(0, 0, 20, 10);
        // 世 is a CJK character with width 2
        let lines = vec![vec![Segment::new("\u{4e16}")]]; // 世界
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(80, 10));
        compositor.compose(&mut buf);

        // First cell should have the wide character
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "\u{4e16}");
                assert!(cell.width == 2);
            }
            None => unreachable!(),
        }

        // Second cell should be continuation (width 0)
        match buf.get(1, 0) {
            Some(cell) => {
                assert!(cell.width == 0);
            }
            None => unreachable!(),
        }

        // Third cell should have the second character
        match buf.get(2, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "");
                assert!(cell.width == 2);
            }
            None => unreachable!(),
        }
    }
}

#[cfg(test)]
mod integration_tests {
    use super::*;
    use crate::color::{Color, NamedColor};
    use crate::geometry::{Rect, Size};
    use crate::segment::Segment;
    use crate::style::Style;

    #[test]
    fn integration_chat_layout() {
        let mut compositor = Compositor::new(80, 24);

        // Header at top (z=0)
        let header_region = Rect::new(0, 0, 80, 1);
        let header_lines = vec![vec![Segment::new("Chat App Header")]];
        compositor.add_layer(Layer::new(1, header_region, 0, header_lines));

        // Messages area (z=0)
        let messages_region = Rect::new(0, 1, 80, 20);
        let messages_lines = vec![vec![Segment::new("Message 1")]];
        compositor.add_layer(Layer::new(2, messages_region, 0, messages_lines));

        // Input bar at bottom (z=0)
        let input_region = Rect::new(0, 21, 80, 3);
        let input_lines = vec![vec![Segment::new("Type here...")]];
        compositor.add_layer(Layer::new(3, input_region, 0, input_lines));

        // Modal overlay (z=10) centered
        let modal_region = Rect::new(20, 8, 40, 8);
        let modal_lines = vec![vec![Segment::new("Modal Dialog")]];
        compositor.add_layer(Layer::new(4, modal_region, 10, modal_lines));

        let mut buf = ScreenBuffer::new(Size::new(80, 24));
        compositor.compose(&mut buf);

        // Header text should be visible at row 0
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "C");
            }
            None => unreachable!(),
        }

        // Modal should overlay messages at row 8, column 20
        match buf.get(20, 8) {
            Some(cell) => {
                assert!(cell.grapheme == "M");
            }
            None => unreachable!(),
        }

        // Input bar should be visible at row 21
        match buf.get(0, 21) {
            Some(cell) => {
                assert!(cell.grapheme == "T");
            }
            None => unreachable!(),
        }
    }

    #[test]
    fn integration_three_overlapping_windows() {
        let mut compositor = Compositor::new(80, 24);

        // Bottom window (z=0)
        let window1_region = Rect::new(0, 0, 40, 20);
        let window1_lines = vec![vec![Segment::new("Window 1")]];
        compositor.add_layer(Layer::new(1, window1_region, 0, window1_lines));

        // Middle window (z=5)
        let window2_region = Rect::new(20, 5, 40, 15);
        let window2_lines = vec![vec![Segment::new("Window 2")]];
        compositor.add_layer(Layer::new(2, window2_region, 5, window2_lines));

        // Top window (z=10)
        let window3_region = Rect::new(30, 10, 30, 10);
        let window3_lines = vec![vec![Segment::new("Window 3")]];
        compositor.add_layer(Layer::new(3, window3_region, 10, window3_lines));

        let mut buf = ScreenBuffer::new(Size::new(80, 24));
        compositor.compose(&mut buf);

        // Position (0, 0) should have Window 1 (only window here)
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "W");
            }
            None => unreachable!(),
        }

        // Position (20, 5) should have Window 2 (overlaps Window 1)
        match buf.get(20, 5) {
            Some(cell) => {
                assert!(cell.grapheme == "W");
            }
            None => unreachable!(),
        }

        // Position (30, 10) should have Window 3 (highest z-index)
        match buf.get(30, 10) {
            Some(cell) => {
                assert!(cell.grapheme == "W");
            }
            None => unreachable!(),
        }
    }

    #[test]
    fn integration_styled_segments_preserved() {
        let mut compositor = Compositor::new(80, 24);

        let red_style = Style {
            fg: Some(Color::Named(NamedColor::Red)),
            bold: true,
            ..Default::default()
        };

        let blue_style = Style {
            fg: Some(Color::Named(NamedColor::Blue)),
            italic: true,
            ..Default::default()
        };

        let mut red_seg = Segment::new("Red ");
        red_seg.style = red_style.clone();

        let mut blue_seg = Segment::new("Blue");
        blue_seg.style = blue_style.clone();

        let region = Rect::new(0, 0, 40, 10);
        let lines = vec![vec![red_seg, blue_seg]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(80, 24));
        compositor.compose(&mut buf);

        // First character should have red style
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.style.bold);
                assert!(matches!(cell.style.fg, Some(Color::Named(NamedColor::Red))));
            }
            None => unreachable!(),
        }

        // Fifth character (index 4) should have blue style
        match buf.get(4, 0) {
            Some(cell) => {
                assert!(cell.style.italic);
                assert!(matches!(
                    cell.style.fg,
                    Some(Color::Named(NamedColor::Blue))
                ));
            }
            None => unreachable!(),
        }
    }

    #[test]
    fn integration_resize_recompose() {
        // Compose at 80x24
        let mut compositor1 = Compositor::new(80, 24);
        let region1 = Rect::new(0, 0, 40, 10);
        let lines1 = vec![vec![Segment::new("Test")]];
        compositor1.add_layer(Layer::new(1, region1, 0, lines1));

        let mut buf1 = ScreenBuffer::new(Size::new(80, 24));
        compositor1.compose(&mut buf1);

        match buf1.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "T");
            }
            None => unreachable!(),
        }

        // Now compose at 120x30
        let mut compositor2 = Compositor::new(120, 30);
        let region2 = Rect::new(0, 0, 60, 15);
        let lines2 = vec![vec![Segment::new("Resized")]];
        compositor2.add_layer(Layer::new(1, region2, 0, lines2));

        let mut buf2 = ScreenBuffer::new(Size::new(120, 30));
        compositor2.compose(&mut buf2);

        match buf2.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "R");
            }
            None => unreachable!(),
        }

        // Both buffers should work correctly
        assert!(buf1.width() == 80);
        assert!(buf2.width() == 120);
    }
}

#[cfg(test)]
mod advanced_integration_tests {
    use super::*;
    use crate::color::{Color, NamedColor};
    use crate::geometry::{Rect, Size};
    use crate::segment::Segment;
    use crate::style::Style;

    /// Task 7, Test 1: Syntax-highlighted code with multiple styled segments.
    #[test]
    fn syntax_highlighted_code() {
        let mut compositor = Compositor::new(40, 5);

        let keyword_style = Style::new().fg(Color::Named(NamedColor::Blue)).bold(true);
        let ident_style = Style::new().fg(Color::Named(NamedColor::White));
        let paren_style = Style::new().fg(Color::Named(NamedColor::Yellow));

        let segments = vec![
            Segment::styled("fn", keyword_style.clone()),
            Segment::styled(" ", Style::default()),
            Segment::styled("main", ident_style.clone()),
            Segment::styled("()", paren_style.clone()),
        ];

        let region = Rect::new(0, 0, 40, 5);
        compositor.add_layer(Layer::new(1, region, 0, vec![segments]));

        let mut buf = ScreenBuffer::new(Size::new(40, 5));
        compositor.compose(&mut buf);

        // "fn" at positions 0-1 should have blue, bold
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "f");
                assert!(cell.style.bold);
                assert!(matches!(
                    cell.style.fg,
                    Some(Color::Named(NamedColor::Blue))
                ));
            }
            None => unreachable!(),
        }
        match buf.get(1, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "n");
                assert!(cell.style.bold);
            }
            None => unreachable!(),
        }

        // Space at position 2 should have default style
        match buf.get(2, 0) {
            Some(cell) => {
                assert!(cell.grapheme == " ");
            }
            None => unreachable!(),
        }

        // "main" at positions 3-6 should have white fg
        match buf.get(3, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "m");
                assert!(matches!(
                    cell.style.fg,
                    Some(Color::Named(NamedColor::White))
                ));
            }
            None => unreachable!(),
        }

        // "()" at positions 7-8 should have yellow fg
        match buf.get(7, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "(");
                assert!(matches!(
                    cell.style.fg,
                    Some(Color::Named(NamedColor::Yellow))
                ));
            }
            None => unreachable!(),
        }
    }

    /// Task 7, Test 2: Overlapping styled windows with different background colors.
    #[test]
    fn overlapping_styled_windows() {
        let mut compositor = Compositor::new(20, 5);

        // Bottom window (z=0) with green bg, fills region 0,0 -> 20,5
        let green_bg = Style::new().bg(Color::Named(NamedColor::Green));
        let green_line = vec![Segment::styled("GGGGGGGGGGGGGGGGGGG", green_bg.clone())];
        let bottom_region = Rect::new(0, 0, 20, 5);
        let bottom_lines = vec![green_line.clone(); 5];
        compositor.add_layer(Layer::new(1, bottom_region, 0, bottom_lines));

        // Top window (z=5) with blue bg, covers region 5,1 -> 10,3
        let blue_bg = Style::new().bg(Color::Named(NamedColor::Blue));
        let blue_line = vec![Segment::styled("BBBBB", blue_bg.clone())];
        let top_region = Rect::new(5, 1, 10, 3);
        let top_lines = vec![blue_line.clone(); 3];
        compositor.add_layer(Layer::new(2, top_region, 5, top_lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 5));
        compositor.compose(&mut buf);

        // Row 0, col 5: only bottom window here -> green bg
        match buf.get(5, 0) {
            Some(cell) => {
                assert!(matches!(
                    cell.style.bg,
                    Some(Color::Named(NamedColor::Green))
                ));
            }
            None => unreachable!(),
        }

        // Row 1, col 5: top window starts here -> blue bg
        match buf.get(5, 1) {
            Some(cell) => {
                assert!(matches!(
                    cell.style.bg,
                    Some(Color::Named(NamedColor::Blue))
                ));
            }
            None => unreachable!(),
        }

        // Row 1, col 0: still bottom window region -> green bg
        match buf.get(0, 1) {
            Some(cell) => {
                assert!(matches!(
                    cell.style.bg,
                    Some(Color::Named(NamedColor::Green))
                ));
            }
            None => unreachable!(),
        }
    }

    /// Task 7, Test 3: Full-width CJK text in compositor.
    #[test]
    fn cjk_text_in_compositor() {
        let mut compositor = Compositor::new(20, 3);
        let region = Rect::new(0, 0, 20, 3);
        // "世界" = two CJK chars, each width 2, total width 4
        let lines = vec![vec![Segment::new("\u{4e16}\u{754c}")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // First CJK char at column 0, width 2
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "\u{4e16}");
                assert!(cell.width == 2);
            }
            None => unreachable!(),
        }

        // Continuation cell at column 1
        match buf.get(1, 0) {
            Some(cell) => {
                assert!(cell.width == 0);
            }
            None => unreachable!(),
        }

        // Second CJK char at column 2
        match buf.get(2, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "\u{754c}");
                assert!(cell.width == 2);
            }
            None => unreachable!(),
        }

        // Continuation cell at column 3
        match buf.get(3, 0) {
            Some(cell) => {
                assert!(cell.width == 0);
            }
            None => unreachable!(),
        }
    }

    /// Task 7, Test 4: Multiple rows in a layer.
    #[test]
    fn multiple_rows_in_layer() {
        let mut compositor = Compositor::new(40, 10);
        let region = Rect::new(0, 0, 40, 10);
        let lines = vec![
            vec![Segment::new("Row Zero")],
            vec![Segment::new("Row One")],
            vec![Segment::new("Row Two")],
        ];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(40, 10));
        compositor.compose(&mut buf);

        // Row 0 starts with 'R' from "Row Zero"
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "R");
            }
            None => unreachable!(),
        }
        match buf.get(4, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "Z");
            }
            None => unreachable!(),
        }

        // Row 1 starts with 'R' from "Row One"
        match buf.get(0, 1) {
            Some(cell) => {
                assert!(cell.grapheme == "R");
            }
            None => unreachable!(),
        }
        match buf.get(4, 1) {
            Some(cell) => {
                assert!(cell.grapheme == "O");
            }
            None => unreachable!(),
        }

        // Row 2 starts with 'R' from "Row Two"
        match buf.get(0, 2) {
            Some(cell) => {
                assert!(cell.grapheme == "R");
            }
            None => unreachable!(),
        }
        match buf.get(4, 2) {
            Some(cell) => {
                assert!(cell.grapheme == "T");
            }
            None => unreachable!(),
        }
    }

    /// Task 7, Test 5: Layer partially off-screen.
    #[test]
    fn layer_partially_off_screen() {
        // Screen is 10x5
        let mut compositor = Compositor::new(10, 5);

        // Layer starts at x=7, width=10 — extends to x=17 which is beyond screen width 10
        let region = Rect::new(7, 0, 10, 3);
        let lines = vec![vec![Segment::new("ABCDEFGHIJ")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(10, 5));
        compositor.compose(&mut buf);

        // Column 7 should have 'A'
        match buf.get(7, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "A");
            }
            None => unreachable!(),
        }

        // Column 9 (last column) should have 'C'
        match buf.get(9, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "C");
            }
            None => unreachable!(),
        }

        // No out-of-bounds access — buffer should be fine
        assert!(buf.get(10, 0).is_none());
    }

    /// Task 7, Test 6: Zero-layer compositor produces all blank cells.
    #[test]
    fn zero_layer_compositor_all_blank() {
        let compositor = Compositor::new(20, 10);
        let mut buf = ScreenBuffer::new(Size::new(20, 10));
        compositor.compose(&mut buf);

        for y in 0..10 {
            for x in 0..20 {
                match buf.get(x, y) {
                    Some(cell) => {
                        assert!(cell.is_blank());
                    }
                    None => unreachable!(),
                }
            }
        }
    }

    /// Task 7, Test 7: Background layer with overlay covering middle portion.
    #[test]
    fn styled_segments_split_by_overlay() {
        let mut compositor = Compositor::new(20, 3);

        // Background: "Hello World" at (0,0), z=0
        let bg_region = Rect::new(0, 0, 20, 3);
        let bg_lines = vec![vec![Segment::new("Hello World")]];
        compositor.add_layer(Layer::new(1, bg_region, 0, bg_lines));

        // Overlay: "XXXXX" at x=3, covering positions 3-7, z=10
        let overlay_region = Rect::new(3, 0, 5, 3);
        let overlay_lines = vec![vec![Segment::new("XXXXX")]];
        compositor.add_layer(Layer::new(2, overlay_region, 10, overlay_lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // Positions 0-2: "Hel" from background
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "H");
            }
            None => unreachable!(),
        }
        match buf.get(1, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "e");
            }
            None => unreachable!(),
        }
        match buf.get(2, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "l");
            }
            None => unreachable!(),
        }

        // Positions 3-7: "XXXXX" from overlay
        match buf.get(3, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "X");
            }
            None => unreachable!(),
        }
        match buf.get(7, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "X");
            }
            None => unreachable!(),
        }

        // Position 8: "W" from background ("Hello World" offset by 8 = 'W')
        // The background text "Hello World" has chars at positions:
        // H(0) e(1) l(2) l(3) o(4) (5) W(6) o(7) r(8) l(9) d(10)
        // But the overlay covers 3-7 of the layer, so background position 8
        // should show "o" (position 8 in "Hello World" = 'r')
        // Wait — "Hello World" is 11 chars, at layer origin x=0.
        // Background position 8 maps to "Hello World"[8] = 'r'
        match buf.get(8, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "r");
            }
            None => unreachable!(),
        }
    }

    /// Task 7, Test 8: Large number of layers — topmost always wins.
    #[test]
    fn many_layers_topmost_wins() {
        let mut compositor = Compositor::new(20, 5);

        // Create 25 layers, all covering the same region, with increasing z-index
        // Each layer has its own single character
        for i in 0u64..25 {
            let ch = char::from(b'A' + (i as u8) % 26);
            let region = Rect::new(0, 0, 20, 5);
            let lines = vec![vec![Segment::new(ch.to_string())]];
            compositor.add_layer(Layer::new(i + 1, region, i as i32, lines));
        }

        let mut buf = ScreenBuffer::new(Size::new(20, 5));
        compositor.compose(&mut buf);

        // The topmost layer (z=24) has character 'Y' (b'A' + 24)
        match buf.get(0, 0) {
            Some(cell) => {
                assert!(cell.grapheme == "Y");
            }
            None => unreachable!(),
        }
    }
}

#[cfg(test)]
mod unicode_pipeline_tests {
    use super::*;
    use crate::color::{Color, NamedColor};
    use crate::geometry::{Rect, Size};
    use crate::segment::Segment;
    use crate::style::Style;

    /// Test 1: CJK text layer produces correct primary and continuation cells.
    #[test]
    fn cjk_text_layer_correct_cells() {
        let mut compositor = Compositor::new(20, 3);
        let region = Rect::new(0, 0, 20, 3);
        // Three CJK chars: 世界人 — each width 2, total width 6
        let lines = vec![vec![Segment::new("\u{4e16}\u{754c}\u{4eba}")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // Column 0: primary "世" width 2
        match buf.get(0, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{4e16}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        // Column 1: continuation
        match buf.get(1, 0) {
            Some(c) => assert_eq!(c.width, 0),
            None => unreachable!(),
        }
        // Column 2: primary "界" width 2
        match buf.get(2, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{754c}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        // Column 3: continuation
        match buf.get(3, 0) {
            Some(c) => assert_eq!(c.width, 0),
            None => unreachable!(),
        }
        // Column 4: primary "人" width 2
        match buf.get(4, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{4eba}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        // Column 5: continuation
        match buf.get(5, 0) {
            Some(c) => assert_eq!(c.width, 0),
            None => unreachable!(),
        }
        // Column 6: blank
        match buf.get(6, 0) {
            Some(c) => assert!(c.is_blank()),
            None => unreachable!(),
        }
    }

    /// Test 2: Emoji text layer produces correct cells.
    #[test]
    fn emoji_text_layer_correct_cells() {
        let mut compositor = Compositor::new(20, 3);
        let region = Rect::new(0, 0, 20, 3);
        // Two emoji: 😀🎉 — each width 2
        let lines = vec![vec![Segment::new("\u{1f600}\u{1f389}")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // Column 0: primary emoji, width 2
        match buf.get(0, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{1f600}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        // Column 1: continuation
        match buf.get(1, 0) {
            Some(c) => assert_eq!(c.width, 0),
            None => unreachable!(),
        }
        // Column 2: second emoji, width 2
        match buf.get(2, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{1f389}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        // Column 3: continuation
        match buf.get(3, 0) {
            Some(c) => assert_eq!(c.width, 0),
            None => unreachable!(),
        }
    }

    /// Test 3: Mixed Latin + CJK + emoji in one layer — all widths correct.
    #[test]
    fn mixed_latin_cjk_emoji_widths() {
        let mut compositor = Compositor::new(20, 3);
        let region = Rect::new(0, 0, 20, 3);
        // "Hi" (2) + "世" (2) + "😀" (2) = total width 6
        let lines = vec![vec![Segment::new("Hi\u{4e16}\u{1f600}")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // Columns 0-1: "H", "i" (each width 1)
        match buf.get(0, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "H");
                assert_eq!(c.width, 1);
            }
            None => unreachable!(),
        }
        match buf.get(1, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "i");
                assert_eq!(c.width, 1);
            }
            None => unreachable!(),
        }
        // Columns 2-3: CJK "世" (width 2) + continuation
        match buf.get(2, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{4e16}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        match buf.get(3, 0) {
            Some(c) => assert_eq!(c.width, 0),
            None => unreachable!(),
        }
        // Columns 4-5: emoji "😀" (width 2) + continuation
        match buf.get(4, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{1f600}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        match buf.get(5, 0) {
            Some(c) => assert_eq!(c.width, 0),
            None => unreachable!(),
        }
    }

    /// Test 4: Wide char at screen right edge — clipped correctly (no crash).
    #[test]
    fn wide_char_at_screen_right_edge_clipped() {
        // Screen width 5
        let mut compositor = Compositor::new(5, 1);
        let region = Rect::new(0, 0, 5, 1);
        // "ABCD世" = width 6: the CJK char starts at column 4 but needs column 5 too
        // The compositor writes 'A'(0), 'B'(1), 'C'(2), 'D'(3), then tries "世" at col 4
        // Since "世" is width 2 and the screen width is 5, column 5 is out of bounds
        // The buffer's set() will handle this by replacing with blank
        let lines = vec![vec![Segment::new("ABCD\u{4e16}")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(5, 1));
        compositor.compose(&mut buf);

        // Columns 0-3 should have A, B, C, D
        match buf.get(0, 0) {
            Some(c) => assert_eq!(c.grapheme, "A"),
            None => unreachable!(),
        }
        match buf.get(3, 0) {
            Some(c) => assert_eq!(c.grapheme, "D"),
            None => unreachable!(),
        }
        // Column 4: the wide char can't fit, should be blank (buffer protection)
        match buf.get(4, 0) {
            Some(c) => {
                // Buffer set() replaces wide chars at last column with blank
                assert!(c.is_blank());
            }
            None => unreachable!(),
        }
        // No crash, no out-of-bounds
        assert!(buf.get(5, 0).is_none());
    }

    /// Test 5: Combining marks in a layer — preserved in buffer cells.
    #[test]
    fn combining_marks_preserved_in_buffer() {
        let mut compositor = Compositor::new(20, 3);
        let region = Rect::new(0, 0, 20, 3);
        // "e\u{0301}" = e with combining acute accent = single grapheme, width 1
        let lines = vec![vec![Segment::new("e\u{0301}X")]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // Column 0: the composed grapheme "e\u{0301}" should be there
        match buf.get(0, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "e\u{0301}");
                assert_eq!(c.width, 1);
            }
            None => unreachable!(),
        }
        // Column 1: "X"
        match buf.get(1, 0) {
            Some(c) => assert_eq!(c.grapheme, "X"),
            None => unreachable!(),
        }
    }

    /// Test 6: Styled wide chars — style preserved in buffer.
    #[test]
    fn styled_wide_chars_preserved() {
        let mut compositor = Compositor::new(20, 3);
        let region = Rect::new(0, 0, 20, 3);
        let style = Style::new().fg(Color::Named(NamedColor::Red)).bold(true);
        // CJK text with style
        let lines = vec![vec![Segment::styled("\u{4e16}\u{754c}", style.clone())]];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // Column 0: "世" with red+bold style
        match buf.get(0, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{4e16}");
                assert!(c.style.bold);
                assert!(matches!(c.style.fg, Some(Color::Named(NamedColor::Red))));
            }
            None => unreachable!(),
        }
        // Column 2: "界" with same style
        match buf.get(2, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{754c}");
                assert!(c.style.bold);
                assert!(matches!(c.style.fg, Some(Color::Named(NamedColor::Red))));
            }
            None => unreachable!(),
        }
    }

    /// Test 7: Overlapping layers with different Unicode scripts — topmost wins.
    #[test]
    fn overlapping_unicode_scripts_topmost_wins() {
        let mut compositor = Compositor::new(20, 3);

        // Bottom layer (z=0): CJK text
        let bottom_region = Rect::new(0, 0, 20, 3);
        let bottom_lines = vec![vec![Segment::new("\u{4e16}\u{754c}\u{4eba}\u{6c11}")]];
        compositor.add_layer(Layer::new(1, bottom_region, 0, bottom_lines));

        // Top layer (z=10): Latin text at same position, overlapping first 4 columns
        let top_region = Rect::new(0, 0, 4, 3);
        let top_lines = vec![vec![Segment::new("ABCD")]];
        compositor.add_layer(Layer::new(2, top_region, 10, top_lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 3));
        compositor.compose(&mut buf);

        // Columns 0-3: should have "ABCD" from top layer
        match buf.get(0, 0) {
            Some(c) => assert_eq!(c.grapheme, "A"),
            None => unreachable!(),
        }
        match buf.get(1, 0) {
            Some(c) => assert_eq!(c.grapheme, "B"),
            None => unreachable!(),
        }
        match buf.get(2, 0) {
            Some(c) => assert_eq!(c.grapheme, "C"),
            None => unreachable!(),
        }
        match buf.get(3, 0) {
            Some(c) => assert_eq!(c.grapheme, "D"),
            None => unreachable!(),
        }

        // Column 4 onwards: should have CJK from bottom layer
        // CJK "世界人民": 世(0-1), 界(2-3), 人(4-5), 民(6-7)
        // Since top layer covers 0-3, bottom layer columns 4-5 should show 人
        match buf.get(4, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{4eba}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
    }

    /// Test 8: Multiple rows of CJK text — correct row-by-row rendering.
    #[test]
    fn multiple_rows_cjk_text() {
        let mut compositor = Compositor::new(20, 5);
        let region = Rect::new(0, 0, 20, 5);
        let lines = vec![
            vec![Segment::new("\u{4e16}\u{754c}")], // 世界 (row 0)
            vec![Segment::new("\u{4eba}\u{6c11}")], // 人民 (row 1)
            vec![Segment::new("\u{5927}\u{5b66}")], // 大学 (row 2)
        ];
        compositor.add_layer(Layer::new(1, region, 0, lines));

        let mut buf = ScreenBuffer::new(Size::new(20, 5));
        compositor.compose(&mut buf);

        // Row 0: "世" at col 0, "界" at col 2
        match buf.get(0, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{4e16}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        match buf.get(2, 0) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{754c}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }

        // Row 1: "人" at col 0, "民" at col 2
        match buf.get(0, 1) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{4eba}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        match buf.get(2, 1) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{6c11}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }

        // Row 2: "大" at col 0, "学" at col 2
        match buf.get(0, 2) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{5927}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }
        match buf.get(2, 2) {
            Some(c) => {
                assert_eq!(c.grapheme, "\u{5b66}");
                assert_eq!(c.width, 2);
            }
            None => unreachable!(),
        }

        // Row 3: should be all blank (no content)
        match buf.get(0, 3) {
            Some(c) => assert!(c.is_blank()),
            None => unreachable!(),
        }
    }
}