Skip to main content

comb/core/
buffer.rs

1//! The cell grid: a `width × height` array of [`Cell`]s that widgets draw into.
2//! Two buffers (front = on screen, back = next frame) are diffed so the terminal
3//! only receives the cells that actually changed.
4
5use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
6
7use crate::core::geom::{Align, Rect, Size};
8use crate::core::style::Style;
9use crate::core::text::Line;
10
11/// Display columns for a label with `pad` blank cells on each side.
12pub fn label_cols(text: &str, pad: u16) -> u16 {
13    let w = UnicodeWidthStr::width(text) as u16;
14    w.saturating_add(pad.saturating_mul(2))
15}
16
17/// Shared chip width that exactly centers the greatest number of labels.
18///
19/// A label can have equal left and right pads only when its display width has
20/// the same parity as the chip. When the labels have mixed parity, this picks
21/// the majority parity; ties keep the narrowest possible chip. This makes the
22/// unavoidable one-cell imbalance affect the fewest labels.
23pub fn chip_cols(labels: &[&str], pad: u16) -> u16 {
24    let w = labels
25        .iter()
26        .map(|t| label_cols(t, pad))
27        .max()
28        .unwrap_or(pad.saturating_mul(2));
29
30    let (even, odd) = labels.iter().fold((0usize, 0usize), |(even, odd), text| {
31        if UnicodeWidthStr::width(*text) % 2 == 0 {
32            (even + 1, odd)
33        } else {
34            (even, odd + 1)
35        }
36    });
37    let preferred_parity = if odd > even { 1 } else { 0 };
38
39    if w % 2 == preferred_parity {
40        w
41    } else {
42        w.saturating_add(1)
43    }
44}
45
46/// Pad `text` to exactly `width` display columns (centered).
47///
48/// When the gap is odd, the extra column goes on the **right**.
49pub fn center_pad(text: &str, width: u16) -> String {
50    pad_align(text, width, Align::Center)
51}
52
53fn clip_text(text: &str, width: u16) -> (String, u16) {
54    let mut out = String::new();
55    let mut tw = 0u16;
56    for ch in text.chars() {
57        let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
58        if w == 0 {
59            continue;
60        }
61        if tw + w > width {
62            break;
63        }
64        out.push(ch);
65        tw += w;
66    }
67    (out, tw)
68}
69
70fn pad_align(text: &str, width: u16, align: Align) -> String {
71    let (core, tw) = clip_text(text, width);
72    if tw >= width {
73        return core;
74    }
75    let gap = width - tw;
76    let (left, right) = match align {
77        Align::Start => (0, gap),
78        Align::End => (gap, 0),
79        Align::Center => {
80            let left = gap / 2;
81            (left, gap - left)
82        }
83    };
84    let mut s = String::with_capacity(width as usize);
85    for _ in 0..left {
86        s.push(' ');
87    }
88    s.push_str(&core);
89    for _ in 0..right {
90        s.push(' ');
91    }
92    s
93}
94
95/// Marker in the cell to the right of a double-width glyph. Skipped when
96/// flushing ANSI so the terminal does not advance an extra column.
97pub const WIDE_CONT: char = '\u{FFFE}';
98
99/// One character cell. `'\0'` marks a *transparent* cell — it is skipped when a
100/// surface is composited, letting lower layers show through.
101#[derive(Clone, Copy, PartialEq, Eq, Debug)]
102pub struct Cell {
103    pub ch: char,
104    pub style: Style,
105}
106
107impl Cell {
108    pub const fn blank() -> Self {
109        Cell {
110            ch: ' ',
111            style: Style::new(),
112        }
113    }
114
115    pub const fn transparent() -> Self {
116        Cell {
117            ch: '\0',
118            style: Style::new(),
119        }
120    }
121
122    pub fn is_transparent(&self) -> bool {
123        self.ch == '\0'
124    }
125}
126
127impl Default for Cell {
128    fn default() -> Self {
129        Cell::blank()
130    }
131}
132
133#[derive(Clone)]
134pub struct Buffer {
135    pub width: u16,
136    pub height: u16,
137    cells: Vec<Cell>,
138}
139
140impl Buffer {
141    /// A buffer of blank (opaque space) cells — used for the screen root.
142    pub fn blank(size: Size) -> Self {
143        Buffer::filled(size, Cell::blank())
144    }
145
146    /// A buffer of transparent cells — used for overlay surfaces.
147    pub fn transparent(size: Size) -> Self {
148        Buffer::filled(size, Cell::transparent())
149    }
150
151    pub fn filled(size: Size, cell: Cell) -> Self {
152        Buffer {
153            width: size.width,
154            height: size.height,
155            cells: vec![cell; size.area() as usize],
156        }
157    }
158
159    pub fn size(&self) -> Size {
160        Size::new(self.width, self.height)
161    }
162
163    pub fn area(&self) -> Rect {
164        Rect::new(0, 0, self.width, self.height)
165    }
166
167    fn index(&self, x: u16, y: u16) -> Option<usize> {
168        if x < self.width && y < self.height {
169            Some(y as usize * self.width as usize + x as usize)
170        } else {
171            None
172        }
173    }
174
175    pub fn get(&self, x: u16, y: u16) -> Option<&Cell> {
176        self.index(x, y).map(|i| &self.cells[i])
177    }
178
179    pub fn cell_mut(&mut self, x: u16, y: u16) -> Option<&mut Cell> {
180        self.index(x, y).map(|i| &mut self.cells[i])
181    }
182
183    pub fn set(&mut self, x: u16, y: u16, ch: char, style: Style) {
184        if let Some(c) = self.cell_mut(x, y) {
185            c.ch = ch;
186            // Patch, don't replace: `None` colours inherit the cell underneath.
187            // Critical for panels — `set_line` clears short-line tails with
188            // `Style::new()`, which must not punch black holes through a painted bg.
189            c.style = c.style.patch(style);
190        }
191    }
192
193    /// Write one grapheme cell, honouring East-Asian / emoji display width.
194    /// Returns columns advanced (0, 1, or 2).
195    fn put_glyph(&mut self, x: u16, y: u16, ch: char, style: Style, limit: u16) -> u16 {
196        if x >= limit {
197            return 0;
198        }
199        let w = UnicodeWidthChar::width(ch).unwrap_or(0);
200        if w == 0 {
201            // Combining / zero-width: keep layout stable; skip.
202            return 0;
203        }
204        if w >= 2 {
205            // Need two cells; if only one remains, fall back to a space.
206            if x + 1 >= limit {
207                self.set(x, y, ' ', style);
208                return 1;
209            }
210            self.set(x, y, ch, style);
211            self.set(x + 1, y, WIDE_CONT, style);
212            return 2;
213        }
214        self.set(x, y, ch, style);
215        1
216    }
217
218    /// Write `s` starting at `(x, y)`, clipping at the buffer edge. Returns the
219    /// column just past the last glyph written.
220    pub fn set_str(&mut self, x: u16, y: u16, s: &str, style: Style) -> u16 {
221        let mut cx = x;
222        for ch in s.chars() {
223            if cx >= self.width {
224                break;
225            }
226            let adv = self.put_glyph(cx, y, ch, style, self.width);
227            if adv == 0 && UnicodeWidthChar::width(ch).unwrap_or(0) == 0 {
228                continue;
229            }
230            if adv == 0 {
231                break;
232            }
233            cx = cx.saturating_add(adv);
234        }
235        cx
236    }
237
238    /// Draw a styled line at `(x, y)`, each span keeping its own style, clipped
239    /// to `max_width` cells (and the buffer edge).
240    pub fn set_line(&mut self, x: u16, y: u16, line: &Line, max_width: u16) {
241        self.set_line_on(x, y, line, max_width, Style::new());
242    }
243
244    /// Like [`set_line`], but every span is patched with `base` (typically a
245    /// panel background) so fg-only highlight styles don't wipe the row bg.
246    /// Always clears the remainder of the row so scroll / short lines cannot
247    /// leave stale glyphs behind.
248    pub fn set_line_on(&mut self, x: u16, y: u16, line: &Line, max_width: u16, base: Style) {
249        let mut cx = x;
250        let limit = x.saturating_add(max_width).min(self.width);
251        for span in &line.spans {
252            let st = span.style.patch(base);
253            for ch in span.content.chars() {
254                if cx >= limit {
255                    // Still clear the rest of the row below.
256                    break;
257                }
258                let adv = self.put_glyph(cx, y, ch, st, limit);
259                if adv == 0 {
260                    if UnicodeWidthChar::width(ch).unwrap_or(0) == 0 {
261                        continue;
262                    }
263                    break;
264                }
265                cx = cx.saturating_add(adv);
266            }
267            if cx >= limit {
268                break;
269            }
270        }
271        // Clear vacated cells — required for scroll artifacts and width changes.
272        while cx < limit {
273            self.set(cx, y, ' ', base);
274            cx += 1;
275        }
276    }
277
278    /// Draw `lines` top-down within `area`, starting at logical index `scroll`,
279    /// clipped to the area's height and width. The Paragraph-with-scroll of comb.
280    pub fn set_lines(&mut self, area: Rect, lines: &[Line], scroll: usize) {
281        self.set_lines_on(area, lines, scroll, Style::new());
282    }
283
284    /// Like [`set_lines`], patching every cell with `base` (e.g. panel bg).
285    /// Empty rows in the viewport are always cleared.
286    pub fn set_lines_on(&mut self, area: Rect, lines: &[Line], scroll: usize, base: Style) {
287        for row in 0..area.height {
288            let idx = scroll + row as usize;
289            let y = area.y + row;
290            match lines.get(idx) {
291                Some(line) => self.set_line_on(area.x, y, line, area.width, base),
292                None => {
293                    self.paint(Rect::new(area.x, y, area.width, 1), base);
294                }
295            }
296        }
297    }
298
299    /// Fill a rectangle with `ch`/`style` (intersected with the buffer).
300    pub fn fill(&mut self, rect: Rect, ch: char, style: Style) {
301        let r = rect.intersection(self.area());
302        for y in r.y..r.bottom() {
303            for x in r.x..r.right() {
304                self.set(x, y, ch, style);
305            }
306        }
307    }
308
309    /// Paint a background over a rectangle, leaving spaces. Handy for panels.
310    pub fn paint(&mut self, rect: Rect, style: Style) {
311        self.fill(rect, ' ', style);
312    }
313
314    /// Fill a horizontal band with `style`, then draw `text` inside it.
315    ///
316    /// The whole band is painted first, then one padded line is written so chip
317    /// backgrounds stay solid. [`Align::Center`] uses [`center_pad`].
318    pub fn put_str_aligned(
319        &mut self,
320        x: u16,
321        y: u16,
322        width: u16,
323        text: &str,
324        style: Style,
325        align: Align,
326    ) {
327        if width == 0 || y >= self.height {
328            return;
329        }
330        let x = x.min(self.width);
331        let width = width.min(self.width.saturating_sub(x));
332        if width == 0 {
333            return;
334        }
335        self.paint(Rect::new(x, y, width, 1), style);
336        let padded = match align {
337            Align::Center => center_pad(text, width),
338            Align::Start => pad_align(text, width, Align::Start),
339            Align::End => pad_align(text, width, Align::End),
340        };
341        self.set_line_on(
342            x,
343            y,
344            &Line::from(crate::core::text::Span::styled(padded, style)),
345            width,
346            style,
347        );
348    }
349
350    /// Fill `area` with `style` and center `text` horizontally + vertically.
351    ///
352    /// Use [`chip_cols`] to choose a shared width that centers as many labels
353    /// as possible when their display widths have mixed parity.
354    pub fn put_label(&mut self, area: Rect, text: &str, style: Style) {
355        let area = area.intersection(self.area());
356        if area.is_empty() {
357            return;
358        }
359        self.paint(area, style);
360        let y = area.y + area.height / 2;
361        self.put_str_aligned(area.x, y, area.width, text, style, Align::Center);
362    }
363
364    /// Copy `src` onto this buffer at `(ox, oy)`. When `skip_transparent`, cells
365    /// marked transparent in `src` don't overwrite what's underneath.
366    pub fn blit(&mut self, ox: u16, oy: u16, src: &Buffer, skip_transparent: bool) {
367        for sy in 0..src.height {
368            for sx in 0..src.width {
369                let cell = src.cells[sy as usize * src.width as usize + sx as usize];
370                if skip_transparent && cell.is_transparent() {
371                    continue;
372                }
373                self.set(ox + sx, oy + sy, cell.ch, cell.style);
374            }
375        }
376    }
377
378    /// The cells that differ from `prev` (same dimensions assumed), as
379    /// `(x, y, cell)`, in row-major order — ready to emit to the terminal.
380    pub fn diff<'a>(&'a self, prev: &Buffer) -> Vec<(u16, u16, &'a Cell)> {
381        let mut out = Vec::new();
382        if self.width != prev.width || self.height != prev.height {
383            // Different geometry: treat everything as changed.
384            for y in 0..self.height {
385                for x in 0..self.width {
386                    out.push((x, y, &self.cells[self.index(x, y).unwrap()]));
387                }
388            }
389            return out;
390        }
391        for (i, (a, b)) in self.cells.iter().zip(prev.cells.iter()).enumerate() {
392            if a != b {
393                let x = (i % self.width as usize) as u16;
394                let y = (i / self.width as usize) as u16;
395                out.push((x, y, a));
396            }
397        }
398        out
399    }
400
401    /// The whole buffer as text, rows joined by `\n` (transparent / wide-cont
402    /// cells become spaces). Handy for snapshot-style assertions in tests.
403    pub fn text(&self) -> String {
404        let mut s = String::with_capacity((self.width as usize + 1) * self.height as usize);
405        for y in 0..self.height {
406            for x in 0..self.width {
407                let ch = self.cells[y as usize * self.width as usize + x as usize].ch;
408                s.push(if ch == '\0' || ch == WIDE_CONT {
409                    ' '
410                } else {
411                    ch
412                });
413            }
414            if y + 1 < self.height {
415                s.push('\n');
416            }
417        }
418        s
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425    use crate::core::style::{Color, Style};
426    use crate::core::text::Span;
427
428    #[test]
429    fn set_str_clips_at_edge() {
430        let mut b = Buffer::blank(Size::new(4, 1));
431        let next = b.set_str(2, 0, "hello", Style::new());
432        assert_eq!(next, 4); // stopped at the right edge
433        let row: String = (0..4).map(|x| b.get(x, 0).unwrap().ch).collect();
434        assert_eq!(row, "  he");
435    }
436
437    #[test]
438    fn diff_reports_only_changes() {
439        let a = Buffer::blank(Size::new(3, 1));
440        let mut b = a.clone();
441        b.set(1, 0, 'x', Style::new().fg(Color::rgb(9, 9, 9)));
442        let d = b.diff(&a);
443        assert_eq!(d.len(), 1);
444        assert_eq!((d[0].0, d[0].1, d[0].2.ch), (1, 0, 'x'));
445    }
446
447    #[test]
448    fn set_line_clears_remainder_of_row() {
449        let mut b = Buffer::blank(Size::new(8, 1));
450        b.set_str(0, 0, "abcdefgh", Style::new());
451        b.set_line(0, 0, &Line::from("hi"), 8);
452        let row: String = (0..8).map(|x| b.get(x, 0).unwrap().ch).collect();
453        assert_eq!(row, "hi      ");
454    }
455
456    #[test]
457    fn set_line_preserves_painted_panel_bg_on_tail() {
458        let panel = Color::rgb(0x22, 0x22, 0x22);
459        let mut b = Buffer::blank(Size::new(10, 1));
460        b.paint(Rect::new(0, 0, 10, 1), Style::new().bg(panel));
461        // Short line + clear remainder (Style::new base) must keep panel bg.
462        b.set_line(
463            0,
464            0,
465            &Line::from(Span::styled(
466                "Settings",
467                Style::new().fg(Color::rgb(0xe0, 0xe0, 0xe0)),
468            )),
469            10,
470        );
471        for x in 0..10 {
472            assert_eq!(
473                b.get(x, 0).unwrap().style.bg,
474                Some(panel),
475                "col {x} lost panel bg"
476            );
477        }
478        assert_eq!(b.get(0, 0).unwrap().ch, 'S');
479        assert_eq!(b.get(8, 0).unwrap().ch, ' ');
480    }
481
482    #[test]
483    fn set_lines_clears_empty_viewport_rows() {
484        let mut b = Buffer::blank(Size::new(4, 3));
485        b.set_str(0, 0, "aaaa", Style::new());
486        b.set_str(0, 1, "bbbb", Style::new());
487        b.set_str(0, 2, "cccc", Style::new());
488        let lines = vec![Line::from("x")];
489        b.set_lines(Rect::new(0, 0, 4, 3), &lines, 0);
490        assert_eq!(b.get(0, 0).unwrap().ch, 'x');
491        assert_eq!(b.get(1, 0).unwrap().ch, ' ');
492        assert_eq!(b.get(0, 1).unwrap().ch, ' ');
493        assert_eq!(b.get(0, 2).unwrap().ch, ' ');
494    }
495
496    #[test]
497    fn wide_glyph_reserves_two_cells() {
498        let mut b = Buffer::blank(Size::new(4, 1));
499        b.set_str(0, 0, "あ", Style::new());
500        assert_eq!(b.get(0, 0).unwrap().ch, 'あ');
501        assert_eq!(b.get(1, 0).unwrap().ch, WIDE_CONT);
502        assert_eq!(b.get(2, 0).unwrap().ch, ' ');
503    }
504
505    #[test]
506    fn chip_cols_prefers_the_majority_label_parity() {
507        assert_eq!(chip_cols(&["MAKE", "MARK", "SEND"], 1), 6);
508        assert_eq!(center_pad("MAKE", 6), " MAKE ");
509        assert_eq!(center_pad("MARK", 6), " MARK ");
510        assert_eq!(center_pad("SEND", 6), " SEND ");
511    }
512
513    #[test]
514    fn put_label_preserves_shared_action_width() {
515        let bg = Color::rgb(0x5a, 0x8f, 0xb0);
516        let style = Style::new().bg(bg).fg(Color::rgb(0x11, 0x11, 0x11));
517        let w = chip_cols(&["MAKE", "MARK", "SEND"], 1);
518        assert_eq!(w, 6);
519        for (word, expect) in [("MAKE", " MAKE "), ("MARK", " MARK "), ("SEND", " SEND ")] {
520            let mut b = Buffer::blank(Size::new(w, 3));
521            b.put_label(Rect::new(0, 0, w, 3), word, style);
522            let mid: String = (0..w).map(|x| b.get(x, 1).unwrap().ch).collect();
523            assert_eq!(mid, expect, "{word}");
524            let text_width = UnicodeWidthStr::width(word);
525            let pad = (w as usize - text_width) / 2;
526            assert_eq!(&mid[..pad], " ".repeat(pad));
527            assert_eq!(&mid[pad + text_width..], " ".repeat(pad));
528        }
529    }
530}