r3bl_tui 0.7.7

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
// Copyright (c) 2025 R3BL LLC. Licensed under Apache License, Version 2.0.

//! # Stage 4: Backend Converter (Shared)
//!
//! This module implements **Stage 4 of the rendering pipeline**: converting the
//! [`OffscreenBuffer`] (produced by the Compositor in Stage 3) into optimized
//! [`RenderOpOutputVec`] operations for backend execution.
//!
//! <div class="warning">
//!
//! **For the complete 6-stage rendering pipeline with visual diagrams and stage
//! reference table**, see the [rendering pipeline overview].
//!
//! </div>
//!
//! ## Why This Lives in [`offscreen_buffer/`]
//!
//! Stage 4 is fundamentally an **`OffscreenBuffer` operation**:
//! - It reads FROM the buffer (like other buffer operations)
//! - It uses [`diff_chunks`] (also in this module) for selective redraw optimization
//! - It's buffer-centric, not backend-specific
//!
//! ## Backend Independence
//!
//! This converter is **shared by both Crossterm and `DirectToAnsi` backends**.
//! The backends only differ in Stage 5 (Backend Executor):
//! - Crossterm: [`crossterm_backend` mod docs]
//! - `DirectToAnsi`: [`direct_to_ansi` mod docs]
//!
//! # You Are Here: **Stage 4** (Backend Converter/Shared)
//!
//! ```text
//! [Stage 1: App/Component]
//!//! [Stage 2: Pipeline]
//!//! [Stage 3: Compositor]
//!//! [Stage 4: Backend Converter] ← YOU ARE HERE (shared by all backends)
//!//! [Stage 5: Backend Executor]
//!//! [Stage 6: Terminal]
//! ```
//!
//! **Input**: [`OffscreenBuffer`] (rendered pixels from compositor)
//! **Output**: [`RenderOpOutputVec`] (optimized terminal operations)
//! **Role**: Convert [`OffscreenBuffer`] to backend-agnostic rendering operations
//!
//! ## What This Stage Does
//!
//! The Backend Converter scans the [`OffscreenBuffer`] and generates optimized
//! [`RenderOpOutputVec`] operations ready for terminal execution. It can:
//! - Perform diff calculations against the previous buffer for selective redraw
//! - Convert grid of styled characters to styled text painting operations
//! - Optimize by grouping adjacent operations with the same styling
//! - Handle state tracking via [`RenderOpsLocalData`]
//!
//! This stage is crucial for performance: by diffing buffers, only changed pixels are
//! rendered in subsequent frames, eliminating unnecessary terminal updates.
//!
//! [`OffscreenBuffer`]: crate::OffscreenBuffer
//! [`RenderOpOutputVec`]: crate::RenderOpOutputVec
//! [`RenderOpsLocalData`]: crate::RenderOpsLocalData
//! [`crossterm_backend` mod docs]: mod@crate::tui::terminal_lib_backends::crossterm_backend
//! [`diff_chunks`]: mod@crate::tui::terminal_lib_backends::offscreen_buffer::diff_chunks
//! [`direct_to_ansi` mod docs]: mod@crate::direct_to_ansi
//! [rendering pipeline overview]: mod@crate::terminal_lib_backends#rendering-pipeline-architecture
//! [`offscreen_buffer/`]: mod@crate::tui::terminal_lib_backends::offscreen_buffer

// Copyright (c) 2022-2025 R3BL LLC. Licensed under Apache License, Version 2.0.
use crate::{ColIndex, DEBUG_TUI_COMPOSITOR, DEBUG_TUI_SHOW_PIPELINE, FlushKind,
            GCStringOwned, InlineString, LockedOutputDevice, OffscreenBuffer,
            OffscreenBufferPaint, PixelChar, PixelCharDiffChunks, RenderOpCommon,
            RenderOpFlush, RenderOpOutput, RenderOpOutputVec, RenderOpsExec, RowIndex,
            Size, TuiStyle, ch, col, glyphs::SPACER_GLYPH, row,
            terminal_lib_backends::crossterm_backend::PaintRenderOpImplCrossterm};

#[derive(Debug)]
pub struct OffscreenBufferPaintImplCrossterm;

impl OffscreenBufferPaint for OffscreenBufferPaintImplCrossterm {
    fn paint(
        &mut self,
        render_ops: RenderOpOutputVec,
        flush_kind: FlushKind,
        window_size: Size,
        locked_output_device: LockedOutputDevice<'_>,
        is_mock: bool,
    ) {
        let mut skip_flush = false;

        if let FlushKind::ClearBeforeFlush = flush_kind {
            PaintRenderOpImplCrossterm.clear_before_flush(locked_output_device);
        }

        // Execute each RenderOpOutput using the ExecutableRenderOps trait.
        render_ops.execute_all(
            &mut skip_flush,
            window_size,
            locked_output_device,
            is_mock,
        );

        // Flush everything to the terminal.
        if !skip_flush {
            PaintRenderOpImplCrossterm.flush(locked_output_device);
        }

        // Debug output.
        DEBUG_TUI_SHOW_PIPELINE.then(|| {
            // % is Display, ? is Debug.
            tracing::info!(
                message = "🎨 offscreen_buffer_paint_impl_crossterm::paint() ok 🟢",
                render_ops = ?render_ops
            );
        });
    }

    fn paint_diff(
        &mut self,
        render_ops: RenderOpOutputVec,
        window_size: Size,
        locked_output_device: LockedOutputDevice<'_>,
        is_mock: bool,
    ) {
        let mut skip_flush = false;

        // Execute each RenderOpOutput using the ExecutableRenderOps trait.
        render_ops.execute_all(
            &mut skip_flush,
            window_size,
            locked_output_device,
            is_mock,
        );

        // Flush everything to the terminal.
        if !skip_flush {
            PaintRenderOpImplCrossterm.flush(locked_output_device);
        }

        // Debug output.
        DEBUG_TUI_SHOW_PIPELINE.then(|| {
            // % is Display, ? is Debug.
            tracing::info!(
                message = "🎨 offscreen_buffer_paint_impl_crossterm::paint_diff() ok 🟢",
                render_ops = ?render_ops
            );
        });
    }

    /// Process each [`PixelChar`] and generate a [`RenderOpOutput`]
    /// for it. Return a [`RenderOpOutputVec`] containing all the [`RenderOpOutput`]s.
    ///
    /// > Note that each [`PixelChar`] gets the full [`TuiStyle`] embedded in it (not just
    /// > a part of it that is different than the previous char). This means that it is
    /// > possible to quickly "diff" between 2 of them, since the [`TuiStyle`] is part of
    /// > the [`PixelChar`]. This is important for selective re-rendering of the
    /// > offscreen buffer.
    ///
    /// Here's the algorithm used in this function using pseudo-code:
    /// - When going thru every [`PixelChar`] in a line:
    ///   - If the [`PixelChar`] is [`Void`], [`Spacer`], or [`PlainText`] then handle
    ///     (display character, [`TuiStyle`])
    ///     - line buffer -  accumulates over loop iterations.
    ///     - `render_helper::flush_all_buffers()` - flushes.
    ///   - Make sure to flush at the:
    ///     - End of line.
    ///     - When style changes.
    ///
    /// [`PlainText`]: PixelChar::PlainText
    /// [`RenderOpOutputVec`]: crate::RenderOpOutputVec
    /// [`RenderOpOutput`]: crate::RenderOpOutput
    /// [`Spacer`]: PixelChar::Spacer
    /// [`TuiStyle`]: crate::TuiStyle
    /// [`Void`]: PixelChar::Void
    fn render(&mut self, ofs_buf: &OffscreenBuffer) -> RenderOpOutputVec {
        use render_helper::Context;

        let mut context = Context::new();

        // For each line in the offscreen buffer.
        for (row_index, line) in ofs_buf.buffer.iter().enumerate() {
            context.clear_for_new_line(row(row_index));

            // For each pixel char in the line.
            for (pixel_char_index, pixel_char) in line.iter().enumerate() {
                let (pixel_char_content, pixel_char_style): (String, Option<TuiStyle>) =
                    match pixel_char {
                        PixelChar::Void => continue,
                        PixelChar::Spacer => (SPACER_GLYPH.to_string(), None),
                        PixelChar::PlainText {
                            display_char,
                            style,
                        } => (display_char.to_string(), Some(*style)),
                    };

                let is_style_same_as_prev = render_helper::style_eq(
                    pixel_char_style.as_ref(),
                    context.prev_style.as_ref(),
                );
                let is_at_end_of_line = ch(pixel_char_index) == (ch(line.len()) - ch(1));
                let is_first_loop_iteration = row_index == 0 && pixel_char_index == 0;

                // Deal w/: fg and bg colors | text attrib style | ANSI <-> PLAIN.
                // switchover.
                if !is_style_same_as_prev {
                    // The style changed / render path has changed and something is.
                    // already in the buffer, so flush it!
                    render_helper::flush_all_buffers(&mut context);
                }

                // Deal w/: fg and bg colors | text attrib style.
                if is_first_loop_iteration || !is_style_same_as_prev {
                    context.render_ops += RenderOpCommon::ResetColor;
                    if let Some(style) = pixel_char_style
                        && let Some(color) = style.color_fg
                    {
                        context.render_ops += RenderOpCommon::SetFgColor(color);
                    }
                    if let Some(style) = pixel_char_style
                        && let Some(color) = style.color_bg
                    {
                        context.render_ops += RenderOpCommon::SetBgColor(color);
                    }
                    // Update prev_style.
                    context.prev_style = pixel_char_style;
                }

                // Buffer it.
                context.buffer_plain_text.push_str(&pixel_char_content);

                // Flush it.
                if is_at_end_of_line {
                    render_helper::flush_all_buffers(&mut context);
                }
            } // End for each pixel char in the line.
        } // End for each line in the offscreen buffer.

        // This handles the edge case when there is still something in the temp buffer,
        // but the loop has exited.
        if !context.buffer_plain_text.is_empty() {
            render_helper::flush_all_buffers(&mut context);
        }

        context.render_ops
    }

    fn render_diff(&mut self, diff_chunks: &PixelCharDiffChunks) -> RenderOpOutputVec {
        DEBUG_TUI_COMPOSITOR.then(|| {
            // % is Display, ? is Debug.
            tracing::info!(
                message = "🎨 offscreen_buffer_paint_impl_crossterm::render_diff() ok 🟢",
                diff_chunks = ?diff_chunks
            );
        });

        let mut it = RenderOpOutputVec::new();

        for (position, pixel_char) in diff_chunks.iter() {
            it.push(RenderOpCommon::MoveCursorPositionAbs(*position));
            it.push(RenderOpCommon::ResetColor);
            match pixel_char {
                PixelChar::Void => { /* continue */ }
                PixelChar::Spacer => {
                    it.push(
                        RenderOpOutput::CompositorNoClipTruncPaintTextWithAttributes(
                            SPACER_GLYPH.into(),
                            None,
                        ),
                    );
                }
                PixelChar::PlainText {
                    display_char,
                    style,
                    ..
                } => {
                    it.push(RenderOpCommon::ApplyColors(Some(*style)));
                    it.push(
                        RenderOpOutput::CompositorNoClipTruncPaintTextWithAttributes(
                            InlineString::from_str(&display_char.to_string()),
                            Some(*style),
                        ),
                    );
                }
            }
        }

        it
    }
}

mod render_helper {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    #[derive(Debug, Clone)]
    pub struct Context {
        pub display_col_index_for_line: ColIndex,
        pub display_row_index: RowIndex,
        pub buffer_plain_text: InlineString,
        pub prev_style: Option<TuiStyle>,
        pub render_ops: RenderOpOutputVec,
    }

    impl Context {
        pub fn new() -> Self {
            Context {
                display_col_index_for_line: col(0),
                buffer_plain_text: InlineString::new(),
                render_ops: RenderOpOutputVec::new(),
                display_row_index: row(0),
                prev_style: None,
            }
        }

        pub fn clear_for_new_line(&mut self, row_index: RowIndex) {
            self.buffer_plain_text.clear();
            self.display_col_index_for_line = col(0);
            self.display_row_index = row_index;
        }
    }

    /// `this` is eq to `other` if they are both `Some` and their following fields are eq:
    /// - `color_fg`
    /// - `color_bg`
    /// - `bold`
    /// - `dim`
    /// - `underline`
    /// - `reverse`
    /// - `hidden`
    /// - `strikethrough`
    pub fn style_eq(this: Option<&TuiStyle>, other: Option<&TuiStyle>) -> bool {
        match (this, other) {
            (Some(this), Some(other)) => {
                this.color_fg == other.color_fg
                    && this.color_bg == other.color_bg
                    && this.attribs.bold == other.attribs.bold
                    && this.attribs.dim == other.attribs.dim
                    && this.attribs.underline == other.attribs.underline
                    && this.attribs.reverse == other.attribs.reverse
                    && this.attribs.hidden == other.attribs.hidden
                    && this.attribs.strikethrough == other.attribs.strikethrough
            }
            (None, None) => true,
            _ => false,
        }
    }

    pub fn flush_all_buffers(context: &mut Context) {
        if !context.buffer_plain_text.is_empty() {
            render_helper::flush_plain_text_line_buffer(context);
        }
    }

    pub fn flush_plain_text_line_buffer(context: &mut Context) {
        // Generate `RenderOpOutput` operations for each `PixelChar` and add it to
        // `render_ops`.
        let pos = context.display_col_index_for_line + context.display_row_index;

        // Deal w/ position.
        context.render_ops += RenderOpCommon::MoveCursorPositionAbs(pos);

        // Deal w/ style attribs & actually paint the `temp_line_buffer`.
        context.render_ops +=
            RenderOpOutput::CompositorNoClipTruncPaintTextWithAttributes(
                context.buffer_plain_text.clone(),
                context.prev_style,
            );

        // Update `display_col_index_for_line`.
        let display_width = GCStringOwned::from(&context.buffer_plain_text).width();
        *context.display_col_index_for_line += *display_width;

        // Clear the buffer!
        context.buffer_plain_text.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::{render_helper::style_eq, *};
    use crate::{ColWidth, RenderOpsLocalData, assert_eq2,
                compositor_render_ops_to_ofs_buf::print_text_with_attributes, height,
                new_style, tui_color, width};

    /// Helper function to make an `OffscreenBuffer`.
    fn make_offscreen_buffer_plain_text() -> OffscreenBuffer {
        let window_size = width(10) + height(2);
        let mut ofs_buf = OffscreenBuffer::new_empty(window_size);

        // Input:  R0 "hello1234😃"
        //            C0123456789
        // Output: R0 "hello1234╳"
        //            C0123456789
        let text = "hello1234😃";
        // The style colors should be overwritten by fg_color and bg_color.
        let maybe_style = Some(
            new_style!(dim bold color_fg:{tui_color!(cyan)} color_bg:{tui_color!(cyan)}),
        );
        ofs_buf.cursor_pos = col(0) + row(0);
        let render_local_data = RenderOpsLocalData {
            fg_color: Some(tui_color!(green)),
            bg_color: Some(tui_color!(blue)),
            ..Default::default()
        };
        let maybe_max_display_col_count: Option<ColWidth> = Some(width(10));
        print_text_with_attributes(
            text,
            maybe_style.as_ref(),
            &mut ofs_buf,
            maybe_max_display_col_count,
            &render_local_data,
        )
        .ok();
        ofs_buf

        // Output:
        // my_offscreen_buffer:
        // window_size: [width:10, height:2],
        // row_index: [0]
        //   0: "h" Some(Style { _id + bold + dim | fg: Some(green) | bg: Some(blue) |
        // padding: 0 })   1: "e" Some(Style { _id + bold + dim | fg: Some(green)
        // | bg: Some(blue) | padding: 0 })   2: "l" Some(Style { _id + bold + dim
        // | fg: Some(green) | bg: Some(blue) | padding: 0 })   3: "l" Some(Style
        // { _id + bold + dim | fg: Some(green) | bg: Some(blue) | padding: 0 })
        //   4: "o" Some(Style { _id + bold + dim | fg: Some(green) | bg: Some(blue) |
        // padding: 0 })   5: "1" Some(Style { _id + bold + dim | fg: Some(green)
        // | bg: Some(blue) | padding: 0 })   6: "2" Some(Style { _id + bold + dim
        // | fg: Some(green) | bg: Some(blue) | padding: 0 })   7: "3" Some(Style
        // { _id + bold + dim | fg: Some(green) | bg: Some(blue) | padding: 0 })
        //   8: "4" Some(Style { _id + bold + dim | fg: Some(green) | bg: Some(blue) |
        // padding: 0 })   9: ╳
        // row_index: [1]
        //   0: ╳ ..
        //   9: ╳
    }

    #[test]
    fn test_render_plain_text() {
        let my_offscreen_buffer = make_offscreen_buffer_plain_text();
        // println!("my_offscreen_buffer: \n{:#?}", my_offscreen_buffer);
        let mut paint = OffscreenBufferPaintImplCrossterm {};
        let render_ops = paint.render(&my_offscreen_buffer);
        // println!("render_ops: {:#?}", render_ops);

        // Output:
        // render_ops:
        // - RenderOpOutputVec.len(): 10
        // - [ResetColor]
        // - [SetFgColor(green)]
        // - [SetBgColor(blue)]
        // - [MoveCursorPositionAbs([col:0, row:0])]
        // - [PrintTextWithAttributes(9 bytes, Style { _id + bold + dim | fg: Some(green)
        //   | bg: Some(blue) | padding: 0 })]
        // - [ResetColor]
        // - [MoveCursorPositionAbs([col:9, row:0])]
        // - [PrintTextWithAttributes(1 bytes, None)]
        // - [MoveCursorPositionAbs([col:0, row:1])]
        // - [PrintTextWithAttributes(10 bytes, None)]

        assert_eq2!(render_ops.len(), 10);
        assert_eq2!(
            render_ops[0],
            RenderOpOutput::Common(RenderOpCommon::ResetColor)
        );
        assert_eq2!(
            render_ops[1],
            RenderOpOutput::Common(RenderOpCommon::SetFgColor(tui_color!(green)))
        );
        assert_eq2!(
            render_ops[2],
            RenderOpOutput::Common(RenderOpCommon::SetBgColor(tui_color!(blue)))
        );
        assert_eq2!(
            render_ops[3],
            RenderOpOutput::Common(RenderOpCommon::MoveCursorPositionAbs(
                col(0) + row(0)
            ))
        );
        assert_eq2!(
            render_ops[4],
            RenderOpOutput::CompositorNoClipTruncPaintTextWithAttributes(
                "hello1234".into(),
                Some(
                    new_style!(dim bold color_fg:{tui_color!(green)} color_bg:{tui_color!(blue)})
                )
            )
        );
        assert_eq2!(
            render_ops[5],
            RenderOpOutput::Common(RenderOpCommon::ResetColor)
        );
        assert_eq2!(
            render_ops[6],
            RenderOpOutput::Common(RenderOpCommon::MoveCursorPositionAbs(
                col(9) + row(0)
            ))
        );
        assert_eq2!(
            render_ops[7],
            RenderOpOutput::CompositorNoClipTruncPaintTextWithAttributes(
                SPACER_GLYPH.into(),
                None
            )
        );
        assert_eq2!(
            render_ops[8],
            RenderOpOutput::Common(RenderOpCommon::MoveCursorPositionAbs(
                col(0) + row(1)
            ))
        );
        assert_eq2!(
            render_ops[9],
            RenderOpOutput::CompositorNoClipTruncPaintTextWithAttributes(
                (SPACER_GLYPH.repeat(10)).into(),
                None
            )
        );
    }

    #[test]
    fn test_render_helper_style_eq() {
        let style1 = Some(
            new_style!(dim bold color_fg:{tui_color!(cyan)} color_bg:{tui_color!(cyan)}),
        );
        let style2 = Some(
            new_style!(dim bold color_fg:{tui_color!(cyan)} color_bg:{tui_color!(cyan)}),
        );

        assert_eq2!(style_eq(style1.as_ref(), style2.as_ref()), true);

        let style_3 = Some(
            new_style!(italic color_fg:{tui_color!(black)} color_bg:{tui_color!(cyan)}),
        );

        assert_eq2!(style_eq(style1.as_ref(), style_3.as_ref()), false);
    }
}