nandi/jolt-nativepublic Fork 0
dce285fb5a5ec1f331b8afa7b2bdc4ed5e1bbd46
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.

Paint a reaction, and give an emoji the two columns it takes dce285f · on dce285fb5a5ec1f331b8afa7b2bdc4ed5e1bbd46 · nandi · 16d ago
screen.rs · 381 lines · 11.9 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
//! 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,
        }
    }
}

/// How many columns one character takes on screen.
///
/// Zero for the parts of a glyph that are not drawn — a variation selector, a
/// zero-width joiner, a skin tone — two for the emoji a terminal draws double
/// width, and one for everything else. This is the whole of what this backend
/// knows about character width, and it is enough for what a chat client puts
/// on a screen: text, and the emoji in it.
pub fn char_cols(ch: char) -> u16 {
    let c = ch as u32;
    match c {
        0xFE00..=0xFE0F | 0x200D | 0x1F3FB..=0x1F3FF => 0,
        0x1F000.. => 2,
        0x2600..=0x27BF => 2,
        _ => 1,
    }
}

/// The columns `text` takes, the same way [`Screen::text`] spends them.
pub fn text_cols(text: &str) -> u16 {
    text.chars().map(char_cols).sum::<u16>().max(0)
}

/// 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, Copy, Debug, PartialEq, Eq)]
pub struct Cell {
    pub ch: char,
    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: ' ',
            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
        }
    }

    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.cells[i] = Cell {
                ch,
                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.cells[i] = Cell {
                ch: ' ',
                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 ch in text.chars() {
            if col >= width {
                break;
            }
            // 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 = char_cols(ch);
            if cols == 0 {
                // A joiner or a variation selector: part of the glyph before
                // it, and drawn with it. Keeping it in a cell of its own would
                // spend a column on something with no picture.
                continue;
            }
            if col + cols > width {
                // Half of a wide glyph is a different character, so the last
                // column stays blank rather than showing one.
                break;
            }
            self.set(x.saturating_add(col), y, ch, style);
            if cols == 2 {
                self.set_trail(x.saturating_add(col + 1), y, style);
            }
            col += cols;
        }
        col
    }

    /// 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 row: String = self.cells[start..start + self.w as usize]
            .iter()
            .filter(|c| !c.trail)
            .map(|c| c.ch)
            .collect();
        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 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));
    }
}