minui 0.7.3

A minimalist framework for building terminal UIs in Rust.
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
//! Efficient terminal screen buffer implementation with change tracking.
//!
//! This module provides the core buffering functionality that enables MinUI's efficient
//! rendering system. It implements a double-buffered approach with intelligent change
//! detection and optimization.

use crate::{ColorPair, Result};

/// Represents a single character cell in the terminal buffer.
///
/// Each cell stores a character and optional color information. Dirty row ranges provide
/// change tracking without adding per-cell bookkeeping.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Cell {
    pub(crate) ch: char,
    pub(crate) colors: Option<ColorPair>,
}

/// Represents a batched change to the terminal buffer.
///
/// Buffer changes are generated during the rendering process to represent
/// contiguous runs of characters that need to be updated in the terminal.
/// This batching approach significantly reduces the number of cursor movements
/// and color changes required.
///
/// # Fields
///
/// - `y`, `x`: Starting position of the change
/// - `text`: The string of characters to write (may be multiple characters)
/// - `colors`: Color styling to apply to the entire text run
#[derive(Clone, Copy, Debug)]
pub(crate) struct BufferChange {
    pub(crate) y: u16,
    pub(crate) x: u16,
    pub(crate) start_idx: usize,
    pub(crate) len: usize,
    pub(crate) colors: Option<ColorPair>,
}

#[derive(Clone, Copy, Debug)]
struct DirtyRange {
    min_x: u16,
    max_x: u16,
}

impl Cell {
    /// Creates an empty cell (space character with no colors).
    pub fn empty() -> Self {
        Self {
            ch: ' ',
            colors: None,
        }
    }
}

/// A double-buffered screen representation with intelligent change detection.
///
/// `Buffer` is the core of MinUI's efficient rendering system. It maintains two copies
/// of the screen state (current and previous) and tracks which areas have changed,
/// enabling minimal terminal updates.
///
/// # Architecture
///
/// The buffer uses several optimization strategies:
///
/// ## Double Buffering
/// - **Current Buffer**: The desired state of the screen
/// - **Previous Buffer**: The last rendered state
/// - **Change Detection**: Only cells that differ between buffers are updated
///
/// ## Dirty Region Tracking
/// - Tracks the minimum and maximum X and Y coordinates that have changed
/// - Skips processing of unchanged regions entirely
/// - Reduces processing time for sparse updates
///
/// ## Run-Length Encoding
/// - Groups consecutive characters with identical styling
/// - Reduces cursor movements and color changes
/// - Significantly improves rendering performance
///
/// # Performance Characteristics
///
/// - **Memory**: Two compact cell buffers plus one dirty range per row
/// - **Time Complexity**: O(changed_cells) for processing
/// - **Terminal I/O**: Minimized through batching and change detection
///
/// # Example Usage
///
/// ```rust,ignore
/// // Buffer is used internally by TerminalWindow
/// let mut buffer = Buffer::new(80, 24);
///
/// // Write some content
/// buffer.write_str(0, 0, "Hello, World!", None)?;
/// buffer.write_char(1, 5, '★', Some(ColorPair::new(Color::Yellow, Color::Black)))?;
///
/// // Process changes for rendering
/// let changes = buffer.process_changes();
/// // changes now contains optimized rendering commands
/// ```
pub struct Buffer {
    width: u16,
    height: u16,
    current: Vec<Cell>,  // What should be displayed
    previous: Vec<Cell>, // What was last rendered
    dirty_rows: Vec<Option<DirtyRange>>,
    changes: Vec<BufferChange>,
}

impl Buffer {
    pub(crate) fn new(width: u16, height: u16) -> Self {
        let size = width as usize * height as usize;
        let current = vec![Cell::empty(); size];
        let previous = vec![Cell::empty(); size];

        Self {
            width,
            height,
            current,
            previous,
            dirty_rows: vec![None; height as usize],
            changes: Vec::new(),
        }
    }

    fn coords_to_index(&self, x: u16, y: u16) -> usize {
        (y as usize * self.width as usize) + x as usize
    }

    fn mark_dirty_span(&mut self, y: u16, min_x: u16, max_x: u16) {
        let Some(row) = self.dirty_rows.get_mut(y as usize) else {
            return;
        };

        match row {
            Some(range) => {
                range.min_x = range.min_x.min(min_x);
                range.max_x = range.max_x.max(max_x);
            }
            None => {
                *row = Some(DirtyRange { min_x, max_x });
            }
        }
    }

    #[allow(dead_code)]
    pub(crate) fn write_char(
        &mut self,
        y: u16,
        x: u16,
        ch: char,
        colors: Option<ColorPair>,
    ) -> Result<()> {
        if x >= self.width || y >= self.height {
            return Err(crate::Error::BufferSizeError {
                x,
                y,
                width: self.width,
                height: self.height,
            });
        }

        let idx = self.coords_to_index(x, y);
        let cell = &mut self.current[idx];

        if cell.ch != ch || cell.colors != colors {
            cell.ch = ch;
            cell.colors = colors;
            self.mark_dirty_span(y, x, x);
        }

        Ok(())
    }

    pub(crate) fn write_str(
        &mut self,
        y: u16,
        x: u16,
        s: &str,
        colors: Option<ColorPair>,
    ) -> Result<()> {
        if x >= self.width || y >= self.height {
            return Err(crate::Error::BufferSizeError {
                x,
                y,
                width: self.width,
                height: self.height,
            });
        }

        let row_start = self.coords_to_index(0, y);
        let mut x_pos = x;
        let mut min_changed: Option<u16> = None;
        let mut max_changed: u16 = x;

        for ch in s.chars() {
            if x_pos >= self.width {
                break; // Stop at edge of buffer
            }

            let idx = row_start + x_pos as usize;
            let cell = &mut self.current[idx];
            if cell.ch != ch || cell.colors != colors {
                cell.ch = ch;
                cell.colors = colors;

                if min_changed.is_none() {
                    min_changed = Some(x_pos);
                }
                max_changed = x_pos;
            }

            x_pos = x_pos.saturating_add(1);
        }

        if let Some(min_x) = min_changed {
            self.mark_dirty_span(y, min_x, max_changed);
        }

        Ok(())
    }

    pub(crate) fn clear(&mut self) {
        for y in 0..self.height {
            let row_start = self.coords_to_index(0, y);
            let mut min_changed = None;
            let mut max_changed = 0;

            for x in 0..self.width {
                let cell = &mut self.current[row_start + x as usize];
                if cell.ch != ' ' || cell.colors.is_some() {
                    *cell = Cell::empty();
                    min_changed.get_or_insert(x);
                    max_changed = x;
                }
            }

            if let Some(min_x) = min_changed {
                self.mark_dirty_span(y, min_x, max_changed);
            }
        }
    }

    pub(crate) fn clear_line(&mut self, y: u16) -> Result<()> {
        if y >= self.height {
            return Err(crate::Error::LineOutOfBoundsError {
                y,
                height: self.height,
            });
        }

        let start_idx = self.coords_to_index(0, y);
        let mut min_changed = None;
        let mut max_changed = 0;
        for x in 0..self.width {
            let cell = &mut self.current[start_idx + x as usize];
            if cell.ch != ' ' || cell.colors.is_some() {
                *cell = Cell::empty();
                min_changed.get_or_insert(x);
                max_changed = x;
            }
        }

        if let Some(min_x) = min_changed {
            self.mark_dirty_span(y, min_x, max_changed);
        }

        Ok(())
    }

    pub(crate) fn clear_area(&mut self, start_y: u16, start_x: u16, end_y: u16, end_x: u16) {
        for y in start_y..=end_y {
            let row_start = self.coords_to_index(0, y);
            let mut min_changed = None;
            let mut max_changed = 0;

            for x in start_x..=end_x {
                let cell = &mut self.current[row_start + x as usize];
                if cell.ch != ' ' || cell.colors.is_some() {
                    *cell = Cell::empty();
                    min_changed.get_or_insert(x);
                    max_changed = x;
                }
            }

            if let Some(min_x) = min_changed {
                self.mark_dirty_span(y, min_x, max_changed);
            }
        }
    }

    pub(crate) fn process_changes(&mut self) -> usize {
        self.changes.clear();

        for y in 0..self.height {
            let Some(range) = self.dirty_rows[y as usize] else {
                continue;
            };

            let row_start = self.coords_to_index(0, y);
            let mut x = range.min_x as usize;
            let max_x = range.max_x as usize;
            while x <= max_x {
                let idx = row_start + x;
                let current = &self.current[idx];
                let previous = &self.previous[idx];

                if current == previous {
                    x += 1;
                    continue;
                }

                // Find run of consecutive changed cells with same colors.
                let mut run_length = 1usize;
                while x + run_length <= max_x {
                    let next_idx = idx + run_length;
                    let next_cell = &self.current[next_idx];
                    let next_prev = &self.previous[next_idx];

                    if next_cell.colors != current.colors || next_cell == next_prev {
                        break;
                    }

                    run_length += 1;
                }

                // Always create a change for updated content, including spaces
                // (spaces are important for clearing previously occupied cells).
                self.changes.push(BufferChange {
                    y,
                    x: x as u16,
                    start_idx: idx,
                    len: run_length,
                    colors: current.colors,
                });

                x += run_length;
            }
        }

        self.changes.len()
    }

    /// Marks the pending changes as successfully rendered.
    ///
    /// Keeping this separate from `process_changes` means a failed terminal write can be retried,
    /// and the desired buffer remains authoritative for incremental drawing.
    pub(crate) fn commit_changes(&mut self) {
        for (y, row) in self.dirty_rows.iter_mut().enumerate() {
            if let Some(range) = row.take() {
                let row_start = y * self.width as usize;
                let start_idx = row_start + range.min_x as usize;
                let end_idx = row_start + range.max_x as usize + 1;
                self.previous[start_idx..end_idx]
                    .copy_from_slice(&self.current[start_idx..end_idx]);
            }
        }
        self.changes.clear();
    }

    pub(crate) fn change(&self, index: usize) -> BufferChange {
        self.changes[index]
    }

    pub(crate) fn change_text(&self, change: BufferChange, output: &mut String) {
        output.clear();
        output.reserve(change.len);
        output.extend(
            self.current[change.start_idx..change.start_idx + change.len]
                .iter()
                .map(|cell| cell.ch),
        );
    }

    /// Get buffer statistics for debugging/profiling
    #[allow(dead_code)]
    pub(crate) fn get_stats(&self) -> BufferStats {
        let dirty_rows = self.dirty_rows.iter().filter(|row| row.is_some()).count();
        let dirty_cols = self
            .dirty_rows
            .iter()
            .filter_map(|row| row.map(|range| (range.max_x - range.min_x + 1) as usize))
            .sum();
        let modified_cells = self
            .dirty_rows
            .iter()
            .enumerate()
            .map(|(y, row)| {
                let Some(range) = row else {
                    return 0;
                };

                let row_start = y * self.width as usize;
                let start_idx = row_start + range.min_x as usize;
                let end_idx = row_start + range.max_x as usize + 1;

                self.current[start_idx..end_idx]
                    .iter()
                    .zip(&self.previous[start_idx..end_idx])
                    .filter(|(current, previous)| current != previous)
                    .count()
            })
            .sum();

        BufferStats {
            width: self.width,
            height: self.height,
            dirty_rows,
            dirty_cols,
            modified_cells,
        }
    }
}

#[derive(Debug)]
#[allow(dead_code)]
pub struct BufferStats {
    pub width: u16,
    pub height: u16,
    pub dirty_rows: usize,
    pub dirty_cols: usize,
    pub modified_cells: usize,
}

#[cfg(test)]
mod tests {
    use super::Buffer;

    #[test]
    fn clear_area_marks_only_changed_cells() {
        let mut buffer = Buffer::new(5, 2);

        buffer.write_str(0, 0, "abcde", None).unwrap();
        buffer.commit_changes();
        buffer.clear_area(0, 1, 0, 3);

        let stats = buffer.get_stats();
        assert_eq!(stats.dirty_rows, 1);
        assert_eq!(stats.dirty_cols, 3);
        assert_eq!(stats.modified_cells, 3);
        assert_eq!(buffer.process_changes(), 1);

        let mut output = String::new();
        buffer.change_text(buffer.change(0), &mut output);
        assert_eq!(output, "   ");
    }

    #[test]
    fn clear_area_ignores_cells_that_are_already_clear() {
        let mut buffer = Buffer::new(5, 2);

        buffer.clear_area(0, 1, 1, 3);

        let stats = buffer.get_stats();
        assert_eq!(stats.dirty_rows, 0);
        assert_eq!(stats.dirty_cols, 0);
        assert_eq!(stats.modified_cells, 0);
        assert_eq!(buffer.process_changes(), 0);
    }

    #[test]
    fn stats_count_dirty_cells_that_still_differ_from_previous_frame() {
        let mut buffer = Buffer::new(5, 2);

        buffer.write_str(0, 1, "ab", None).unwrap();
        let stats = buffer.get_stats();

        assert_eq!(stats.dirty_rows, 1);
        assert_eq!(stats.dirty_cols, 2);
        assert_eq!(stats.modified_cells, 2);
    }

    #[test]
    fn reverted_dirty_cells_produce_no_terminal_changes() {
        let mut buffer = Buffer::new(5, 2);

        buffer.write_str(0, 1, "a", None).unwrap();
        buffer.write_str(0, 1, " ", None).unwrap();

        let stats = buffer.get_stats();
        assert_eq!(stats.dirty_rows, 1);
        assert_eq!(stats.dirty_cols, 1);
        assert_eq!(stats.modified_cells, 0);
        assert_eq!(buffer.process_changes(), 0);

        buffer.commit_changes();
        let stats = buffer.get_stats();
        assert_eq!(stats.dirty_rows, 0);
        assert_eq!(stats.dirty_cols, 0);
        assert_eq!(stats.modified_cells, 0);
    }

    #[test]
    fn change_text_reuses_output_storage() {
        let mut buffer = Buffer::new(5, 1);
        let mut output = String::from("stale text");

        buffer.write_str(0, 0, "hey", None).unwrap();
        assert_eq!(buffer.process_changes(), 1);
        buffer.change_text(buffer.change(0), &mut output);

        assert_eq!(output, "hey");
    }
}