vize_fresco 0.128.0

Fresco - Vue TUI framework (Terminal User Interface)
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
//! Terminal backend using crossterm.

use std::io::{self, Write};

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    event::{DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture},
    execute, queue,
    style::{Attribute, Print, SetAttribute, SetBackgroundColor, SetForegroundColor},
    terminal::{
        Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode,
        enable_raw_mode,
    },
};

use super::{buffer::Buffer, cell::Style, cursor::Cursor};

/// Terminal mode switches used during backend initialization.
#[derive(Debug, Clone, Copy)]
pub struct TerminalOptions {
    pub raw_mode: bool,
    pub alternate_screen: bool,
    pub mouse_capture: bool,
    pub bracketed_paste: bool,
    pub hide_cursor: bool,
}

impl Default for TerminalOptions {
    fn default() -> Self {
        Self {
            raw_mode: true,
            alternate_screen: true,
            mouse_capture: false,
            bracketed_paste: true,
            hide_cursor: true,
        }
    }
}

/// Terminal backend for rendering.
pub struct Backend {
    /// Current buffer (what should be displayed)
    current: Buffer,
    /// Previous buffer (what was displayed last frame)
    previous: Buffer,
    /// Current cursor state
    cursor: Cursor,
    /// Whether alternate screen is enabled
    alternate_screen: bool,
    /// Whether the cursor was hidden during initialization
    cursor_hidden: bool,
    /// Whether raw mode is enabled
    raw_mode: bool,
    /// Whether mouse capture is enabled
    mouse_capture: bool,
    /// Whether bracketed paste is enabled
    bracketed_paste: bool,
    /// Terminal width
    width: u16,
    /// Terminal height
    height: u16,
}

impl Backend {
    /// Create a new backend with the current terminal size.
    pub fn new() -> io::Result<Self> {
        let (width, height) = crossterm::terminal::size()?;
        Ok(Self {
            current: Buffer::new(width, height),
            previous: Buffer::new(width, height),
            cursor: Cursor::new(),
            alternate_screen: false,
            cursor_hidden: false,
            raw_mode: false,
            mouse_capture: false,
            bracketed_paste: false,
            width,
            height,
        })
    }

    /// Initialize the terminal for TUI mode.
    pub fn init(&mut self) -> io::Result<()> {
        self.init_with_options(TerminalOptions::default())
    }

    /// Initialize the terminal for TUI mode with explicit mode options.
    pub fn init_with_options(&mut self, options: TerminalOptions) -> io::Result<()> {
        if options.raw_mode {
            enable_raw_mode()?;
            self.raw_mode = true;
        }

        let mut stdout = io::stdout();

        if options.alternate_screen {
            execute!(stdout, EnterAlternateScreen)?;
            self.alternate_screen = true;
        }

        if options.bracketed_paste {
            execute!(stdout, EnableBracketedPaste)?;
            self.bracketed_paste = true;
        }

        if options.mouse_capture {
            execute!(stdout, EnableMouseCapture)?;
            self.mouse_capture = true;
        }

        if options.hide_cursor {
            execute!(stdout, Hide)?;
            self.cursor_hidden = true;
        }
        Ok(())
    }

    /// Initialize with mouse capture enabled.
    pub fn init_with_mouse(&mut self) -> io::Result<()> {
        self.init_with_options(TerminalOptions {
            mouse_capture: true,
            ..TerminalOptions::default()
        })
    }

    /// Restore the terminal to normal mode.
    pub fn restore(&mut self) -> io::Result<()> {
        let mut stdout = io::stdout();

        if self.mouse_capture {
            execute!(stdout, DisableMouseCapture)?;
            self.mouse_capture = false;
        }

        if self.bracketed_paste {
            execute!(stdout, DisableBracketedPaste)?;
            self.bracketed_paste = false;
        }

        if self.alternate_screen {
            execute!(stdout, LeaveAlternateScreen)?;
            self.alternate_screen = false;
        }

        if self.cursor_hidden {
            execute!(stdout, Show)?;
            self.cursor_hidden = false;
        }

        if self.raw_mode {
            disable_raw_mode()?;
            self.raw_mode = false;
        }
        Ok(())
    }

    /// Get terminal width.
    #[inline]
    pub fn width(&self) -> u16 {
        self.width
    }

    /// Get terminal height.
    #[inline]
    pub fn height(&self) -> u16 {
        self.height
    }

    /// Get current buffer for modification.
    #[inline]
    pub fn buffer_mut(&mut self) -> &mut Buffer {
        &mut self.current
    }

    /// Get current buffer for reading.
    #[inline]
    pub fn buffer(&self) -> &Buffer {
        &self.current
    }

    /// Get cursor for modification.
    #[inline]
    pub fn cursor_mut(&mut self) -> &mut Cursor {
        &mut self.cursor
    }

    /// Get cursor for reading.
    #[inline]
    pub fn cursor(&self) -> &Cursor {
        &self.cursor
    }

    /// Check if terminal size has changed and resize buffers if needed.
    pub fn sync_size(&mut self) -> io::Result<bool> {
        let (width, height) = crossterm::terminal::size()?;
        if width != self.width || height != self.height {
            self.width = width;
            self.height = height;
            self.current.resize(width, height);
            self.previous.resize(width, height);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Clear the screen completely.
    pub fn clear(&mut self) -> io::Result<()> {
        self.current.clear();
        self.previous.clear();
        execute!(io::stdout(), Clear(ClearType::All))?;
        Ok(())
    }

    /// Render the current buffer to the terminal.
    /// Uses differential rendering for efficiency.
    pub fn flush(&mut self) -> io::Result<()> {
        let mut stdout = io::stdout();
        let mut last_style = Style::new();
        let mut last_x: i32 = -1;
        let mut last_y: i32 = -1;

        // Collect changes
        let changes: Vec<_> = self.current.diff(&self.previous).collect();

        for (x, y, cell) in changes {
            // Skip continuation cells
            if cell.is_continuation {
                continue;
            }

            // Move cursor if not adjacent
            if x as i32 != last_x + 1 || y as i32 != last_y {
                queue!(stdout, MoveTo(x, y))?;
            }

            // Apply style changes
            if cell.style != last_style {
                self.apply_style(&mut stdout, &cell.style, &last_style)?;
                last_style = cell.style;
            }

            // Print the character
            queue!(stdout, Print(&cell.symbol))?;

            last_x = x as i32;
            last_y = y as i32;
        }

        // Reset style
        queue!(
            stdout,
            SetForegroundColor(crossterm::style::Color::Reset),
            SetBackgroundColor(crossterm::style::Color::Reset),
            SetAttribute(Attribute::Reset)
        )?;

        // Update cursor
        if self.cursor.visible {
            let cursor_style = if self.cursor.blinking {
                self.cursor.shape.to_blinking_cursor_style()
            } else {
                self.cursor.shape.to_cursor_style()
            };
            queue!(
                stdout,
                MoveTo(self.cursor.x, self.cursor.y),
                cursor_style,
                Show
            )?;
        } else {
            queue!(stdout, Hide)?;
        }

        stdout.flush()?;

        // Swap buffers
        std::mem::swap(&mut self.current, &mut self.previous);
        self.current.clear();

        Ok(())
    }

    /// Apply style changes to stdout.
    fn apply_style<W: Write>(&self, writer: &mut W, new: &Style, old: &Style) -> io::Result<()> {
        // Foreground color
        if new.fg != old.fg {
            if let Some(fg) = new.fg {
                queue!(writer, SetForegroundColor(fg.into()))?;
            } else {
                queue!(writer, SetForegroundColor(crossterm::style::Color::Reset))?;
            }
        }

        // Background color
        if new.bg != old.bg {
            if let Some(bg) = new.bg {
                queue!(writer, SetBackgroundColor(bg.into()))?;
            } else {
                queue!(writer, SetBackgroundColor(crossterm::style::Color::Reset))?;
            }
        }

        // Attributes
        if new.bold != old.bold {
            queue!(
                writer,
                SetAttribute(if new.bold {
                    Attribute::Bold
                } else {
                    Attribute::NormalIntensity
                })
            )?;
        }

        if new.dim != old.dim {
            queue!(
                writer,
                SetAttribute(if new.dim {
                    Attribute::Dim
                } else {
                    Attribute::NormalIntensity
                })
            )?;
        }

        if new.italic != old.italic {
            queue!(
                writer,
                SetAttribute(if new.italic {
                    Attribute::Italic
                } else {
                    Attribute::NoItalic
                })
            )?;
        }

        if new.underline != old.underline {
            queue!(
                writer,
                SetAttribute(if new.underline {
                    Attribute::Underlined
                } else {
                    Attribute::NoUnderline
                })
            )?;
        }

        if new.blink != old.blink {
            queue!(
                writer,
                SetAttribute(if new.blink {
                    Attribute::SlowBlink
                } else {
                    Attribute::NoBlink
                })
            )?;
        }

        if new.strikethrough != old.strikethrough {
            queue!(
                writer,
                SetAttribute(if new.strikethrough {
                    Attribute::CrossedOut
                } else {
                    Attribute::NotCrossedOut
                })
            )?;
        }

        if new.reverse != old.reverse {
            queue!(
                writer,
                SetAttribute(if new.reverse {
                    Attribute::Reverse
                } else {
                    Attribute::NoReverse
                })
            )?;
        }

        if new.hidden != old.hidden {
            queue!(
                writer,
                SetAttribute(if new.hidden {
                    Attribute::Hidden
                } else {
                    Attribute::NoHidden
                })
            )?;
        }

        Ok(())
    }
}

impl Default for Backend {
    fn default() -> Self {
        // Panic path by trait-contract limitation: `Default` cannot return an
        // I/O error. Callers that need recoverable terminal initialization should
        // use `Backend::new`; this impl is kept for ergonomic tests and builders.
        Self::new().expect("Failed to create backend")
    }
}

impl Drop for Backend {
    fn drop(&mut self) {
        let _ = self.restore();
    }
}

#[cfg(test)]
mod tests {
    use super::{Backend, TerminalOptions};

    #[test]
    fn test_backend_size() {
        // This test requires a terminal, so we just check it doesn't panic
        if let Ok(backend) = Backend::new() {
            assert!(backend.width() > 0);
            assert!(backend.height() > 0);
        }
    }

    #[test]
    fn terminal_options_default_preserves_legacy_init_modes() {
        let options = TerminalOptions::default();

        assert!(options.alternate_screen);
        assert!(!options.mouse_capture);
        assert!(options.bracketed_paste);
        assert!(options.raw_mode);
        assert!(options.hide_cursor);
    }
}