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
use crossterm::style::Color;
use std::fmt;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
/// Parameters for cell styling.
#[derive(Debug, Clone, Copy)]
struct StyleParams {
fg: Color,
bg: Color,
bold: bool,
italic: bool,
underline: bool,
dim: bool,
}
/// A single cell in the terminal buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cell {
pub ch: char,
pub fg: Color,
pub bg: Color,
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub dim: bool,
/// True if this cell is the second half of a wide character (e.g., emoji, CJK).
/// The renderer should skip these cells since the wide char already occupies the space.
pub wide_continuation: bool,
}
impl Default for Cell {
fn default() -> Self {
Self {
ch: ' ',
fg: Color::Reset,
bg: Color::Reset,
bold: false,
italic: false,
underline: false,
dim: false,
wide_continuation: false,
}
}
}
impl Cell {
/// Create a new cell with just character and colors.
pub fn new(ch: char, fg: Color, bg: Color) -> Self {
Self {
ch,
fg,
bg,
..Default::default()
}
}
/// Create a styled cell.
pub fn styled(
ch: char,
fg: Color,
bg: Color,
bold: bool,
italic: bool,
underline: bool,
dim: bool,
) -> Self {
Self {
ch,
fg,
bg,
bold,
italic,
underline,
dim,
wide_continuation: false,
}
}
/// Create a wide character continuation cell (second half of emoji/CJK).
/// The renderer should skip these cells.
pub fn wide_continuation(fg: Color, bg: Color) -> Self {
Self {
ch: ' ',
fg,
bg,
wide_continuation: true,
..Default::default()
}
}
/// Create a styled wide character continuation cell.
pub fn wide_continuation_styled(
fg: Color,
bg: Color,
bold: bool,
italic: bool,
underline: bool,
dim: bool,
) -> Self {
Self {
ch: ' ',
fg,
bg,
bold,
italic,
underline,
dim,
wide_continuation: true,
}
}
}
/// A rectangular region within the buffer.
#[derive(Debug, Clone, Copy)]
pub struct Rect {
pub x: u16,
pub y: u16,
pub width: u16,
pub height: u16,
}
impl Rect {
pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
Self {
x,
y,
width,
height,
}
}
}
/// A 2D buffer of cells representing the terminal screen.
#[derive(Debug, Clone)]
pub struct Buffer {
cells: Vec<Cell>,
pub width: u16,
pub height: u16,
}
impl Buffer {
/// Create a new buffer filled with empty cells.
pub fn new(width: u16, height: u16) -> Self {
let size = (width as usize) * (height as usize);
Self {
cells: vec![Cell::default(); size],
width,
height,
}
}
/// Get the index into the cells vector for a given position.
fn index(&self, x: u16, y: u16) -> Option<usize> {
if x < self.width && y < self.height {
Some((y as usize) * (self.width as usize) + (x as usize))
} else {
None
}
}
/// Get a cell at a position.
pub fn get(&self, x: u16, y: u16) -> Option<&Cell> {
self.index(x, y).map(|i| &self.cells[i])
}
/// Set a cell at a position.
pub fn set_cell(&mut self, x: u16, y: u16, cell: Cell) {
if let Some(i) = self.index(x, y) {
self.cells[i] = cell;
}
}
/// Set a character at a position with colors.
pub fn set(&mut self, x: u16, y: u16, ch: char, fg: Color, bg: Color) {
self.set_cell(x, y, Cell::new(ch, fg, bg));
}
/// Write a string at a position, clipping at buffer boundaries.
///
/// Handles grapheme clusters and wide characters (CJK, emoji) properly:
/// - Iterates by grapheme clusters (user-perceived characters)
/// - Wide characters (display width 2) advance the column by 2
/// - Wide char continuations are marked so the renderer can skip them
pub fn write_str(&mut self, x: u16, y: u16, s: &str, fg: Color, bg: Color) {
let mut col = x;
for grapheme in s.graphemes(true) {
if col >= self.width {
break;
}
let width = UnicodeWidthStr::width(grapheme);
if width == 0 {
continue; // Skip zero-width characters
}
// For wide characters, check if we have room for both columns
if width == 2 && col + 1 >= self.width {
// Wide char would overflow - write a space instead and stop
self.set_cell(col, y, Cell::new(' ', fg, bg));
break;
}
// Use first char of grapheme for the cell
// (Full grapheme cluster support would require Cell to store String)
let ch = grapheme.chars().next().unwrap_or(' ');
self.set_cell(col, y, Cell::new(ch, fg, bg));
// For wide characters, mark the next cell as a continuation
if width == 2 {
self.set_cell(col + 1, y, Cell::wide_continuation(fg, bg));
}
col += width as u16;
}
}
/// Write a styled string at a position, clipping at buffer boundaries.
///
/// Handles grapheme clusters and wide characters (CJK, emoji) properly:
/// - Iterates by grapheme clusters (user-perceived characters)
/// - Wide characters (display width 2) advance the column by 2
/// - Wide char continuations are marked so the renderer can skip them
#[allow(clippy::too_many_arguments)]
pub fn write_str_styled(
&mut self,
x: u16,
y: u16,
s: &str,
fg: Color,
bg: Color,
bold: bool,
italic: bool,
underline: bool,
dim: bool,
) {
let style = StyleParams {
fg,
bg,
bold,
italic,
underline,
dim,
};
self.write_str_styled_impl(x, y, s, style);
}
/// Internal implementation of write_str_styled using StyleParams.
fn write_str_styled_impl(&mut self, x: u16, y: u16, s: &str, style: StyleParams) {
let mut col = x;
for grapheme in s.graphemes(true) {
if col >= self.width {
break;
}
let width = UnicodeWidthStr::width(grapheme);
if width == 0 {
continue; // Skip zero-width characters
}
// For wide characters, check if we have room for both columns
if width == 2 && col + 1 >= self.width {
// Wide char would overflow - write a space instead and stop
self.set_cell(
col,
y,
Cell::styled(' ', style.fg, style.bg, style.bold, style.italic, style.underline, style.dim),
);
break;
}
// Use first char of grapheme for the cell
// (Full grapheme cluster support would require Cell to store String)
let ch = grapheme.chars().next().unwrap_or(' ');
self.set_cell(
col,
y,
Cell::styled(ch, style.fg, style.bg, style.bold, style.italic, style.underline, style.dim),
);
// For wide characters, mark the next cell as a continuation
if width == 2 {
self.set_cell(
col + 1,
y,
Cell::wide_continuation_styled(style.fg, style.bg, style.bold, style.italic, style.underline, style.dim),
);
}
col += width as u16;
}
}
/// Get the full rect of this buffer.
pub fn rect(&self) -> Rect {
Rect::new(0, 0, self.width, self.height)
}
/// Clear the buffer to empty cells.
#[allow(dead_code)]
pub fn clear(&mut self) {
for cell in &mut self.cells {
*cell = Cell::default();
}
}
/// Fill the buffer with a specific foreground and background color.
pub fn fill(&mut self, fg: Color, bg: Color) {
for cell in &mut self.cells {
cell.ch = ' ';
cell.fg = fg;
cell.bg = bg;
cell.bold = false;
cell.italic = false;
cell.underline = false;
cell.dim = false;
}
}
/// Convert the buffer to a string (for testing/snapshots).
fn buffer_to_string(&self) -> String {
let mut result = String::new();
for y in 0..self.height {
for x in 0..self.width {
if let Some(cell) = self.get(x, y) {
// Skip wide character continuations - the wide char already added its character
if cell.wide_continuation {
continue;
}
result.push(cell.ch);
}
}
// Trim trailing spaces from each line
let trimmed = result.trim_end_matches(' ');
result.truncate(trimmed.len());
result.push('\n');
}
// Remove trailing empty lines
while result.ends_with("\n\n") {
result.pop();
}
result
}
/// Compute the differences between this buffer and another.
/// Returns a list of (x, y, cell) for cells that differ.
pub fn diff<'a>(&'a self, other: &'a Buffer) -> Vec<(u16, u16, &'a Cell)> {
let mut changes = Vec::new();
for y in 0..self.height {
for x in 0..self.width {
let self_cell = self.get(x, y);
let other_cell = other.get(x, y);
match (self_cell, other_cell) {
(Some(a), Some(b)) if a != b => {
changes.push((x, y, a));
}
(Some(a), None) => {
changes.push((x, y, a));
}
_ => {}
}
}
}
changes
}
}
impl fmt::Display for Buffer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.buffer_to_string())
}
}