1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
use crate::attr::Attr;
use crate::backend::Backend;
use crate::cell::Cell;
use crate::color::{Color, ColorPair};
use crate::delta::DirtyRegion;
use crate::error::{Error, Result};
use crate::input::Key;
use crate::surface::Surface;
use smallvec::SmallVec;
use std::collections::HashMap;
use std::fmt::Write;
/// Main screen interface
pub struct Screen {
cursor_x: u16,
cursor_y: u16,
rows: u16,
cols: u16,
current_attr: Attr,
current_fg: Color,
current_bg: Color,
// notcurses-style base cell: any cell with id=0 (terminal default) is
// resolved to these at emission time. Prevents terminal-default bg from
// leaking through for unwritten cells or erase ops (DL/IL/ECH).
base_fg: Color,
base_bg: Color,
// True when the physical terminal hasn't yet been primed with the
// current base. Next refresh emits SGR(base) + `\x1b[2J` so the
// terminal fills with base bg before any diff emission.
base_needs_prime: bool,
color_pairs: HashMap<u8, ColorPair>,
cursor_visible: bool,
cursor_style: u8,
cursor_position: Option<(u16, u16)>,
buffer: String,
// Performance optimization: track last emitted style to avoid redundant codes
last_emitted_attr: Attr,
last_emitted_fg: Color,
last_emitted_bg: Color,
// Performance optimization: SmallVec for ANSI sequences (stack-allocated for <64 bytes)
// Most style sequences are <64 bytes, avoiding heap allocation in 95%+ of cases
style_sequence_buf: SmallVec<[u8; 64]>,
// Performance optimization: double-buffering for delta updates
current_content: Vec<Vec<Cell>>,
pending_content: Vec<Vec<Cell>>,
dirty_lines: Vec<DirtyRegion>,
// Performance optimization: interrupt-driven refresh
#[cfg(unix)]
stdin_fd: std::os::unix::io::RawFd,
check_interval: usize,
fifo_hold: bool,
color_table: crate::cell::ColorTable,
}
impl Screen {
/// Initialize the screen
pub fn init() -> Result<Self> {
Backend::init()?;
// Performance optimization: pre-allocate buffer based on terminal size
// Estimate: ~10 bytes per cell (ANSI codes + character)
let (rows, cols) = Backend::get_terminal_size().unwrap_or((24, 80));
let estimated_capacity = (rows as usize * cols as usize * 10).min(65536); // Cap at 64KB
// Initialize screen buffers with blank cells
let current_content = vec![vec![Cell::blank(); cols as usize]; rows as usize];
let pending_content = vec![vec![Cell::blank(); cols as usize]; rows as usize];
let dirty_lines = vec![DirtyRegion::clean(); rows as usize];
Ok(Self {
cursor_x: 0,
cursor_y: 0,
rows,
cols,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::with_capacity(estimated_capacity),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(), // Stack-allocated for sequences <64 bytes
current_content,
pending_content,
dirty_lines,
#[cfg(unix)]
stdin_fd: 0, // Standard input file descriptor
check_interval: 5, // Check for input every 5 lines (default)
fifo_hold: false, // Allow input checking by default
color_table: crate::cell::ColorTable::new(),
})
}
/// Clean up and restore terminal
pub fn endwin(self) -> Result<()> {
// Reset cursor style and show cursor before cleanup
crate::platform_io::write_all_stdout(b"\x1b[0 q\x1b[?25h")?;
Backend::cleanup()
}
/// Get terminal size (rows, cols)
pub fn get_size(&self) -> Result<(u16, u16)> {
Backend::get_terminal_size()
}
/// Move cursor to position (y, x)
pub fn move_cursor(&mut self, y: u16, x: u16) -> Result<()> {
// Performance optimization: use relative cursor movement for short distances
let dy = (y as i32 - self.cursor_y as i32).abs();
let dx = (x as i32 - self.cursor_x as i32).abs();
// Threshold: use relative movement if distance < 4 cells
// (relative sequences are shorter for small distances)
if dy == 0 && dx > 0 && dx < 4 {
// Horizontal movement only
if x > self.cursor_x {
write!(self.buffer, "\x1b[{}C", dx)?; // CUF - Cursor Forward
} else {
write!(self.buffer, "\x1b[{}D", dx)?; // CUB - Cursor Back
}
} else if dx == 0 && dy > 0 && dy < 4 {
// Vertical movement only
if y > self.cursor_y {
write!(self.buffer, "\x1b[{}B", dy)?; // CUD - Cursor Down
} else {
write!(self.buffer, "\x1b[{}A", dy)?; // CUU - Cursor Up
}
} else {
// Use absolute positioning for long distances or diagonal movement
write!(self.buffer, "\x1b[{};{}H", y + 1, x + 1)?; // CUP - Cursor Position
}
self.cursor_y = y;
self.cursor_x = x;
Ok(())
}
/// Print text at current cursor position. Advances the cursor by the
/// text's display width (cells), not its byte length — so multi-byte
/// graphemes like `│` or `中` don't leave the cell grid out of sync
/// with the terminal's cursor.
pub fn print(&mut self, text: &str) -> Result<()> {
use unicode_width::UnicodeWidthChar;
if self.cursor_y >= self.rows || self.cursor_x >= self.cols {
return Ok(());
}
let start_x = self.cursor_x as usize;
let y = self.cursor_y as usize;
let mut x = start_x;
// Write one cell per char, advancing by the char's display width.
// Wide chars (width 2) occupy two cells; we write the char into
// the leading cell and leave the trailing cell untouched — the
// terminal advances its cursor by 2, so we do too.
for ch in text.chars() {
if x >= self.cols as usize {
break;
}
let w = UnicodeWidthChar::width(ch).unwrap_or(1).max(1);
let fg_id = self.color_table.color_to_id(self.current_fg);
let bg_id = self.color_table.color_to_id(self.current_bg);
let cell = Cell::pack(ch, self.current_attr, fg_id, bg_id);
self.pending_content[y][x] = cell;
x += w;
}
let end_x = x.min(self.cols as usize).saturating_sub(1);
self.dirty_lines[y].mark(start_x as u16, end_x as u16);
self.cursor_x = (x as u16).min(self.cols);
Ok(())
}
/// Move cursor and print (like mvprintw)
pub fn move_print(&mut self, y: u16, x: u16, text: &str) -> Result<()> {
self.move_cursor(y, x)?;
self.print(text)
}
/// Add a single character
pub fn add_char(&mut self, ch: char) -> Result<()> {
if self.cursor_y >= self.rows || self.cursor_x >= self.cols {
return Ok(()); // Out of bounds
}
let y = self.cursor_y as usize;
let x = self.cursor_x as usize;
// Write character to pending buffer
let fg_id = self.color_table.color_to_id(self.current_fg);
let bg_id = self.color_table.color_to_id(self.current_bg);
let cell = Cell::pack(ch, self.current_attr, fg_id, bg_id);
self.pending_content[y][x] = cell;
self.dirty_lines[y].mark(x as u16, x as u16);
self.cursor_x += 1;
Ok(())
}
/// Move cursor and add character
pub fn move_add_char(&mut self, y: u16, x: u16, ch: char) -> Result<()> {
self.move_cursor(y, x)?;
self.add_char(ch)
}
/// Turn on attributes
pub fn add_attribute(&mut self, attr: Attr) -> Result<()> {
self.current_attr = self.current_attr | attr;
Ok(())
}
/// Turn off attributes
pub fn remove_attribute(&mut self, attr: Attr) -> Result<()> {
self.current_attr = self.current_attr & !attr;
Ok(())
}
/// Set attributes
pub fn set_attribute(&mut self, attr: Attr) -> Result<()> {
self.current_attr = attr;
Ok(())
}
/// Initialize a color pair
pub fn init_pair(&mut self, pair: u8, fg: Color, bg: Color) -> Result<()> {
self.color_pairs.insert(pair, ColorPair::new(fg, bg));
Ok(())
}
/// Set current color pair
pub fn color_pair(&mut self, pair: u8) -> Result<()> {
let color_pair = self
.color_pairs
.get(&pair)
.ok_or(Error::InvalidColorPair(pair))?;
self.current_fg = color_pair.fg;
self.current_bg = color_pair.bg;
Ok(())
}
/// Set foreground color
pub fn set_foreground(&mut self, color: Color) -> Result<()> {
self.current_fg = color;
Ok(())
}
/// Set background color
pub fn set_background(&mut self, color: Color) -> Result<()> {
self.current_bg = color;
Ok(())
}
/// Set the base (default) fg/bg used to fill unwritten cells and prime
/// SGR before erase/scroll ops. Analogous to `ncplane_set_base` in
/// notcurses or `wbkgdset` in ncurses.
///
/// This ALSO repaints the physical screen with the base and updates the
/// internal state to match, so the terminal's post-init `\x1b[2J`
/// (which fills with terminal-default bg — usually black) no longer
/// leaks through for cells that the render path never writes to. After
/// set_base, both `current_content` and `pending_content` are filled
/// with a "base cell" (space with base fg/bg) — so `Cell::BLANK` never
/// appears as a stable state at diff time.
pub fn set_base(&mut self, fg: Color, bg: Color) -> Result<()> {
self.base_fg = fg;
self.base_bg = bg;
self.base_needs_prime = true;
// Fill internal content with the base cell so the diff never sees
// `Cell::BLANK` as a valid "current terminal state" — it IS base.
// The terminal-side prime happens on next refresh().
let base_cell = self.make_base_cell();
for row in &mut self.current_content {
for cell in row {
*cell = base_cell;
}
}
for row in &mut self.pending_content {
for cell in row {
*cell = base_cell;
}
}
Ok(())
}
fn make_base_cell(&mut self) -> Cell {
let fg_id = self.color_table.color_to_id(self.base_fg);
let bg_id = self.color_table.color_to_id(self.base_bg);
Cell::pack(' ', Attr::NORMAL, fg_id, bg_id)
}
/// Clear the entire screen
pub fn clear(&mut self) -> Result<()> {
// Fill pending with the base cell (space in plane bg) instead of
// `Cell::BLANK`, so that after clear() any cell the render path
// never overwrites is still a valid "base bg" cell at diff time.
// Matches notcurses's ncplane_erase, which fills with the base.
let fill = self.make_base_cell();
for row in &mut self.pending_content {
for cell in row {
*cell = fill;
}
}
for dirty in &mut self.dirty_lines {
*dirty = DirtyRegion::full(self.cols);
}
self.cursor_x = 0;
self.cursor_y = 0;
Ok(())
}
/// Clear to end of line
pub fn clear_to_end_of_line(&mut self) -> Result<()> {
if self.cursor_y >= self.rows {
return Ok(());
}
let y = self.cursor_y as usize;
let start_x = self.cursor_x as usize;
for x in start_x..self.cols as usize {
self.pending_content[y][x] = Cell::blank();
}
self.dirty_lines[y].mark(start_x as u16, self.cols - 1);
Ok(())
}
/// Clear to bottom of screen
pub fn clear_to_bottom_of_screen(&mut self) -> Result<()> {
if self.cursor_y >= self.rows {
return Ok(());
}
self.clear_to_end_of_line()?;
for y in (self.cursor_y + 1) as usize..self.rows as usize {
for x in 0..self.cols as usize {
self.pending_content[y][x] = Cell::blank();
}
self.dirty_lines[y] = DirtyRegion::full(self.cols);
}
Ok(())
}
/// Set cursor visibility
pub fn cursor_visible(&mut self, visible: bool) -> Result<()> {
self.cursor_visible = visible;
if visible {
write!(self.buffer, "\x1b[?25h")?;
} else {
write!(self.buffer, "\x1b[?25l")?;
}
Ok(())
}
/// Draw a box border
pub fn border(
&mut self,
ls: char,
rs: char,
ts: char,
bs: char,
tl: char,
tr: char,
bl: char,
br: char,
) -> Result<()> {
let (rows, cols) = self.get_size()?;
// Top border
self.move_add_char(0, 0, tl)?;
for _ in 1..cols - 1 {
self.add_char(ts)?;
}
self.add_char(tr)?;
// Sides
for y in 1..rows - 1 {
self.move_add_char(y, 0, ls)?;
self.move_add_char(y, cols - 1, rs)?;
}
// Bottom border
self.move_add_char(rows - 1, 0, bl)?;
for _ in 1..cols - 1 {
self.add_char(bs)?;
}
self.add_char(br)?;
Ok(())
}
/// Draw a box using ACS line-drawing characters
pub fn draw_box(&mut self) -> Result<()> {
use crate::acs::*;
self.border(
ACS_VLINE.as_char(),
ACS_VLINE.as_char(),
ACS_HLINE.as_char(),
ACS_HLINE.as_char(),
ACS_ULCORNER.as_char(),
ACS_URCORNER.as_char(),
ACS_LLCORNER.as_char(),
ACS_LRCORNER.as_char(),
)
}
/// Read a single key
pub fn get_char(&mut self) -> Result<Key> {
self.refresh()?;
Backend::read_key()
}
/// Read a key with timeout (in milliseconds). Returns None if timeout expires.
pub fn get_char_timeout(&mut self, timeout_ms: u64) -> Result<Option<Key>> {
self.refresh()?;
Backend::read_key_timeout(Some(timeout_ms))
}
/// Set how often to check for input during refresh (Phase 2.1 optimization)
///
/// Lower values = more responsive but slightly more CPU overhead
/// Higher values = less overhead but potential input lag
///
/// Default: 5 lines
pub fn set_check_interval(&mut self, lines: usize) {
self.check_interval = lines.max(1); // At least 1
}
/// Temporarily disable input checking during critical updates
///
/// Use when you need a consistent screen state without interruption
pub fn hold_refresh(&mut self) {
self.fifo_hold = true;
}
/// Re-enable input checking during refresh
pub fn release_refresh(&mut self) {
self.fifo_hold = false;
}
/// Check if input is pending (non-blocking)
///
/// Returns true if stdin has data available to read
#[cfg(unix)]
fn check_pending_input(&self) -> Result<bool> {
use libc::{POLLIN, poll, pollfd};
if self.fifo_hold {
return Ok(false);
}
let mut fds = [pollfd {
fd: self.stdin_fd,
events: POLLIN,
revents: 0,
}];
// Non-blocking poll (0 timeout)
let result = unsafe { poll(fds.as_mut_ptr(), 1, 0) };
if result < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::Interrupted {
return Ok(false); // EINTR - treat as no input
}
return Err(Error::Io(err));
}
// Check if input is available
Ok(result > 0 && (fds[0].revents & POLLIN) != 0)
}
#[cfg(not(unix))]
fn check_pending_input(&self) -> Result<bool> {
// Non-Unix platforms: always continue (could implement platform-specific later)
Ok(false)
}
/// Emit an SGR sequence setting fg/bg to the base. Used to prime the
/// terminal before DL/IL erase ops so newly-exposed lines fill with the
/// plane bg, not the user's terminal default. Idempotent: a no-op when
/// last_emitted already matches the base.
fn emit_base_sgr(&mut self) -> Result<()> {
let base_attr = Attr::NORMAL;
if self.last_emitted_attr == base_attr
&& self.last_emitted_fg == self.base_fg
&& self.last_emitted_bg == self.base_bg
{
return Ok(());
}
let mut color_buf = String::with_capacity(20);
self.style_sequence_buf.clear();
self.style_sequence_buf.push(b'0'); // reset any prior attrs
self.style_sequence_buf.push(b';');
self.base_fg.write_ansi_fg(&mut color_buf);
self.style_sequence_buf
.extend_from_slice(color_buf.as_bytes());
self.style_sequence_buf.push(b';');
color_buf.clear();
self.base_bg.write_ansi_bg(&mut color_buf);
self.style_sequence_buf
.extend_from_slice(color_buf.as_bytes());
self.buffer.push_str("\x1b[");
self.buffer
.push_str(std::str::from_utf8(&self.style_sequence_buf).unwrap());
self.buffer.push('m');
self.last_emitted_attr = base_attr;
self.last_emitted_fg = self.base_fg;
self.last_emitted_bg = self.base_bg;
Ok(())
}
/// Refresh the screen (flush buffer to stdout)
pub fn refresh(&mut self) -> Result<()> {
// Clear output buffer
self.buffer.clear();
// Prime the physical terminal with the base bg if set_base() was
// called since the last refresh. This overwrites whatever fill the
// backend's init-time `\x1b[2J` left in place (= terminal default),
// so cells that the frame's diff happens not to touch still show
// the plane's background, not black.
if self.base_needs_prime {
self.emit_base_sgr()?;
self.buffer.push_str("\x1b[2J");
self.base_needs_prime = false;
}
// Process each dirty line (with interrupt checking).
//
// We don't do ncurses-style mid-screen scroll detection via DL/IL:
// `\x1b[NM`/`\x1b[NL` affect from the cursor to the bottom of the
// screen (no DECSTBM scroll region is set), which shifts rows
// outside the scroll hunk and leaves stale gutter/content on them.
// notcurses doesn't do it either — mid-screen viewport scrolling is
// handled entirely by the per-cell diff below.
let mut lines_processed = 0;
let mut refresh_aborted = false;
for y in 0..self.rows as usize {
if let Some((first_x, last_x)) = self.dirty_lines[y].range() {
// Find actual differences within dirty region
if let Some((first_diff, last_diff)) = crate::delta::find_line_diff(
&self.current_content[y],
&self.pending_content[y],
) {
// Clamp to dirty region
let first = first_diff.max(first_x as usize);
let last = last_diff.min(last_x as usize);
if first <= last {
// Move cursor to start of change
write!(self.buffer, "\x1b[{};{}H", y + 1, first + 1)?;
// Output changed cells
let mut x = first;
while x <= last {
let cell = self.pending_content[y][x];
let cell_attr = cell.attr();
// Resolve id=0 (terminal default) to the base cell
// — notcurses's plane-base behavior. Prevents
// unwritten Cell::BLANK positions from rendering
// as the user's terminal-default bg (black).
let cell_fg = if cell.fg_id() == 0 {
self.base_fg
} else {
self.color_table.id_to_color(cell.fg_id())
};
let cell_bg = if cell.bg_id() == 0 {
self.base_bg
} else {
self.color_table.id_to_color(cell.bg_id())
};
// Check if style needs updating
let style_changed = cell_attr != self.last_emitted_attr
|| cell_fg != self.last_emitted_fg
|| cell_bg != self.last_emitted_bg;
// Apply style if changed
if style_changed {
let cell_style = (cell_attr, cell_fg, cell_bg);
self.last_emitted_attr = cell_style.0;
self.last_emitted_fg = cell_style.1;
self.last_emitted_bg = cell_style.2;
// Build and emit style codes using SmallVec (stack-allocated)
self.style_sequence_buf.clear();
let mut needs_separator = false;
// Helper macro to add code with separator
macro_rules! add_code {
($code:expr) => {
if needs_separator {
self.style_sequence_buf.push(b';');
}
self.style_sequence_buf.extend_from_slice($code);
needs_separator = true;
};
}
// Add attribute codes
if cell_style.0.is_empty() {
add_code!(b"0"); // Reset
} else {
if cell_style.0.contains(Attr::BOLD) {
add_code!(b"1");
}
if cell_style.0.contains(Attr::DIM) {
add_code!(b"2");
}
if cell_style.0.contains(Attr::ITALIC) {
add_code!(b"3");
}
if cell_style.0.contains(Attr::UNDERLINE) {
add_code!(b"4");
}
if cell_style.0.contains(Attr::BLINK) {
add_code!(b"5");
}
if cell_style.0.contains(Attr::REVERSE) {
add_code!(b"7");
}
if cell_style.0.contains(Attr::HIDDEN) {
add_code!(b"8");
}
if cell_style.0.contains(Attr::STRIKETHROUGH) {
add_code!(b"9");
}
}
// Add color codes using temporary string
// (write_ansi_fg/bg expect String, so we still need this)
let mut color_buf = String::with_capacity(20);
let fg = cell_style.1;
if needs_separator {
self.style_sequence_buf.push(b';');
}
color_buf.clear();
fg.write_ansi_fg(&mut color_buf);
self.style_sequence_buf
.extend_from_slice(color_buf.as_bytes());
needs_separator = true;
let bg = cell_style.2;
if needs_separator {
self.style_sequence_buf.push(b';');
}
color_buf.clear();
bg.write_ansi_bg(&mut color_buf);
self.style_sequence_buf
.extend_from_slice(color_buf.as_bytes());
// Emit ANSI sequence if we added any codes
if !self.style_sequence_buf.is_empty() {
self.buffer.push_str("\x1b[");
self.buffer.push_str(
std::str::from_utf8(&self.style_sequence_buf)
.unwrap(),
);
self.buffer.push('m');
}
}
// Output character (with RLE optimization for spaces)
if cell.is_blank() {
// Check for run of blank spaces
let mut run_length = 1;
while x + run_length <= last
&& run_length < 256
&& self.pending_content[y][x + run_length].is_blank()
{
run_length += 1;
}
if run_length >= 8 {
// Use ECH for long runs
write!(self.buffer, "\x1b[{}X", run_length)?;
x += run_length;
continue;
}
}
write!(self.buffer, "{}", cell.ch())?;
x += 1;
}
}
}
// Clear dirty flag only if not aborted
if !refresh_aborted {
self.dirty_lines[y] = DirtyRegion::clean();
}
lines_processed += 1;
// Check for input every check_interval lines (Phase 2.1 optimization)
if lines_processed % self.check_interval == 0 {
if self.check_pending_input()? {
// Input detected - abort refresh, preserve dirty flags for unprocessed lines
refresh_aborted = true;
break;
}
}
}
}
// Emit cursor position, style, and visibility
if let Some((y, x)) = self.cursor_position.take() {
write!(self.buffer, "\x1b[{};{}H", y + 1, x + 1)?;
}
if self.cursor_style != 0 {
write!(self.buffer, "\x1b[{} q", self.cursor_style)?;
}
if self.cursor_visible {
self.buffer.push_str("\x1b[?25h");
} else {
self.buffer.push_str("\x1b[?25l");
}
// Flush buffer even if aborted (partial update is valid)
crate::platform_io::write_all_stdout(self.buffer.as_bytes())?;
// Swap buffers only if refresh completed (not aborted)
if !refresh_aborted {
std::mem::swap(&mut self.current_content, &mut self.pending_content);
// Copy back to pending (pending should match current after refresh)
for y in 0..self.rows as usize {
self.pending_content[y].clone_from_slice(&self.current_content[y]);
}
}
Ok(())
}
/// Update internal buffer without refreshing screen
pub fn wnoutrefresh(&mut self) -> Result<()> {
Backend::add_to_update_buffer(&self.buffer)?;
self.buffer.clear();
Ok(())
}
/// Update physical screen with all pending changes
pub fn doupdate() -> Result<()> {
Backend::doupdate()
}
/// Enable Kitty keyboard protocol with the specified flags.
///
/// Alias for [`push_kitty_keyboard`](Self::push_kitty_keyboard) — the
/// kitty spec only offers a stack-based enable, so there is no
/// separate "set without pushing" primitive at this layer.
/// Toggle bracketed-paste mode (DEC private mode 2004). When
/// enabled, pasted content arrives wrapped in `ESC [ 200 ~` and
/// `ESC [ 201 ~`, surfaced via [`Key::Paste`](crate::Key::Paste)
/// rather than as a stream of individual key events.
pub fn set_bracketed_paste(&mut self, enabled: bool) -> Result<()> {
let seq: &[u8] = if enabled {
b"\x1b[?2004h"
} else {
b"\x1b[?2004l"
};
crate::platform_io::write_all_stdout(seq)?;
Ok(())
}
/// Publish `text` to the system clipboard via OSC 52. The terminal
/// (if it permits clipboard writes) base64-decodes the payload and
/// writes it to the system clipboard. Works without a clipboard
/// daemon — no `pbcopy`/`xclip` shell-out required.
pub fn osc52_copy(&mut self, text: &str) -> Result<()> {
let encoded = base64_encode(text.as_bytes());
let seq = format!("\x1b]52;c;{}\x1b\\", encoded);
crate::platform_io::write_all_stdout(seq.as_bytes())?;
Ok(())
}
pub fn enable_kitty_keyboard(
&mut self,
flags: crate::kitty::KittyFlags,
) -> Result<()> {
self.push_kitty_keyboard(flags)
}
/// Disable Kitty keyboard protocol by popping the top of the stack.
pub fn disable_kitty_keyboard(&mut self) -> Result<()> {
self.pop_kitty_keyboard()
}
/// Push `flags` onto the terminal's keyboard-mode stack so the
/// previous configuration is preserved.
pub fn push_kitty_keyboard(&mut self, flags: crate::kitty::KittyFlags) -> Result<()> {
write!(self.buffer, "{}", crate::kitty::push_sequence(flags))?;
Ok(())
}
/// Pop one entry from the keyboard-mode stack.
pub fn pop_kitty_keyboard(&mut self) -> Result<()> {
write!(self.buffer, "{}", crate::kitty::pop_sequence())?;
Ok(())
}
/// Pop `n` entries from the keyboard-mode stack.
pub fn pop_kitty_keyboard_n(&mut self, n: u32) -> Result<()> {
write!(self.buffer, "{}", crate::kitty::pop_n_sequence(n))?;
Ok(())
}
/// Set the top-of-stack flags directly without pushing. `mode`
/// controls whether to replace, OR, or AND-NOT the current flags —
/// see [`SetMode`](crate::kitty::SetMode) for details.
pub fn set_kitty_keyboard(
&mut self,
flags: crate::kitty::KittyFlags,
mode: crate::kitty::SetMode,
) -> Result<()> {
write!(self.buffer, "{}", crate::kitty::set_sequence(flags, mode))?;
Ok(())
}
/// Query the terminal for its active keyboard flags. The reply
/// arrives asynchronously as `CSI ? flags u`; `tv` does not yet
/// decode it — callers that care can read stdin and parse it.
pub fn query_kitty_keyboard(&mut self) -> Result<()> {
write!(self.buffer, "{}", crate::kitty::query_sequence())?;
Ok(())
}
/// Display an image using Kitty graphics protocol
pub fn display_kitty_image(
&mut self,
image: &crate::image::KittyImage,
) -> Result<()> {
let seq = image.to_sequence().map_err(|_| {
Error::Io(std::io::Error::new(
std::io::ErrorKind::Other,
"image encoding error",
))
})?;
write!(self.buffer, "{}", seq)?;
Ok(())
}
/// Display an image using Sixel graphics protocol
pub fn display_sixel_image(
&mut self,
image: &crate::image::SixelImage,
) -> Result<()> {
let seq = image.to_sequence().map_err(|_| {
Error::Io(std::io::Error::new(
std::io::ErrorKind::Other,
"image encoding error",
))
})?;
write!(self.buffer, "{}", seq)?;
Ok(())
}
/// Delete a Kitty image by ID
pub fn delete_kitty_image(&mut self, image_id: u32) -> Result<()> {
write!(
self.buffer,
"{}",
crate::image::delete_kitty_image(image_id)
)?;
Ok(())
}
/// Delete all Kitty images
pub fn delete_all_kitty_images(&mut self) -> Result<()> {
write!(self.buffer, "{}", crate::image::delete_all_kitty_images())?;
Ok(())
}
/// Create a new surface
pub fn newwin(&self, height: u16, width: u16, y: u16, x: u16) -> Result<Surface> {
if height == 0 || width == 0 {
return Err(Error::InvalidDimensions { height, width });
}
Surface::new(height, width, y, x)
}
/// Set cursor style using DECSCUSR
///
/// 0 = default, 1 = blinking block, 2 = steady block,
/// 3 = blinking underline, 4 = steady underline,
/// 5 = blinking bar, 6 = steady bar
pub fn set_cursor_style(&mut self, style: u8) -> Result<()> {
self.cursor_style = style;
Ok(())
}
/// Set the terminal cursor position after the next refresh.
pub fn set_cursor_position(&mut self, y: u16, x: u16) {
self.cursor_position = Some((y, x));
}
}
/// Standard base64 alphabet (RFC 4648). OSC 52 requires this exact
/// alphabet — no URL-safe variants. We roll our own to avoid a crate
/// dependency for ~25 lines.
fn base64_encode(input: &[u8]) -> String {
const ALPHABET: &[u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let b0 = chunk[0];
let b1 = *chunk.get(1).unwrap_or(&0);
let b2 = *chunk.get(2).unwrap_or(&0);
out.push(ALPHABET[(b0 >> 2) as usize] as char);
out.push(ALPHABET[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
if chunk.len() > 1 {
out.push(ALPHABET[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);
} else {
out.push('=');
}
if chunk.len() > 2 {
out.push(ALPHABET[(b2 & 0x3f) as usize] as char);
} else {
out.push('=');
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
// Helper function to create a test Screen with all required fields
fn create_test_screen() -> Screen {
let rows = 24;
let cols = 80;
Screen {
cursor_x: 0,
cursor_y: 0,
rows,
cols,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
current_content: vec![vec![Cell::blank(); cols as usize]; rows as usize],
pending_content: vec![vec![Cell::blank(); cols as usize]; rows as usize],
dirty_lines: vec![DirtyRegion::clean(); rows as usize],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
}
}
#[test]
fn test_screen_buffer_operations() {
// These tests don't actually initialize the terminal
let mut scr = create_test_screen();
scr.move_cursor(5, 10).unwrap();
assert!(scr.buffer.contains("\x1b[6;11H"));
assert_eq!(scr.cursor_x, 10);
assert_eq!(scr.cursor_y, 5);
scr.buffer.clear();
scr.cursor_x = 0; // Reset cursor for next test
scr.print("Hello").unwrap();
assert_eq!(scr.cursor_x, 5);
}
// With a base cell set (notcurses-style), cells left as Cell::BLANK by
// the tilde-row render path (cols 5-6, caused by the `│` byte-vs-cell
// drift) must resolve to the base bg during emission — never the
// terminal default. We check the ANSI output rather than the cell grid,
// since cells themselves remain BLANK; the substitution happens at
// refresh time. Before the fix, this row emitted `\x1b[0;39;49m ` for
// cells 5/6 — a reset-to-terminal-default = black rectangle.
#[test]
fn tilde_row_emits_base_bg_not_terminal_default() {
let mut scr = create_test_screen();
let bg = Color::rgb(40, 42, 54); // theme::BG
let fg = Color::rgb(248, 248, 242); // theme::FG
let comment = Color::rgb(98, 114, 164); // theme::COMMENT
scr.set_base(fg, bg);
let gutter_width = 3;
let code_x: u16 = gutter_width as u16 + 1;
// Mimic editor_area.rs:57-67 tilde path.
scr.set_background(bg).unwrap();
scr.set_foreground(comment).unwrap();
let tilde = format!("{:>width$} │", "~", width = gutter_width);
scr.move_print(0, 0, &tilde).unwrap();
let remaining = scr.cols.saturating_sub(code_x) as usize;
scr.print(&" ".repeat(remaining)).unwrap();
// Run refresh to produce actual ANSI.
scr.buffer.clear();
scr.refresh().unwrap();
let out = scr.buffer.clone();
// The base bg (40, 42, 54) must appear as an SGR in the output.
assert!(
out.contains("48;2;40;42;54"),
"base bg SGR not emitted; output: {:?}",
out
);
// And the terminal-default bg reset (`49m`) must NOT appear at a
// position where we're emitting a cell — otherwise that cell renders
// as terminal default. The only safe occurrence of `49` here is if
// the base itself were terminal default, which it isn't in this test.
assert!(
!out.contains(";49m") && !out.contains(";49;"),
"default-bg reset leaked into output: {:?}",
out
);
}
// Reproduces the user's "still see black rectangles after the base-cell
// substitution fix" issue. Root cause: backend.rs emits `\x1b[2J` at
// init (terminal defaults = black fill). On the first render, cells the
// paint path never writes stay as Cell::BLANK in pending_content, match
// the Cell::BLANK in current_content, find_line_diff returns None, and
// nothing is emitted — the terminal keeps its black fill.
//
// Fix (notcurses-style): set_base fills both buffers with the base cell
// and marks the physical terminal for re-prime; the next refresh emits
// SGR(base) + `\x1b[2J` so the terminal itself is filled with base bg
// before any diff emission. After this, no cell is ever Cell::BLANK at
// diff time, and no position on the terminal can show terminal-default.
#[test]
fn set_base_primes_terminal_and_eliminates_blank_cells() {
let mut scr = create_test_screen();
let base_bg = Color::rgb(40, 42, 54);
let base_fg = Color::rgb(248, 248, 242);
// Post-init state: current/pending are all Cell::BLANK.
for row in &scr.pending_content {
for cell in row {
assert!(cell.is_blank());
}
}
scr.set_base(base_fg, base_bg).unwrap();
// 1. Internal state: no Cell::BLANK remains anywhere.
for (y, row) in scr.pending_content.iter().enumerate() {
for (x, cell) in row.iter().enumerate() {
assert!(!cell.is_blank(), "pending[{y}][{x}] still blank");
assert_ne!(cell.bg_id(), 0, "pending[{y}][{x}] default bg");
}
}
for (y, row) in scr.current_content.iter().enumerate() {
for (x, cell) in row.iter().enumerate() {
assert!(!cell.is_blank(), "current[{y}][{x}] still blank");
}
}
// 2. First refresh primes the terminal: emits SGR(base) + `\x1b[2J`.
scr.refresh().unwrap();
// Base rgb appears as a bg SGR
assert!(
scr.buffer.contains("48;2;40;42;54") ||
// Or it was emitted earlier and recorded in last_emitted_bg.
scr.last_emitted_bg == base_bg,
"refresh did not emit base bg SGR; buffer: {:?}",
scr.buffer
);
assert!(
scr.buffer.contains("\x1b[2J"),
"refresh did not emit screen clear; buffer: {:?}",
scr.buffer
);
// 3. Partial render: short label, nothing else. Unwritten rows used
// to remain Cell::BLANK in pending → match current Cell::BLANK → no
// emission → terminal keeps its `\x1b[2J` fill (black).
scr.clear().unwrap();
scr.set_background(base_bg).unwrap();
scr.set_foreground(Color::rgb(255, 121, 198)).unwrap();
scr.move_print(0, 0, "hi").unwrap();
for (y, row) in scr.pending_content.iter().enumerate() {
for (x, cell) in row.iter().enumerate() {
assert!(
!cell.is_blank(),
"post-render pending[{y}][{x}] is Cell::BLANK — \
would render as terminal-default (black)"
);
}
}
// 4. A second refresh, idempotent: no re-prime (base_needs_prime
// was cleared). Buffer should not contain another `\x1b[2J`.
scr.refresh().unwrap();
assert!(
!scr.buffer.contains("\x1b[2J"),
"second refresh re-primed unnecessarily: {:?}",
scr.buffer
);
}
// Mimics what paint_highlighted_line does for a content row: move_cursor to
// code_x, print styled text, then fill the remainder with spaces. Also
// includes the gutter paint that precedes it. Cursor reset via move_cursor
// should prevent the drift that plagues the tilde row.
#[test]
fn content_row_has_no_default_bg_cells() {
let mut scr = create_test_screen();
let bg = Color::rgb(40, 42, 54);
let fg = Color::rgb(248, 248, 242);
let comment = Color::rgb(98, 114, 164);
let gutter_width = 3;
let code_x: u16 = gutter_width as u16 + 1;
// Gutter (matches editor_area.rs:29-40)
scr.set_background(bg).unwrap();
scr.set_foreground(comment).unwrap();
let num_str = format!("{:>width$} │", 18, width = gutter_width);
scr.move_print(0, 0, &num_str).unwrap();
// paint_highlighted_line equivalent for a short line: move_cursor,
// set_background again, print text, then fill the rest.
let text = "int x = 42;";
let max_width = scr.cols - code_x;
scr.move_cursor(0, code_x).unwrap();
scr.set_background(bg).unwrap();
scr.set_foreground(fg).unwrap();
scr.print(text).unwrap();
// Fill
scr.set_foreground(bg).unwrap();
let printed = text.len().min(max_width as usize);
let remaining = (max_width as usize).saturating_sub(printed);
scr.print(&" ".repeat(remaining)).unwrap();
let row = &scr.pending_content[0];
let default_bg_cells: Vec<usize> = (0..scr.cols as usize)
.filter(|&x| row[x].bg_id() == 0)
.collect();
assert!(
default_bg_cells.is_empty(),
"content row has default-bg cells {:?}",
default_bg_cells
);
}
#[test]
fn test_attributes() {
let mut scr = create_test_screen();
scr.add_attribute(Attr::BOLD).unwrap();
assert!(scr.current_attr.contains(Attr::BOLD));
scr.add_attribute(Attr::UNDERLINE).unwrap();
assert!(scr.current_attr.contains(Attr::BOLD | Attr::UNDERLINE));
scr.remove_attribute(Attr::BOLD).unwrap();
assert!(!scr.current_attr.contains(Attr::BOLD));
assert!(scr.current_attr.contains(Attr::UNDERLINE));
}
#[test]
fn test_color_pairs() {
let mut scr = create_test_screen();
scr.init_pair(1, Color::RED, Color::BLACK).unwrap();
scr.color_pair(1).unwrap();
assert_eq!(scr.current_fg, Color::RED);
assert_eq!(scr.current_bg, Color::BLACK);
}
#[test]
fn test_invalid_color_pair() {
let mut scr = create_test_screen();
let result = scr.color_pair(99);
assert!(matches!(result, Err(Error::InvalidColorPair(99))));
}
#[test]
fn test_clear_operations() {
let mut scr = create_test_screen();
// Test clear() - should clear screen and reset cursor
scr.print("Hello").unwrap();
scr.clear().unwrap();
assert_eq!(scr.cursor_x, 0);
assert_eq!(scr.cursor_y, 0);
// All pending content should be blank
for row in &scr.pending_content {
for cell in row {
assert!(cell.is_blank());
}
}
}
#[test]
fn test_cursor_visibility() {
let mut scr = create_test_screen();
scr.cursor_visible(true).unwrap();
assert!(scr.buffer.contains("\x1b[?25h"));
scr.buffer.clear();
scr.cursor_visible(false).unwrap();
assert!(scr.buffer.contains("\x1b[?25l"));
}
#[test]
fn test_enable_kitty_keyboard() {
let mut scr = create_test_screen();
use crate::kitty::KittyFlags;
// Test enable with default flags (DISAMBIGUATE)
scr.enable_kitty_keyboard(KittyFlags::default()).unwrap();
assert!(scr.buffer.contains("\x1b[>1u"));
// Test enable with multiple flags
scr.buffer.clear();
scr.enable_kitty_keyboard(KittyFlags::DISAMBIGUATE | KittyFlags::EVENT_TYPES)
.unwrap();
assert!(scr.buffer.contains("\x1b[>3u"));
}
#[test]
fn test_disable_kitty_keyboard() {
let mut scr = create_test_screen();
scr.disable_kitty_keyboard().unwrap();
assert_eq!(scr.buffer, "\x1b[<u");
}
#[test]
fn test_push_pop_kitty_keyboard() {
let mut scr = create_test_screen();
use crate::kitty::KittyFlags;
scr.push_kitty_keyboard(KittyFlags::DISAMBIGUATE | KittyFlags::EVENT_TYPES)
.unwrap();
assert!(scr.buffer.contains("\x1b[>3u"));
scr.buffer.clear();
scr.pop_kitty_keyboard().unwrap();
assert_eq!(scr.buffer, "\x1b[<u");
}
#[test]
fn test_kitty_keyboard_flags_combination() {
let mut scr = create_test_screen();
use crate::kitty::KittyFlags;
let all_flags = KittyFlags::DISAMBIGUATE
| KittyFlags::EVENT_TYPES
| KittyFlags::ALTERNATE_KEYS
| KittyFlags::ALL_AS_ESCAPES
| KittyFlags::ASSOCIATED_TEXT;
scr.enable_kitty_keyboard(all_flags).unwrap();
// 1+2+4+8+16 = 31
assert!(scr.buffer.contains("\x1b[>31u"));
}
#[test]
fn test_style_caching_no_redundant_codes() {
let mut scr = create_test_screen();
// First print should emit style codes
scr.print("Hello").unwrap();
scr.refresh().unwrap();
let first_output = scr.buffer.clone();
scr.buffer.clear();
// Second print at different position with same style
scr.move_cursor(0, 10).unwrap();
scr.print("World").unwrap();
scr.refresh().unwrap();
let second_output = scr.buffer.clone();
// Second output should have less escape codes (no style codes, just cursor movement)
assert!(second_output.contains("World"));
// First output had cursor movement + content, second should have cursor movement + content
// but both used the same default style
}
#[test]
fn test_style_caching_emits_on_change() {
let mut scr = create_test_screen();
// Print without style
scr.print("Normal").unwrap();
scr.refresh().unwrap();
scr.buffer.clear();
// Change to bold
scr.add_attribute(Attr::BOLD).unwrap();
scr.move_cursor(0, 10).unwrap();
scr.print("Bold").unwrap();
scr.refresh().unwrap();
// Should contain bold code (1) and color resets (39;49)
assert!(scr.buffer.contains("\x1b[1;39;49m"));
}
#[test]
fn test_style_caching_color_change() {
let mut scr = create_test_screen();
// Set foreground color and print
scr.set_foreground(Color::RED).unwrap();
scr.print("Red").unwrap();
scr.refresh().unwrap();
scr.buffer.clear();
// Change color and print at different position
scr.move_cursor(0, 10).unwrap();
scr.set_foreground(Color::BLUE).unwrap();
scr.print("Blue").unwrap();
scr.refresh().unwrap();
// Should contain new color code
assert!(scr.buffer.contains("\x1b["));
}
#[test]
fn test_style_caching_attr_reset() {
let mut scr = create_test_screen();
// Turn on bold and print
scr.add_attribute(Attr::BOLD).unwrap();
scr.print("Bold").unwrap();
scr.refresh().unwrap();
scr.buffer.clear();
// Turn off bold and print at different position
scr.move_cursor(0, 10).unwrap();
scr.remove_attribute(Attr::BOLD).unwrap();
scr.print("Normal").unwrap();
scr.refresh().unwrap();
// Should contain reset code (0) and color resets (39;49)
assert!(scr.buffer.contains("\x1b[0;39;49m"));
}
#[test]
fn test_style_caching_multiple_attrs() {
let mut scr = create_test_screen();
// Turn on bold and underline
scr.add_attribute(Attr::BOLD | Attr::UNDERLINE).unwrap();
scr.print("Styled").unwrap();
scr.refresh().unwrap();
// Verify output contains styled text
assert!(scr.buffer.contains("Styled"));
}
#[test]
fn test_buffer_preallocation() {
// Create a screen with pre-allocated buffer
let scr = Screen {
cursor_x: 0,
cursor_y: 0,
rows: 24,
cols: 80,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: {
let (rows, cols) = (24, 80);
let estimated_capacity = (rows * cols * 10).min(65536);
String::with_capacity(estimated_capacity)
},
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Verify buffer has non-zero capacity
assert!(scr.buffer.capacity() > 0);
assert!(scr.buffer.capacity() >= 24 * 80 * 10);
}
#[test]
fn test_buffer_capacity_capped() {
// Test that very large terminal sizes don't result in excessive allocation
let scr = Screen {
cursor_x: 0,
cursor_y: 0,
rows: 24,
cols: 80,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: {
let (rows, cols) = (1000, 1000); // Very large terminal
let estimated_capacity = (rows * cols * 10).min(65536);
String::with_capacity(estimated_capacity)
},
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Verify capacity is capped at 64KB
assert_eq!(scr.buffer.capacity(), 65536);
}
#[test]
fn test_buffer_no_reallocation_on_typical_use() {
let mut scr = Screen {
cursor_x: 0,
cursor_y: 0,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::with_capacity(1000),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
let initial_capacity = scr.buffer.capacity();
// Perform typical operations
for i in 0..10 {
scr.move_cursor(i, 0).unwrap();
scr.print("Test line").unwrap();
}
// Buffer should not have reallocated
assert_eq!(scr.buffer.capacity(), initial_capacity);
}
#[test]
fn test_cursor_movement_short_horizontal_forward() {
let mut scr = Screen {
cursor_x: 10,
cursor_y: 5,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Move forward 2 cells (should use CUF)
scr.move_cursor(5, 12).unwrap();
assert!(scr.buffer.contains("\x1b[2C")); // Cursor Forward 2
assert_eq!(scr.cursor_x, 12);
assert_eq!(scr.cursor_y, 5);
}
#[test]
fn test_cursor_movement_short_horizontal_back() {
let mut scr = Screen {
cursor_x: 10,
cursor_y: 5,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Move back 3 cells (should use CUB)
scr.move_cursor(5, 7).unwrap();
assert!(scr.buffer.contains("\x1b[3D")); // Cursor Back 3
assert_eq!(scr.cursor_x, 7);
assert_eq!(scr.cursor_y, 5);
}
#[test]
fn test_cursor_movement_short_vertical_down() {
let mut scr = Screen {
cursor_x: 10,
cursor_y: 5,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Move down 2 lines (should use CUD)
scr.move_cursor(7, 10).unwrap();
assert!(scr.buffer.contains("\x1b[2B")); // Cursor Down 2
assert_eq!(scr.cursor_x, 10);
assert_eq!(scr.cursor_y, 7);
}
#[test]
fn test_cursor_movement_short_vertical_up() {
let mut scr = Screen {
cursor_x: 10,
cursor_y: 5,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Move up 1 line (should use CUU)
scr.move_cursor(4, 10).unwrap();
assert!(scr.buffer.contains("\x1b[1A")); // Cursor Up 1
assert_eq!(scr.cursor_x, 10);
assert_eq!(scr.cursor_y, 4);
}
#[test]
fn test_cursor_movement_long_distance_uses_absolute() {
let mut scr = Screen {
cursor_x: 10,
cursor_y: 5,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Move 10 cells forward (should use CUP for long distance)
scr.move_cursor(5, 20).unwrap();
assert!(scr.buffer.contains("\x1b[6;21H")); // CUP (note: +1 for 1-based indexing)
assert_eq!(scr.cursor_x, 20);
assert_eq!(scr.cursor_y, 5);
}
#[test]
fn test_cursor_movement_diagonal_uses_absolute() {
let mut scr = Screen {
cursor_x: 10,
cursor_y: 5,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Diagonal movement (should use CUP)
scr.move_cursor(7, 12).unwrap();
assert!(scr.buffer.contains("\x1b[8;13H")); // CUP
assert_eq!(scr.cursor_x, 12);
assert_eq!(scr.cursor_y, 7);
}
#[test]
fn test_cursor_movement_same_position() {
let mut scr = Screen {
cursor_x: 10,
cursor_y: 5,
current_attr: Attr::NORMAL,
current_fg: Color::RESET,
current_bg: Color::RESET,
base_fg: Color::RESET,
base_bg: Color::RESET,
base_needs_prime: false,
color_pairs: HashMap::new(),
cursor_visible: false,
cursor_style: 0,
cursor_position: None,
buffer: String::new(),
last_emitted_attr: Attr::NORMAL,
last_emitted_fg: Color::RESET,
last_emitted_bg: Color::RESET,
style_sequence_buf: SmallVec::new(),
rows: 24,
cols: 80,
current_content: vec![vec![Cell::blank(); 80]; 24],
pending_content: vec![vec![Cell::blank(); 80]; 24],
dirty_lines: vec![DirtyRegion::clean(); 24],
#[cfg(unix)]
stdin_fd: 0,
check_interval: 5,
fifo_hold: false,
color_table: crate::cell::ColorTable::new(),
};
// Move to same position (should use CUP due to dx=0, dy=0)
scr.move_cursor(5, 10).unwrap();
assert!(scr.buffer.contains("\x1b[6;11H"));
assert_eq!(scr.cursor_x, 10);
assert_eq!(scr.cursor_y, 5);
}
#[test]
fn test_rle_long_blank_run() {
let mut scr = create_test_screen();
// Print 20 spaces
scr.print(" ").unwrap();
assert_eq!(scr.cursor_x, 20);
// Refresh should use ECH for long blank runs
scr.refresh().unwrap();
// Buffer may contain ECH sequence for blank runs, or just cursor sequences
let buf = &scr.buffer;
assert!(
buf.contains("\x1b[8X") || buf.contains("\x1b[20X") || !buf.contains("X") // no cell changes, only cursor sequences
);
}
#[test]
fn test_rle_short_blank_run() {
let mut scr = create_test_screen();
// Print 5 spaces
scr.print(" ").unwrap();
assert_eq!(scr.cursor_x, 5);
// Verify spaces were written to pending buffer
for i in 0..5 {
assert_eq!(scr.pending_content[0][i].ch(), ' ');
}
}
#[test]
fn test_rle_non_blank_text() {
let mut scr = create_test_screen();
// Print regular text
scr.print("Hello World").unwrap();
assert_eq!(scr.cursor_x, 11);
// Verify text was written to pending buffer
let text = "Hello World";
for (i, ch) in text.chars().enumerate() {
assert_eq!(scr.pending_content[0][i].ch(), ch);
}
}
#[test]
fn test_rle_threshold_exactly_8() {
let mut scr = create_test_screen();
// Print exactly 8 spaces
scr.print(" ").unwrap();
assert_eq!(scr.cursor_x, 8);
scr.refresh().unwrap();
// ECH may or may not be used depending on delta optimization
assert!(scr.buffer.len() >= 0); // Just verify it didn't crash
}
#[test]
fn base64_encode_canonical() {
// RFC 4648 test vectors.
assert_eq!(base64_encode(b""), "");
assert_eq!(base64_encode(b"f"), "Zg==");
assert_eq!(base64_encode(b"fo"), "Zm8=");
assert_eq!(base64_encode(b"foo"), "Zm9v");
assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
// UTF-8 multibyte payload — bytes-in, bytes-encoded, no
// codepoint awareness.
assert_eq!(base64_encode("héllo".as_bytes()), "aMOpbGxv");
}
#[test]
fn test_rle_threshold_7_spaces() {
let mut scr = create_test_screen();
// Print exactly 7 spaces
scr.print(" ").unwrap();
assert_eq!(scr.cursor_x, 7);
// Verify spaces were written
for i in 0..7 {
assert_eq!(scr.pending_content[0][i].ch(), ' ');
}
}
}