nandi/jolt-nativepublic Fork 0
main
Commits
Clone
git clone https://git.rickub.com/nandi/jolt-native.git
git clone ssh://git@rickub.com/nandi/jolt-native.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

screen.rs · 497 lines · 16.8 KBRust Blame HistoryRaw
  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
//! A grid of styled cells, and the colours that go in it.
//!
//! Everything this crate paints goes here first, and only [`crate::term`] ever
//! turns it into escape sequences. That split is deliberate and is the same one
//! glimmer-tui makes on the jolt side: painting into a grid needs no terminal,
//! no raw mode and no TTY, so the whole widget layer is testable in a unit test
//! and in CI — `tui_headless` opens a screen and nothing else.

/// A terminal colour, in the three ways a caller can write one.
///
/// `Default` is not black: it is "whatever the terminal was using", which is
/// what a theme-respecting TUI wants for most of its surface.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Color {
    #[default]
    Default,
    /// An index into the xterm 256-colour palette. 0–15 are the named ones.
    Indexed(u8),
    Rgb(u8, u8, u8),
}

impl Color {
    /// Parse a colour prop: a name (`red`, `bright-blue`, `default`), a palette
    /// index (`"33"`), a hex triple (`#ff6432` or `#f64`), or `r,g,b`.
    ///
    /// Answers `None` for anything else, which the caller reads as "leave the
    /// colour alone" rather than as an error — a typo'd colour should not take
    /// the widget away.
    pub fn parse(text: &str) -> Option<Self> {
        let text = text.trim();
        if text.is_empty() {
            return None;
        }
        if let Some(hex) = text.strip_prefix('#') {
            return Self::from_hex(hex);
        }
        if let Ok(index) = text.parse::<u8>() {
            return Some(Self::Indexed(index));
        }
        if text.contains(',') {
            let parts: Vec<&str> = text.split(',').map(str::trim).collect();
            if let [r, g, b] = parts[..] {
                return Some(Self::Rgb(r.parse().ok()?, g.parse().ok()?, b.parse().ok()?));
            }
            return None;
        }
        let (name, bright) = match text.strip_prefix("bright-") {
            Some(rest) => (rest, true),
            None => (text, false),
        };
        let base = match name {
            "black" => 0,
            "red" => 1,
            "green" => 2,
            "yellow" => 3,
            "blue" => 4,
            "magenta" => 5,
            "cyan" => 6,
            "white" => 7,
            "default" if !bright => return Some(Self::Default),
            _ => return None,
        };
        Some(Self::Indexed(base + if bright { 8 } else { 0 }))
    }

    fn from_hex(hex: &str) -> Option<Self> {
        let bytes = hex.as_bytes();
        let nib = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
        match bytes.len() {
            3 => {
                let (r, g, b) = (nib(bytes[0])?, nib(bytes[1])?, nib(bytes[2])?);
                Some(Self::Rgb(r * 17, g * 17, b * 17))
            }
            6 => {
                let pair = |i: usize| Some(nib(bytes[i])? * 16 + nib(bytes[i + 1])?);
                Some(Self::Rgb(pair(0)?, pair(2)?, pair(4)?))
            }
            _ => None,
        }
    }
}

/// True for a character that is part of the glyph before it rather than one of
/// its own: a variation selector, a zero-width joiner, a skin tone.
fn continues_glyph(ch: char) -> bool {
    matches!(ch as u32, 0xFE00..=0xFE0F | 0x200D | 0x1F3FB..=0x1F3FF)
}

/// Split `text` into what a terminal draws as single glyphs.
///
/// One character is usually one glyph, but an emoji is often several: `↩️` is
/// an arrow and a variation selector saying to draw it as a picture, and a
/// family is three people and the joiners between them. Cutting between those
/// characters is what makes a reply arrow come out as the small mono arrow
/// rather than the emoji — the selector says which of the two a terminal
/// draws, and it has to travel with the character it is about.
pub fn glyphs(text: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut joining = false;
    for ch in text.chars() {
        let continues = continues_glyph(ch);
        if (continues || joining) && !out.is_empty() {
            out.last_mut().expect("not empty").push(ch);
        } else {
            out.push(ch.to_string());
        }
        // A joiner welds what follows it onto what came before.
        joining = ch as u32 == 0x200D;
    }
    out
}

/// How many columns one glyph takes on screen.
///
/// Two for the emoji a terminal draws double width, one for everything else.
/// A character out of the emoji blocks is drawn wide on its own; an older
/// symbol or dingbat is drawn wide when it carries the selector that asks for
/// the picture, and narrow — a character among characters — when it does not.
/// This is the whole of what this backend knows about width, and it is enough
/// for what a chat client puts on a screen: text, and the emoji in it.
pub fn glyph_cols(glyph: &str) -> u16 {
    let mut chars = glyph.chars();
    let Some(base) = chars.next() else {
        return 0;
    };
    let emoji_presentation = glyph.chars().any(|c| c as u32 == 0xFE0F);
    match base as u32 {
        0x1F000.. => 2,
        0x2000..=0x2BFF if emoji_presentation => 2,
        _ => 1,
    }
}

/// The columns `text` takes, the same way [`Screen::text`] spends them.
pub fn text_cols(text: &str) -> u16 {
    glyphs(text).iter().map(|g| glyph_cols(g)).sum()
}

/// The attribute bits a cell can carry. A `u8` rather than a set of `bool`s
/// because a cell is copied a great many times a frame.
pub mod attr {
    pub const BOLD: u8 = 1 << 0;
    pub const DIM: u8 = 1 << 1;
    pub const UNDERLINE: u8 = 1 << 2;
    pub const REVERSE: u8 = 1 << 3;
    pub const BLINK: u8 = 1 << 4;
    pub const ITALIC: u8 = 1 << 5;
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Style {
    pub fg: Color,
    pub bg: Color,
    pub attrs: u8,
}

impl Style {
    pub fn with(mut self, bits: u8) -> Self {
        self.attrs |= bits;
        self
    }

    pub fn fg(mut self, color: Color) -> Self {
        self.fg = color;
        self
    }

    pub fn has(&self, bits: u8) -> bool {
        self.attrs & bits != 0
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cell {
    pub ch: char,
    /// The rest of the glyph, where it took more than one character: the
    /// selector that asks for a picture, the joiners in a family. Printed
    /// straight after `ch`, which is the only way a terminal draws them as
    /// the one glyph they are.
    pub tail: Option<Box<str>>,
    pub style: Style,
    /// The right half of a double-width character. It holds no character of
    /// its own: the glyph in the cell to its left is drawn across both, and
    /// writing anything here would print a second copy one column over.
    pub trail: bool,
}

impl Default for Cell {
    fn default() -> Self {
        Self {
            ch: ' ',
            tail: None,
            style: Style::default(),
            trail: false,
        }
    }
}

/// A rectangle in cells. Columns and rows, origin top left.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rect {
    pub x: u16,
    pub y: u16,
    pub w: u16,
    pub h: u16,
}

impl Rect {
    pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
        Self { x, y, w, h }
    }

    pub fn is_empty(&self) -> bool {
        self.w == 0 || self.h == 0
    }

    pub fn contains(&self, x: u16, y: u16) -> bool {
        x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
    }

    /// The rect left after taking `n` cells off every side. Saturating, so
    /// padding larger than the rect answers an empty one rather than wrapping.
    pub fn shrink(&self, n: u16) -> Self {
        let take = n.saturating_mul(2);
        Self {
            x: self.x.saturating_add(n),
            y: self.y.saturating_add(n),
            w: self.w.saturating_sub(take),
            h: self.h.saturating_sub(take),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Screen {
    w: u16,
    h: u16,
    cells: Vec<Cell>,
}

impl Screen {
    pub fn new(w: u16, h: u16) -> Self {
        Self {
            w,
            h,
            cells: vec![Cell::default(); w as usize * h as usize],
        }
    }

    pub fn width(&self) -> u16 {
        self.w
    }

    pub fn height(&self) -> u16 {
        self.h
    }

    pub fn rect(&self) -> Rect {
        Rect::new(0, 0, self.w, self.h)
    }

    pub fn resize(&mut self, w: u16, h: u16) {
        if (w, h) != (self.w, self.h) {
            *self = Self::new(w, h);
        }
    }

    pub fn clear(&mut self) {
        self.cells.fill(Cell::default());
    }

    pub fn cell(&self, x: u16, y: u16) -> Option<&Cell> {
        if x < self.w && y < self.h {
            self.cells.get(y as usize * self.w as usize + x as usize)
        } else {
            None
        }
    }

    /// Make room at `i` for a cell that is, or is not, the right half of a
    /// wide glyph. Painting over half of a wide glyph takes the whole glyph
    /// off a terminal, so the grid has to lose the other half too: a lead
    /// left without its trail, or a trail without its lead, is a cell the
    /// flush believes is on screen and a terminal has already erased — and
    /// since it never changes again, it is never repainted. That is the
    /// stray pencil left behind once a row's chips are gone.
    fn displace(&mut self, i: usize, trail: bool) {
        let x = i % self.w as usize;
        if !trail && self.cells[i].trail && x > 0 {
            let lead = &mut self.cells[i - 1];
            lead.ch = ' ';
            lead.tail = None;
        }
        if x + 1 < self.w as usize && self.cells[i + 1].trail {
            let rest = &mut self.cells[i + 1];
            rest.ch = ' ';
            rest.tail = None;
            rest.trail = false;
        }
    }

    pub fn set(&mut self, x: u16, y: u16, ch: char, style: Style) {
        if x < self.w && y < self.h {
            let i = y as usize * self.w as usize + x as usize;
            self.displace(i, false);
            self.cells[i] = Cell {
                ch,
                tail: None,
                style,
                trail: false,
            };
        }
    }

    /// The cell a double-width character's right half sits in.
    fn set_trail(&mut self, x: u16, y: u16, style: Style) {
        if x < self.w && y < self.h {
            let i = y as usize * self.w as usize + x as usize;
            self.displace(i, true);
            self.cells[i] = Cell {
                ch: ' ',
                tail: None,
                style,
                trail: true,
            };
        }
    }

    /// Write `text` at `x, y`, clipped to `width` columns. Answers how many
    /// columns were used.
    pub fn text(&mut self, x: u16, y: u16, width: u16, text: &str, style: Style) -> u16 {
        let mut col = 0u16;
        for glyph in glyphs(text) {
            if col >= width {
                break;
            }
            let mut chars = glyph.chars();
            let ch = chars.next().unwrap_or(' ');
            // A control character in a label would move the cursor; show it as
            // a dot instead of letting it rearrange the screen.
            let ch = if (ch as u32) < 0x20 { '·' } else { ch };
            let cols = glyph_cols(&glyph);
            if col + cols > width {
                // Half of a wide glyph is a different character, so the last
                // column stays blank rather than showing one.
                break;
            }
            let at = x.saturating_add(col);
            self.set(at, y, ch, style);
            let rest: String = chars.collect();
            if !rest.is_empty() {
                self.set_tail(at, y, rest);
            }
            if cols == 2 {
                self.set_trail(x.saturating_add(col + 1), y, style);
            }
            col += cols;
        }
        col
    }

    /// Put a whole cell down as it is — what a scroll does when it copies the
    /// visible window of its content across. Cell by character would drop the
    /// rest of a glyph and the right half of a wide one, which is a reply
    /// arrow painted as the small mono arrow and a row a column out.
    pub fn put(&mut self, x: u16, y: u16, cell: Cell) {
        if x < self.w && y < self.h {
            let i = y as usize * self.w as usize + x as usize;
            self.displace(i, cell.trail);
            self.cells[i] = cell;
        }
    }

    /// The rest of a glyph, on the cell its first character went in.
    fn set_tail(&mut self, x: u16, y: u16, rest: String) {
        if x < self.w && y < self.h {
            let i = y as usize * self.w as usize + x as usize;
            self.cells[i].tail = Some(rest.into_boxed_str());
        }
    }

    /// Paint every cell of `rect` with `style`, keeping the characters — that
    /// is what a background is: a colour behind whatever is already there.
    pub fn fill(&mut self, rect: Rect, style: Style) {
        for y in rect.y..rect.y.saturating_add(rect.h) {
            for x in rect.x..rect.x.saturating_add(rect.w) {
                if x < self.w && y < self.h {
                    let i = y as usize * self.w as usize + x as usize;
                    // The character stays, and so does whether it is the half
                    // of one: a background is a colour, not a repaint.
                    self.cells[i].style = style;
                }
            }
        }
    }

    /// One row as text, trailing blanks trimmed. The whole reason the grid is
    /// addressable: a test asserts on lines, not on escape sequences.
    pub fn line(&self, y: u16) -> String {
        if y >= self.h {
            return String::new();
        }
        let start = y as usize * self.w as usize;
        // Without the trailing halves: they hold no character, and a reader —
        // a test, a bug report — wants the line as it looks.
        let mut row = String::new();
        for cell in self.cells[start..start + self.w as usize].iter() {
            if cell.trail {
                continue;
            }
            row.push(cell.ch);
            if let Some(tail) = &cell.tail {
                row.push_str(tail);
            }
        }
        row.trim_end().to_owned()
    }

    #[cfg(test)]
    pub fn lines(&self) -> Vec<String> {
        (0..self.h).map(|y| self.line(y)).collect()
    }

    pub(crate) fn cells(&self) -> &[Cell] {
        &self.cells
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn painting_over_half_of_a_wide_glyph_takes_the_other_half_with_it() {
        // Over the left half: the pencil's right half must not stay behind as
        // a trail with nothing to its left.
        let mut screen = Screen::new(6, 1);
        screen.text(0, 0, 6, "a✏️b", Style::default());
        screen.set(1, 0, 'x', Style::default());
        assert_eq!(screen.line(0), "ax b");
        assert!(!screen.cell(2, 0).unwrap().trail);

        // Over the right half: the left half is blank, as a terminal shows it.
        let mut screen = Screen::new(6, 1);
        screen.text(0, 0, 6, "a✏️b", Style::default());
        screen.set(2, 0, 'x', Style::default());
        assert_eq!(screen.line(0), "a xb");
        assert!(screen.cell(1, 0).unwrap().tail.is_none());

        // A wide glyph laid over the right half of another keeps only itself.
        let mut screen = Screen::new(6, 1);
        screen.text(0, 0, 6, "a✏️b", Style::default());
        screen.text(2, 0, 4, "🙂", Style::default());
        assert_eq!(screen.line(0), "a 🙂");
    }

    #[test]
    fn colours_parse_in_every_shape_a_caller_writes_them() {
        assert_eq!(Color::parse("red"), Some(Color::Indexed(1)));
        assert_eq!(Color::parse("bright-blue"), Some(Color::Indexed(12)));
        assert_eq!(Color::parse("default"), Some(Color::Default));
        assert_eq!(Color::parse("33"), Some(Color::Indexed(33)));
        assert_eq!(Color::parse("#ff6432"), Some(Color::Rgb(255, 100, 50)));
        assert_eq!(Color::parse("#f64"), Some(Color::Rgb(255, 102, 68)));
        assert_eq!(Color::parse("255,100,50"), Some(Color::Rgb(255, 100, 50)));
    }

    #[test]
    fn an_unreadable_colour_is_no_colour_rather_than_an_error() {
        assert_eq!(Color::parse("puce"), None);
        assert_eq!(Color::parse("#gg0000"), None);
        assert_eq!(Color::parse(""), None);
    }

    #[test]
    fn text_clips_to_the_width_it_was_given() {
        let mut screen = Screen::new(10, 2);
        screen.text(0, 0, 4, "abcdefg", Style::default());
        assert_eq!(screen.line(0), "abcd");
    }

    #[test]
    fn a_control_character_cannot_move_the_cursor() {
        let mut screen = Screen::new(6, 1);
        screen.text(0, 0, 6, "a\rb", Style::default());
        assert_eq!(screen.line(0), "a·b");
    }

    #[test]
    fn filling_a_rect_keeps_the_characters_under_it() {
        let mut screen = Screen::new(4, 1);
        screen.text(0, 0, 4, "hi", Style::default());
        screen.fill(screen.rect(), Style::default().with(attr::REVERSE));
        assert_eq!(screen.line(0), "hi");
        assert!(screen.cell(0, 0).unwrap().style.has(attr::REVERSE));
    }
}