termint 0.8.0

Library for colored printing and Terminal User Interfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use std::{
    fmt::Display,
    io::{Write, stdout},
    ops::{Index, IndexMut},
};

use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::{
    enums::{Color, Cursor, Modifier},
    geometry::{Rect, Vec2},
    style::Style,
};

use super::cell::Cell;

/// A buffer that stores the result of the widget render method. Every widget
/// interacts with the buffer, instead of printing to the terminal.
///
/// [`Term`](crate::term::Term) struct automatically renders on the whole
/// screen using the [`Buffer`], so you don't have to care about it. But if you
/// would like to do it without the [`Term`](crate::term::Term) struct, you can
/// do it like this:
///
/// ```rust
/// # use termint::{
/// #     buffer::Buffer,
/// #     widgets::{Spacer, LayoutNode, Element, Widget},
/// #     geometry::Rect,
/// # };
/// # fn get_your_element() -> Element<()> { Spacer.into() }
/// // Creates new buffer with desired position and size given by the [`Rect`]
/// let rect = Rect::new(1, 1, 20, 9);
/// let mut buffer = Buffer::empty(rect);
///
/// // Gets element and renders it to the [`Buffer`]
/// let element = get_your_element();
///
/// let mut layout = LayoutNode::new(&element);
/// element.layout(&mut layout, rect);
/// element.render(&mut buffer, &layout);
///
/// // Renders [`Buffer`], which prints the result to the terminal
/// buffer.render();
/// ```
#[derive(Debug, Clone)]
pub struct Buffer {
    rect: Rect,
    content: Vec<Cell>,
}

impl Buffer {
    /// Creates new [`Buffer`] with all cells set to the default cell
    ///
    /// This method accepts parameter that can be converted to [`Rect`] (e.g.
    /// (x, y, width, height), or Rect::new(x, y, width, height)).
    #[must_use]
    pub fn empty<R>(rect: R) -> Self
    where
        R: Into<Rect>,
    {
        let rect = rect.into();
        let area = rect.area();
        Self {
            rect,
            content: vec![Cell::default(); area],
        }
    }

    /// Creates new [`Buffer`] filled with given [`Cell`]
    ///
    /// This method accepts parameter that can be converted to [`Rect`] (e.g.
    /// (x, y, width, height), or Rect::new(x, y, width, height)).
    #[must_use]
    pub fn filled<R>(rect: R, cell: Cell) -> Self
    where
        R: Into<Rect>,
    {
        let rect = rect.into();
        let area = rect.area();
        Self {
            rect,
            content: vec![cell; area],
        }
    }

    /// Prints the content of the buffer to standard output
    pub fn render(&self) {
        let mut id = 0;
        let mut style = (Color::Default, Color::Default, Modifier::empty());

        for y in 0..self.height() {
            print!("{}", Cursor::Pos(self.x(), self.y() + y));
            for _ in 0..self.width() {
                let child = &self.content[id];
                style = Self::render_cell(child, style);
                id += 1;
            }
        }
        print!("\x1b[0m");
        _ = stdout().flush();
    }

    /// Prints buffer characters, that are different then in given
    /// buffer
    ///
    /// When the buffer sizes differ, it re-renders the whole buffer
    pub fn render_diff(&self, diff: &Buffer) {
        // TODO: make it compare the cells on shared positions
        if self.rect() != diff.rect() {
            self.render();
            return;
        }

        let mut id = 0;
        let mut style = (Color::Default, Color::Default, Modifier::empty());

        for y in 0..self.height() {
            let mut prev = false;
            for x in 0..self.width() {
                let child = &self.content[id];
                let dchild = &diff.content[id];

                id += 1;
                if child == dchild {
                    prev = false;
                    continue;
                }

                if !prev {
                    print!("{}", Cursor::Pos(self.x() + x, self.y() + y))
                }
                style = Self::render_cell(child, style);
                prev = true;
            }
        }

        print!("\x1b[0m");
        _ = stdout().flush();
    }

    /// Gets subset of the buffer based on given rectangle
    ///
    /// # Panics
    /// Panics if the given rectangle isn't contained in the buffer
    #[must_use]
    pub fn subset(&self, rect: Rect) -> Buffer {
        let mut buffer = Buffer::empty(rect);

        for pos in rect.into_iter() {
            buffer.set(self[self.index_of(&pos)].clone(), &pos);
        }
        buffer
    }

    /// Merges given buffer to the current. If the given buffer is not
    /// contained in the current buffer, current buffer will be resized so to
    /// contain the given buffer.
    pub fn merge(&mut self, buffer: Buffer) {
        let rect = self.rect().union(buffer.rect());

        let mut merged = Buffer::empty(rect);
        for (i, pos) in self.rect().into_iter().enumerate() {
            merged.set(self.content[i].clone(), &pos);
        }
        for (i, pos) in buffer.rect().into_iter().enumerate() {
            merged.set(buffer.content[i].clone(), &pos);
        }

        self.rect = merged.rect;
        self.content = merged.content;
    }

    /// Moves buffer to given position
    pub fn move_to(&mut self, pos: Vec2) {
        self.rect.move_to(pos);
    }

    /// Gets [`Cell`] reference from the buffer on given position
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn cell(&self, pos: &Vec2) -> Option<&Cell> {
        let id = self.index_of(pos);
        self.content.get(id)
    }

    /// Gets [`Cell`] mutable reference from the buffer on given position
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn cell_mut(&mut self, pos: &Vec2) -> Option<&mut Cell> {
        let id = self.index_of(pos);
        self.content.get_mut(id)
    }

    /// Sets [`Cell`] on given position in the buffer to given value
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set(&mut self, cell: Cell, pos: &Vec2) {
        let id = self.index_of(pos);
        self.content[id] = cell;
    }

    /// Prints given string to the [`Buffer`] starting at the given position.
    ///
    /// Truncates the string if it cannot fit the buffer.
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_str<T>(&mut self, str: T, pos: &Vec2)
    where
        T: AsRef<str>,
    {
        let mut id = self.index_of(pos);
        let mut left = self.content.len().saturating_sub(id);

        let graphemes = UnicodeSegmentation::graphemes(str.as_ref(), true)
            .map(|t| (t, t.width()))
            .filter(|(_, w)| *w > 0)
            .map_while(|(t, w)| {
                left = left.checked_sub(w)?;
                Some((t, w))
            });
        for (grapheme, width) in graphemes {
            self.content[id].val(grapheme);

            let next = id + width;
            id += 1;
            while id < next {
                self.content[id].val("\0");
                id += 1;
            }
        }
    }

    /// Prints given string to the [`Buffer`] with given [`Style`] starting at
    /// the given position.
    ///
    /// Truncates the string if it cannot fit the buffer.
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_str_styled<T, S>(&mut self, str: T, pos: &Vec2, style: S)
    where
        T: AsRef<str>,
        S: Into<Style>,
    {
        let mut id = self.index_of(pos);
        let mut left = self.content.len().saturating_sub(id);

        let style = style.into();
        let graphemes = UnicodeSegmentation::graphemes(str.as_ref(), true)
            .map(|t| (t, t.width()))
            .filter(|(_, w)| *w > 0)
            .map_while(|(t, w)| {
                left = left.checked_sub(w)?;
                Some((t, w))
            });
        for (grapheme, width) in graphemes {
            self.content[id].val(grapheme).style(style);

            let next = id + width;
            id += 1;
            while id < next {
                self.content[id].val("\0");
                id += 1;
            }
        }
    }

    /// Sets value of the [`Cell`] on given position in the buffer
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_val(&mut self, val: &str, pos: &Vec2) {
        let id = self.index_of(pos);
        self.content[id].val(val);
    }

    /// Sets char value of the [`Cell`] on given position in the buffer
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_char(&mut self, c: char, pos: &Vec2) {
        let id = self.index_of(pos);
        self.content[id].char(c);
    }

    /// Sets style of the [`Cell`] on given position in the buffer
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_style(&mut self, style: Style, pos: &Vec2) {
        let id = self.index_of(pos);
        self.content[id].style(style);
    }

    /// Sets foreground of the [`Cell`] on given position in the buffer
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_fg(&mut self, fg: Color, pos: &Vec2) {
        let id = self.index_of(pos);
        self.content[id].fg(fg);
    }

    /// Sets background of the [`Cell`] on given position in the buffer
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_bg(&mut self, bg: Color, pos: &Vec2) {
        let id = self.index_of(pos);
        self.content[id].bg(bg);
    }

    /// Sets modifier of the [`Cell`] on given position in the buffer
    ///
    /// # Panics
    /// Panics if the given position is outside of the buffer
    pub fn set_modifier(&mut self, modifier: Modifier, pos: &Vec2) {
        let id = self.index_of(pos);
        self.content[id].modifier(modifier);
    }

    /// Sets the style of each [`Cell`] in the given area of the buffer.
    pub fn set_area_style(&mut self, style: Style, area: Rect) {
        for pos in area {
            if let Some(id) = self.index_of_opt(&pos) {
                self.content[id].style(style);
            }
        }
    }

    /// Gets reference to [`Rect`] of the [`Buffer`]
    pub fn rect(&self) -> &Rect {
        &self.rect
    }

    /// Gets reference to position of the [`Buffer`]
    pub fn pos(&self) -> &Vec2 {
        self.rect.pos()
    }

    /// Gets x coordinate of the [`Buffer`]
    pub fn x(&self) -> usize {
        self.rect.x()
    }

    /// Gets x coordinate of the [`Buffer`]
    pub fn left(&self) -> usize {
        self.rect.left()
    }

    /// Gets x coordinate of the most right cell of the [`Buffer`]
    pub fn right(&self) -> usize {
        self.rect.right()
    }

    /// Gets y coordinate of the [`Buffer`]
    pub fn y(&self) -> usize {
        self.rect.y()
    }

    /// Gets y coordinate of the [`Buffer`]
    pub fn top(&self) -> usize {
        self.rect.top()
    }

    /// Gets y coordinate of the most bottom cell of the [`Buffer`]
    pub fn bottom(&self) -> usize {
        self.rect.bottom()
    }

    /// Gets reference to size of the [`Buffer`]
    pub fn size(&self) -> &Vec2 {
        self.rect.size()
    }

    /// Gets width of the [`Buffer`]
    pub fn width(&self) -> usize {
        self.rect.width()
    }

    /// Gets height of the [`Buffer`]
    pub fn height(&self) -> usize {
        self.rect.height()
    }

    /// Gets area of the [`Buffer`]
    pub fn area(&self) -> usize {
        self.rect.area()
    }

    /// Gets [`Buffer`] content
    pub fn content(&self) -> &[Cell] {
        &self.content
    }

    /// Gets [`Cell`] index based on given position. Does not check if given
    /// position is inside of the buffer.
    pub fn index_of(&self, pos: &Vec2) -> usize {
        (pos.x - self.x()) + (pos.y - self.y()) * self.rect.width()
    }

    /// Gets [`Cell`] optional index based on given position. Returns `None` if
    /// the position is outside of the buffer
    pub fn index_of_opt(&self, pos: &Vec2) -> Option<usize> {
        if !self.rect.contains_pos(pos) {
            return None;
        }
        Some((pos.x - self.x()) + (pos.y - self.y()) * self.rect.width())
    }

    /// Gets position of the [`Cell`] based on index. Does not check if given
    /// index is inside of the buffer.
    pub fn pos_of(&self, id: usize) -> Vec2 {
        let (x, y) = (id % self.width(), id / self.width());
        Vec2::new(x + self.x(), y + self.y())
    }

    /// Gets optional position of the [`Cell`] based on index. Returns `None`
    /// if the position is outside of the buffer
    pub fn pos_of_opt(&self, id: usize) -> Option<Vec2> {
        if id >= self.content.len() {
            return None;
        }
        let (x, y) = (id % self.width(), id / self.width());
        Some(Vec2::new(x + self.x(), y + self.y()))
    }
}

impl Buffer {
    /// Renders given cell and returns current style
    fn render_cell(
        cell: &Cell,
        mut style: (Color, Color, Modifier),
    ) -> (Color, Color, Modifier) {
        if cell.val == "\0" {
            return style;
        }

        if cell.modifier != style.2 {
            if !style.2.is_empty() {
                print!("\x1b[0m");
            }
            print!("{}", cell.modifier);
            style = (Color::Default, Color::Default, cell.modifier);
        }
        if cell.fg != style.0 {
            style.0 = cell.fg;
            print!("{}", cell.fg.to_fg());
        }
        if cell.bg != style.1 {
            style.1 = cell.bg;
            print!("{}", cell.bg.to_bg());
        }
        print!("{}", cell.val);
        style
    }

    fn write_cell(
        f: &mut std::fmt::Formatter<'_>,
        cell: &Cell,
        style: &mut (Color, Color, Modifier),
    ) -> std::fmt::Result {
        if cell.modifier != style.2 {
            if !style.2.is_empty() {
                write!(f, "\x1b[0m")?;
            }
            write!(f, "{}", cell.modifier)?;
            *style = (Color::Default, Color::Default, cell.modifier);
        }
        if cell.fg != style.0 {
            style.0 = cell.fg;
            write!(f, "{}", cell.fg.to_fg())?;
        }
        if cell.bg != style.1 {
            style.1 = cell.bg;
            write!(f, "{}", cell.bg.to_bg())?;
        }
        write!(f, "{}", cell.val)
    }
}

impl Display for Buffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut id = 0;
        let mut style = (Color::Default, Color::Default, Modifier::empty());

        for y in 0..self.height() {
            if y != 0 {
                writeln!(f)?;
            }
            for _x in 0..self.width() {
                let child = &self.content[id];
                Self::write_cell(f, child, &mut style)?;
                id += 1;
            }
        }
        write!(f, "\x1b[0m")
    }
}

impl Index<usize> for Buffer {
    type Output = Cell;

    fn index(&self, index: usize) -> &Self::Output {
        self.content.get(index).unwrap_or_else(|| {
            panic!("index {index} is outside of the buffer")
        })
    }
}

impl IndexMut<usize> for Buffer {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.content.get_mut(index).unwrap_or_else(|| {
            panic!("index {index} is outside of the buffer")
        })
    }
}

impl<P> Index<P> for Buffer
where
    P: Into<Vec2>,
{
    type Output = Cell;

    fn index(&self, index: P) -> &Self::Output {
        let pos = index.into();
        self.cell(&pos).unwrap_or_else(|| {
            panic!("position {pos} is outside of the buffer")
        })
    }
}

impl<P> IndexMut<P> for Buffer
where
    P: Into<Vec2>,
{
    fn index_mut(&mut self, index: P) -> &mut Self::Output {
        let pos = index.into();
        self.cell_mut(&pos).unwrap_or_else(|| {
            panic!("position {pos} is outside of the buffer")
        })
    }
}