ftui-extras 0.4.0

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

//! Console abstraction for ergonomic styled output.
//!
//! The Console provides rich-style output helpers adapted to ftui's constraints:
//! - **Segment-first**: Works with structured text + style (not raw strings)
//! - **One-writer safe**: No ad-hoc terminal writes; all output goes through
//!   explicit sinks (buffers, log sinks, etc.)
//!
//! # Quick Start
//!
//! ```
//! use ftui_extras::console::{Console, ConsoleSink};
//! use ftui_text::Segment;
//! use ftui_style::Style;
//!
//! // Create a console with capture sink for testing
//! let sink = ConsoleSink::capture();
//! let mut console = Console::new(80, sink);
//!
//! // Print styled text
//! console.print(Segment::text("Hello, "));
//! console.print(Segment::styled("world!", Style::new().bold()));
//! console.newline();
//!
//! // Get captured output
//! let output = console.into_captured();
//! assert!(output.contains("Hello, world!"));
//! ```
//!
//! # Style Stack
//!
//! The Console maintains a style stack for nested styling:
//!
//! ```
//! use ftui_extras::console::{Console, ConsoleSink};
//! use ftui_render::cell::PackedRgba;
//! use ftui_text::Segment;
//! use ftui_style::Style;
//!
//! let sink = ConsoleSink::capture();
//! let mut console = Console::new(80, sink);
//!
//! // Push base style (blue foreground)
//! console.push_style(Style::new().fg(PackedRgba::rgb(0, 0, 255)));
//! console.print(Segment::text("Blue text"));
//!
//! // Nested style (inherits blue, adds bold)
//! console.push_style(Style::new().bold());
//! console.print(Segment::text(" + bold"));
//! console.pop_style();
//!
//! console.print(Segment::text(" back to just blue"));
//! console.pop_style();
//! ```
//!
//! # Width-Aware Wrapping
//!
//! Text is automatically wrapped at the configured width:
//!
//! ```
//! use ftui_extras::console::{Console, ConsoleSink, WrapMode};
//! use ftui_text::Segment;
//!
//! let sink = ConsoleSink::capture();
//! let mut console = Console::with_options(40, sink, WrapMode::Word);
//!
//! console.print(Segment::text("This is a long line that will wrap automatically when it exceeds the console width."));
//! ```

use std::borrow::Cow;
use std::io::{self, Write};

use ftui_render::sanitize::sanitize;
use ftui_style::Style;
use ftui_text::{Segment, display_width, grapheme_width};
use unicode_segmentation::UnicodeSegmentation;

#[cfg(test)]
use ftui_render::cell::PackedRgba;
#[cfg(test)]
use ftui_style::StyleFlags;

// ============================================================================
// Wrap Mode
// ============================================================================

/// Text wrapping mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WrapMode {
    /// No wrapping; text may overflow.
    None,
    /// Wrap at word boundaries.
    #[default]
    Word,
    /// Wrap at character boundaries (may break words).
    Character,
}

// ============================================================================
// Console Sink
// ============================================================================

/// Output sink for Console.
///
/// The Console never writes directly to stdout/stderr. Instead, output goes
/// through a sink that can be:
/// - A capture buffer (for testing)
/// - A writer (for output to files, logs, etc.)
/// - A custom implementation
pub enum ConsoleSink {
    /// Capture output in memory (for testing).
    Capture(Vec<CapturedLine>),
    /// Write to an io::Write implementation.
    Writer(Box<dyn Write + Send>),
}

impl ConsoleSink {
    /// Create a capture sink for testing.
    #[must_use]
    pub fn capture() -> Self {
        Self::Capture(Vec::new())
    }

    /// Create a writer sink.
    pub fn writer<W: Write + Send + 'static>(w: W) -> Self {
        Self::Writer(Box::new(w))
    }

    /// Write a line to the sink.
    fn write_line(&mut self, line: &ConsoleBuffer) -> io::Result<()> {
        match self {
            Self::Capture(lines) => {
                lines.push(line.to_captured());
                Ok(())
            }
            Self::Writer(w) => {
                // Write plain text (styles are captured but not rendered)
                for seg in &line.segments {
                    let safe = sanitize(&seg.text);
                    w.write_all(safe.as_bytes())?;
                }
                w.write_all(b"\n")?;
                Ok(())
            }
        }
    }

    /// Flush the sink.
    fn flush(&mut self) -> io::Result<()> {
        match self {
            Self::Capture(_) => Ok(()),
            Self::Writer(w) => w.flush(),
        }
    }

    /// Get captured lines (only valid for Capture sink).
    #[must_use]
    pub fn captured(&self) -> Option<&[CapturedLine]> {
        match self {
            Self::Capture(lines) => Some(lines),
            Self::Writer(_) => None,
        }
    }
}

impl std::fmt::Debug for ConsoleSink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Capture(lines) => f.debug_tuple("Capture").field(&lines.len()).finish(),
            Self::Writer(_) => f.debug_tuple("Writer").finish(),
        }
    }
}

// ============================================================================
// Captured Output
// ============================================================================

/// A captured line of console output.
#[derive(Debug, Clone)]
pub struct CapturedLine {
    /// Segments in this line.
    pub segments: Vec<CapturedSegment>,
}

impl CapturedLine {
    /// Create a captured line from plain (unstyled) text.
    #[must_use]
    pub fn from_plain(text: &str) -> Self {
        Self {
            segments: vec![CapturedSegment {
                text: text.to_string(),
                style: Style::default(),
            }],
        }
    }

    /// Get the plain text of this line.
    #[must_use]
    pub fn plain_text(&self) -> String {
        self.segments.iter().map(|s| s.text.as_str()).collect()
    }

    /// Get the total display width.
    #[must_use]
    pub fn width(&self) -> usize {
        self.segments.iter().map(|s| display_width(&s.text)).sum()
    }
}

/// A captured segment of styled text.
#[derive(Debug, Clone)]
pub struct CapturedSegment {
    /// The text content.
    pub text: String,
    /// The applied style (merged from style stack).
    pub style: Style,
}

// ============================================================================
// Console Buffer
// ============================================================================

/// Internal line buffer.
#[derive(Debug, Clone, Default)]
struct ConsoleBuffer {
    segments: Vec<BufferSegment>,
    width: usize,
}

#[derive(Debug, Clone)]
struct BufferSegment {
    text: String,
    style: Style,
}

impl ConsoleBuffer {
    fn new() -> Self {
        Self::default()
    }

    fn push(&mut self, text: &str, style: Style) {
        let width = display_width(text);
        self.segments.push(BufferSegment {
            text: text.to_string(),
            style,
        });
        self.width += width;
    }

    fn clear(&mut self) {
        self.segments.clear();
        self.width = 0;
    }

    fn is_empty(&self) -> bool {
        self.segments.is_empty() || self.segments.iter().all(|s| s.text.is_empty())
    }

    fn to_captured(&self) -> CapturedLine {
        CapturedLine {
            segments: self
                .segments
                .iter()
                .map(|s| CapturedSegment {
                    text: s.text.clone(),
                    style: s.style,
                })
                .collect(),
        }
    }
}

// ============================================================================
// Console
// ============================================================================

/// Ergonomic console output helper.
///
/// Provides rich-style output adapted to ftui's constraints:
/// - Segment-first (structured text + style)
/// - One-writer safe (no ad-hoc terminal writes)
/// - Width-aware wrapping
/// - Style stack for nested styling
pub struct Console {
    width: usize,
    sink: ConsoleSink,
    wrap_mode: WrapMode,
    style_stack: Vec<Style>,
    current_line: ConsoleBuffer,
    line_count: usize,
}

impl Console {
    /// Create a new console with the specified width and sink.
    #[must_use]
    pub fn new(width: usize, sink: ConsoleSink) -> Self {
        Self::with_options(width, sink, WrapMode::Word)
    }

    /// Create a new console with custom wrap mode.
    #[must_use]
    pub fn with_options(width: usize, sink: ConsoleSink, wrap_mode: WrapMode) -> Self {
        Self {
            width,
            sink,
            wrap_mode,
            style_stack: Vec::new(),
            current_line: ConsoleBuffer::new(),
            line_count: 0,
        }
    }

    /// Get the console width.
    #[must_use]
    pub const fn width(&self) -> usize {
        self.width
    }

    /// Get the number of lines written.
    #[must_use]
    pub const fn line_count(&self) -> usize {
        self.line_count
    }

    /// Get the current merged style from the style stack.
    #[must_use]
    pub fn current_style(&self) -> Style {
        let mut merged = Style::default();
        for style in &self.style_stack {
            merged = merged.merge(style);
        }
        merged
    }

    /// Push a style onto the stack.
    ///
    /// The style will be merged with existing styles for all subsequent output
    /// until `pop_style` is called.
    pub fn push_style(&mut self, style: Style) {
        self.style_stack.push(style);
    }

    /// Pop a style from the stack.
    ///
    /// Returns the popped style, or `None` if the stack was empty.
    pub fn pop_style(&mut self) -> Option<Style> {
        self.style_stack.pop()
    }

    /// Clear the style stack.
    pub fn clear_styles(&mut self) {
        self.style_stack.clear();
    }

    /// Print a segment.
    ///
    /// The segment's style is merged with the current style stack.
    pub fn print(&mut self, segment: Segment<'_>) {
        let base_style = self.current_style();
        let style = if let Some(seg_style) = segment.style {
            base_style.merge(&seg_style)
        } else {
            base_style
        };

        let text = segment.text.as_ref();

        // Handle control codes
        if let Some(controls) = &segment.control {
            for control in controls {
                if control.is_newline() {
                    self.newline();
                } else if control.is_cr() {
                    // Carriage return: clear current line
                    self.current_line.clear();
                }
            }
        }

        if text.is_empty() {
            return;
        }

        match self.wrap_mode {
            WrapMode::None => {
                self.current_line.push(text, style);
            }
            WrapMode::Word => {
                self.print_word_wrapped(text, style);
            }
            WrapMode::Character => {
                self.print_char_wrapped(text, style);
            }
        }
    }

    /// Print text with word wrapping.
    fn print_word_wrapped(&mut self, text: &str, style: Style) {
        let mut remaining = text;

        while !remaining.is_empty() {
            let remaining_width = self.width.saturating_sub(self.current_line.width);

            if remaining_width == 0 {
                self.flush_line();
                continue;
            }

            // Find next word boundary
            let (word, rest) = split_next_word(remaining);

            if word.is_empty() {
                // Only whitespace left
                if !rest.is_empty() {
                    self.current_line.push(rest, style);
                }
                break;
            }

            let word_width = display_width(word);

            if word_width <= remaining_width {
                // Word fits on current line
                self.current_line.push(word, style);
                remaining = rest;
            } else if self.current_line.is_empty() {
                // Word doesn't fit but line is empty - char wrap
                let (fits, _overflow) = split_at_width(word, remaining_width);
                if !fits.is_empty() {
                    self.current_line.push(fits, style);
                    self.flush_line();
                    // Continue with overflow + rest (everything after fits)
                    remaining = &remaining[fits.len()..];
                } else {
                    // First character is too wide to fit - push it anyway to avoid infinite loop
                    let first_grapheme_end = word
                        .grapheme_indices(true)
                        .nth(1)
                        .map(|(i, _)| i)
                        .unwrap_or(word.len());
                    self.current_line.push(&word[..first_grapheme_end], style);
                    self.flush_line();
                    // Continue after the first char (in remaining, not word, to preserve rest)
                    remaining = &remaining[first_grapheme_end..];
                }
            } else {
                // Word doesn't fit - wrap to next line
                self.flush_line();
            }
        }
    }

    /// Print text with character wrapping.
    fn print_char_wrapped(&mut self, text: &str, style: Style) {
        let mut remaining = text;

        while !remaining.is_empty() {
            let remaining_width = self.width.saturating_sub(self.current_line.width);

            if remaining_width == 0 {
                self.flush_line();
                continue;
            }

            let (fits, overflow) = split_at_width(remaining, remaining_width);
            if !fits.is_empty() {
                self.current_line.push(fits, style);
                remaining = overflow;
            } else {
                // First character is too wide to fit - flush and try again
                // If line is empty and still can't fit, push it anyway to avoid infinite loop
                if self.current_line.is_empty() {
                    // Push first char even if too wide
                    let first_grapheme_end = remaining
                        .grapheme_indices(true)
                        .nth(1)
                        .map(|(i, _)| i)
                        .unwrap_or(remaining.len());
                    self.current_line
                        .push(&remaining[..first_grapheme_end], style);
                    remaining = &remaining[first_grapheme_end..];
                }
                self.flush_line();
            }
        }
    }

    /// Print styled text.
    ///
    /// Convenience method that creates a segment and prints it.
    pub fn print_styled(&mut self, text: impl Into<Cow<'static, str>>, style: Style) {
        self.print(Segment::styled(text, style));
    }

    /// Print plain text.
    ///
    /// Convenience method that creates a segment and prints it.
    pub fn print_text(&mut self, text: impl Into<Cow<'static, str>>) {
        self.print(Segment::text(text));
    }

    /// Print a newline.
    pub fn newline(&mut self) {
        self.flush_line();
    }

    /// Print text followed by a newline.
    pub fn println(&mut self, segment: Segment<'_>) {
        self.print(segment);
        self.newline();
    }

    /// Print styled text followed by a newline.
    pub fn println_styled(&mut self, text: impl Into<Cow<'static, str>>, style: Style) {
        self.print_styled(text, style);
        self.newline();
    }

    /// Print plain text followed by a newline.
    pub fn println_text(&mut self, text: impl Into<Cow<'static, str>>) {
        self.print_text(text);
        self.newline();
    }

    /// Print a blank line.
    pub fn blank_line(&mut self) {
        self.flush_line();
        let _ = self.sink.write_line(&ConsoleBuffer::new());
        self.line_count += 1;
    }

    /// Print a horizontal rule.
    pub fn rule(&mut self, char: char) {
        self.flush_line();
        let rule_text: String = std::iter::repeat_n(char, self.width).collect();
        self.current_line.push(&rule_text, self.current_style());
        self.flush_line();
    }

    /// Flush the current line to the sink.
    fn flush_line(&mut self) {
        if !self.current_line.is_empty() {
            let _ = self.sink.write_line(&self.current_line);
            self.line_count += 1;
        }
        self.current_line.clear();
    }

    /// Flush any remaining output.
    pub fn flush(&mut self) -> io::Result<()> {
        self.flush_line();
        self.sink.flush()
    }

    /// Consume the console and return captured output (if using capture sink).
    #[must_use]
    pub fn into_captured(mut self) -> String {
        self.flush_line();
        match self.sink {
            ConsoleSink::Capture(lines) => lines
                .iter()
                .map(CapturedLine::plain_text)
                .collect::<Vec<_>>()
                .join("\n"),
            ConsoleSink::Writer(_) => String::new(),
        }
    }

    /// Consume the console and return captured lines (if using capture sink).
    #[must_use]
    pub fn into_captured_lines(mut self) -> Vec<CapturedLine> {
        self.flush_line();
        match self.sink {
            ConsoleSink::Capture(lines) => lines,
            ConsoleSink::Writer(_) => Vec::new(),
        }
    }

    /// Get access to the sink.
    #[must_use]
    pub fn sink(&self) -> &ConsoleSink {
        &self.sink
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Split text at the next word boundary.
///
/// Returns (word_including_trailing_space, rest).
fn split_next_word(text: &str) -> (&str, &str) {
    // Skip leading whitespace
    let start = text
        .char_indices()
        .find(|(_, c)| !c.is_whitespace())
        .map(|(i, _)| i)
        .unwrap_or(text.len());

    if start == text.len() {
        return (text, "");
    }

    // Find end of word
    let end = text[start..]
        .char_indices()
        .find(|(_, c)| c.is_whitespace())
        .map(|(i, _)| start + i)
        .unwrap_or(text.len());

    // Include one trailing space if present
    let end_with_space = if end < text.len() && text[end..].starts_with(' ') {
        end + 1
    } else {
        end
    };

    (&text[..end_with_space], &text[end_with_space..])
}

/// Split text at approximately the given display width.
///
/// Returns (fits, overflow) where `fits.width() <= max_width`.
fn split_at_width(text: &str, max_width: usize) -> (&str, &str) {
    if display_width(text) <= max_width {
        return (text, "");
    }

    let mut width = 0;
    let mut split_idx = 0;

    for grapheme in text.graphemes(true) {
        let g_width = grapheme_width(grapheme);
        if width + g_width > max_width {
            break;
        }
        width += g_width;
        split_idx += grapheme.len();
    }

    (&text[..split_idx], &text[split_idx..])
}

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

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

    const RED: PackedRgba = PackedRgba::rgb(255, 0, 0);
    const BLUE: PackedRgba = PackedRgba::rgb(0, 0, 255);

    #[test]
    fn console_basic_output() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.print_text("Hello, world!");
        console.newline();

        let output = console.into_captured();
        assert_eq!(output, "Hello, world!");
    }

    #[test]
    fn console_styled_output() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.print(Segment::styled("Bold", Style::new().bold()));
        console.newline();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].segments[0].text, "Bold");
        assert!(lines[0].segments[0].style.has_attr(StyleFlags::BOLD));
    }

    #[test]
    fn console_style_stack() {
        let sink = ConsoleSink::capture();
        // Use WrapMode::None to avoid word-splitting segments
        let mut console = Console::with_options(80, sink, WrapMode::None);

        console.push_style(Style::new().fg(RED));
        console.print_text("Red");
        console.push_style(Style::new().bold());
        console.print_text("Bold");
        console.pop_style();
        console.print_text("Red");
        console.newline();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].segments.len(), 3);

        // First segment: red
        assert_eq!(lines[0].segments[0].style.fg, Some(RED));
        assert!(!lines[0].segments[0].style.has_attr(StyleFlags::BOLD));

        // Second segment: red + bold
        assert_eq!(lines[0].segments[1].style.fg, Some(RED));
        assert!(lines[0].segments[1].style.has_attr(StyleFlags::BOLD));

        // Third segment: red only
        assert_eq!(lines[0].segments[2].style.fg, Some(RED));
        assert!(!lines[0].segments[2].style.has_attr(StyleFlags::BOLD));
    }

    #[test]
    fn console_word_wrap() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(20, sink, WrapMode::Word);

        console.print_text("This is a test of word wrapping in the console.");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        assert!(lines.len() > 1);

        // Each line should be <= 20 chars wide
        for line in &lines {
            assert!(line.width() <= 20, "Line too wide: {:?}", line.plain_text());
        }
    }

    #[test]
    fn console_word_wrap_long_word_with_rest() {
        // Regression test: long word followed by more text should not lose the rest
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(10, sink, WrapMode::Word);

        console.print_text("superlongword more text");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        let all_text: String = lines
            .iter()
            .map(|l| l.plain_text())
            .collect::<Vec<_>>()
            .join("");
        // Verify no text was lost
        assert_eq!(all_text.replace(" ", ""), "superlongwordmoretext");

        // Verify all lines fit within width
        for line in &lines {
            assert!(line.width() <= 10, "Line too wide: {:?}", line.plain_text());
        }
    }

    #[test]
    fn console_word_wrap_wide_char_boundary() {
        // Test word wrap with wide characters that need char-wrapping
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(3, sink, WrapMode::Word);

        console.print_text("中文 test");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        let all_text: String = lines
            .iter()
            .map(|l| l.plain_text())
            .collect::<Vec<_>>()
            .join("");
        // Verify no text was lost (including space handling)
        assert!(all_text.contains("中") && all_text.contains("文") && all_text.contains("test"));
    }

    #[test]
    fn console_char_wrap() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(10, sink, WrapMode::Character);

        console.print_text("HelloWorld123456");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "HelloWorld");
        assert_eq!(lines[1].plain_text(), "123456");
    }

    #[test]
    fn console_no_wrap() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(10, sink, WrapMode::None);

        console.print_text("This text is longer than 10 chars");
        console.newline();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert!(lines[0].width() > 10);
    }

    #[test]
    fn console_rule() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(10, sink);

        console.rule('-');

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "----------");
    }

    #[test]
    fn console_blank_line() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.print_text("Before");
        console.newline();
        console.blank_line();
        console.print_text("After");
        console.newline();

        let output = console.into_captured();
        assert_eq!(output, "Before\n\nAfter");
    }

    #[test]
    fn console_line_count() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        assert_eq!(console.line_count(), 0);

        console.println_text("Line 1");
        assert_eq!(console.line_count(), 1);

        console.println_text("Line 2");
        assert_eq!(console.line_count(), 2);
    }

    #[test]
    fn split_next_word_basic() {
        assert_eq!(split_next_word("hello world"), ("hello ", "world"));
        assert_eq!(split_next_word("hello"), ("hello", ""));
        assert_eq!(split_next_word("  hello"), ("  hello", ""));
        assert_eq!(split_next_word(""), ("", ""));
    }

    #[test]
    fn split_at_width_basic() {
        assert_eq!(split_at_width("hello", 10), ("hello", ""));
        assert_eq!(split_at_width("hello", 3), ("hel", "lo"));
        assert_eq!(split_at_width("hello", 0), ("", "hello"));
    }

    #[test]
    fn split_at_width_wide_chars() {
        // Wide char '中' has width 2
        assert_eq!(split_at_width("中文", 2), ("中", "文"));
        assert_eq!(split_at_width("中文", 1), ("", "中文")); // Can't fit
        assert_eq!(split_at_width("中文", 4), ("中文", ""));
    }

    #[test]
    fn console_wide_char_wrap() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(5, sink, WrapMode::Character);

        console.print_text("中文测试");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        // Each wide char is 2 cells, so "中文" = 4, "测试" = 4
        // Width 5 means "中文" fits (4 <= 5), then "测" fits (2 <= 5)
        assert_eq!(lines[0].plain_text(), "中文");
        assert_eq!(lines[1].plain_text(), "测试");
    }

    #[test]
    fn console_segment_with_newline() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.print(Segment::text("Line 1"));
        console.print(Segment::newline());
        console.print(Segment::text("Line 2"));
        console.newline();

        let output = console.into_captured();
        assert_eq!(output, "Line 1\nLine 2");
    }

    #[test]
    fn console_clear_styles() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.push_style(Style::new().bold());
        console.push_style(Style::new().italic());
        assert_eq!(console.style_stack.len(), 2);

        console.clear_styles();
        assert_eq!(console.style_stack.len(), 0);
    }

    #[test]
    fn console_current_style_merges() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.push_style(Style::new().fg(RED));
        console.push_style(Style::new().bg(BLUE).bold());

        let current = console.current_style();
        assert_eq!(current.fg, Some(RED));
        assert_eq!(current.bg, Some(BLUE));
        assert!(current.has_attr(StyleFlags::BOLD));
    }

    // --- ConsoleSink ---

    #[test]
    fn console_sink_capture_is_empty_initially() {
        let sink = ConsoleSink::capture();
        assert_eq!(sink.captured().unwrap().len(), 0);
    }

    #[test]
    fn console_sink_writer_returns_none_for_captured() {
        let sink = ConsoleSink::writer(Vec::<u8>::new());
        assert!(sink.captured().is_none());
    }

    #[test]
    fn console_sink_writer_output() {
        let buf: Vec<u8> = Vec::new();
        let sink = ConsoleSink::writer(buf);
        let mut console = Console::new(80, sink);

        console.println_text("hello");
        console.flush().unwrap();

        // into_captured returns empty string for writer sinks
        let output = console.into_captured();
        assert_eq!(output, "");
    }

    #[derive(Clone, Default)]
    struct SharedWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    impl Write for SharedWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0
                .lock()
                .map_err(|_| io::Error::other("poisoned test writer"))?
                .extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn console_sink_writer_sanitizes_escape_injection_payloads() {
        let shared = SharedWriter::default();
        let probe = shared.clone();
        let sink = ConsoleSink::writer(shared);
        let mut console = Console::new(80, sink);

        console.println_text("safe\x1b]52;c;SGVsbG8=\x1b\\tail\u{009d}x");
        console.flush().unwrap();

        let bytes = probe.0.lock().unwrap().clone();
        let output = String::from_utf8(bytes).unwrap();
        assert!(
            output.contains("safetailx\n"),
            "visible payload should be preserved"
        );
        assert!(
            !output.contains("52;c;SGVsbG8"),
            "OSC payload must not be forwarded by writer sink"
        );
        assert!(
            !output.contains('\u{009d}'),
            "C1 controls must be stripped from writer sink output"
        );
    }

    #[test]
    fn console_sink_debug_format() {
        let cap = ConsoleSink::capture();
        let dbg = format!("{:?}", cap);
        assert!(dbg.contains("Capture"));

        let w = ConsoleSink::writer(Vec::<u8>::new());
        let dbg = format!("{:?}", w);
        assert!(dbg.contains("Writer"));
    }

    // --- CapturedLine ---

    #[test]
    fn captured_line_from_plain() {
        let line = CapturedLine::from_plain("abc");
        assert_eq!(line.plain_text(), "abc");
        assert_eq!(line.width(), 3);
        assert_eq!(line.segments.len(), 1);
        assert_eq!(line.segments[0].style, Style::default());
    }

    #[test]
    fn captured_line_width_with_wide_chars() {
        let line = CapturedLine::from_plain("中文");
        assert_eq!(line.width(), 4); // each CJK char = 2 columns
    }

    #[test]
    fn captured_line_empty() {
        let line = CapturedLine::from_plain("");
        assert_eq!(line.plain_text(), "");
        assert_eq!(line.width(), 0);
    }

    // --- ConsoleBuffer ---

    #[test]
    fn console_buffer_is_empty_when_only_empty_segments() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(80, sink, WrapMode::None);

        // Print empty text — should not create a real line
        console.print_text("");
        console.newline();

        // flush_line only writes if !is_empty, and is_empty returns true
        // if all segments have empty text
        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 0);
    }

    // --- WrapMode ---

    #[test]
    fn wrap_mode_default_is_word() {
        assert_eq!(WrapMode::default(), WrapMode::Word);
    }

    // --- Console construction ---

    #[test]
    fn console_width_accessor() {
        let console = Console::new(42, ConsoleSink::capture());
        assert_eq!(console.width(), 42);
    }

    #[test]
    fn console_with_options_sets_wrap_mode() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(10, sink, WrapMode::Character);

        console.print_text("ABCDEFGHIJKLM");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        assert_eq!(lines[0].plain_text(), "ABCDEFGHIJ"); // character-wrapped
    }

    // --- Style stack edge cases ---

    #[test]
    fn pop_style_on_empty_stack_returns_none() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        assert!(console.pop_style().is_none());
    }

    #[test]
    fn pop_style_returns_pushed_style() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        let style = Style::new().bold();
        console.push_style(style);
        let popped = console.pop_style().unwrap();
        assert!(popped.has_attr(StyleFlags::BOLD));
    }

    #[test]
    fn current_style_empty_stack_is_default() {
        let console = Console::new(80, ConsoleSink::capture());
        assert_eq!(console.current_style(), Style::default());
    }

    #[test]
    fn style_stack_deep_nesting() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.push_style(Style::new().fg(RED));
        console.push_style(Style::new().bg(BLUE));
        console.push_style(Style::new().bold());
        console.push_style(Style::new().italic());

        let merged = console.current_style();
        assert_eq!(merged.fg, Some(RED));
        assert_eq!(merged.bg, Some(BLUE));
        assert!(merged.has_attr(StyleFlags::BOLD));
        assert!(merged.has_attr(StyleFlags::ITALIC));
    }

    // --- print_styled / println_styled ---

    #[test]
    fn println_styled_includes_newline() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.println_styled("styled line", Style::new().bold());

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "styled line");
        assert!(lines[0].segments[0].style.has_attr(StyleFlags::BOLD));
    }

    #[test]
    fn print_styled_merges_with_stack() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(80, sink, WrapMode::None);

        console.push_style(Style::new().fg(RED));
        console.print_styled("text", Style::new().bold());
        console.newline();

        let lines = console.into_captured_lines();
        // Should have RED from stack + BOLD from segment
        assert_eq!(lines[0].segments[0].style.fg, Some(RED));
        assert!(lines[0].segments[0].style.has_attr(StyleFlags::BOLD));
    }

    // --- println / println_text ---

    #[test]
    fn println_text_creates_line() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.println_text("hello");
        console.println_text("world");

        let output = console.into_captured();
        assert_eq!(output, "hello\nworld");
    }

    // --- blank_line ---

    #[test]
    fn blank_line_increments_line_count() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.blank_line();
        assert_eq!(console.line_count(), 1);

        console.blank_line();
        assert_eq!(console.line_count(), 2);
    }

    // --- rule ---

    #[test]
    fn rule_uses_custom_character() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(5, sink);

        console.rule('=');

        let lines = console.into_captured_lines();
        assert_eq!(lines[0].plain_text(), "=====");
    }

    #[test]
    fn rule_with_pending_content_flushes_first() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(10, sink, WrapMode::None);

        console.print_text("hello");
        console.rule('-');

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "hello");
        assert_eq!(lines[1].plain_text(), "----------");
    }

    // --- into_captured_lines for Writer sink ---

    #[test]
    fn into_captured_lines_returns_empty_for_writer() {
        let sink = ConsoleSink::writer(Vec::<u8>::new());
        let console = Console::new(80, sink);
        let lines = console.into_captured_lines();
        assert!(lines.is_empty());
    }

    // --- Word wrapping edge cases ---

    #[test]
    fn word_wrap_single_space() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(80, sink, WrapMode::Word);

        console.print_text(" ");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), " ");
    }

    #[test]
    fn word_wrap_exact_width_fit() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(5, sink, WrapMode::Word);

        console.print_text("abcde");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "abcde");
    }

    #[test]
    fn word_wrap_width_1() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(1, sink, WrapMode::Word);

        console.print_text("abc");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        // Each char gets its own line
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0].plain_text(), "a");
        assert_eq!(lines[1].plain_text(), "b");
        assert_eq!(lines[2].plain_text(), "c");
    }

    // --- Character wrapping edge cases ---

    #[test]
    fn char_wrap_exact_multiple() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(3, sink, WrapMode::Character);

        console.print_text("abcdef");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "abc");
        assert_eq!(lines[1].plain_text(), "def");
    }

    #[test]
    fn char_wrap_wide_char_at_boundary() {
        // Width 3: can't fit a 2-wide char in the last 1 cell
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(3, sink, WrapMode::Character);

        console.print_text("a中b");
        console.flush().unwrap();

        let lines = console.into_captured_lines();
        // "a" fits (1/3), "中" fits (3/3), then "b" wraps
        assert_eq!(lines[0].plain_text(), "a中");
        assert_eq!(lines[1].plain_text(), "b");
    }

    // --- split_next_word ---

    #[test]
    fn split_next_word_multiple_spaces() {
        let (word, rest) = split_next_word("  hello  world");
        // Skips leading whitespace, finds "hello", includes one trailing space
        assert_eq!(word, "  hello ");
        assert_eq!(rest, " world");
    }

    #[test]
    fn split_next_word_all_whitespace() {
        let (word, rest) = split_next_word("   ");
        // All whitespace: start == text.len() path
        assert_eq!(word, "   ");
        assert_eq!(rest, "");
    }

    #[test]
    fn split_next_word_no_trailing_space() {
        let (word, rest) = split_next_word("word");
        assert_eq!(word, "word");
        assert_eq!(rest, "");
    }

    #[test]
    fn split_next_word_tab_as_whitespace() {
        let (word, rest) = split_next_word("hello\tworld");
        // \t is whitespace, so splits there
        assert_eq!(word, "hello");
        assert_eq!(rest, "\tworld");
    }

    // --- split_at_width ---

    #[test]
    fn split_at_width_already_fits() {
        assert_eq!(split_at_width("ab", 10), ("ab", ""));
    }

    #[test]
    fn split_at_width_empty() {
        assert_eq!(split_at_width("", 5), ("", ""));
    }

    #[test]
    fn split_at_width_zero_width() {
        assert_eq!(split_at_width("abc", 0), ("", "abc"));
    }

    // --- Multiple segments on one line ---

    #[test]
    fn multiple_prints_same_line() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(80, sink, WrapMode::None);

        console.print_text("Hello, ");
        console.print_text("world!");
        console.newline();

        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "Hello, world!");
        assert_eq!(lines[0].segments.len(), 2);
    }

    // --- Flush behavior ---

    #[test]
    fn flush_writes_pending_content() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.print_text("pending");
        assert_eq!(console.line_count(), 0);

        console.flush().unwrap();
        assert_eq!(console.line_count(), 1);
    }

    #[test]
    fn into_captured_flushes_pending() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.print_text("no newline");
        // into_captured should flush
        let output = console.into_captured();
        assert_eq!(output, "no newline");
    }

    #[test]
    fn into_captured_lines_flushes_pending() {
        let sink = ConsoleSink::capture();
        let mut console = Console::new(80, sink);

        console.print_text("no newline");
        let lines = console.into_captured_lines();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "no newline");
    }

    // --- Segment style override ---

    #[test]
    fn segment_style_supplements_stack() {
        let sink = ConsoleSink::capture();
        let mut console = Console::with_options(80, sink, WrapMode::None);

        console.push_style(Style::new().fg(RED));
        // Segment adds BOLD on top of stack's RED fg
        console.print(Segment::styled("text", Style::new().bold()));
        console.newline();

        let lines = console.into_captured_lines();
        // Stack's fg persists, segment's bold merges in
        assert_eq!(lines[0].segments[0].style.fg, Some(RED));
        assert!(lines[0].segments[0].style.has_attr(StyleFlags::BOLD));
    }
}