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
//! ScreenBuffer: a 2D grid of styled cells plus a diff algorithm.
//!
//! Rich itself doesn't expose a public "cell buffer" in the same way Textual does, but a
//! screen buffer + diff is a foundational building block for future TUIs.
//!
//! This module provides:
//! - `Cell` and `ScreenBuffer` (width × height grid)
//! - Conversion from rendered lines / segments into a `ScreenBuffer`
//! - A `diff_to_segments` method that produces terminal controls + styled text segments
//! to update one buffer into another (cursor-safe, no newlines).
use crate::cells::char_width;
use crate::segment::{ControlType, Segment, Segments};
use crate::style::Style;
use crate::{Console, ConsoleOptions, Renderable};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cell {
/// Text to print at this cell (may be empty for wide continuations).
pub text: String,
/// Style for this cell.
pub style: Option<Style>,
/// True if this cell is the trailing continuation of a wide glyph.
pub continuation: bool,
}
impl Cell {
pub fn blank(style: Option<Style>) -> Self {
Self {
text: " ".to_string(),
style,
continuation: false,
}
}
pub fn continuation(style: Option<Style>) -> Self {
Self {
text: String::new(),
style,
continuation: true,
}
}
pub fn width(&self) -> usize {
if self.continuation {
0
} else {
crate::cell_len(&self.text)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScreenBuffer {
pub width: usize,
pub height: usize,
default_style: Option<Style>,
cells: Vec<Cell>,
}
impl ScreenBuffer {
pub fn new(width: usize, height: usize, style: Option<Style>) -> Self {
let width = width.max(1);
let height = height.max(1);
Self {
width,
height,
default_style: style,
cells: vec![Cell::blank(style); width * height],
}
}
fn idx(&self, x: usize, y: usize) -> usize {
y * self.width + x
}
pub fn get(&self, x: usize, y: usize) -> &Cell {
&self.cells[self.idx(x, y)]
}
pub fn get_mut(&mut self, x: usize, y: usize) -> &mut Cell {
let idx = self.idx(x, y);
&mut self.cells[idx]
}
pub fn as_plain_lines(&self) -> Vec<String> {
let mut lines = Vec::with_capacity(self.height);
for y in 0..self.height {
let mut line = String::new();
for x in 0..self.width {
let cell = self.get(x, y);
if cell.continuation {
continue;
}
if cell.text.is_empty() {
line.push(' ');
} else {
line.push_str(&cell.text);
}
}
lines.push(crate::cells::set_cell_size(&line, self.width));
}
lines
}
/// Render a renderable to a ScreenBuffer.
///
/// This uses `Console::render_lines` and then converts the rendered lines to cells.
pub fn from_renderable(
console: &Console,
options: &ConsoleOptions,
renderable: &dyn Renderable,
style: Option<Style>,
) -> Self {
let (width, height) = options.size;
let lines = console.render_lines(renderable, Some(options), style, true, false);
let lines = Segment::set_shape(&lines, width, Some(height), style, false);
Self::from_lines(&lines, width, height, style)
}
/// Build a ScreenBuffer from pre-rendered lines.
///
/// The caller is expected to provide lines already padded/cropped to `width` × `height`.
pub fn from_lines(
lines: &[Vec<Segment>],
width: usize,
height: usize,
default_style: Option<Style>,
) -> Self {
let mut buffer = ScreenBuffer::new(width, height, default_style);
for (y, line) in lines.iter().take(height).enumerate() {
buffer.write_line(y, line);
}
buffer
}
fn clear_line(&mut self, y: usize) {
for x in 0..self.width {
*self.get_mut(x, y) = Cell::blank(self.default_style);
}
}
fn write_line(&mut self, y: usize, line: &[Segment]) {
if y >= self.height {
return;
}
self.clear_line(y);
let mut x: usize = 0;
let mut last_non_zero: Option<(usize, usize)> = None; // (x, width)
for seg in line {
if seg.control.is_some() {
continue;
}
let style = seg.style;
for ch in seg.text.chars() {
let w = char_width(ch);
if w == 0 {
// Combine with previous cell, if any.
if let Some((prev_x, prev_w)) = last_non_zero {
let cell = self.get_mut(prev_x, y);
cell.text.push(ch);
// Keep style from the segment currently being processed to match Rich behavior
// for combining marks following styled text.
cell.style = style;
// If previous glyph was wide, combining marks should still attach to the start.
last_non_zero = Some((prev_x, prev_w));
}
continue;
}
if x >= self.width {
return;
}
if w == 2 && x + 1 >= self.width {
// Can't place a wide glyph in the last column; fall back to a space.
*self.get_mut(x, y) = Cell::blank(style);
x += 1;
last_non_zero = Some((x.saturating_sub(1), 1));
continue;
}
*self.get_mut(x, y) = Cell {
text: ch.to_string(),
style,
continuation: false,
};
last_non_zero = Some((x, w));
if w == 2 {
*self.get_mut(x + 1, y) = Cell::continuation(style);
x += 2;
} else {
x += 1;
}
}
}
}
fn write_line_at(&mut self, y: usize, start_x: usize, max_width: usize, line: &[Segment]) {
if y >= self.height {
return;
}
if start_x >= self.width || max_width == 0 {
return;
}
let mut x: usize = start_x;
let max_x = (start_x + max_width).min(self.width);
let mut last_non_zero: Option<(usize, usize)> = None; // (x, width)
for seg in line {
if seg.control.is_some() {
continue;
}
let style = seg.style;
for ch in seg.text.chars() {
let w = char_width(ch);
if w == 0 {
if let Some((prev_x, prev_w)) = last_non_zero {
// Only if the previous cell is still inside the region.
if prev_x >= start_x && prev_x < max_x {
let cell = self.get_mut(prev_x, y);
cell.text.push(ch);
cell.style = style;
last_non_zero = Some((prev_x, prev_w));
}
}
continue;
}
if x >= max_x {
return;
}
if w == 2 && x + 1 >= max_x {
// Can't place a wide glyph at the end of the region; fall back to a space.
*self.get_mut(x, y) = Cell::blank(style);
x += 1;
last_non_zero = Some((x.saturating_sub(1), 1));
continue;
}
*self.get_mut(x, y) = Cell {
text: ch.to_string(),
style,
continuation: false,
};
last_non_zero = Some((x, w));
if w == 2 {
*self.get_mut(x + 1, y) = Cell::continuation(style);
x += 2;
} else {
x += 1;
}
}
}
}
/// Blit pre-rendered lines into the buffer at an offset.
///
/// Lines should be padded/cropped to the region width. This method will clip to the
/// screen bounds.
pub fn blit_lines(&mut self, x: usize, y: usize, width: usize, lines: &[Vec<Segment>]) {
if width == 0 {
return;
}
for (row, line) in lines.iter().enumerate() {
let yy = y + row;
if yy >= self.height {
break;
}
self.write_line_at(yy, x, width, line);
}
}
/// Convert the buffer to styled lines (no newlines).
pub fn to_styled_lines(&self) -> Vec<Vec<Segment>> {
let mut lines: Vec<Vec<Segment>> = Vec::with_capacity(self.height);
for y in 0..self.height {
let mut line: Vec<Segment> = Vec::new();
let mut current_style: Option<Style> = None;
let mut run = String::new();
let flush = |line: &mut Vec<Segment>, run: &mut String, style: Option<Style>| {
if run.is_empty() {
return;
}
let mut seg = Segment::new(std::mem::take(run));
seg.style = style;
line.push(seg);
};
for x in 0..self.width {
let cell = self.get(x, y);
if cell.continuation {
continue;
}
let text = if cell.text.is_empty() {
" "
} else {
cell.text.as_str()
};
if cell.style == current_style {
run.push_str(text);
} else {
flush(&mut line, &mut run, current_style);
current_style = cell.style;
run.push_str(text);
}
}
flush(&mut line, &mut run, current_style);
lines.push(line);
}
lines
}
fn cell_span_width(&self, x: usize, y: usize) -> usize {
let cell = self.get(x, y);
if cell.continuation {
0
} else {
let w = cell.width();
if w == 0 { 1 } else { w }
}
}
/// Compute an update sequence that transforms `previous` into `self`.
///
/// The returned segments:
/// - Optionally start with `Home` (cursor to 0,0)
/// - Use cursor controls (no `\n`) for positioning
/// - Emit styled text for changed spans
fn diff_to_segments_impl(&self, previous: &ScreenBuffer, include_home: bool) -> Segments {
assert_eq!(self.width, previous.width, "buffer widths differ");
assert_eq!(self.height, previous.height, "buffer heights differ");
let mut out = Segments::new();
if include_home {
out.push(Segment::control(ControlType::Home));
}
let mut cursor_x: usize = 0;
let mut cursor_y: usize = 0;
for y in 0..self.height {
let mut x: usize = 0;
while x < self.width {
let curr = self.get(x, y);
let prev = previous.get(x, y);
// Never start updates on continuation cells.
if curr.continuation || prev.continuation {
x += 1;
continue;
}
if curr == prev {
x += 1;
continue;
}
let mut span = self
.cell_span_width(x, y)
.max(previous.cell_span_width(x, y))
.max(1);
span = span.min(self.width.saturating_sub(x));
// Extend span over subsequent differing cells.
let mut end_x = x + span;
while end_x < self.width {
let c = self.get(end_x, y);
let p = previous.get(end_x, y);
if c.continuation || p.continuation {
end_x += 1;
continue;
}
if c == p {
break;
}
let extra = self
.cell_span_width(end_x, y)
.max(previous.cell_span_width(end_x, y))
.max(1);
end_x = (end_x + extra).min(self.width);
}
// Move cursor to (x, y)
if y != cursor_y {
if y > cursor_y {
out.push(Segment::control(ControlType::CursorDown(
(y - cursor_y) as u16,
)));
} else {
out.push(Segment::control(ControlType::CursorUp(
(cursor_y - y) as u16,
)));
}
cursor_y = y;
cursor_x = 0;
out.push(Segment::control(ControlType::CarriageReturn));
}
if x != cursor_x {
// Normalize to start-of-line then move forward.
out.push(Segment::control(ControlType::CarriageReturn));
cursor_x = 0;
if x > 0 {
out.push(Segment::control(ControlType::CursorForward(x as u16)));
cursor_x = x;
}
}
// Emit the updated span as styled segments.
let mut run_x = x;
while run_x < end_x {
let cell = self.get(run_x, y);
if cell.continuation {
run_x += 1;
continue;
}
let w = self.cell_span_width(run_x, y).max(1);
let text = if cell.text.is_empty() {
" ".to_string()
} else {
cell.text.clone()
};
let mut seg = Segment::new(text);
seg.style = cell.style;
out.push(seg);
cursor_x += w;
run_x += w;
}
x = end_x;
}
}
// Leave cursor at column 0 on the last row so live render cursor math remains stable.
let target_y = self.height.saturating_sub(1);
if target_y != cursor_y {
if target_y > cursor_y {
out.push(Segment::control(ControlType::CursorDown(
(target_y - cursor_y) as u16,
)));
} else {
out.push(Segment::control(ControlType::CursorUp(
(cursor_y - target_y) as u16,
)));
}
}
out.push(Segment::control(ControlType::CarriageReturn));
out
}
/// Compute an update sequence that transforms `previous` into `self`.
///
/// The returned segments:
/// - Start with `Home` (cursor to 0,0)
/// - Use cursor controls (no `\n`) for positioning
/// - Emit styled text for changed spans
pub fn diff_to_segments(&self, previous: &ScreenBuffer) -> Segments {
self.diff_to_segments_impl(previous, true)
}
/// Compute an update sequence relative to the current cursor origin.
///
/// Unlike `diff_to_segments`, this does *not* emit `Home` and is intended for
/// embedding in larger cursor-positioned render flows (e.g. Live updates).
pub fn diff_to_segments_from_origin(&self, previous: &ScreenBuffer) -> Segments {
self.diff_to_segments_impl(previous, false)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Text;
fn apply_segments(mut buffer: ScreenBuffer, segments: &Segments) -> ScreenBuffer {
let mut x: usize = 0;
let mut y: usize = 0;
let mut last_non_zero: Option<(usize, usize)> = None; // (x, width)
let width = buffer.width;
let height = buffer.height;
for seg in segments.iter() {
if let Some(ctrl) = &seg.control {
match ctrl {
ControlType::Home => {
x = 0;
y = 0;
}
ControlType::CarriageReturn => x = 0,
ControlType::CursorUp(n) => y = y.saturating_sub(*n as usize),
ControlType::CursorDown(n) => {
y = (y + *n as usize).min(height.saturating_sub(1))
}
ControlType::CursorForward(n) => {
x = (x + *n as usize).min(width.saturating_sub(1))
}
ControlType::CursorBackward(n) => x = x.saturating_sub(*n as usize),
_ => {}
}
continue;
}
for ch in seg.text.chars() {
let w = char_width(ch);
if x >= width || y >= height {
break;
}
if w == 0 {
if let Some((prev_x, prev_w)) = last_non_zero {
let cell = buffer.get_mut(prev_x, y);
cell.text.push(ch);
cell.style = seg.style;
last_non_zero = Some((prev_x, prev_w));
}
continue;
}
if w == 2 && x + 1 >= width {
break;
}
*buffer.get_mut(x, y) = Cell {
text: ch.to_string(),
style: seg.style,
continuation: false,
};
last_non_zero = Some((x, w));
if w == 2 {
*buffer.get_mut(x + 1, y) = Cell::continuation(seg.style);
x += 2;
} else {
x += 1;
}
}
}
buffer
}
#[test]
fn test_screen_buffer_from_renderable_plain() {
let console = Console::new();
let mut options = console.options().clone();
options.size = (5, 2);
options.max_width = 5;
options.max_height = 2;
let buf = ScreenBuffer::from_renderable(&console, &options, &Text::plain("hi"), None);
assert_eq!(buf.as_plain_lines()[0], "hi ");
assert_eq!(buf.as_plain_lines()[1], " ");
}
#[test]
fn test_screen_buffer_diff_applies() {
let console = Console::new();
let mut options = console.options().clone();
options.size = (10, 3);
options.max_width = 10;
options.max_height = 3;
let prev = ScreenBuffer::from_renderable(&console, &options, &Text::plain("A"), None);
let next = ScreenBuffer::from_renderable(&console, &options, &Text::plain("B"), None);
let diff = next.diff_to_segments(&prev);
let applied = apply_segments(prev.clone(), &diff);
assert_eq!(applied, next);
}
#[test]
fn test_screen_buffer_diff_handles_wide_char() {
let console = Console::new();
let mut options = console.options().clone();
options.size = (6, 1);
options.max_width = 6;
options.max_height = 1;
// Wide CJK character (2 cells)
let prev = ScreenBuffer::from_renderable(&console, &options, &Text::plain("你"), None);
let next = ScreenBuffer::from_renderable(&console, &options, &Text::plain("a"), None);
let diff = next.diff_to_segments(&prev);
let applied = apply_segments(prev.clone(), &diff);
assert_eq!(applied, next);
}
#[test]
fn test_screen_buffer_diff_uses_no_newlines() {
let console = Console::new();
let mut options = console.options().clone();
options.size = (10, 2);
options.max_width = 10;
options.max_height = 2;
let prev = ScreenBuffer::from_renderable(&console, &options, &Text::plain("A"), None);
let next = ScreenBuffer::from_renderable(&console, &options, &Text::plain("B"), None);
let diff = next.diff_to_segments(&prev);
assert!(diff.iter().all(|s| !s.text.contains('\n')));
}
}