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
/*
 *   Copyright (c) 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.
 */

//! This module contains the implementation of the render cache for the editor buffer.
//! Currently the cache can only hold 1 entry at a time. The cache is invalidated if the
//! content of the editor buffer changes, or if the scroll offset or window size changes.
//!
//! - The key is derived from the scroll offset and window size.
//! - The value is a [`RenderOps`] struct that contains the render operations to render
//!   the content of the editor buffer to the screen.
//!
//! In the future, if there is a need to store multiple entries in the cache, the cache
//! can be implemented as a [`crate::RingBuffer`] or [`crate::InlineVec`] of
//! [`CacheEntry`] structs.

use std::ops::{Deref, DerefMut};

use super::EditorBuffer;
use crate::{engine_public_api, EditorEngine, HasFocus, RenderArgs, RenderOps, ScrOfs,
            Size};

pub(in crate::tui::editor::editor_buffer) mod key {
    use super::{ScrOfs, Size};

    /// Cache key is combination of `scroll_offset` and `window_size`.
    #[derive(Clone, Debug, PartialEq)]
    pub struct Key((ScrOfs, Size));

    impl Key {
        #[must_use]
        pub fn new(scr_ofs: ScrOfs, window_size: Size) -> Self {
            (scr_ofs, window_size).into()
        }
    }

    impl From<(ScrOfs, Size)> for Key {
        fn from((scr_ofs, window_size): (ScrOfs, Size)) -> Self {
            Self((scr_ofs, window_size))
        }
    }
}
pub use key::*;
// Allow code below to all the symbols in this mod.

pub(in crate::tui::editor::editor_buffer) mod cache_entry {
    use super::{key::Key, RenderOps};

    /// Cache entry is a combination of a single key and single value.
    #[derive(Clone, Debug, PartialEq)]
    pub struct CacheEntry(pub Key, pub RenderOps);

    impl CacheEntry {
        pub fn new(arg_key: impl Into<Key>, value: RenderOps) -> Self {
            Self(arg_key.into(), value)
        }
    }
}
pub use cache_entry::*;
// Allow code below to all the symbols in this mod.

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UseRenderCache {
    Yes,
    No,
}

/// Holds a single cache entry that represents the render operations to render the content
/// of the editor buffer to the current viewport and (terminal) screen size. The key
/// encodes information about the scroll offset and window size, which is used to derive
/// the viewport information.
#[derive(Clone, Default, Debug, PartialEq)]
pub struct RenderCache {
    pub entry: Option<cache_entry::CacheEntry>,
}

mod render_cache_impl_block {
    use super::{cache_entry, engine_public_api, CacheEntry, Deref, DerefMut,
                EditorBuffer, EditorEngine, HasFocus, Key, RenderArgs, RenderCache,
                RenderOps, Size, UseRenderCache};

    impl Deref for RenderCache {
        type Target = Option<cache_entry::CacheEntry>;

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

    impl DerefMut for RenderCache {
        fn deref_mut(&mut self) -> &mut Self::Target { &mut self.entry }
    }
    impl RenderCache {
        pub fn clear(&mut self) { self.entry = None; }

        pub fn get(&self, arg_key: impl Into<Key>) -> Option<&RenderOps> {
            let key: Key = arg_key.into();
            if key == self.entry.as_ref()?.0 {
                Some(&self.entry.as_ref()?.1)
            } else {
                None
            }
        }

        /// This cache only holds a single entry. So if there is an existing entry, it is
        /// replaced with the new entry.
        pub fn insert(&mut self, arg_key: impl Into<Key>, value: RenderOps) {
            let key: Key = arg_key.into();
            self.entry = Some(CacheEntry::new(key, value));
        }

        /// Render the content of the editor buffer to the screen from the cache if the
        /// content has not been modified.
        ///
        /// The cache miss occurs if
        /// - Scroll Offset changes
        /// - Window size changes
        /// - Content of the editor changes
        pub fn render_content(
            buffer: &mut EditorBuffer,
            engine: &mut EditorEngine,
            window_size: Size,
            has_focus: &mut HasFocus,
            render_ops: &mut RenderOps,
            use_cache: UseRenderCache,
        ) {
            // Cache enabled & hit so early return.
            if matches!(use_cache, UseRenderCache::Yes)
                && let Some(cached_output) =
                    buffer.render_cache.get((buffer.get_scr_ofs(), window_size))
                {
                    *render_ops = cached_output.clone();
                    return;
                }

            // Cached disabled, or miss due to:
            // - Content has been modified.
            // - Scroll Offset or Window size has been modified.
            // So re-render content, generate & write to render_ops.
            engine_public_api::render_content(
                RenderArgs {
                    engine,
                    buffer,
                    has_focus,
                },
                render_ops,
            );

            match use_cache {
                // Cache is enabled, so update it.
                UseRenderCache::Yes => buffer
                    .render_cache
                    .insert((buffer.get_scr_ofs(), window_size), render_ops.clone()),
                // Cache is disabled, so invalidate it (it should contain nothing at this
                // point).
                UseRenderCache::No => buffer.render_cache.clear(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{assert_eq2, col, height, render_ops, row, scr_ofs, width, RenderOp};

    /// Fake `render_ops` to be used in the tests.
    fn get_render_ops_og() -> RenderOps {
        render_ops!(
            @new
            RenderOp::ClearScreen, RenderOp::ResetColor
        )
    }

    /// Fake window size to be used in the tests.
    fn get_window_size_og() -> Size { height(70) + width(15) }

    #[test]
    fn test_cache_can_be_disabled() {
        let buffer = &mut EditorBuffer::default();
        let engine = &mut EditorEngine::default();
        let has_focus = &mut HasFocus::default();

        // Cache should be empty.
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            None
        );

        // The very first request to cache is always missed since cache is empty.
        let render_ops_mut = &mut get_render_ops_og();
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );

        // Cache should have been populated with the render_ops_og.
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            Some(&get_render_ops_og())
        );

        // Disable cache and re-render content.
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::No,
        );

        // Cache should have been cleared.
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            None
        );
    }

    #[test]
    fn test_assert_cache_hit_for_multiple_renders() {
        let buffer = &mut EditorBuffer::default();
        let engine = &mut EditorEngine::default();
        let has_focus = &mut HasFocus::default();

        // Cache should be empty.
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            None
        );

        // The very first request to cache is always missed since cache is empty.
        let render_ops_mut = &mut get_render_ops_og();
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );

        // Cache should have been populated with the render_ops_og.
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            Some(&get_render_ops_og())
        );

        // Subsequent requests to cache should be hits.
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            Some(&get_render_ops_og())
        );

        // Modify the `render_ops_mut` manually (eg: when the caret is added using
        // `render_caret`). This should not change the content and result in a cache
        // hit.
        render_ops_mut.clear();
        assert!(render_ops_mut.is_empty());
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );
        // `render_ops_mut` should have been restored to `render_ops_og` by
        // render_content(.., UseRenderCache::Yes).
        assert!(!render_ops_mut.is_empty());
        assert_eq2!(render_ops_mut, &get_render_ops_og());
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            Some(&get_render_ops_og())
        );
    }

    #[test]
    fn test_assert_cache_miss_for_first_render() {
        let buffer = &mut EditorBuffer::default();
        let engine = &mut EditorEngine::default();
        let has_focus = &mut HasFocus::default();

        // Cache should be empty.
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            None
        );

        // The very first request to cache is always missed since cache is empty.
        let render_ops_mut = &mut get_render_ops_og();
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );

        // Cache should have been populated with the render_ops_og.
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            Some(&get_render_ops_og())
        );

        // Modify the `render_ops_mut` manually (eg: when the caret is added using
        // `render_caret`). This should not change the content and result in a cache
        // hit.
        render_ops_mut.clear();
        assert!(render_ops_mut.is_empty());
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );
        // `render_ops_mut` should have been restored to `render_ops_og` by
        // render_content(.., UseRenderCache::Yes).
        assert!(!render_ops_mut.is_empty());
        assert_eq2!(render_ops_mut, &get_render_ops_og());
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            Some(&get_render_ops_og())
        );
    }

    #[test]
    fn test_window_size_change_causes_cache_miss() {
        let buffer = &mut EditorBuffer::default();
        let engine = &mut EditorEngine::default();
        let has_focus = &mut HasFocus::default();

        // The very first request to cache is always missed since cache is empty.
        let render_ops_mut = &mut get_render_ops_og();
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );

        // Change in window size should invalidate the cache and result in a cache miss.
        let window_size_new = height(50) + width(15);
        assert!(window_size_new != get_window_size_og());
        RenderCache::render_content(
            buffer,
            engine,
            window_size_new,
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og())),
            None
        );
        assert_eq2!(
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), window_size_new)),
            Some(&get_render_ops_og())
        );
    }

    #[test]
    fn test_scroll_offset_change_causes_cache_miss() {
        let buffer = &mut EditorBuffer::default();
        let engine = &mut EditorEngine::default();
        let has_focus = &mut HasFocus::default();

        // The very first request to cache is always missed since cache is empty.
        let render_ops_mut = &mut get_render_ops_og();
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );

        // Change in scroll_offset should invalidate the cache and result in a cache miss.
        let scr_ofs_old = buffer.get_scr_ofs();
        let scr_ofs_new = scr_ofs(col(1) + row(1));
        assert!(scr_ofs_new != scr_ofs_old);

        buffer.content.scr_ofs = scr_ofs_new;
        RenderCache::render_content(
            buffer,
            engine,
            get_window_size_og(),
            has_focus,
            render_ops_mut,
            UseRenderCache::Yes,
        );
        assert_eq2!(
            buffer.render_cache.get((scr_ofs_old, get_window_size_og())),
            None
        );
        assert_eq2!(
            buffer.render_cache.get((scr_ofs_new, get_window_size_og())),
            Some(&get_render_ops_og())
        );
    }

    #[test]
    fn test_content_change_invalidates_cache() {
        let buffer = &mut EditorBuffer::default();
        let engine = &mut EditorEngine::default();
        let has_focus = &mut HasFocus::default();

        // Change in content should invalidate the cache.
        let snapshot_1 = {
            buffer.init_with(["r3bl"]);
            RenderCache::render_content(
                buffer,
                engine,
                get_window_size_og(),
                has_focus,
                &mut get_render_ops_og(),
                UseRenderCache::Yes,
            );
            assert!(buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og()))
                .is_some());
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og()))
                .unwrap()
                .clone()
        };

        // Change in content should invalidate the cache.
        let snapshot_2 = {
            buffer.init_with(["r3bl", "r3bl"]);
            RenderCache::render_content(
                buffer,
                engine,
                get_window_size_og(),
                has_focus,
                &mut get_render_ops_og(),
                UseRenderCache::Yes,
            );
            assert!(buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og()))
                .is_some());
            buffer
                .render_cache
                .get((buffer.get_scr_ofs(), get_window_size_og()))
                .unwrap()
                .clone()
        };

        assert!(snapshot_1 != snapshot_2);
    }
}