Debian Codegraph @

helix-tui/src/buffer.rs

raw symbols SCIP
1 //! Contents of a terminal screen. A [Buffer] is made up of [Cell]s.
2 use crate::text::{Span, Spans};
3 use helix_core::unicode::width::{UnicodeWidthChar, UnicodeWidthStr};
4 use helix_view::graphics::{Color, Modifier, Rect, Style, UnderlineStyle};
5 use std::cmp::min;
6 use unicode_segmentation::UnicodeSegmentation;
7
8 pub const SYMBOL_CAPACITY: usize = 28;
9 pub type Symbol = arrayvec::ArrayString<SYMBOL_CAPACITY>;
10
11 /// One cell of the terminal. Contains one stylized grapheme.
12 #[derive(Debug, Clone, PartialEq, Eq)]
13 pub struct Cell {
14 pub symbol: Symbol,
15 /// Cached display width of `symbol` to avoid multiple recomputes in the hot path.
16 width: u8,
17 pub fg: Color,
18 pub bg: Color,
19 pub underline_color: Color,
20 pub underline_style: UnderlineStyle,
21 pub modifier: Modifier,
22 }
23
24 /// Char when attempting to set symbol that exceeds capacity: οΏ½
25 const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
26
27 impl Cell {
28 /// Set the cell's grapheme
29 pub fn set_symbol(&mut self, symbol: &str) -> &mut Cell {
30 self.symbol.clear();
31 if self.symbol.try_push_str(symbol).is_err() {
32 debug_assert!(
33 symbol.len() > SYMBOL_CAPACITY,
34 "Symbols can't exceed {SYMBOL_CAPACITY} bytes.\nTried to push {symbol} (size in bytes: {})",
35 symbol.len()
36 );
37 self.symbol.push(REPLACEMENT_CHARACTER);
38 }
39 self.width = self.symbol.width() as u8;
40 self
41 }
42
43 /// Like `set_symbol`, but the caller has already computed the display width.
44 /// Used on the render hot path where the width is known.
45 pub(crate) fn set_symbol_with_width(&mut self, symbol: &str, width: u8) -> &mut Cell {
46 self.symbol.clear();
47 if self.symbol.try_push_str(symbol).is_err() {
48 debug_assert!(
49 symbol.len() > 28,
50 "Symbols can't exceed 28 bytes.\nTried to push {} (size in bytes: {})",
51 symbol,
52 symbol.len()
53 );
54 self.symbol.push(REPLACEMENT_CHARACTER);
55 self.width = REPLACEMENT_CHARACTER.width().unwrap_or(1) as u8;
56 } else {
57 self.width = width;
58 }
59 self
60 }
61
62 /// Display width (in terminal columns) of the cell's grapheme.
63 pub fn width(&self) -> usize {
64 self.width as usize
65 }
66
67 /// Set the cell's grapheme to a [char]
68 pub fn set_char(&mut self, ch: char) -> &mut Cell {
69 self.symbol.clear();
70 self.symbol.push(ch);
71 self.width = ch.width().unwrap_or(0) as u8;
72 self
73 }
74
75 /// Set the foreground [Color]
76 pub fn set_fg(&mut self, color: Color) -> &mut Cell {
77 self.fg = color;
78 self
79 }
80
81 /// Set the background [Color]
82 pub fn set_bg(&mut self, color: Color) -> &mut Cell {
83 self.bg = color;
84 self
85 }
86
87 /// Set the [Style] of the cell
88 pub fn set_style(&mut self, style: Style) -> &mut Cell {
89 if let Some(c) = style.fg {
90 self.fg = c;
91 }
92 if let Some(c) = style.bg {
93 self.bg = c;
94 }
95 if let Some(c) = style.underline_color {
96 self.underline_color = c;
97 }
98 if let Some(style) = style.underline_style {
99 self.underline_style = style;
100 }
101
102 self.modifier.insert(style.add_modifier);
103 self.modifier.remove(style.sub_modifier);
104 self
105 }
106
107 /// Returns the current style of the cell
108 pub fn style(&self) -> Style {
109 Style::default()
110 .fg(self.fg)
111 .bg(self.bg)
112 .underline_color(self.underline_color)
113 .underline_style(self.underline_style)
114 .add_modifier(self.modifier)
115 }
116
117 /// Resets the cell to a default blank state
118 pub fn reset(&mut self) {
119 *self = Self::default();
120 }
121 }
122
123 impl Default for Cell {
124 fn default() -> Cell {
125 Cell {
126 symbol: Symbol::from(" ").unwrap(),
127 width: 1,
128 fg: Color::Reset,
129 bg: Color::Reset,
130 underline_color: Color::Reset,
131 underline_style: UnderlineStyle::Reset,
132 modifier: Modifier::empty(),
133 }
134 }
135 }
136
137 /// A buffer that maps to the desired content of the terminal after the draw call
138 ///
139 /// No widget in the library interacts directly with the terminal. Instead each of them is required
140 /// to draw their state to an intermediate buffer. It is basically a grid where each cell contains
141 /// a grapheme, a foreground color and a background color. This grid will then be used to output
142 /// the appropriate escape sequences and characters to draw the UI as the user has defined it.
143 ///
144 /// # Examples:
145 ///
146 /// ```
147 /// use helix_tui::buffer::{Buffer, Cell, Symbol};
148 /// use helix_view::graphics::{Rect, Color, UnderlineStyle, Style, Modifier};
149 ///
150 /// let mut buf = Buffer::empty(Rect{x: 0, y: 0, width: 10, height: 5});
151 /// buf[(0, 2)].set_symbol("x");
152 /// assert_eq!(&*buf[(0, 2)].symbol, "x");
153 /// buf.set_string(3, 0, "string", Style::default().fg(Color::Red).bg(Color::White));
154 /// let mut expected = Cell::default();
155 /// expected.set_symbol("r");
156 /// expected.set_style(Style::default().fg(Color::Red).bg(Color::White));
157 /// assert_eq!(buf[(5, 0)], expected);
158 /// buf[(5, 0)].set_char('x');
159 /// assert_eq!(&*buf[(5, 0)].symbol, "x");
160 /// ```
161 #[derive(Debug, Default, Clone, PartialEq, Eq)]
162 pub struct Buffer {
163 /// The area represented by this buffer
164 pub area: Rect,
165 /// The content of the buffer. The length of this Vec should always be equal to area.width *
166 /// area.height
167 pub content: Vec<Cell>,
168 }
169
170 impl Buffer {
171 /// Returns a Buffer with all cells set to the default one
172 #[must_use]
173 pub fn empty(area: Rect) -> Buffer {
174 Buffer::filled(area, &Cell::default())
175 }
176
177 /// Returns a Buffer with all cells initialized with the attributes of the given Cell
178 #[must_use]
179 pub fn filled(area: Rect, cell: &Cell) -> Buffer {
180 let size = area.area();
181 let content = vec![cell.clone(); size];
182 Buffer { area, content }
183 }
184
185 /// Returns a Buffer containing the given lines
186 #[must_use]
187 pub fn with_lines<S>(lines: Vec<S>) -> Buffer
188 where
189 S: AsRef<str>,
190 {
191 let height = lines.len() as u16;
192 let width = lines
193 .iter()
194 .map(|i| i.as_ref().width() as u16)
195 .max()
196 .unwrap_or_default();
197 let mut buffer = Buffer::empty(Rect {
198 x: 0,
199 y: 0,
200 width,
201 height,
202 });
203 for (y, line) in lines.iter().enumerate() {
204 buffer.set_string(0, y as u16, line.as_ref(), Style::default());
205 }
206 buffer
207 }
208
209 /// Returns the content of the buffer as a slice
210 pub fn content(&self) -> &[Cell] {
211 &self.content
212 }
213
214 /// Returns the area covered by this buffer
215 pub fn area(&self) -> &Rect {
216 &self.area
217 }
218
219 /// Returns a reference to Cell at the given coordinates
220 pub fn get(&self, x: u16, y: u16) -> Option<&Cell> {
221 self.index_of_opt(x, y).map(|i| &self.content[i])
222 }
223
224 /// Returns a mutable reference to Cell at the given coordinates
225 pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut Cell> {
226 self.index_of_opt(x, y).map(|i| &mut self.content[i])
227 }
228
229 /// Tells whether the global (x, y) coordinates are inside the Buffer's area.
230 ///
231 /// Global coordinates are offset by the Buffer's area offset (`x`/`y`).
232 ///
233 /// # Examples
234 ///
235 /// ```
236 /// # use helix_tui::buffer::Buffer;
237 /// # use helix_view::graphics::Rect;
238 /// let rect = Rect::new(200, 100, 10, 10);
239 /// let buffer = Buffer::empty(rect);
240 /// // Global coordinates inside the Buffer's area
241 /// assert!(buffer.in_bounds(209, 100));
242 /// // Global coordinates outside the Buffer's area
243 /// assert!(!buffer.in_bounds(210, 100));
244 /// ```
245 ///
246 /// Global coordinates are offset by the Buffer's area offset (`x`/`y`).
247 pub fn in_bounds(&self, x: u16, y: u16) -> bool {
248 x >= self.area.left()
249 && x < self.area.right()
250 && y >= self.area.top()
251 && y < self.area.bottom()
252 }
253
254 /// Returns the index in the `Vec<Cell>` for the given global (x, y) coordinates.
255 ///
256 /// Global coordinates are offset by the Buffer's area offset (`x`/`y`).
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// # use helix_tui::buffer::Buffer;
262 /// # use helix_view::graphics::Rect;
263 /// let rect = Rect::new(200, 100, 10, 10);
264 /// let buffer = Buffer::empty(rect);
265 /// // Global coordinates to the top corner of this Buffer's area
266 /// assert_eq!(buffer.index_of(200, 100), 0);
267 /// ```
268 ///
269 /// # Panics
270 ///
271 /// Panics when given an coordinate that is outside of this Buffer's area.
272 pub fn index_of(&self, x: u16, y: u16) -> usize {
273 debug_assert!(
274 self.in_bounds(x, y),
275 "Trying to access position outside the buffer: x={}, y={}, area={:?}",
276 x,
277 y,
278 self.area
279 );
280 ((y - self.area.y) as usize) * (self.area.width as usize) + ((x - self.area.x) as usize)
281 }
282
283 /// Returns the index in the `Vec<Cell>` for the given global (x, y) coordinates,
284 /// or `None` if the coordinates are outside the buffer's area.
285 fn index_of_opt(&self, x: u16, y: u16) -> Option<usize> {
286 if self.in_bounds(x, y) {
287 Some(self.index_of(x, y))
288 } else {
289 None
290 }
291 }
292
293 /// Returns the (global) coordinates of a cell given its index
294 ///
295 /// Global coordinates are offset by the Buffer's area offset (`x`/`y`).
296 ///
297 /// # Examples
298 ///
299 /// ```
300 /// # use helix_tui::buffer::Buffer;
301 /// # use helix_view::graphics::Rect;
302 /// let rect = Rect::new(200, 100, 10, 10);
303 /// let buffer = Buffer::empty(rect);
304 /// assert_eq!(buffer.pos_of(0), (200, 100));
305 /// assert_eq!(buffer.pos_of(14), (204, 101));
306 /// ```
307 ///
308 /// # Panics
309 ///
310 /// Panics when given an index that is outside the Buffer's content.
311 pub fn pos_of(&self, i: usize) -> (u16, u16) {
312 debug_assert!(
313 i < self.content.len(),
314 "Trying to get the coords of a cell outside the buffer: i={} len={}",
315 i,
316 self.content.len()
317 );
318 (
319 (self.area.x as usize + (i % self.area.width as usize)) as u16,
320 (self.area.y as usize + (i / self.area.width as usize)) as u16,
321 )
322 }
323
324 /// Print a string, starting at the position (x, y)
325 pub fn set_string(&mut self, x: u16, y: u16, string: &str, style: Style) {
326 self.set_stringn(x, y, string, usize::MAX, style);
327 }
328
329 /// Print at most the first `width` columns of `string`, starting at (x, y),
330 /// stopping at the end of the buffer line. Returns the position right after
331 /// the last cell written.
332 pub fn set_stringn(
333 &mut self,
334 x: u16,
335 y: u16,
336 string: &str,
337 width: usize,
338 style: Style,
339 ) -> (u16, u16) {
340 // prevent panic if out of range
341 if !self.in_bounds(x, y) {
342 return (x, y);
343 }
344
345 let mut index = self.index_of(x, y);
346 let mut x_offset = x as usize;
347 let max_x_offset = min(self.area.right() as usize, width.saturating_add(x as usize));
348
349 for s in string.graphemes(true) {
350 let grapheme_width = s.width();
351 if grapheme_width == 0 {
352 continue;
353 }
354 // `x_offset + grapheme_width > max_x_offset` could be integer overflow on
355 // 32-bit machines if we change dimensions to usize or u32 and someone
356 // resizes the terminal to 1x2^32.
357 if grapheme_width > max_x_offset.saturating_sub(x_offset) {
358 break;
359 }
360
361 self.content[index].set_symbol(s);
362 self.content[index].set_style(style);
363 // Reset following cells if multi-width (they would be hidden by the grapheme),
364 for i in index + 1..index + grapheme_width {
365 self.content[i].reset();
366 }
367 index += grapheme_width;
368 x_offset += grapheme_width;
369 }
370
371 (x_offset as u16, y)
372 }
373
374 /// Fast path: print a single grapheme of pre-computed width with no unicode
375 /// segmentation / width recomputation. Caller must guarantee the grapheme +
376 /// width fit inside the buffer area and that `width >= 1`.
377 ///
378 /// This is the per-cell render path; it is hot enough that we skip everything
379 /// `set_stringn` does (segmenting, calling `.width()`, bounds-checking each
380 /// grapheme).
381 #[inline]
382 pub fn set_grapheme(&mut self, x: u16, y: u16, grapheme: &str, width: usize, style: Style) {
383 let index = self.index_of(x, y);
384 let cell = &mut self.content[index];
385 cell.set_symbol_with_width(grapheme, width as u8);
386 cell.set_style(style);
387 // Reset following cells if the grapheme spans multiple columns; they
388 // would be hidden by the grapheme but must not carry stale content.
389 for i in index + 1..index + width {
390 self.content[i].reset();
391 }
392 }
393
394 /// Fast path for tab expansion: write each char of `tab` into its own
395 /// single-column cell starting at (x, y), all sharing `style`.
396 ///
397 /// Unlike [`Self::set_grapheme`], the columns are written as independent
398 /// width-1 cells rather than one wide cell, so background styles (selection,
399 /// cursorline) cover every column. Caller must guarantee each char is one column
400 /// and that the whole run fits inside the buffer area.
401 #[inline]
402 pub fn set_tab(&mut self, x: u16, y: u16, tab: &str, style: Style) {
403 let mut index = self.index_of(x, y);
404 for (i, ch) in tab.char_indices() {
405 let cell = &mut self.content[index];
406 cell.set_symbol_with_width(&tab[i..i + ch.len_utf8()], 1);
407 cell.set_style(style);
408 index += 1;
409 }
410 }
411
412 /// Print at most the first `width` characters of a string if enough space is available
413 /// until the end of the line.
414 /// If `ellipsis` is true appends a `…` at the end of truncated lines.
415 /// If `truncate_start` is `true`, adds a `…` at the beginning of truncated lines.
416 #[allow(clippy::too_many_arguments)]
417 pub fn set_string_anchored(
418 &mut self,
419 x: u16,
420 y: u16,
421 truncate_start: bool,
422 truncate_end: bool,
423 string: &str,
424 width: usize,
425 style: impl Fn(usize) -> Style, // Map a grapheme's string offset to a style
426 ) -> (u16, u16) {
427 // prevent panic if out of range
428 if !self.in_bounds(x, y) || width == 0 {
429 return (x, y);
430 }
431
432 let mut index = self.index_of(x, y);
433 let mut rendered_width = 0;
434 let mut graphemes = string.grapheme_indices(true);
435
436 if truncate_start {
437 for _ in 0..graphemes.next().map(|(_, g)| g.width()).unwrap_or_default() {
438 self.content[index].set_symbol("…");
439 index += 1;
440 rendered_width += 1;
441 }
442 }
443
444 for (byte_offset, s) in graphemes {
445 let grapheme_width = s.width();
446 if truncate_end && rendered_width + grapheme_width >= width {
447 break;
448 }
449 if grapheme_width == 0 {
450 continue;
451 }
452
453 self.content[index].set_symbol(s);
454 self.content[index].set_style(style(byte_offset));
455
456 // Reset following cells if multi-width (they would be hidden by the grapheme):
457 for i in index + 1..index + grapheme_width {
458 self.content[i].reset();
459 }
460
461 index += grapheme_width;
462 rendered_width += grapheme_width;
463 }
464
465 if truncate_end {
466 for _ in 0..width.saturating_sub(rendered_width) {
467 self.content[index].set_symbol("…");
468 index += 1;
469 }
470 }
471
472 (x, y)
473 }
474
475 /// Print at most the first `width` characters of a string if enough space is available
476 /// until the end of the line. If `ellipsis` is true appends a `…` at the end of
477 /// truncated lines. If `truncate_start` is `true`, truncate the beginning of the string
478 /// instead of the end.
479 #[allow(clippy::too_many_arguments)]
480 pub fn set_string_truncated(
481 &mut self,
482 x: u16,
483 y: u16,
484 string: &str,
485 width: usize,
486 style: impl Fn(usize) -> Style, // Map a grapheme's string offset to a style
487 ellipsis: bool,
488 truncate_start: bool,
489 ) -> (u16, u16) {
490 // prevent panic if out of range
491 if !self.in_bounds(x, y) || width == 0 {
492 return (x, y);
493 }
494
495 let mut index = self.index_of(x, y);
496 let mut x_offset = x as usize;
497 let width = if ellipsis { width - 1 } else { width };
498 let graphemes = string.grapheme_indices(true);
499 let max_offset = min(self.area.right() as usize, width.saturating_add(x as usize));
500 if !truncate_start {
501 for (byte_offset, s) in graphemes {
502 let width = s.width();
503 if width == 0 {
504 continue;
505 }
506 // `x_offset + width > max_offset` could be integer overflow on 32-bit machines if we
507 // change dimensions to usize or u32 and someone resizes the terminal to 1x2^32.
508 if width > max_offset.saturating_sub(x_offset) {
509 break;
510 }
511
512 self.content[index].set_symbol(s);
513 self.content[index].set_style(style(byte_offset));
514 // Reset following cells if multi-width (they would be hidden by the grapheme),
515 for i in index + 1..index + width {
516 self.content[i].reset();
517 }
518 index += width;
519 x_offset += width;
520 }
521 if ellipsis && x_offset - (x as usize) < string.width() {
522 self.content[index].set_symbol("…");
523 }
524 } else {
525 let mut start_index = self.index_of(x, y);
526 let mut index = self.index_of(max_offset as u16, y);
527
528 let content_width = string.width();
529 let truncated = content_width > width;
530 if ellipsis && truncated {
531 self.content[start_index].set_symbol("…");
532 start_index += 1;
533 }
534 if !truncated {
535 index -= width - content_width;
536 }
537 for (byte_offset, s) in graphemes.rev() {
538 let width = s.width();
539 if width == 0 {
540 continue;
541 }
542 let start = index - width;
543 if start < start_index {
544 break;
545 }
546 self.content[start].set_symbol(s);
547 self.content[start].set_style(style(byte_offset));
548 for i in start + 1..index {
549 self.content[i].reset();
550 }
551 index -= width;
552 x_offset += width;
553 }
554 }
555 (x_offset as u16, y)
556 }
557
558 /// Print at most the first `width` characters of a [Spans] if enough space is available
559 /// until the end of the line. Appends a `…` at the end of truncated lines.
560 pub fn set_spans_truncated(&mut self, x: u16, y: u16, spans: &Spans, width: u16) -> (u16, u16) {
561 // prevent panic if out of range
562 if !self.in_bounds(x, y) || width == 0 {
563 return (x, y);
564 }
565
566 let mut x_offset = x as usize;
567 let max_offset = min(self.area.right(), width.saturating_add(x));
568 let mut start_index = self.index_of(x, y);
569 let mut index = self.index_of(max_offset, y);
570
571 let content_width = spans.width();
572 let truncated = content_width > width as usize;
573 if truncated {
574 self.content[start_index].set_symbol("…");
575 start_index += 1;
576 } else {
577 index -= width as usize - content_width;
578 }
579 for span in spans.0.iter().rev() {
580 for s in span.content.graphemes(true).rev() {
581 let width = s.width();
582 if width == 0 {
583 continue;
584 }
585 let start = index - width;
586 if start < start_index {
587 break;
588 }
589 self.content[start].set_symbol(s);
590 self.content[start].set_style(span.style);
591 for i in start + 1..index {
592 self.content[i].reset();
593 }
594 index -= width;
595 x_offset += width;
596 }
597 }
598 (x_offset as u16, y)
599 }
600
601 /// Print at most the first `width` characters of a [Spans] if enough space is available
602 /// until the end of the line
603 pub fn set_spans(&mut self, x: u16, y: u16, spans: &Spans, width: u16) -> (u16, u16) {
604 let mut remaining_width = width;
605 let mut x = x;
606 for span in &spans.0 {
607 if remaining_width == 0 {
608 break;
609 }
610 let pos = self.set_stringn(
611 x,
612 y,
613 span.content.as_ref(),
614 remaining_width as usize,
615 span.style,
616 );
617 let w = pos.0.saturating_sub(x);
618 x = pos.0;
619 remaining_width = remaining_width.saturating_sub(w);
620 }
621 (x, y)
622 }
623
624 /// Print at most the first `width` characters of a [Span] if enough space is available
625 /// until the end of the line
626 pub fn set_span(&mut self, x: u16, y: u16, span: &Span, width: u16) -> (u16, u16) {
627 self.set_stringn(x, y, span.content.as_ref(), width as usize, span.style)
628 }
629
630 #[deprecated(
631 since = "0.10.0",
632 note = "You should use styling capabilities of `Buffer::set_style`"
633 )]
634 pub fn set_background(&mut self, area: Rect, color: Color) {
635 for y in area.top()..area.bottom() {
636 for x in area.left()..area.right() {
637 self[(x, y)].set_bg(color);
638 }
639 }
640 }
641
642 /// Set all cells in the [area](Rect) to the given [Style]
643 pub fn set_style(&mut self, area: Rect, style: Style) {
644 for y in area.top()..area.bottom() {
645 for x in area.left()..area.right() {
646 self[(x, y)].set_style(style);
647 }
648 }
649 }
650
651 /// Resize the buffer so that the mapped area matches the given area and that the buffer
652 /// length is equal to area.width * area.height
653 pub fn resize(&mut self, area: Rect) {
654 let length = area.area();
655 if self.content.len() > length {
656 self.content.truncate(length);
657 } else {
658 self.content.resize(length, Default::default());
659 }
660 self.area = area;
661 }
662
663 /// Reset all cells in the buffer
664 pub fn reset(&mut self) {
665 for c in &mut self.content {
666 c.reset();
667 }
668 }
669
670 /// Clear an area in the buffer
671 pub fn clear(&mut self, area: Rect) {
672 for x in area.left()..area.right() {
673 for y in area.top()..area.bottom() {
674 self[(x, y)].reset();
675 }
676 }
677 }
678
679 /// Clear an area in the buffer with a default style.
680 pub fn clear_with(&mut self, area: Rect, style: Style) {
681 for x in area.left()..area.right() {
682 for y in area.top()..area.bottom() {
683 let cell = &mut self[(x, y)];
684 cell.reset();
685 cell.set_style(style);
686 }
687 }
688 }
689
690 /// Merge an other buffer into this one
691 pub fn merge(&mut self, other: &Buffer) {
692 let area = self.area.union(other.area);
693 let cell: Cell = Default::default();
694 self.content.resize(area.area(), cell.clone());
695
696 // Move original content to the appropriate space
697 let size = self.area.area();
698 for i in (0..size).rev() {
699 let (x, y) = self.pos_of(i);
700 // New index in content
701 let k = ((y - area.y) * area.width + x - area.x) as usize;
702 if i != k {
703 self.content[k] = self.content[i].clone();
704 self.content[i] = cell.clone();
705 }
706 }
707
708 // Push content of the other buffer into this one (may erase previous
709 // data)
710 let size = other.area.area();
711 for i in 0..size {
712 let (x, y) = other.pos_of(i);
713 // New index in content
714 let k = ((y - area.y) * area.width + x - area.x) as usize;
715 self.content[k] = other.content[i].clone();
716 }
717 self.area = area;
718 }
719
720 /// Builds a minimal sequence of coordinates and Cells necessary to update the UI from
721 /// self to other.
722 ///
723 /// We're assuming that buffers are well-formed, that is no double-width cell is followed by
724 /// a non-blank cell.
725 ///
726 /// # Multi-width characters handling:
727 ///
728 /// ```text
729 /// (Index:) `01`
730 /// Prev: `γ‚³`
731 /// Next: `aa`
732 /// Updates: `0: a, 1: a'
733 /// ```
734 ///
735 /// ```text
736 /// (Index:) `01`
737 /// Prev: `a `
738 /// Next: `γ‚³`
739 /// Updates: `0: γ‚³` (double width symbol at index 0 - skip index 1)
740 /// ```
741 ///
742 /// ```text
743 /// (Index:) `012`
744 /// Prev: `aaa`
745 /// Next: `aγ‚³`
746 /// Updates: `0: a, 1: γ‚³` (double width symbol at index 1 - skip index 2)
747 /// ```
748 pub fn diff<'a>(&self, other: &'a Buffer) -> Vec<(u16, u16, &'a Cell)> {
749 let previous_buffer = &self.content;
750 let next_buffer = &other.content;
751 let width = self.area.width;
752
753 let mut updates: Vec<(u16, u16, &Cell)> = vec![];
754 // Cells invalidated by drawing/replacing preceding multi-width characters:
755 let mut invalidated: usize = 0;
756 // Cells from the current buffer to skip due to preceding multi-width characters taking their
757 // place (the skipped cells should be blank anyway):
758 let mut to_skip: usize = 0;
759 for (i, (current, previous)) in next_buffer.iter().zip(previous_buffer.iter()).enumerate() {
760 if (current != previous || invalidated > 0) && to_skip == 0 {
761 let x = (i % width as usize) as u16;
762 let y = (i / width as usize) as u16;
763 updates.push((x, y, &next_buffer[i]));
764 }
765
766 let current_width = current.width();
767 to_skip = current_width.saturating_sub(1);
768
769 let affected_width = std::cmp::max(current_width, previous.width());
770 invalidated = std::cmp::max(affected_width, invalidated).saturating_sub(1);
771 }
772 updates
773 }
774 }
775
776 impl std::ops::Index<(u16, u16)> for Buffer {
777 type Output = Cell;
778
779 fn index(&self, (x, y): (u16, u16)) -> &Self::Output {
780 let i = self.index_of(x, y);
781 &self.content[i]
782 }
783 }
784
785 impl std::ops::IndexMut<(u16, u16)> for Buffer {
786 fn index_mut(&mut self, (x, y): (u16, u16)) -> &mut Self::Output {
787 let i = self.index_of(x, y);
788 &mut self.content[i]
789 }
790 }
791
792 #[cfg(test)]
793 mod tests {
794 use super::*;
795
796 fn cell(s: &str) -> Cell {
797 let mut cell = Cell::default();
798 cell.set_symbol(s);
799 cell
800 }
801
802 #[test]
803 fn it_translates_to_and_from_coordinates() {
804 let rect = Rect::new(200, 100, 50, 80);
805 let buf = Buffer::empty(rect);
806
807 // First cell is at the upper left corner.
808 assert_eq!(buf.pos_of(0), (200, 100));
809 assert_eq!(buf.index_of(200, 100), 0);
810
811 // Last cell is in the lower right.
812 assert_eq!(buf.pos_of(buf.content.len() - 1), (249, 179));
813 assert_eq!(buf.index_of(249, 179), buf.content.len() - 1);
814 }
815
816 #[test]
817 #[should_panic(expected = "outside the buffer")]
818 #[cfg(debug_assertions)]
819 fn pos_of_panics_on_out_of_bounds() {
820 let rect = Rect::new(0, 0, 10, 10);
821 let buf = Buffer::empty(rect);
822
823 // There are a total of 100 cells; zero-indexed means that 100 would be the 101st cell.
824 buf.pos_of(100);
825 }
826
827 #[test]
828 #[should_panic(expected = "outside the buffer")]
829 #[cfg(debug_assertions)]
830 fn index_of_panics_on_out_of_bounds() {
831 let rect = Rect::new(0, 0, 10, 10);
832 let buf = Buffer::empty(rect);
833
834 // width is 10; zero-indexed means that 10 would be the 11th cell.
835 buf.index_of(10, 0);
836 }
837
838 #[test]
839 fn buffer_set_string() {
840 let area = Rect::new(0, 0, 5, 1);
841 let mut buffer = Buffer::empty(area);
842
843 // Zero-width
844 buffer.set_stringn(0, 0, "aaa", 0, Style::default());
845 assert_eq!(buffer, Buffer::with_lines(vec![" "]));
846
847 buffer.set_string(0, 0, "aaa", Style::default());
848 assert_eq!(buffer, Buffer::with_lines(vec!["aaa "]));
849
850 // Width limit:
851 buffer.set_stringn(0, 0, "bbbbbbbbbbbbbb", 4, Style::default());
852 assert_eq!(buffer, Buffer::with_lines(vec!["bbbb "]));
853
854 buffer.set_string(0, 0, "12345", Style::default());
855 assert_eq!(buffer, Buffer::with_lines(vec!["12345"]));
856
857 // Width truncation:
858 buffer.set_string(0, 0, "123456", Style::default());
859 assert_eq!(buffer, Buffer::with_lines(vec!["12345"]));
860 }
861
862 #[test]
863 fn buffer_set_string_zero_width() {
864 let area = Rect::new(0, 0, 1, 1);
865 let mut buffer = Buffer::empty(area);
866
867 // U+200B is the zero-width space codepoint
868 assert_eq!("\u{200B}".width(), 0);
869
870 // Leading grapheme with zero width
871 let s = "\u{200B}a";
872 buffer.set_stringn(0, 0, s, 1, Style::default());
873 assert_eq!(buffer, Buffer::with_lines(vec!["a"]));
874
875 // Trailing grapheme with zero width
876 let s = "a\u{200B}";
877 buffer.set_stringn(0, 0, s, 1, Style::default());
878 assert_eq!(buffer, Buffer::with_lines(vec!["a"]));
879 }
880
881 #[test]
882 fn buffer_set_string_double_width() {
883 let area = Rect::new(0, 0, 5, 1);
884 let mut buffer = Buffer::empty(area);
885 buffer.set_string(0, 0, "コン", Style::default());
886 assert_eq!(buffer, Buffer::with_lines(vec!["コン "]));
887
888 // Only 1 space left.
889 buffer.set_string(0, 0, "コンピ", Style::default());
890 assert_eq!(buffer, Buffer::with_lines(vec!["コン "]));
891 }
892
893 #[test]
894 fn buffer_with_lines() {
895 let buffer =
896 Buffer::with_lines(vec!["β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”", "│コンピγƒ₯β”‚", "β”‚γƒΌa δΈŠγ§β”‚", "β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜"]);
897 assert_eq!(buffer.area.x, 0);
898 assert_eq!(buffer.area.y, 0);
899 assert_eq!(buffer.area.width, 10);
900 assert_eq!(buffer.area.height, 4);
901 }
902
903 #[test]
904 fn buffer_diffing_empty_empty() {
905 let area = Rect::new(0, 0, 40, 40);
906 let prev = Buffer::empty(area);
907 let next = Buffer::empty(area);
908 let diff = prev.diff(&next);
909 assert_eq!(diff, vec![]);
910 }
911
912 #[test]
913 fn buffer_diffing_empty_filled() {
914 let area = Rect::new(0, 0, 40, 40);
915 let prev = Buffer::empty(area);
916 let next = Buffer::filled(area, Cell::default().set_symbol("a"));
917 let diff = prev.diff(&next);
918 assert_eq!(diff.len(), 40 * 40);
919 }
920
921 #[test]
922 fn buffer_diffing_filled_filled() {
923 let area = Rect::new(0, 0, 40, 40);
924 let prev = Buffer::filled(area, Cell::default().set_symbol("a"));
925 let next = Buffer::filled(area, Cell::default().set_symbol("a"));
926 let diff = prev.diff(&next);
927 assert_eq!(diff, vec![]);
928 }
929
930 #[test]
931 fn buffer_diffing_single_width() {
932 let prev = Buffer::with_lines(vec![
933 " ",
934 "β”ŒTitle─┐ ",
935 "β”‚ β”‚ ",
936 "β”‚ β”‚ ",
937 "β””β”€β”€β”€β”€β”€β”€β”˜ ",
938 ]);
939 let next = Buffer::with_lines(vec![
940 " ",
941 "β”ŒTITLE─┐ ",
942 "β”‚ β”‚ ",
943 "β”‚ β”‚ ",
944 "β””β”€β”€β”€β”€β”€β”€β”˜ ",
945 ]);
946 let diff = prev.diff(&next);
947 assert_eq!(
948 diff,
949 vec![
950 (2, 1, &cell("I")),
951 (3, 1, &cell("T")),
952 (4, 1, &cell("L")),
953 (5, 1, &cell("E")),
954 ]
955 );
956 }
957
958 #[test]
959 #[rustfmt::skip]
960 fn buffer_diffing_multi_width() {
961 let prev = Buffer::with_lines(vec![
962 "β”ŒTitle─┐ ",
963 "β””β”€β”€β”€β”€β”€β”€β”˜ ",
964 ]);
965 let next = Buffer::with_lines(vec![
966 "β”Œη§°ε·β”€β”€β” ",
967 "β””β”€β”€β”€β”€β”€β”€β”˜ ",
968 ]);
969 let diff = prev.diff(&next);
970 assert_eq!(
971 diff,
972 vec![
973 (1, 0, &cell("η§°")),
974 // Skipped "i"
975 (3, 0, &cell("号")),
976 // Skipped "l"
977 (5, 0, &cell("─")),
978 ]
979 );
980 }
981
982 #[test]
983 fn buffer_diffing_multi_width_offset() {
984 let prev = Buffer::with_lines(vec!["β”Œη§°ε·β”€β”€β”"]);
985 let next = Buffer::with_lines(vec!["β”Œβ”€η§°ε·β”€β”"]);
986
987 let diff = prev.diff(&next);
988 assert_eq!(
989 diff,
990 vec![(1, 0, &cell("─")), (2, 0, &cell("η§°")), (4, 0, &cell("号")),]
991 );
992 }
993
994 #[test]
995 fn buffer_merge() {
996 let mut one = Buffer::filled(
997 Rect {
998 x: 0,
999 y: 0,
1000 width: 2,
1001 height: 2,
1002 },
1003 Cell::default().set_symbol("1"),
1004 );
1005 let two = Buffer::filled(
1006 Rect {
1007 x: 0,
1008 y: 2,
1009 width: 2,
1010 height: 2,
1011 },
1012 Cell::default().set_symbol("2"),
1013 );
1014 one.merge(&two);
1015 assert_eq!(one, Buffer::with_lines(vec!["11", "11", "22", "22"]));
1016 }
1017
1018 #[test]
1019 fn buffer_merge2() {
1020 let mut one = Buffer::filled(
1021 Rect {
1022 x: 2,
1023 y: 2,
1024 width: 2,
1025 height: 2,
1026 },
1027 Cell::default().set_symbol("1"),
1028 );
1029 let two = Buffer::filled(
1030 Rect {
1031 x: 0,
1032 y: 0,
1033 width: 2,
1034 height: 2,
1035 },
1036 Cell::default().set_symbol("2"),
1037 );
1038 one.merge(&two);
1039 assert_eq!(
1040 one,
1041 Buffer::with_lines(vec!["22 ", "22 ", " 11", " 11"])
1042 );
1043 }
1044
1045 #[test]
1046 fn buffer_merge3() {
1047 let mut one = Buffer::filled(
1048 Rect {
1049 x: 3,
1050 y: 3,
1051 width: 2,
1052 height: 2,
1053 },
1054 Cell::default().set_symbol("1"),
1055 );
1056 let two = Buffer::filled(
1057 Rect {
1058 x: 1,
1059 y: 1,
1060 width: 3,
1061 height: 4,
1062 },
1063 Cell::default().set_symbol("2"),
1064 );
1065 one.merge(&two);
1066 let mut merged = Buffer::with_lines(vec!["222 ", "222 ", "2221", "2221"]);
1067 merged.area = Rect {
1068 x: 1,
1069 y: 1,
1070 width: 4,
1071 height: 4,
1072 };
1073 assert_eq!(one, merged);
1074 }
1075
1076 // ==================== Unicode / Emoji Tests ====================
1077
1078 #[test]
1079 fn cell_set_symbol_various_unicode() {
1080 let test_cases = ["πŸ”₯", "πŸ‘©β€πŸ’»", "πŸ‡«πŸ‡·", "πŸ‘‹πŸ½", "e\u{0301}", "ν•œ", "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦"];
1081
1082 for symbol in test_cases {
1083 let mut cell = Cell::default();
1084 cell.set_symbol(symbol);
1085 assert_eq!(cell.symbol, *symbol);
1086 }
1087 }
1088
1089 #[test]
1090 fn buffer_set_string_double_width_and_emoji() {
1091 let area = Rect::new(0, 0, 12, 1);
1092 let mut buffer = Buffer::empty(area);
1093
1094 // Mix of emojis, CJK, and ASCII
1095 buffer.set_string(0, 0, "πŸ”₯ζΌ’a", Style::default());
1096
1097 assert_eq!(&*buffer[(0, 0)].symbol, "πŸ”₯");
1098 assert_eq!(&*buffer[(1, 0)].symbol, " "); // Covered by emoji
1099 assert_eq!(&*buffer[(2, 0)].symbol, "ζΌ’");
1100 assert_eq!(&*buffer[(3, 0)].symbol, " "); // Covered by CJK
1101 assert_eq!(&*buffer[(4, 0)].symbol, "a");
1102 }
1103
1104 #[test]
1105 fn buffer_set_string_combining_diacritics() {
1106 // "EΔ₯oŝanĝo Δ‰iuΔ΅aΕ­de" using combining marks
1107 let text = "Eh\u{0302}os\u{0302}ang\u{0302}o c\u{0302}iuj\u{0302}au\u{0306}de";
1108 let area = Rect::new(0, 0, 20, 1);
1109 let mut buffer = Buffer::empty(area);
1110
1111 buffer.set_string(0, 0, text, Style::default());
1112
1113 let graphemes: Vec<_> = text.graphemes(true).collect();
1114 for (i, &g) in graphemes.iter().enumerate() {
1115 assert_eq!(&*buffer[(i as u16, 0)].symbol, g);
1116 }
1117 }
1118
1119 #[test]
1120 fn buffer_diffing_with_emoji() {
1121 let prev = Buffer::with_lines(vec!["πŸ”₯test"]);
1122 let next = Buffer::with_lines(vec!["xxtest"]);
1123
1124 let diff = prev.diff(&next);
1125
1126 // Should update positions where the emoji was
1127 assert!(diff.iter().any(|(x, _, c)| *x == 0 && &*c.symbol == "x"));
1128 }
1129
1130 #[test]
1131 fn buffer_truncation_with_wide_chars() {
1132 let area = Rect::new(0, 0, 5, 1);
1133 let mut buffer = Buffer::empty(area);
1134
1135 // "AAAA" (4) + "ζΌ’" (2) = 6, but buffer is 5 wide
1136 buffer.set_string(0, 0, "AAAAζΌ’", Style::default());
1137
1138 // Should not partially render the wide char
1139 assert_eq!(&*buffer[(4, 0)].symbol, " ");
1140 }
1141
1142 #[test]
1143 fn buffer_overwrite_emoji_and_ascii() {
1144 let area = Rect::new(0, 0, 8, 1);
1145 let mut buffer = Buffer::empty(area);
1146
1147 // Write emoji then overwrite with ASCII
1148 buffer.set_string(0, 0, "πŸ”₯πŸš€", Style::default());
1149 buffer.set_string(0, 0, "abcd", Style::default());
1150
1151 assert_eq!(&*buffer[(0, 0)].symbol, "a");
1152 assert_eq!(&*buffer[(1, 0)].symbol, "b");
1153
1154 // Write ASCII then overwrite with emoji
1155 buffer.set_string(0, 0, "abcd", Style::default());
1156 buffer.set_string(0, 0, "πŸ”₯πŸš€", Style::default());
1157
1158 assert_eq!(&*buffer[(0, 0)].symbol, "πŸ”₯");
1159 assert_eq!(&*buffer[(2, 0)].symbol, "πŸš€");
1160 }
1161
1162 // ==================== Adversarial Unicode Tests ====================
1163 // These test valid but unusual Unicode that stresses edge cases
1164
1165 #[test]
1166 fn adversarial_zalgo_text() {
1167 // Base character with stacked combining marks
1168 let zalgo = "X\u{0303}\u{0304}\u{0305}";
1169 let area = Rect::new(0, 0, 10, 1);
1170 let mut buffer = Buffer::empty(area);
1171
1172 buffer.set_string(0, 0, zalgo, Style::default());
1173
1174 assert_eq!(&*buffer[(0, 0)].symbol, zalgo);
1175 assert_eq!(&*buffer[(1, 0)].symbol, " ");
1176 }
1177
1178 #[test]
1179 fn adversarial_zero_width_chars() {
1180 // Zero-width joiners and spaces
1181 let text = "a\u{200B}b\u{200D}c";
1182 let area = Rect::new(0, 0, 10, 1);
1183 let mut buffer = Buffer::empty(area);
1184
1185 buffer.set_string(0, 0, text, Style::default());
1186
1187 // Zero-width chars shouldn't take space
1188 assert_eq!(&*buffer[(0, 0)].symbol, "a");
1189 // ZWJ attaches to the preceding character
1190 assert_eq!(&*buffer[(1, 0)].symbol, "b\u{200D}");
1191 assert_eq!(&*buffer[(2, 0)].symbol, "c");
1192 }
1193
1194 #[test]
1195 fn adversarial_bidi_and_formatting() {
1196 // RTL override and BOM
1197 let bidi = "\u{202E}abc\u{202C}";
1198 let bom = "\u{FEFF}text";
1199 let area = Rect::new(0, 0, 10, 1);
1200 let mut buffer = Buffer::empty(area);
1201
1202 buffer.set_string(0, 0, bidi, Style::default());
1203 assert_eq!(&*buffer[(0, 0)].symbol, "a");
1204
1205 buffer.set_string(0, 0, bom, Style::default());
1206 assert_eq!(&*buffer[(0, 0)].symbol, "t");
1207 }
1208
1209 #[test]
1210 fn adversarial_supplementary_planes() {
1211 // High codepoints from supplementary planes
1212 let supp = "\u{10000}π„žπ’€€π“€€";
1213 let area = Rect::new(0, 0, 10, 1);
1214 let mut buffer = Buffer::empty(area);
1215
1216 buffer.set_string(0, 0, supp, Style::default());
1217
1218 assert!(!buffer[(0, 0)].symbol.is_empty());
1219 }
1220
1221 #[test]
1222 fn adversarial_regional_indicators() {
1223 // Unpaired and triple regional indicators
1224 let single_ri = "\u{1F1E6}";
1225 let three = "\u{1F1FA}\u{1F1F8}\u{1F1E6}"; // US flag + orphan
1226 let area = Rect::new(0, 0, 10, 1);
1227 let mut buffer = Buffer::empty(area);
1228
1229 buffer.set_string(0, 0, single_ri, Style::default());
1230 assert_eq!(&*buffer[(0, 0)].symbol, single_ri);
1231
1232 buffer.set_string(0, 0, three, Style::default());
1233 assert!(!buffer[(0, 0)].symbol.is_empty());
1234 }
1235
1236 #[test]
1237 fn adversarial_tag_sequence_england() {
1238 // Subdivision flag using tag sequence
1239 let england = "🏴\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}";
1240 let area = Rect::new(0, 0, 10, 1);
1241 let mut buffer = Buffer::empty(area);
1242
1243 buffer.set_string(0, 0, england, Style::default());
1244 assert_eq!(&*buffer[(0, 0)].symbol, england);
1245 }
1246
1247 #[test]
1248 fn adversarial_private_use_and_specials() {
1249 // PUA and replacement characters
1250 let pua = "\u{E000}\u{FFFD}\u{FFFC}";
1251 let area = Rect::new(0, 0, 10, 1);
1252 let mut buffer = Buffer::empty(area);
1253
1254 buffer.set_string(0, 0, pua, Style::default());
1255 assert_eq!(&*buffer[(0, 0)].symbol, "\u{E000}");
1256 }
1257
1258 #[test]
1259 fn adversarial_empty_string() {
1260 let area = Rect::new(0, 0, 10, 1);
1261 let mut buffer = Buffer::empty(area);
1262
1263 buffer.set_string(0, 0, "", Style::default());
1264 assert_eq!(&*buffer[(0, 0)].symbol, " ");
1265 }
1266
1267 #[test]
1268 fn adversarial_extreme_zalgo_uses_replacement() {
1269 // Extreme zalgo: many combining characters exceed capacity
1270 let mut extreme = String::from("X");
1271 for _ in 0..50 {
1272 extreme.push('\u{0303}');
1273 }
1274
1275 let area = Rect::new(0, 0, 10, 1);
1276 let mut buffer = Buffer::empty(area);
1277 buffer.set_string(0, 0, &extreme, Style::default());
1278
1279 // Should use replacement character
1280 assert_eq!(&*buffer[(0, 0)].symbol, REPLACEMENT_CHARACTER.to_string());
1281 }
1282
1283 #[test]
1284 fn adversarial_extremely_long_grapheme_uses_replacement() {
1285 let mut absurd = String::from("o");
1286 for i in 0..100 {
1287 let combining = match i % 4 {
1288 0 => '\u{0300}',
1289 1 => '\u{0301}',
1290 2 => '\u{0302}',
1291 _ => '\u{0303}',
1292 };
1293 absurd.push(combining);
1294 }
1295
1296 let area = Rect::new(0, 0, 10, 1);
1297 let mut buffer = Buffer::empty(area);
1298 buffer.set_string(0, 0, &absurd, Style::default());
1299
1300 // Should use replacement character
1301 assert_eq!(&*buffer[(0, 0)].symbol, REPLACEMENT_CHARACTER.to_string());
1302 }
1303
1304 #[test]
1305 fn adversarial_long_zwj_chain_uses_replacement() {
1306 let mut chain = String::from("πŸ‘¨");
1307 for _ in 0..10 {
1308 chain.push_str("\u{200D}πŸ‘¨");
1309 }
1310
1311 let area = Rect::new(0, 0, 50, 1);
1312 let mut buffer = Buffer::empty(area);
1313 buffer.set_string(0, 0, &chain, Style::default());
1314
1315 // Should use replacement character
1316 assert_eq!(&*buffer[(0, 0)].symbol, REPLACEMENT_CHARACTER.to_string());
1317 }
1318 }