r3bl_tui 0.7.2

TUI library to build modern apps inspired by React, Elm, with Flexbox, CSS, editor component, emoji support, and more
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
 *   Copyright (c) 2022-2025 R3BL LLC
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
use std::{fmt::{self, Debug},
          ops::{Deref, DerefMut}};

use diff_chunks::PixelCharDiffChunks;
use smallvec::smallvec;

use super::{FlushKind, RenderOps};
use crate::{col, dim_underline, fg_green, fg_magenta, get_mem_size, inline_string, ok,
            row, tiny_inline_string, CachedMemorySize, ColWidth, GetMemSize, InlineVec,
            List, LockedOutputDevice, MemoizedMemorySize, MemorySize, Pos, Size,
            TinyInlineString, TuiColor, TuiStyle};

/// Represents a grid of cells where the row/column index maps to the terminal screen.
///
/// This works regardless of the size of each cell. Cells can contain emoji who's display
/// width is greater than one. This complicates things since a "😃" takes up 2 display
/// widths.
///
/// Let's say one cell has a "😃" in it. The cell's display width is 2. The cell's byte
/// size is 4. The next cell after it will have to contain nothing or void.
///
/// Why? This is because the col & row indices of the grid map to display col & row
/// indices of the terminal screen. By inserting a [`PixelChar::Void`] pixel char in the
/// next cell, we signal the rendering logic to skip it since it has already been painted.
/// And this is different than a [`PixelChar::Spacer`] which has to be painted!
#[derive(Clone, PartialEq)]
pub struct OffscreenBuffer {
    pub buffer: PixelCharLines,
    pub window_size: Size,
    pub my_pos: Pos,
    pub my_fg_color: Option<TuiColor>,
    pub my_bg_color: Option<TuiColor>,
    /// Memoized memory size calculation for performance.
    /// This avoids expensive recalculation in
    /// [`crate::main_event_loop::EventLoopState::log_telemetry_info()`]
    /// which is called in a hot loop on every render.
    memory_size_calc_cache: MemoizedMemorySize,
}

impl GetMemSize for OffscreenBuffer {
    /// This is the actual calculation, but should rarely be called directly.
    /// Use [`Self::get_mem_size_cached()`] for performance-critical code.
    fn get_mem_size(&self) -> usize {
        self.buffer.get_mem_size()
            + std::mem::size_of::<Size>()
            + std::mem::size_of::<Pos>()
            + std::mem::size_of::<Option<TuiColor>>()
            + std::mem::size_of::<Option<TuiColor>>()
    }
}

impl CachedMemorySize for OffscreenBuffer {
    fn memory_size_cache(&self) -> &MemoizedMemorySize {
        &self.memory_size_calc_cache
    }

    fn memory_size_cache_mut(&mut self) -> &mut MemoizedMemorySize {
        &mut self.memory_size_calc_cache
    }
}

pub mod diff_chunks {
    use super::{Deref, List, PixelChar, Pos};

    /// This is a wrapper type so the [`std::fmt::Debug`] can be implemented for it, that
    /// won't conflict with [List]'s implementation of the trait.
    #[derive(Clone, Default, PartialEq)]
    pub struct PixelCharDiffChunks {
        pub inner: List<DiffChunk>,
    }

    pub type DiffChunk = (Pos, PixelChar);

    impl Deref for PixelCharDiffChunks {
        type Target = List<DiffChunk>;

        fn deref(&self) -> &Self::Target { &self.inner }
    }

    impl From<List<DiffChunk>> for PixelCharDiffChunks {
        fn from(list: List<DiffChunk>) -> Self { Self { inner: list } }
    }
}

mod offscreen_buffer_impl {
    use super::{col, fg_green, fmt, inline_string, ok, row, CachedMemorySize, Debug,
                Deref, DerefMut, GetMemSize, List, MemoizedMemorySize, MemorySize,
                OffscreenBuffer, PixelChar, PixelCharDiffChunks, PixelCharLines, Pos,
                Size};

    impl Debug for PixelCharDiffChunks {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            for (pos, pixel_char) in self.iter() {
                writeln!(f, "\t{pos:?}: {pixel_char:?}")?;
            }
            ok!()
        }
    }

    impl Deref for OffscreenBuffer {
        type Target = PixelCharLines;

        fn deref(&self) -> &Self::Target { &self.buffer }
    }

    impl DerefMut for OffscreenBuffer {
        /// Returns a mutable reference to the buffer.
        ///
        /// **Important**: This invalidates and recalculates the `memory_size_calc_cache`
        /// field to ensure telemetry always shows accurate memory size instead of
        /// "?".
        fn deref_mut(&mut self) -> &mut Self::Target {
            // Invalidate and recalculate cache when buffer is accessed mutably
            self.invalidate_memory_size_calc_cache();
            &mut self.buffer
        }
    }

    impl Debug for OffscreenBuffer {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            writeln!(f, "window_size: {:?}, ", self.window_size)?;

            let height = self.window_size.row_height.as_usize();
            for row_index in 0..height {
                if let Some(row) = self.buffer.get(row_index) {
                    // Print row separator if needed (not the first item).
                    if row_index > 0 {
                        writeln!(f)?;
                    }

                    // Print the row index (styled) in "this" line.
                    writeln!(
                        f,
                        "{}",
                        fg_green(&inline_string!("row_index: {}", row_index))
                    )?;

                    // Print the row itself in the "next" line.
                    write!(f, "{row:?}")?;
                }
            }

            writeln!(f)
        }
    }

    impl OffscreenBuffer {
        /// Gets the cached memory size value, recalculating if necessary.
        /// This is used in
        /// [`crate::main_event_loop::EventLoopState::log_telemetry_info()`] for
        /// performance-critical telemetry logging. The expensive memory calculation is
        /// only performed if the cache is invalid or empty.
        #[must_use]
        pub fn get_mem_size_cached(&mut self) -> MemorySize {
            self.get_cached_memory_size()
        }

        /// Invalidates and immediately recalculates the memory size cache.
        /// Call this when buffer content changes to ensure the cache is always valid.
        fn invalidate_memory_size_calc_cache(&mut self) {
            self.invalidate_memory_size_cache();
            self.update_memory_size_cache(); // Force immediate recalculation to avoid "?" in telemetry
        }

        /// Checks for differences between self and other. Returns a list of positions and
        /// pixel chars if there are differences (from other).
        #[must_use]
        pub fn diff(&self, other: &Self) -> Option<PixelCharDiffChunks> {
            if self.window_size != other.window_size {
                return None;
            }

            let mut acc = List::default();

            for (row_idx, (self_row, other_row)) in
                self.buffer.iter().zip(other.buffer.iter()).enumerate()
            {
                for (col_idx, (self_pixel_char, other_pixel_char)) in
                    self_row.iter().zip(other_row.iter()).enumerate()
                {
                    if self_pixel_char != other_pixel_char {
                        let pos = col(col_idx) + row(row_idx);
                        acc.push((pos, *other_pixel_char));
                    }
                }
            }
            Some(PixelCharDiffChunks::from(acc))
        }

        /// Create a new buffer and fill it with empty chars.
        #[must_use]
        pub fn new_with_capacity_initialized(window_size: Size) -> Self {
            let mut buffer = Self {
                buffer: PixelCharLines::new_with_capacity_initialized(window_size),
                window_size,
                my_pos: Pos::default(),
                my_fg_color: None,
                my_bg_color: None,
                memory_size_calc_cache: MemoizedMemorySize::default(),
            };
            // Explicitly calculate and cache the initial memory size.
            // We know the cache is empty (invariant), so directly populate it.
            let size = buffer.get_mem_size();
            buffer
                .memory_size_calc_cache
                .upsert(|| MemorySize::new(size));
            buffer
        }

        // Make sure each line is full of empty chars.
        pub fn clear(&mut self) {
            for line in self.buffer.iter_mut() {
                for pixel_char in line.iter_mut() {
                    if pixel_char != &PixelChar::Spacer {
                        *pixel_char = PixelChar::Spacer;
                    }
                }
            }
            // Invalidate and recalculate cache when buffer is cleared.
            self.invalidate_memory_size_calc_cache();
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PixelCharLines {
    pub lines: InlineVec<PixelCharLine>,
}

mod pixel_char_lines_impl {
    use super::{get_mem_size, smallvec, Deref, DerefMut, GetMemSize, InlineVec,
                PixelCharLine, PixelCharLines, Size};

    impl GetMemSize for PixelCharLines {
        fn get_mem_size(&self) -> usize { get_mem_size::slice_size(self.lines.as_ref()) }
    }

    impl Deref for PixelCharLines {
        type Target = InlineVec<PixelCharLine>;
        fn deref(&self) -> &Self::Target { &self.lines }
    }

    impl DerefMut for PixelCharLines {
        fn deref_mut(&mut self) -> &mut Self::Target { &mut self.lines }
    }

    impl PixelCharLines {
        #[must_use]
        pub fn new_with_capacity_initialized(window_size: Size) -> Self {
            let window_height = window_size.row_height;
            let window_width = window_size.col_width;
            Self {
                lines: smallvec![
                    PixelCharLine::new_with_capacity_initialized(window_width);
                    window_height.as_usize()
                ],
            }
        }
    }
}

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PixelCharLine {
    pub pixel_chars: Vec<PixelChar>,
}

impl GetMemSize for PixelCharLine {
    fn get_mem_size(&self) -> usize {
        get_mem_size::slice_size(self.pixel_chars.as_ref())
    }
}

mod pixel_char_line_impl {
    use super::{dim_underline, fmt, ok, smallvec, tiny_inline_string, ColWidth, Debug,
                Deref, DerefMut, InlineVec, PixelChar, PixelCharLine, TinyInlineString};

    impl Debug for PixelCharLine {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            // Pretty print only so many chars per line (depending on the terminal width
            // in which log.fish is run).
            const MAX_PIXEL_CHARS_PER_LINE: usize = 6;

            let mut void_indices: InlineVec<usize> = smallvec![];
            let mut spacer_indices: InlineVec<usize> = smallvec![];
            let mut void_count: InlineVec<TinyInlineString> = smallvec![];
            let mut spacer_count: InlineVec<TinyInlineString> = smallvec![];

            let mut char_count = 0;

            // Loop: for each PixelChar in a line (pixel_chars_lines[row_index]).
            for (col_index, pixel_char) in self.iter().enumerate() {
                match pixel_char {
                    PixelChar::Void => {
                        void_count.push(TinyInlineString::from(col_index.to_string()));
                        void_indices.push(col_index);
                    }
                    PixelChar::Spacer => {
                        spacer_count.push(TinyInlineString::from(col_index.to_string()));
                        spacer_indices.push(col_index);
                    }
                    PixelChar::PlainText { .. } => {}
                }

                // Index message.
                write!(
                    f,
                    "{}{:?}",
                    dim_underline(&tiny_inline_string!("{col_index:03}")),
                    pixel_char
                )?;

                // Add \n every MAX_CHARS_PER_LINE characters.
                char_count += 1;
                if char_count >= MAX_PIXEL_CHARS_PER_LINE {
                    char_count = 0;
                    writeln!(f)?;
                }
            }

            // Pretty print the spacers & voids (of any of either or both) at the end of
            // the output.
            {
                if !void_count.is_empty() {
                    write!(f, "void [ ")?;
                    fmt_impl_index_values(&void_indices, f)?;
                    write!(f, " ]")?;

                    // Add spacer divider if spacer count exists (next).
                    if !spacer_count.is_empty() {
                        write!(f, " | ")?;
                    }
                }

                if !spacer_count.is_empty() {
                    // Add comma divider if void count exists (previous).
                    if !void_count.is_empty() {
                        write!(f, ", ")?;
                    }
                    write!(f, "spacer [ ")?;
                    fmt_impl_index_values(&spacer_indices, f)?;
                    write!(f, " ]")?;
                }
            }

            ok!()
        }
    }

    fn fmt_impl_index_values(
        values: &[usize],
        f: &mut fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        mod helpers {
            pub enum Peek {
                NextItemContinuesRange,
                NextItemDoesNotContinueRange,
            }

            pub fn peek_does_next_item_continues_range(
                values: &[usize],
                index: usize,
            ) -> Peek {
                if values.get(index + 1).is_none() {
                    return Peek::NextItemDoesNotContinueRange;
                }
                if values[index + 1] == values[index] + 1 {
                    Peek::NextItemContinuesRange
                } else {
                    Peek::NextItemDoesNotContinueRange
                }
            }

            pub enum CurrentRange {
                DoesNotExist,
                Exists,
            }

            pub fn does_current_range_exist(current_range: &[usize]) -> CurrentRange {
                if current_range.is_empty() {
                    CurrentRange::DoesNotExist
                } else {
                    CurrentRange::Exists
                }
            }
        }

        // Track state thru loop iteration.
        let mut acc_current_range: InlineVec<usize> = smallvec![];

        // Main loop.
        for (index, value) in values.iter().enumerate() {
            match (
                helpers::peek_does_next_item_continues_range(values, index),
                helpers::does_current_range_exist(&acc_current_range),
            ) {
                // Start new current range OR the next value continues the current range.
                (helpers::Peek::NextItemContinuesRange,
                helpers::CurrentRange::DoesNotExist | helpers::CurrentRange::Exists) => {
                    acc_current_range.push(*value);
                }
                // The next value does not continue the current range & the current range
                // does not exist.
                (
                    helpers::Peek::NextItemDoesNotContinueRange,
                    helpers::CurrentRange::DoesNotExist,
                ) => {
                    if index > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{value}")?;
                }
                // The next value does not continue the current range & the current range
                // exists.
                (
                    helpers::Peek::NextItemDoesNotContinueRange,
                    helpers::CurrentRange::Exists,
                ) => {
                    if index > 0 {
                        write!(f, ", ")?;
                    }
                    acc_current_range.push(*value);
                    write!(
                        f,
                        "{}-{}",
                        acc_current_range[0],
                        acc_current_range[acc_current_range.len() - 1]
                    )?;
                    acc_current_range.clear();
                }
            }
        }

        ok!()
    }

    // This represents a single row on the screen (i.e. a line of text).
    impl PixelCharLine {
        /// Create a new row with the given width and fill it with the empty chars.
        #[must_use]
        pub fn new_with_capacity_initialized(window_width: ColWidth) -> Self {
            Self {
                pixel_chars: vec![PixelChar::Spacer; window_width.as_usize()],
            }
        }
    }

    impl Deref for PixelCharLine {
        type Target = Vec<PixelChar>;
        fn deref(&self) -> &Self::Target { &self.pixel_chars }
    }

    impl DerefMut for PixelCharLine {
        fn deref_mut(&mut self) -> &mut Self::Target { &mut self.pixel_chars }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum PixelChar {
    Void,
    Spacer,
    PlainText {
        display_char: char,
        maybe_style: Option<TuiStyle>,
    },
}

impl GetMemSize for PixelChar {
    fn get_mem_size(&self) -> usize {
        // Since PixelChar is now Copy, its size is fixed
        std::mem::size_of::<PixelChar>()
    }
}

const EMPTY_CHAR: char = '';
const VOID_CHAR: char = '';

mod pixel_char_impl {
    use super::{fg_magenta, fmt, ok, Debug, PixelChar, EMPTY_CHAR, VOID_CHAR};

    impl Default for PixelChar {
        fn default() -> Self { Self::Spacer }
    }

    impl Debug for PixelChar {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            const WIDTH: usize = 16;

            match self {
                PixelChar::Void => {
                    write!(f, " V {VOID_CHAR:░^WIDTH$}")?;
                }
                PixelChar::Spacer => {
                    write!(f, " S {EMPTY_CHAR:░^WIDTH$}")?;
                }
                PixelChar::PlainText {
                    display_char,
                    maybe_style,
                } => {
                    match maybe_style {
                        // Content + style.
                        Some(style) => {
                            write!(
                                f,
                                " {} '{display_char}'→{style: ^WIDTH$}",
                                fg_magenta("P")
                            )?;
                        }
                        // Content, no style.
                        _ => {
                            write!(f, " {} '{display_char}': ^WIDTH$", fg_magenta("P"))?;
                        }
                    }
                }
            }

            ok!()
        }
    }
}

pub trait OffscreenBufferPaint {
    fn render(&mut self, offscreen_buffer: &OffscreenBuffer) -> RenderOps;

    fn render_diff(&mut self, diff_chunks: &PixelCharDiffChunks) -> RenderOps;

    fn paint(
        &mut self,
        render_ops: RenderOps,
        flush_kind: FlushKind,
        window_size: Size,
        locked_output_device: LockedOutputDevice<'_>,
        is_mock: bool,
    );

    fn paint_diff(
        &mut self,
        render_ops: RenderOps,
        window_size: Size,
        locked_output_device: LockedOutputDevice<'_>,
        is_mock: bool,
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{assert_eq2, height, new_style, tui_color, width};

    #[test]
    fn test_offscreen_buffer_construction() {
        let window_size = width(10) + height(2);
        let my_offscreen_buffer =
            OffscreenBuffer::new_with_capacity_initialized(window_size);
        assert_eq2!(my_offscreen_buffer.buffer.len(), 2);
        assert_eq2!(my_offscreen_buffer.buffer[0].len(), 10);
        assert_eq2!(my_offscreen_buffer.buffer[1].len(), 10);
        for line in my_offscreen_buffer.buffer.iter() {
            for pixel_char in line.iter() {
                assert_eq2!(pixel_char, &PixelChar::Spacer);
            }
        }
        // println!("my_offscreen_buffer: \n{:#?}", my_offscreen_buffer);
    }

    #[test]
    fn test_offscreen_buffer_re_init() {
        let window_size = width(10) + height(2);
        let mut my_offscreen_buffer =
            OffscreenBuffer::new_with_capacity_initialized(window_size);

        my_offscreen_buffer.buffer[0][0] = PixelChar::PlainText {
            display_char: 'a',
            maybe_style: Some(new_style!(color_bg: {tui_color!(green)})),
        };

        my_offscreen_buffer.buffer[1][9] = PixelChar::PlainText {
            display_char: 'z',
            maybe_style: Some(new_style!(color_bg: {tui_color!(red)})),
        };

        // println!("my_offscreen_buffer: \n{:#?}", my_offscreen_buffer);
        my_offscreen_buffer.clear();
        for line in my_offscreen_buffer.buffer.iter() {
            for pixel_char in line.iter() {
                assert_eq2!(pixel_char, &PixelChar::Spacer);
            }
        }
        // println!("my_offscreen_buffer: \n{:#?}", my_offscreen_buffer);
    }

    #[test]
    fn test_memory_size_caching() {
        let window_size = width(10) + height(2);
        let mut my_offscreen_buffer =
            OffscreenBuffer::new_with_capacity_initialized(window_size);

        // First call should calculate and cache
        let size1 = my_offscreen_buffer.get_mem_size_cached();
        assert_ne!(format!("{size1}"), "?");

        // Second call should use cached value (no recalculation)
        let size2 = my_offscreen_buffer.get_mem_size_cached();
        assert_eq!(format!("{size1}"), format!("{}", size2));

        // Modify buffer through DerefMut (invalidates cache)
        my_offscreen_buffer.buffer[0][0] = PixelChar::PlainText {
            display_char: 'x',
            maybe_style: None,
        };

        // Next call should recalculate
        let size3 = my_offscreen_buffer.get_mem_size_cached();
        assert_ne!(format!("{size3}"), "?");

        // Clear should also invalidate cache
        my_offscreen_buffer.clear();
        let size4 = my_offscreen_buffer.get_mem_size_cached();
        assert_ne!(format!("{size4}"), "?");
    }
}